I am working on a project where I need to transfer data between android and raspberry pi via Bluetooth. However, I am new to this and I don't have deep understanding on what happens when two devices are paired. Based on assumption that the two devices of interest are already paired, where would the starting point be for programming for such task? I've been reading on BluetoothSocket, but I am still unsure of where to start. Can anyone help me please?
Thank you so much in advance!
I have been looking into this same issue, here is the reading I found on my end. I was looking to specifically code in python so that's the angle of the first one, the second is C++, but has a really thorough intro.
https://people.csail.mit.edu/albert/bluez-intro/index.html
and this one is really good too, the intro isnt too dense:
http://beej.us/guide/bgnet/output/html/multipage/index.html
The specific parts to look at involve the planning aspect. The intro of the beej programming guide shows specifically what sockets are and how they fit in a network sense. This means streaming sockets and datagram sockets. It also shows which of the sockets are used and which are availible. Chapters 1 through 3 gave me a solid enough reading basis to use the second document to determine a few things.
Chapter 2 of the MIT document goes into specific detail about each of the steps that must occur at a structural level including L2CAP + UDT, RCOMM, and whatever the stream one was. From reading these I was able to determine that the network I wanted to use was an L2CAP. I hope these help point you in the right direction though as far as what network you want to setup and what language you want to program in.
I've been working on the same task little while ago. The point is, that in order to start sending and receiving data you have to establish connection first. There is two side- device which connects (creates socket) and the other receiving connection (bluetooth server socket), giving out connection once connection is complete. After connection is established, you should stop receiving incoming connection or attempting establishing any connections.
From implementation perspective, you should implement few threads for managing all those stages - connection thread, accept thread, communucation thread. There is a great example from Google: https://github.com/googlesamples/android-BluetoothChat . It uses that technic. The only drawback is that it uses Handler (Android feature, allowing thereads to communicate) for informing user about Bluetooth events. I modified it a bit by introducing another thread, receiving status updates and calling methods from callback interface, feel free to use code from project: https://github.com/AlexShutov/LEDLights.
Related
I have to exchange data between two bluetooth devices, one of them will be an Android device. For simplicity's sake you can assume the other device will be a generic linux device running bluez producing data similar to the data a fitness tracker would produce.
The scenario seems a straightforward use case for Bluetooth Low Energy. The problem i am currently running into comes from the fact that communication has to be reliable (reliable in the way TCP is reliable). This means:
no losses
no corruption of data
order needs to be preserved
no duplicates
no phantom packets
While losses are prevented at link layer level, the order for instance seems not to be explicitly preserved when working with Low Energy (using indications would probably achieve this).
Not having done a lot of work with Bluetooth I am currently overwhelmed quite a bit with the amount of options while at the same time no option seems to fit the bill nicely.
Is there a "best-practice" for setting up reliable communication between two bluetooth devices? A Bluetooth Low Energy solution would be preferable, but is not mandatory.
Once your Bluetooth connection is setup its reliable. So you don't have to be worried about data loss or corruption.
So the things you're worried about can be easily handled in your side. You'll get proper connection and disconnection callback while setting up a BroadcastReceiver for your BluetoothAdapter.
In case of any disconnection you may have to restart the procedure for connection again and once its established properly you may resend the data.
I don't know about your purpose yet, but one thing I need to mention here is, I would not recommend Bluetooth communication if you're holding the connection for long time. Some devices disconnects the connection automatically after some time if there's no continuos transmission.
Android has Bluetooth support, but it only allow to send ot receive data from stream. There is a very good sample project from Google: https://github.com/googlesamples/android-BluetoothChat . The only drawback of this sample is that it use Handler to nitify about Bluetooth events. I changed it a bit so it use another Thread and from it calls methods of interface you set, take a look at project: https://github.com/AlexShutov/LEDLights . This is ordinary Bluetooth, not BLE, hope it will help
Android's BLE stack is as good as the link layer specification. So you can use "write without response" in one direction and notifications for the other direction. Just make sure your peripheral side does not drop incoming writes.
BLE uses 24-bit CRC. for the amount of data transmitted using BLE the CRC is quite robust and the possibility of corruption is very low ( note that TCP CRC is 16bit and the Ethernet CRC is 32bit, please see http://www.evanjones.ca/tcp-and-ethernet-checksums-fail.html).
The ordering issues in wired network is a result of routing packets through different routes to the same destination ( plese see If TCP is connection oriented why do packets follow different paths?) . This is partially due to the use of sliding window acknowledgement protocol, which allows a number of packets to be transmitted before being acknowledged.In BLE there is no routing and the acknowledgement scheme is a variation of stop and wait ARQ scheme(2-bit lazy acknowledgement), this means that it is not possible to send a new packet without being acknowledged. These two factors makes the possibility of having an out of order transmission highly unlikely.
Socket programming question here.
My interface comprises of an Android device(client), A wireless module hosting an access point, and an Arduino Uno(server).
My Android client class works when 1 user connects and sends commands to my Arduino server class.
I want to make my program friendly to many users at the same time. My server will only read in values from 1 connected client at a time.
After some research I've found that Arduino does not allow multithreading naturally, which is why i've decided to look into a number of libraries.
The Arduino library that I've decided to use for this specific issue is protothreads. Unfortunately, i've been unable to find any examples of creating a server with Arduino to accept a client's commands. Furthermore I'm having a lot of trouble figuring out how to make this library work in my favor.
Now for my question,
How exactly can I allow my Arduino server to constantly listen for
incoming messages from more than 1 client device?
Or is there something I can do on the client side that would make this communication possible?
Could you get away with accepting the socket responding and the closing it. Similar to a web page. As not to have multiple sockets open at once. Note uno only has 2k of ram flash goes quick. By one and close each stands alone and naturaly allow many different connections. Just one at a time.
I'm developing an none market appliction which run on 20-30 android devices (target specific to tablets with android honeycomb / ICS OS) maintaining connection over local WIFI network for a 1-2 hours period of time, and need to exchange data (simple objects representing commands) between them.
most of the time one specific tablet behave like a server which sending the commands, and the other devices like clients which receives the commands, but the "clients" also sending commands to the "server" sometimes.
as solution to this communication demand - I'm using for a while an open source
library which encapsulates TCP client/server protocol, called - Kryonet.
I found it very easy to use, and basically doing the job, although it sometimes "unstable" - a lot of disconnections accrues. I can't afford this disconnections, it's dammege the whole flow and use-case, causing the client's to lose commands.
I'm doing some recovery logic which re-connect the clients and send them what they have missed, but it's not good enough for the use-case.
recently I've heard about multicast broadcast protocol, and found even an open source library calls - JGroups which implement this protocol optimally, and expose easy and simple to use interface. still didn't tried it, but got advice from someone who knows, saying it should be better the the TCP client/server for my purpose.
what is the best approach I should use for implement the behavior I described ? (not necessarily one of the two I suggested)
TIA
Although JGroups has promise as a better solution for your situation, you may want to experiment a bit more to determine why the disconnects are happening. Since your clients and server are all tablets, there are a few other causes that are unrelated:
1) If the connections are not being maintained in a Service then they will be extremely unreliable by default. (See this question about singletons being destroyed in Android)
2) If the sockets have not been set to 'keepalive' then they will time out after an arbitrary number of seconds.
3) The devices you are using may shut down some persistent connections when they go to sleep.
4) The tablets may be exiting WiFi range, and switching over to a mobile network.
Try the network portion of your code on a number of desktop machines to determine if the problem is with Kryonet or your code, or if the problem is in running it on Android.
Is it possible to set up the Android Bluetooth Chat sample app to connect more than one person at a time, and have a mini chat room? What would that entail?
tl;dr version: Bluetooth sucks for this, don't use it, use wifi instead, probably backed by a web backend.
I have investigated this issue thoroughly throughout the years in the interests of a social wireless network research project. My general advice is: it doesn't work with more than two / three people. Bluetooth just isn't designed with wireless peer to peer networks in mind.
In general, it seems that the cheap Bluetooth controllers included on Android devices (especially HTC's devices, iirc) don't really handle any more than two or three connections at a time. I'm unsure if this is a hardware or firmware problem, but I can recount some basic anecdotes. I was working to implement this idea at the SDK level (i.e., without firmware modifications) around the beginning of 2011, and was able to get a peer to get two additional connections (i.e., three devices, each connecting to the other two) to work for a period of a few minutes to an hour before the connections would suddenly die and the socket would become unusable, requiring reconnection. Unfortunately, 20 minutes was an upper bound, and generally it was impossible to get connections to more than one other device at all reliably.
The goal of the project was to support multiple people interacting with each other silently in the background, but this never materialized, instead we ditched Bluetooth and went with wifi instead, which worked much much better. In the abstract, I think people view Bluetooth as a possible medium for reliable peer to peer communication, but it wasn't really designed that way: it's more of a medium used for short range communication between small devices (think headsets).
Be aware that if you want to do this, the maximum number of devices to which you can connect is fixed, because as per the Bluetooth spec, a piconet supports a maximum of seven devices. (See the wikipedia article.)
The required change is simple: you use a different UUID for each device. This can be implemented a number of ways, using an out of band exchange mechanism, or simple scheme where you assign UUIDs in an increasing fashion and when connecting to the network, try each in succession.
Here are some relevant Google groups threads:
Bluetooth peer to peer networks
Multiple connections on Android Bluetooth
I remember posting a more elaborate one detailing how to do this (with code) that I might dig up as well.., if I can find it. It should be from late 2010 or early 2011.
So the answer is, in the abstract, yes, you can try to do this, by using multiple UUIDs (after you use one, that's it, and you have to try another using some assignment protocol). However, in practice, after a lot of trial and error, this doesn't really work for what you probably want to use it for, and it's a lot better to go with an internet backend instead. By the way, this is also good for another reason, most users don't really like to turn on their Bluetooth for fear of their battery being drained..
Leaving this here, in case it helps someone else.
I was able to make my custom chat room following official bluetooth tutorial and modifying it a little.
Unfortunately, I cannot provide most of my code, but main idea is:
Every device is acts both as server and as a client. When Chat is started, device starts its server thread. Server thread is the same as official but doesn't ends when accept connection. It just keep listening.
Client thread is identical as in tutorial.
Both server and client thread manages connection same. I created separated threads for accepting messages following this tutorial and one for sending them.
private void manageConnectedSocket(BluetoothSocket socket) {
//create thread responsible for sending messages.
SendingThread w = new SendingThread(socket);
MainActivity.addSendingThread(w);
//Creates listener for messages to accept.
MainActivity.addListener(socket);
}
Now in main activity always when user click send button, for each worker (sending thread) send message to remote device. Listening is running asynchronously.
IMPORTANT:
You need to handle exceptions when message send fails and remove sending and recieving thread for device when you detect it is disconected. In my case I used well known UUID "00001101-0000-1000-8000-00805f9b34fb". For every device.
You need to wait 3 second between atempts to connect as client because some devices has weak bluetooth hardware and it is refusing connect as client.
Bt connection is supporting up to 7 -10 connections. So you will be limited in that range. I think it is designed for extensions of main device and not for random comunication
Source: search "bluetooth programming" on google
As a beginner in Android programming I have a question:
I want to receive data (two bytes) from a bluetooth/serial module connected to a microprocessor. This data should be printed to the screen and updated say once per second. I found this already: How to prevent Android bluetooth RFCOMM connection from dying immediately after .connect()?
Which should be a working code but nothing is happening.
I changed the mac address to 00:11:12:05:03:67, which should correspond with my bluetooth module.
Am I heading completely in the wrong direction with this? I guess what I want is quite basic: just a simple one way data transmission over bluetooth.
Any thoughts will be very much appreciated.
Best wishes,
Kevin
The question you've referred to there is very useful as it provides a workaround for a situation where the usual call to .createRfcommSocketToServiceRecord() fails to work. I have personally used that workaround solution in a project I'm doing right now. What I do is I attempt the .createRfcommSocketToServiceRecord() call first, and if that fails, my code then attempts to connect with the .getClass().getMethod("createRfcommSocket", new Class[]{int.class}); workaround. Having experimented with a number of Bluetooth-to-serial PCBs, some of them tend to be a bit 'awkward' and the latter reflection method works when the .createRfcommSocketToServiceRecord() does not.
However... although that question you referenced does provide a very useful compact piece of code, I don't think it's the best place for you to start. The place you should start is at Android's Bluetooth documentation, which explains the whole process extremely well, including how to use separate Threads to handle discovery, connection, etc. In fact it's really easy to get started using the Bluetooth Chat source code. Using that, you can get up and running and connected to a Bluetooth-serial module very quickly. You just need to make sure you change the UUID to that required for Serial Port Profile (SPP):
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
That will hopefully be enough to have a simple application that will talk to your Bluetooth serial module. The Bluetooth Chat example application also provides you with dialogs that handle device discovery, pairing, and all that good stuff, so you don't have to mess about hard-coding in your device's MAC address like you have been.
If you have problems connecting then you need to be specific about what's actually happening; i.e., what exceptions you're getting, and so forth.