Skip to content

Instantly share code, notes, and snippets.

@ChillarAnand
Last active September 10, 2020 12:56
Show Gist options
  • Save ChillarAnand/a7be6adeb84a63d48e8dda27aab7ac94 to your computer and use it in GitHub Desktop.
Save ChillarAnand/a7be6adeb84a63d48e8dda27aab7ac94 to your computer and use it in GitHub Desktop.
Cross platform bluetooth terminal with Python serial asyncio - Blog: https://avilpage.com/2020/08/bluetooth-terminal-python-asyncio.html
import sys
import asyncio
import datetime as dt
import serial_asyncio
import aioconsole
async def echo(writer):
stdin, stdout = await aioconsole.get_standard_streams()
async for line in stdin:
data = line.strip()
if not data:
continue
now = str(dt.datetime.now())
print(f'{now} Tx ==> {data.decode()}')
writer.write(line)
async def recv(r):
while True:
data = await r.readuntil(b'\n')
now = str(dt.datetime.now())
print(f'{now} Rx <== {data.strip().decode()}')
async def main(port, baudrate):
reader, writer = await serial_asyncio.open_serial_connection(url=port, baudrate=baudrate)
pecho = echo(writer)
received = recv(reader)
await asyncio.wait([pecho, received])
port = sys.argv[1]
try:
baudrate = sys.argv[2]
except:
baudrate = 9600
loop = asyncio.get_event_loop()
loop.run_until_complete(main(port, baudrate))
loop.close()
@ChillarAnand
Copy link
Author

ChillarAnand commented Sep 3, 2020

# Usage

$ python client.py /dev/cu.Bluetooth-Incoming-Port 9600
ping from mac
2020-09-03 20:57:39.362403 Tx ==> ping from mac

2020-09-03 20:57:41.912708 Rx <== ping from android

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment