mirror of
https://github.com/daniviga/django-ram.git
synced 2025-08-04 13:17:50 +02:00
Change the serial daemon to use sockets
This commit is contained in:
44
daemons/net-to-serial.py
Normal file
44
daemons/net-to-serial.py
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import serial
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
|
||||||
|
class SerialDaemon:
|
||||||
|
def __init__(self):
|
||||||
|
self.ser = serial.Serial('/dev/pts/7') # WIP
|
||||||
|
self.ser.baudrate = 115200
|
||||||
|
|
||||||
|
def __del__(self):
|
||||||
|
try:
|
||||||
|
self.ser.close()
|
||||||
|
except AttributeError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
async def handle_echo(self, reader, writer):
|
||||||
|
data = await reader.read(100)
|
||||||
|
message = data.decode()
|
||||||
|
addr = writer.get_extra_info('peername')
|
||||||
|
|
||||||
|
print(f"Received {message!r} from {addr!r}")
|
||||||
|
|
||||||
|
self.ser.write(data)
|
||||||
|
response = self.read_until()
|
||||||
|
print(f"Send: {response!r}")
|
||||||
|
writer.write(response)
|
||||||
|
await writer.drain()
|
||||||
|
|
||||||
|
print("Close the connection")
|
||||||
|
writer.close()
|
||||||
|
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
sd = SerialDaemon()
|
||||||
|
server = await asyncio.start_server(
|
||||||
|
sd.handle_echo, '127.0.0.1', 2560) # WIP
|
||||||
|
addrs = ', '.join(str(sock.getsockname()) for sock in server.sockets)
|
||||||
|
print(f'Serving on {addrs}')
|
||||||
|
|
||||||
|
async with server:
|
||||||
|
await server.serve_forever()
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(main())
|
@@ -1,42 +0,0 @@
|
|||||||
import serial
|
|
||||||
import logging
|
|
||||||
import socket
|
|
||||||
import asyncio
|
|
||||||
import time
|
|
||||||
import paho.mqtt.client as mqtt
|
|
||||||
from asyncio_mqtt import Client
|
|
||||||
|
|
||||||
MQTT_HOST = "127.0.0.1"
|
|
||||||
MQTT_PORT = 1883
|
|
||||||
|
|
||||||
|
|
||||||
async def mqtt_broker(ser):
|
|
||||||
async with Client(MQTT_HOST, port=MQTT_PORT) as client:
|
|
||||||
await client.subscribe("dcc/commands")
|
|
||||||
async with client.unfiltered_messages() as messages:
|
|
||||||
async for message in messages:
|
|
||||||
print(message.payload.decode())
|
|
||||||
# ser.write(message.payload)
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
client = mqtt.Client()
|
|
||||||
# ser = serial.Serial('/dev/pts/7')
|
|
||||||
# ser.baudrate = 9600
|
|
||||||
ser = None # remove me
|
|
||||||
while True:
|
|
||||||
try:
|
|
||||||
client.connect(MQTT_HOST, MQTT_PORT)
|
|
||||||
break
|
|
||||||
except (socket.gaierror, ConnectionRefusedError):
|
|
||||||
logging.warning('Broker not available')
|
|
||||||
time.sleep(5)
|
|
||||||
|
|
||||||
logging.info('Broker subscribed')
|
|
||||||
client.disconnect()
|
|
||||||
asyncio.run(mqtt_broker(ser))
|
|
||||||
# ser.close()
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
Reference in New Issue
Block a user