linuxbluetoothrfcomm

How can I consistently connect to the same rfcomm port on Linux?


I have several bluetooth device that I'm trying to connect to in Linux. I have no problems with any of the devices except for one. The difference is that all the other devices handle their bluetooth connections in (what I assume to be) the standard way, i.e. they wait for the Host device (the PC) to initiate the connection. The other device, on the other hand, tries to initiate the connection itself every few seconds, with a second or so of sleep in between.

For the other devices, I've been connecting like this:

rfcomm connect /dev/rfcommX <deviceMacAddress>

(where X is any unused rfcomm port number)

Before issuing this command, I run the bluetooth-agent with the needed pairing keys. Everything here works fine.

For the device in question, this works great the first time, before the device has been paired. After pairing, however, the rfcomm connect command has a very high likelihood of failing. This is because the device is itself trying to init the connection.. when the device is sleeping, the connection fails ("Host down").

Instead, I've found that, for this device, the following command works like a charm:

rfcomm listen /dev/rfcommX

(I had to add a serial port via sdptool add SP first)

As the PC will sit there and wait for an incoming connection from the device, this works every single time.

However, the problem comes in when I have more than one device. The rfcomm listen command works brilliantly, but there doesn't seem to be a way to control which device (identified by Mac address) connects to which rfcomm port; if more than one device is switched on, then the first one to try and connect will connect, regardless. In our application, however, we want the user to know which device they are connecting to.

Has anyone dealt with anything like this before? We're getting to the point where we're thinking of writing a custom version of the bluez bluetooth package, so any help here would be greatly appreciated :)


Solution

  • Either write a udev rule that creates a symlink with the same name each time, or follow the appropriate path through /sys to get to the device.