【发布时间】:2016-06-14 04:23:12
【问题描述】:
我正在努力从/向自定义蓝牙低功耗设备读取/发送数据。我正在使用 Microchip RN4020 蓝牙模块。
我找到的每个教程或示例都解释了如何将您的移动应用程序连接到设备,但我没有找到如何与它进行实际交互。 因此,这正是我可以用我的应用程序做和不能做的事情。
对于每个存在的特征,我做了以下:
gatt.readCharacteristic(services.get(i).getCharacteristics().get(j));
这是我打印值时的结果:
getStringValue= Mobi_F934��
getStringValue= null
getStringValue= ����d���
getStringValue= 001EC030F934
getStringValue= 2.1
getStringValue= 1.10
getStringValue= 1.10
getStringValue= Microchip
getStringValue= RN4020
getStringValue=
getStringValue=
我不知道这是否重要......
如何读取从我的 BLE 设备发送的数据?
编辑:我的安卓代码
@TargetApi(21)
public class MainActivity extends ActionBarActivity {
private BluetoothAdapter mBluetoothAdapter;
private int REQUEST_ENABLE_BT = 1;
private Handler mHandler;
private static final long SCAN_PERIOD = 10000;
private BluetoothLeScanner mLEScanner;
private ScanSettings settings;
private List<ScanFilter> filters;
private BluetoothGatt mGatt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler = new Handler();
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, "BLE Not Supported",
Toast.LENGTH_SHORT).show();
finish();
}
// Initializes Bluetooth adapter
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
}
@Override
protected void onResume() {
super.onResume();
// Ensures Bluetooth is available on the device and it is enabled. If not,
// displays a dialog requesting user permission to enable Bluetooth.
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} else {
if (Build.VERSION.SDK_INT >= 21) {
mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build();
filters = new ArrayList<ScanFilter>();
}
scanLeDevice(true);
}
}
@Override
protected void onPause() {
super.onPause();
if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
scanLeDevice(false);
}
}
@Override
protected void onDestroy() {
if (mGatt == null) {
return;
}
mGatt.close();
mGatt = null;
super.onDestroy();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == Activity.RESULT_CANCELED) {
//Bluetooth not enabled.
finish();
return;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void scanLeDevice(final boolean enable) {
if (enable) {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (Build.VERSION.SDK_INT < 21) {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
} else {
mLEScanner.stopScan(mScanCallback);
}
}
}, SCAN_PERIOD);
if (Build.VERSION.SDK_INT < 21) {
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mLEScanner.startScan(filters, settings, mScanCallback);
}
} else {
if (Build.VERSION.SDK_INT < 21) {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
} else {
mLEScanner.stopScan(mScanCallback);
}
}
}
private ScanCallback mScanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
Log.e("callbackType", "MAX " + String.valueOf(callbackType));
Log.e("result", "MAX " + result.toString());
BluetoothDevice btDevice = result.getDevice();
connectToDevice(btDevice);
}
@Override
public void onBatchScanResults(List<ScanResult> results) {
for (ScanResult sr : results) {
Log.e("ScanResult - Results", "MAX " + sr.toString());
}
}
@Override
public void onScanFailed(int errorCode) {
Log.e("Scan Failed", "MAX " + "Error Code: " + errorCode);
}
};
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi,
byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.e("onLeScan", "MAX " + device.toString());
connectToDevice(device);
}
});
}
};
public void connectToDevice(BluetoothDevice device) {
if (mGatt == null) {
mGatt = device.connectGatt(this, false, gattCallback);
scanLeDevice(false);// will stop after first device detection
}
}
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
Log.e("onConnectionStateChange", "MAX " + "Status: " + status);
switch (newState) {
case BluetoothProfile.STATE_CONNECTED:
Log.e("gattCallback", "MAX " + "STATE_CONNECTED");
gatt.discoverServices();
break;
case BluetoothProfile.STATE_DISCONNECTED:
Log.e("gattCallback", "MAX " + "STATE_DISCONNECTED");
break;
default:
Log.e("gattCallback", "MAX " + "STATE_OTHER");
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
List<BluetoothGattService> services = gatt.getServices();
Log.e("onServicesDiscovered", "MAX " + services.toString());
/*
for(int i = 0; i < services.size(); i++){
for (int j = 0; j < services.get(i).getCharacteristics().size(); j++){
Log.e("MAX", "i= " + i + " j= " + j);
gatt.readCharacteristic(services.get(i).getCharacteristics().get
(j));
}
}
*/
gatt.readCharacteristic(services.get(0).getCharacteristics().get(0));
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic
characteristic, int status) {
Log.e("onCharacteristicRead", "MAX " + characteristic.toString());
Log.e("onCharacteristicRead", "MAX " +characteristic.getStringValue(0));
//gatt.disconnect();
}
};
}
编辑 2:我的 arduino 代码
#include <SoftwareSerial.h>
/* Set up BT to arduino uno
BT RN4020 Arduino Uno
------------------------------------------------
Red 3.3V
Green GND
Yellow(RX) TX (digital pin 1)
Orange(TX) RX (digital pin 0)
White PIN 8 (!) This is not GND (!)
Blue 3.3V (Ioref can also be used)
*/
/*
-----------------------------------------------------------------------------
-----EXPLANATION PROGRAM-----------------------------------------------------
----------------------------
Eerst wordt de BT module geïnitialiseerd door verschillende commando's door te
sturen. Bij elk commando wordt gecheckt of de BT module het juiste antwoord
heeft teruggestuurd.
De initialisatie moet gebeuren in CMD mode, de CMD/MLDP pin moet laag zijn. Na
de initialisatie checken we tot de BT module is geconnecteerd met het device.
Als de BT module geconnecteerd is zetten we deze uit CMD mode en in MLDP mode
om het verzenden en ontvangen van data te ondersteunen. Daarna zenden we om de
seconde de string 'test' door.
Dit gebeurt zolang het device geconnecteerd is met de BT module.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-----------------------------
*/
int CMD_MLD_pin = 8; // IO pin for CMD/MLDP pin (LOW --> CMD, HIGH --> MLDP)
void setup() // Initialising BT RN4020
{
pinMode(CMD_MLD_pin, OUTPUT);
digitalWrite(CMD_MLD_pin, LOW); // put CMD/MLDP pin LOW for CMD mode
delay(5000);
/* Initialize Bluetooth */
Serial.begin(115200); // Set up serial connection with required baud rate of
// 115200
delay(1500);
Serial.println("R,1"); //Reboot
while(!Serial.find("Reboot")){} // Waiting until BT RN4020 responds the
required string
while(!Serial.find("CMD")){}
//delay(2000);
Serial.println("SF,1"); // Factory reset
while(!Serial.find("AOK")){}
//delay(1500);
Serial.println("SR,32000000"); // Set device as peripheral
while(!Serial.find("AOK")){}
Serial.println("S-, Mobi"); // Change name of BT
while(!Serial.find("AOK")){}
//delay(1500);
Serial.println("R,1"); // Reboot to make changes effective
while(!Serial.find("Reboot")){}
while(!Serial.find("CMD")){}
//delay(2000);
}
void loop()
{
// Wait until the device responds it is connected
// If the device is connected we will send every second the string 'test'
while(!Serial.find("Connected")){} // Wait until BT RN4020 is connected to a
// device
digitalWrite(CMD_MLD_pin, HIGH); // Go to MLDP to support data stream
while(!Serial.find("MLDP")){} // Wait until BT RN4020 is effectively in MLDP
// mode
delay(500);
while (!Serial.find("Connection End")) // Send string to BTRN4020 while the
// BT RN4020 is conected to a device
{
Serial.println("test");
delay(1000);
}
}
【问题讨论】:
-
BLE 设备通过通知服务发送数据。或者你可以读取服务,数据大多是HEX格式,所以你必须转换它。所以更具体的答案的代码
标签: android bluetooth-lowenergy