Richardjm/wled serial asyncio (#332)

wled: Use pyserial-asyncio for wled

Signed-off-by:  Richard Mitchell <richardjm+moonraker@gmail.com>
This commit is contained in:
Richard Mitchell
2022-01-15 19:22:49 +00:00
committed by GitHub
parent 60f2e3e1c7
commit 5f54a23f3e
2 changed files with 10 additions and 22 deletions

View File

@@ -13,11 +13,9 @@ from enum import Enum
import logging import logging
import json import json
import asyncio import asyncio
import os import serial_asyncio
import serial
from tornado.httpclient import AsyncHTTPClient from tornado.httpclient import AsyncHTTPClient
from tornado.httpclient import HTTPRequest from tornado.httpclient import HTTPRequest
from tornado.escape import json_decode
# Annotation imports # Annotation imports
from typing import ( from typing import (
@@ -27,9 +25,6 @@ from typing import (
Any, Any,
Optional, Optional,
Dict, Dict,
Coroutine,
Tuple,
Union,
) )
if TYPE_CHECKING: if TYPE_CHECKING:
@@ -245,31 +240,24 @@ class StripSerial(Strip):
super().__init__(name, color_order, cfg) super().__init__(name, color_order, cfg)
# Read the serial information (requires wled 0.13 2108250 or greater) # Read the serial information (requires wled 0.13 2108250 or greater)
serialport: str = cfg.get("serial") self.serialport: str = cfg.get("serial")
baud: int = cfg.getint("baud", 115200, above=49) self.baud: int = cfg.getint("baud", 115200, above=49)
# write_timeout of 0 is non-blocking
self.ser = serial.Serial(serialport, baud,
write_timeout=0)
fd = self.ser.fileno()
os.set_blocking(fd, False)
async def send_wled_command_impl(self: StripSerial, async def send_wled_command_impl(self: StripSerial,
state: Dict[str, Any]) -> None: state: Dict[str, Any]) -> None:
async with self.request_mutex: async with self.request_mutex:
logging.debug(f"WLED: serial:{self.ser.name} json:{state}") if not hasattr(self, 'ser'):
_, self.ser = await serial_asyncio.open_serial_connection(
url=self.serialport, baudrate=self.baud)
if not self.ser.is_open: logging.debug(f"WLED: serial:{self.serialport} json:{state}")
self.ser.open()
# asyncio support is still experimental in pySerial
self.ser.write(json.dumps(state).encode()) self.ser.write(json.dumps(state).encode())
def close(self: StripSerial): def close(self: StripSerial):
if self.ser.is_open: if hasattr(self, 'ser'):
self.ser.close() self.ser.close()
logging.info(f"WLED: Closing serial {self.ser.name}") logging.info(f"WLED: Closing serial {self.serialport}")
class WLED: class WLED:
def __init__(self: WLED, config: ConfigHelper) -> None: def __init__(self: WLED, config: ConfigHelper) -> None:

View File

@@ -1,6 +1,6 @@
# Python dependencies for Moonraker # Python dependencies for Moonraker
tornado==6.1.0 tornado==6.1.0
pyserial==3.4 pyserial-asyncio==0.6
pillow==9.0.0 pillow==9.0.0
lmdb==1.2.1 lmdb==1.2.1
streaming-form-data==1.8.1 streaming-form-data==1.8.1