Tested on:Raspbian Buster; Python 3.5; RPi 3B+
Prerequisites:Endlich! Raspberry Pi 3B+ Buster als Bluetooth Audio Player
0

Terminal control with PExpect: automatic Bluetooth connection

PExpect is a handy tool for automating terminal interactions. In this tutorial, you’ll learn how to automatically create a Bluetooth connection to a Raspberry Pi with PExpect.

Installation
Follow the setup instructions from the link above for configuring an RPi as Bluetooth sink. Then, enter in the terminal

Test
Activate Bluetooth on the smartphone and enter then in the terminal

After a few seconds, the smartphone asks to confirm the pairing. After confirming, the smartphone connect to the RPi and stream music onto it.
Note: This only works if the smartphone is the only active Bluetooth device, since the script naively pairs with the first device it finds.

Code explained
The script contains two functions: scan_bluetooth_agents returns a dictionary of all found devices and trust_device takes a device hardware address as input and pairs with that device.
PExpect first creates a process for a terminal program expecting user input and then executes all requried inputs sequentially:

Full script
Click on Full Script to show all of the code.

Links
PExpect documentation: https://pexpect.readthedocs.io/en/stable/

Knight of Pi

Johannes Bergs aka Knight of Pi. Diploma in Bioinformatics, some Webdesign and Python coding then. Living in the beautiful city of Vienna.

Comment

Time limit is exhausted. Please reload CAPTCHA.