So im working around with bluetooth and trying to figure out how to send two strings via a bluetooth connection. From one android device to another.
I found this guide http://developer.android.com/guide/topics/connectivity/bluetooth.html
but it talks alot about setting up the connection. So i went straight down to the chapter about Managing a Connection. The reason i do this is that in the apps i create i plan to setup the bluetooth connection before opening the apps (via the phones usual bluetooth setup) and then open the apps and send when it is necessary.
So my question is how do i find the bluetooth socket that should be setup? Since that should be what im searching for to create the sending and recieving threads?
Hope this is enough information, else tell what more you need and ill try and answer to the best of my ability.
Best Regards Drakthal
The usual bluetooth setup only pairs between devices, it doesn't create a data connection between them (And even if it would, you wouldn't be able to access this Socket object because it's not created in your process).
After Bluetooth is turned on, you can call BluetoothAdapter.getBondedDevices() to get a set of the paired devices. You can then iterate over them, and initiate a connection to the one you want. You can't avoid the connection creation :( If you want a simplified example, you can look here (An answer I posted a while ago, regarding the whole pairing/connecting/sending/receiving subject with bluetooth).
Once you acquired an open connection, sending the 2 string is easy.
String s1 = "A", s2 = "B";
byte[] buf1 = s1.getBytes(), buf2 = s2.getBytes();
OutputStream os = connection.getOutputStream();
os.write(buf1);
os.write(buf2);
os.flush();
connection.close();
Related
I am new to android studios and I have the task to develop an app which transfers data from an app (Acceleration sensor data - i have created this app already which shows the data) to matlab (on the pc).
I don't really know how I should do this. I've experimented a bit with bluetooth apps, but I don't have a clue how to connect to Matlab.
I would be greatful for your help.
Thanks in advance,
Annika
Unfortunately I can not speak to the android side of things, but MatLab can connect to generic devices with the UART interface, which is fairly low level.
The process with some microprocessors that I am using is to connect the device to the PC, and then note the Outgoing com port.
(In windows 10, these can be found in Bluetooth settings -> More Bluetooth options)
Then you can use
s = serial('COM<what you found in settings>');
s.Baudrate=115200;
s.InputBufferSize = 100;
fopen(s{i});
serials = instrfindall;
to open an connection. The critical command is serial, the other parameters depend on your device/ configuration. Sometimes there can be issues, in which case one options is to build a loop that tries again until it works.
You then collect the data sent via UART via
flushinput(serials);
temp = fscanf(serials,'%s');
and then split the string. If data is sent continuously, you wrap this into a while loop.
After you are done, you can clean up via
fclose(s{i});
delete(instrfind)
instrreset
It should be noted, that establishing a connection takes longer, the more enabled COM ports there are. So it might be worth disabling all those you don't need.
For more specific things matlab can do, check out What Is the MATLAB Serial Port Interface
I'm still new to Android studio and I'm having a lot of trouble with Bluetooth, I'm currently making an app where I need to send data between devices. I'm letting the phone's default Bluetooth setup do the pairing but now I need to know how to send the data, I know I need to use input and output streams but I don't know exactly how.
And yes I have searched all over Google, I've followed a lot of Bluetooth tutorials but none of them seem to really explain how to send data from one device to another.
Thanks in advance.
After you establish a secure/insecure connection via bluetooth the rest is just socket programming simply. That is lets think about sending a text. We convert the text to byte and send that by Java OutputStream. In the same manner for the data received we can get it by InputStream.
But remember you need to maintain bunch of code and thread/handler to maintain state and others. Though the basic thing is simply socket programming over Bluetooth socket using the Bluetooth adapter. Have a look at the below repository in github. This creates a chatroom over bluetooth. i.e it sends and receives string data
https://github.com/zahansafallwa/Android-bluetooth-chat-with-emoji/tree/master/app/src/main/java/com/zahan/safallwa/donttalk
Specially have a look at the BluetoothChatService class. That contains codes related to sending data. BluetoothChatService
Edit:
As per your comment lets think that your devices are paired and also connected. Now you only need to send the text. Declare a outputstream
private final OutputStream mmOutStream;
Suppose you have a string. We convert it to byte. Then get our socket outputstream and send data by write() method
String message="this is test data";
byte[] send = message.getBytes();
mmOutStream = socket.getOutputStream(); // here socket is the bluetooth socket you establish
mmOutStream.write(send);//this is what sends the message
Remember:
Edited code is for your understanding only. It is prescribed to use separate thread for sending data.
My understanding is that the SDP is a list of UUIDs that other devices can fetch.
According to this PDF from MIT, "A more general way to think of
SDP is as an information database." Does this mean I can add multiple values to SDP? Since Android has BluetoothDevice.fetchUuidsWithSdp(), how do I set the UUIDs of a device?
Also, what does each section of an UUID mean? UUIDs look like 00000000-0000-1000-8000-00805F9B34FB, but what information does this convey?
An UUID identifies a service that is available on a particular device. So if you call BluetoothDevice.fetchUUidsWithSdp() your BroadcastReceiver will receive the relevant Intent ACTION_UUID containing the device and the service UUID.
The bluetooth specification defines some common UUIDs.
If you don't want to connect to one of these well known services but intent to implement your own bluetooth application, then you have to just generate your own UUID (use uuidgen from a unix console or an online generator) that identifies your application/service.
You can create an UUID instance in java like this UUID uuid = UUID.fromString("785da8ea-1220-11e5-9493-1697f925ec7b");.
So if you create the server side for your bluetooth application on Android you typically do this
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
BluetoothServerSocket serverSocket = adapter.listenUsingRfcommWithServiceRecord("YourHumanReadableServiceName", uuid);
And this is where you "set" your UUID. The Android bluetooth API creates the SDP-entry consisting of YOUR application's UUID and name for you. Other devices can now retrieve this entry. Androids bluetooth stack will now associate a bluetooth channel to your BluetoothServerSocket. If you want to connect to this ServerSocket, the connecting side usually connects doing this:
// you will most likely already have this instance from a discovery or paired device list
BluetoothDevice serverDevice = adapter.getRemoteDevice(bluetoothMacAddress);
// connect to your ServerSocket using the uuid
BluetoothSocket socket = serverDevice.createRfcommSocketToServiceRecord(uuid);
socket.connect();
Android will again do the heavy lifting for you: It checks the SDP-Records on the remote device, looks up the bluetooth channel that corresponds to your service's UUID and connects using this information.
There is a common code snippet spooking around here on SO that advices you to use "reflection" to get to a hidden API looking similar to this code:
try {
// this is the way to go
socket = device.createRfcommSocketToServiceRecord(uuid);
socket.connect( );
} catch ( IOException exception ) {
// don't do that! You will bypass SDP and things will go sideways.
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
socket = (BluetoothSocket) m.invoke(device, 1);
socket.connect();
}
Most people try this and it "just works" in their dev environment but you should know what you do using this. You actively bypass the SDP lookup that retrieves the right bluetooth channel to be used with your service and you will end up connecting to channel 1. If you have more than one Service running on the device, things WILL go sideways in this cases and you will end up in debugging hell ;-)
I developed a small middleware called Blaubot to create small networks using bluetooth/wifi/nfc and experienced all sorts of problems on the devices I used to test with (12 models). It was often the case that the bluetooth stack was not fully functional anymore in cases where it got some load or after many connects/disconnects (which you usually will have, if you are developing your app). In these cases the device.createRfcommSocketToServiceRecord(uuid) would occasionally fail and only turning the bluetooth adapter off and on again helped to bring the bluetooth adapters back to life (in some cases only after a full power cycle). If this happens and you use the reflection method, you will probably not have much fun with bluetooth.
But if you know this and keep concurrent calls to the BluetoothAdapter within bounds, bluetooth connections and the adapters will be pretty stable.
I am trying to receive data (strings) from a Bluetooth enabled device whose MAC_ID is known.
I have searched many examples ,but each article is pointing to Bluetooth Chat example, I think in Bluetooth Chat example, application need to be installed on both the devices for them to be connected and exchange strings.Correct me if I am wrong.
But I need to install application only on Receiver device.I have tried installing the application only on one device and tried connecting to the sender device, without success.
Bluetooth is a peer to peer protocol where you need to have application running on both sides. Hence if you want to exchange data very good example would be Bluetooth chat. If you want to download or transfer a file you should either implement obex or FTP profile based applications.
Yes you need to deploy an application on both sides. If you are really restricted in a way that you only can deploy on one side, you have to figure out which standard protocols/bluetooth profiles the other side is capable of. You can figure that out by doing a SDP lookup. For a device, you will then get a list of UUIDs identifying these services. See the bluetooth spec for well known UUIDs. As #7383 pointed out, your are most probably looking for OBEX or FTP.
If you can deploy on both sides, you can write your own app using Blaubot (disclaimer: I wrote it). A simple Blaubot program would do this:
UUID MY_UUID = UUID.fromString("33bb1246-1472-11e5-b60b-1697f925ec7b");
// onCreate() or in a service, we create a blaubot instance
// using Bluetooth to form a network and Bluetooth + NFC to find devices
IBlaubotDevice ownDevice = new BlaubotDevice();
BlaubotUUIDSet uuidSet = new BlaubotUUIDSet(MY_UUID);
BlaubotBluetoothAdapter bluetoothAdapter = new BlaubotBluetoothAdapter(uuidSet, ownDevice);
BlaubotNFCBeacon nfcBeacon = new BlaubotNFCBeacon();
BlaubotBluetoothBeacon bluetoothBeacon = new BlaubotBluetoothBeacon();
this.mBlaubot = BlaubotAndroidFactory.createBlaubot(MY_UUID, ownDevice, adapter, nfcBeacon, bluetoothBeacon);
// start and wait until connected
this.mBlaubot.startBlaubot();
// create a channel and send your file
IBlaubotChannel fileChannel = this.mBlaubot.createChannel(1);
// convert your file to its bytes
File yourFile = // ... however you get it
byte[] fileBytes = ...// ... see http://stackoverflow.com/questions/858980/file-to-byte-in-java
// send it to all connected devices
fileChannel.publish(fileBytes, true);
// to receive it on the other device, do this:
// subscribe to the channel
fileChannel.subscribe(new IBlaubotMessageListener() {
#Override
public void onMessage(BlaubotMessage message) {
// extract your bytes from the message
byte[] fileBytes = message.getPayload();
// .. do something useful or write it to a file again
// to write it to a file
File file = new File(yourFilePath);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
bos.write(fileBytes);
bos.flush();
bos.close();
}
});
This should be all you need. To allow the devices to connect, you have to pair them before or use NFC (just hold them together, when Blaubot is started). If you go with Blaubot let me know if you have problems that can't be solved with the documentation or the android quickstart guide.
I can only guess what your actual scenario looks like. If you have two android phones, this should work. If that is not the case, you should add more informations about the involved devices. Are we really talking about (classic) Bluetooth connections or are you trying to get data from a Bluetooth Low Energy device?
In this case the famous chat example will not help you either.
im trying to control a bluetooth bracelet with vibration function via HFP (hands free profile) in Android. I've been able to connect to the bracelet and access the input- and outputstream.
My goal is to simulate an incoming call so that the bluetooth bracelet starts vibrating (which seems to be the only way to do that). To do this, im using AT commands. In the bluetooth specs at https://www.bluetooth.org/docman/handlers/downloaddoc.ashx?doc_id=238193 on page 22 you can see the handshake to establish service level connection.
I need to establish this connection to use the "+CIEV" command (see handshake page 48).
But when my bracelet returns the command "AT+CIND=?" I dont know how to respond. I can't find any hints on how to answer with the "CIND:" command. Also I dont know how to send the acknowledgement (is it just "OK"?).
That might even be the completely wrong way to do this. Every suggestion is appreciated. I only found one post on stackoverflow that helped me in some way, rest of the posts I found were unanswered.
By the way, im using a smartphone with Android 4.1.2. The bracelet supports HFP and HSP. Thanks in advance.
UPDATE 10/29/2014
===== Connection through RFCOMM Socket established at this point =====
// read AT+BRSF=0 from device
byte[] buffer = new byte[200];
mBluetoothSocket.getInputStream().read(buffer);
Log.d(TAG, new String(buffer).trim());
//write answer BRSF: ...
mBluetoothSocket.getOutputStream().write("+BRSF=20\r".getBytes());
mBluetoothSocket.getOutputStream().write("OK\r".getBytes());
// read AT+CIND=? command
buffer = new byte[200];
mBluetoothSocket.getInputStream().read(buffer);
Log.d(TAG, new String(buffer).trim());
//write answer CIND: ...
mBluetoothSocket.getOutputStream().write("+CIND: (\"battchg\",(0-5)),(\"signal\",(0-5)),
(\"service\",(0,1)),(\"call\",(0,1)),(\"callsetup\",(0-3)),
(\"callheld\",(0-2)),(\"roam\",(0,1))".getBytes());
mBluetoothSocket.getOutputStream().write("OK".getBytes());
// read AT+CIND?
buffer = new byte[200];
mBluetoothSocket.getInputStream().read(buffer);
Log.d(TAG, new String(buffer).trim());
Following the procedure of the protocol, I should receive the "AT+CIND?" command and then I could send the command "+CIND: 5,5,1,0,0,0,0", but...I dont receive the "AT+CIND?" command. Actually im not receiving anything. Am I missing something? Sending an "OK" doesnt change anything btw...
I was fiddeling with exaclty the same problem. After days of trial and error, I finally got it to work.
I think it depends on the speed at wich you answer the HF's commands, as well as on the correct line-endings ("COMMAND").
Here is my DroidScript which works. It's not cleaned up, but it works.
https://gist.github.com/t-oster/68a568ac4c4e133f67ac
Also, the one example I found that seemed to almost work, it's expecting the responses to be top and tailed with crlf:
"\r\n+BRSF=20\r\n"
"\r\nOK\r\n"
Still struggling with the rest of it myself.
refer to bluetooth hfp 1.5 spec in which you can understand CIEV response
normally when not in any call setup, response can be +CIND = 1,0,0,0,5,0,5
Note these values are based on the hfp spec, on incoming call return +CIEV: ,
ind- indicator for callsetup and value as 1 and then RING commands to the bracelet