Serial Bluetooth Terminal With Python Asyncio - Avil Page
Serial Bluetooth Terminal With Python Asyncio - Avil Page
Introduction
PySerial package provides a tool called miniterm1, which provides a terminal to interact
with any serial ports.
However miniterm sends each and every character as we type instead of sending entire
message at once. In addition to this, it doesn't provide any timestamps on the messages
transferred.
In this article, lets write a simple terminal to address the above issues.
Bluetooth Receiver
pyserial-asyncio2 package provides Async I/O interface for communicating with serial
ports. We can write a simple function to read and print all the messages being received on
a serial port as follows.
import sys
import asyncio
import datetime as dt
import serial_asyncio
while True:
now = str(dt.datetime.now())
receiver = receive(reader)
await asyncio.wait([receiver])
port = sys.argv[1]
baudrate = sys.argv[2]
loop = asyncio.get_event_loop()
loop.run_until_complete(main(port, baudrate))
loop.close()
Now we can connect a phone's bluetooth to a laptop bluetooth. From phone we can send
messages to laptop using bluetooth terminal app like Serial bluetooth terminal4.
https://avilpage.com/2020/08/bluetooth-terminal-python-asyncio.html 1/3
17/10/2022, 15:30 Serial Bluetooth Terminal With Python Asyncio | Avil Page
We can listen to these messages on laptop via serial port by running the following
command.
Bluetooth Sender
Now lets write a sender to send messages typed on the terminal to the bluetooth.
To read input from terminal, we need to use aioconsole 3. It provides async input
equivalent function to read input typed on the terminal.
import sys
import asyncio
import datetime as dt
import serial_asyncio
import aioconsole
data = line.strip()
if not data:
continue
now = str(dt.datetime.now())
writer.write(line)
sender = send(writer)
await asyncio.wait([sender])
port = sys.argv[1]
baudrate = sys.argv[2]
loop = asyncio.get_event_loop()
loop.run_until_complete(main(port, baudrate))
loop.close()
We can run the program with the following command and send messages to phone's
bluetooth.
https://avilpage.com/2020/08/bluetooth-terminal-python-asyncio.html 2/3
17/10/2022, 15:30 Serial Bluetooth Terminal With Python Asyncio | Avil Page
Conclusion
If we combine the above two programmes, we get a simple bluetooth client to interact
with any bluetooth via serial interface. Here is the complete code 5 for the client.
In the next article, lets see how to interact with Bluetooth LE devices.
1. miniterm ↩
2. pyserial-asyncio on PyPi ↩
3. aioconsole on PyPi ↩
bluetooth
featured
python
https://avilpage.com/2020/08/bluetooth-terminal-python-asyncio.html 3/3