Been messing around with some bluetooth chips recently specifically ones with serial port profile, and ran into a rather eclectic corner case. How can I pair a bluetooth device from the shell on Linux? Let's just dive right in.
Step 1
Find your bluetooth device mac address
$ hcitool scan
The output from the command above should be this
Scanning ... 11:22:33:44:55:66 device 1 12:34:56:78:90:12 device 2
Step 2
Setup bluetooth-agent to pass the expected pairing code
$ bluetooth-agent 0000 &
So why are we doing this? Most bluetooth devices need some kind of pairing code ... on mice and keyboards this is usually 1234 or 0000. Most bluetooth management user interfaces (Apple and Gnome to name a few) do an excellent job of automating this step since the pin codes are well known and predictable. Since we're not in GUI land we have to have something reply to the device when we try to connect to it and give up the pairing code.
Step 3
Setup an rfcomm connection and serial port
First we must edit /etc/bluetooth/rfcomm.conf
and put our device's mac address and other important information.
rfcomm0 { # Automatically bind the device at startup bind no; # Bluetooth address of the device device 11:22:33:44:55:66; # RFCOMM channel for the connection channel 3; # Description of the connection comment "This is Device 1's serial port."; }
An important caveat, if you configure your device to not bind at startup (bind no;
) you are going to have to manually spin up rfcomm
using this command before using the serial port (which also requires root permissions).
$ sudo rfcomm connect rfcomm0
Conclusion
For automation purposes especially with serial ports (the particular use case I'm thinking about is tethering a smart phone), I'd make sure to set bind yes;
that way I don't have to run that rfcomm
command. The only thing left is connecting to that new virtual serial port which usually lines up with the rfcomm
name. In our example the file descriptor should be named /dev/rfcomm0
.
Happy Hacking.