messy dirty hack code

This commit is contained in:
Jono Targett 2026-03-14 23:36:24 +10:30
parent e82ad574ab
commit cc2e5cf613
2 changed files with 52 additions and 7 deletions

View File

View File

@ -4,6 +4,7 @@ import asyncio
import uuid import uuid
import aioserial import aioserial
import aiomqtt import aiomqtt
import pyubx2
SERIAL_PORT = "/tmp/ttyV0" SERIAL_PORT = "/tmp/ttyV0"
BAUD = 115200 BAUD = 115200
@ -12,14 +13,58 @@ SERIAL_PUBLISH_TOPIC = "serial/data"
SERIAL_COMMAND_TOPIC = "serial/command" SERIAL_COMMAND_TOPIC = "serial/command"
async def serial_reader(ser, client): async def parse_serial(ser):
while True: """
data = await ser.read_async(64) Async generator: read raw bytes from serial and yield parsed UBX/NMEA messages.
if data: """
await client.publish(SERIAL_PUBLISH_TOPIC, data) buffer = bytearray()
# Hand back to event loop
await asyncio.sleep(0)
# pyubx2 requires a file-like object, so we'll use a memoryview wrapper
class StreamWrapper:
def read(self, n=1):
# grab at most n bytes from buffer
if not buffer:
raise BlockingIOError
out = buffer[:n]
del buffer[:n]
return bytes(out)
ubr = pyubx2.UBXReader(StreamWrapper(), parsing=True)
while True:
# read available data from serial (small chunks)
chunk = await ser.read_async(200)
if chunk:
buffer.extend(chunk)
# attempt to parse as many messages as possible
try:
while True:
raw, parsed = ubr.read()
if raw is None:
break
yield raw, parsed
except (BlockingIOError, Exception):
# incomplete message; wait for more bytes
pass
except pyubx2.UBXStreamError:
pass # silently ignore incomplete packets
else:
await asyncio.sleep(0) # yield control
async def serial_reader(ser, mqtt_client):
"""
Coroutine wrapper around async generator parse_serial.
Feeds parsed UBX/NMEA messages to MQTT.
"""
async for raw, parsed in parse_serial(ser):
# For example, publish raw bytes to MQTT
print(parsed)
await mqtt_client.publish("serial/parsed", str(parsed))
await mqtt_client.publish("serial/raw", raw)
# Optional: inspect parsed fields
# print(parsed)
async def mqtt_command_writer(ser, client): async def mqtt_command_writer(ser, client):
async for message in client.messages: async for message in client.messages: