What if we would like to publish data transmitted over RS232 Serial from an embedded Arduino device to a WebSocket browser client?
When prototyping a cable serial connection is very convenient as RF or networking modules may not yet be implemented. How do we get serial data to provision a cloud API service or web browser interface?
We can achieve this easily with Python and PySerial library:
#!/usr/bin/python import serial import asyncio import datetime import random import websockets ser = serial.Serial( port='/dev/ttyUSB0',\ baudrate=115200,\ parity=serial.PARITY_NONE,\ stopbits=serial.STOPBITS_ONE,\ bytesize=serial.EIGHTBITS,\ timeout=0) print("connected to: " + ser.portstr) async def tx(websocket, path): line = [] while True: for i in ser.read(): c = chr(i) line.append(c) if c == '\n': print(''.join(line)) await websocket.send(''.join(line)) line = [] break start_server = websockets.serve(tx, "127.0.0.1", 5678) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever() ser.close()
Here is a more detailed example of reading serial port data in C language on Linux Platform –
https://blog.mbedded.ninja/programming/operating-systems/linux/linux-serial-ports-using-c-cpp/