How to send serial data via Bluetooth to an unspec

2019-09-10 11:23发布

问题:

I use the following code for an Arduino Uno:

#include <SoftwareSerial.h>

SoftwareSerial device(2, 3); 

void setup()  
{
  device.begin(9600);
}

void loop() 
{
  device.println("33,89,156,203,978,0,0;");
}

No specific device to send to is set.

If I want to receive the data on my laptop (running Ubuntu 14.04) I simply call:

sudo rfcomm bind rfcomm0 [MAC ADDRESS] 1

and

screen /dev/rfcomm0 

in another terminal instance and it works.

How can I achieve the same behaviour with an Android app? The following example code specifies a device. I cannot find any other code. Additionally it only works when I listen on the laptop for an incoming connection like this:

sudo rfcomm listen rfcomm0 [MAC ADDRESS]

I want my Android app to work exactly like the Arduino example. How can I achieve that?

回答1:

Unfortunately Android doesn't appear to have low level Classic Bluetooth APIs which would allow you to do broadcast type behavior. This makes some sense as Android is intended to go into a power limited devices and active radios use energy. If you are required to use Classic Bluetooth (3.x) and Android to handle sending or receiving broadcast type behavior you'll probably need to write a custom ROM.

However there is specification called Bluetooth Low Energy (4.x) allows for less energy consumption but slower/less data throughput. Specifically the Advertising mode. Android devices which are scanning can pick up the short advertised data packet broadcasted by a device called a 'beacon'. Protocols which use this mode are Apple's iBeacon and Google's Eddystone.

Look here for sample apps involving Advertisements:

  • https://github.com/googlesamples/android-BluetoothAdvertisements
  • https://github.com/devunwired/accessory-samples/blob/master/bluetoothadvertiser

Also note that Android devices don't always support BLE Peripheral Mode which is what you will need for your Android device to act like beacon.

Related link: Can an Android device act as an iBeacon?

And a nice list of what devices have been tested: http://altbeacon.github.io/android-beacon-library/beacon-transmitter-devices.html

So in your case you should still be able to use your Sony Xperia Z3 as a Scanner, but will have to buy/build a beacon for testing.