Establishing a Bluetooth Piconet in Android
I am working on establishing a Bluetooth Piconet among multiple devices in a testbed. The topology of this network is known to all devices.
The devices in the test开发者_运维问答bed are Ubuntu Desktop PCs and Android (Eclair) devices. Now, I'm looking at a way of establishing a master slave relationship among these devices in a deterministic way. Specifically, I'm looking for a way to establish an android device as master and open multiple connections with 7 other devices.
I have looked at native implementations using the bluez stack and the NDK, but the bluez stack implementation on my device (Samsung GT 15503) does not conform to the standards I guess and even normal apps like hcitool, hciconfig don't work.
Therefore, I tried using the official SDK and even succeeded in establishing an RFCOMM socket with my laptop (Using the bluetooth chat sample app as a reference). But I'm stuck at the point where I try connecting two or more devices using the same BluetoothServerSocket. Unless I close the original socket, I can't seem to open new connections.
Any suggestions in this regard are greatly appreciated.
I finally figured out what I was doing wrong. Apparently, whenever you call the accept method from a BluetoothServerSocket and get back a socket, you have to close this socket before calling accept again.
I worked around this problem to establish the piconet I wanted by creating 7 different UUIDs and using a BluetoothServerSocket to listen and accept a connection for each of these UUIDs. Once I get a connection for a particular UUID, I close the corresponding server socket and reopen another one for the next UUID.
The following snippet illustrates the idea, which I got from BTClickLinkCompete.
for (int i = 0; i < 7; i++) {
BluetoothServerSocket myServerSocket = mBtAdapter
.listenUsingRfcommWithServiceRecord(srcApp, mUuid.get(i));
BluetoothSocket myBSock = myServerSocket.accept();
myServerSocket.close(); // Close the socket now that the connection
//has been made
//Do stuff with the socket here, like callback to main thread
}
Here, mUuid is an array that stores 7 different uuids. The clients trying to connect to the server will also possess these uuids and will try them out one by one in order because they do not know the number of clients already connected to the server.
Maybe this helps:
You have to call the method accept()
(from BluetoothServerSocket
) for each connection remember that.
When you receive a connection you should start a new thread with what you want to do to that connection and then call the accept()
again
精彩评论