BluetoothCtl pairing with pin using python subprocess on Raspberry Pi

1.5k views Asked by At

I am working on a project to communicate between a raspberry pi & a series of Arduinos, using the HC-05 bluetooth modules, over a bluetooth connection. I am able to pair the arduinos using bluetoothctl and the communicating using python scripts, but I would like to include the pairing process in my scripts as well but I have not found a solution that includes the bluetooth pairing pin in the scripts.

What I've tried:

  1. The PyBluez library, but it is incapable of pairing.
  2. Subprocess, but I can't respond to the pin request (code below), but this results in an error of too many arguments (for bluetoothctl).
import subprocess, shlex
addr = "00:14:03:06:12:84"
pinCode = "1234"

args = ["bluetoothctl", f"pair {addr}", pinCode]
args = shlex(args)
subprocess.Popen(args)
  1. I also tried using the bluetoothctl wrapper, but there's is no pin option here either.

Is pairing via python possible?

1

There are 1 answers

3
ukBaz On

The way Bluez expects this to be done is with the D-Bus Agent API which is documented at https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc/agent-api.txt

There is also a Python example in the Bluez source tree: https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/test/simple-agent

As pairing is normally a one-off provisioning/security step where keys are exchanged and a device is established as trusted, I question the value of automating the pairing process. Do you really want to pair with devices that randomly turn up and are within range?

Subsequent connections between the RPi and HC-05 don't need to have the pairing step happen first. The Raspberry Pi would only be required to call the connection command because the two devices are already paired and trusted.