-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path__main__.py
executable file
·61 lines (49 loc) · 1.31 KB
/
__main__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import asyncio
import sys
from time import time
import serial
import websockets
import json
com_port = None
com_rate = 19200
socket_port = None
ser = None
try:
com_port = sys.argv[1]
socket_port = sys.argv[2]
except IndexError as ex:
print(f"USAGE: {sys.argv[0]} COM_PORT SOCKET_PORT", file=sys.stderr)
exit(1)
async def main():
with serial.Serial(com_port, com_rate, write_timeout=0, timeout=0) as ser:
async def read_serial_to_socket(websocket):
if ser.in_waiting > 0:
msg = ""
b = ser.read().decode("ascii")
while b != "\n":
msg += b
b = ser.read().decode("ascii")
await websocket.send(msg)
async def socket_handler(websocket):
last_update = time()
async for message in websocket:
if time() < last_update + 0.02:
continue
last_update = time()
message = json.loads(message)
pwms = message["servos"].values()
if len(pwms) < 1:
continue
buff = bytearray(3+len(pwms))
buff[0] = 2 # STX
buff[1] = len(pwms) # Number of servos
buff[2: -1] = bytearray(pwms) # PWMs
buff[-1] = sum(buff[2:-1]) % 256 # Checksum
ser.write(buff)
await read_serial_to_socket(websocket)
async with websockets.serve(socket_handler, "localhost", socket_port):
await asyncio.Future()
try:
asyncio.run(main())
except KeyboardInterrupt:
exit(0)