-
Notifications
You must be signed in to change notification settings - Fork 11
/
async_serial_streams.py
40 lines (32 loc) · 1.04 KB
/
async_serial_streams.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
import asyncio
import serial_asyncio
async def main(loop):
reader, _ = await serial_asyncio.open_serial_connection(url='./reader', baudrate=115200)
print('Reader created')
_, writer = await serial_asyncio.open_serial_connection(url='./writer', baudrate=115200)
print('Writer created')
messages = [b'foo\n', b'bar\n', b'baz\n', b'qux\n']
sent = send(writer, messages)
received = recv(reader)
await asyncio.wait([
asyncio.create_task(sent),
asyncio.create_task(received)
])
async def send(w, msgs):
for msg in msgs:
w.write(msg)
print(f'sent: {msg.decode().rstrip()}')
await asyncio.sleep(0.5)
w.write(b'DONE\n')
print('Done sending')
async def recv(r):
while True:
msg = await r.readuntil(b'\n')
if msg.rstrip() == b'DONE':
print('Done receiving')
break
print(f'received: {msg.rstrip().decode()}')
if __name__ == '__main__':
loop = asyncio.new_event_loop()
loop.run_until_complete(main(loop))
loop.close()