65 lines
1.5 KiB
Python
Executable File
65 lines
1.5 KiB
Python
Executable File
#! /usr/bin/env python3
|
|
|
|
import asyncio
|
|
import uuid
|
|
import aioserial
|
|
import aiomqtt
|
|
|
|
SERIAL_PORT = "/tmp/ttyV0"
|
|
BAUD = 115200
|
|
|
|
SERIAL_PUBLISH_TOPIC = "serial/data"
|
|
SERIAL_COMMAND_TOPIC = "serial/command"
|
|
|
|
|
|
async def serial_reader(ser, client):
|
|
while True:
|
|
data = await ser.read_async(64)
|
|
if data:
|
|
await client.publish(SERIAL_PUBLISH_TOPIC, data)
|
|
# Hand back to event loop
|
|
await asyncio.sleep(0)
|
|
|
|
|
|
async def mqtt_command_writer(ser, client):
|
|
async for message in client.messages:
|
|
topic = str(message.topic)
|
|
print(message.topic, message.payload)
|
|
|
|
if str(topic) == SERIAL_COMMAND_TOPIC:
|
|
await ser.write_async(message.payload)
|
|
|
|
|
|
async def main():
|
|
client_id = f"jono-test-{uuid.uuid4()}"
|
|
interval = 5
|
|
|
|
ser = aioserial.AioSerial(
|
|
port=SERIAL_PORT,
|
|
baudrate=BAUD,
|
|
timeout=0.05, # 50 ms
|
|
)
|
|
|
|
while True:
|
|
try:
|
|
async with aiomqtt.Client(
|
|
"127.0.0.1",
|
|
port=1883,
|
|
identifier=client_id,
|
|
) as client:
|
|
await client.subscribe(SERIAL_COMMAND_TOPIC)
|
|
|
|
await asyncio.gather(
|
|
serial_reader(ser, client),
|
|
mqtt_command_writer(ser, client),
|
|
)
|
|
|
|
except aiomqtt.MqttError as e:
|
|
print(e)
|
|
print(f"Connection lost; reconnecting in {interval} seconds...")
|
|
await asyncio.sleep(interval)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
asyncio.run(main())
|