我不确定,但是 HM -10 不支持 rfcom。这意味着您必须使用 GATT 功能进行通信。 BLE 的实体是尽可能使用最小数据包,因此 BLE 不会一直保持连接并使用状态 [attributes] 之类的东西。
因此,例如,几行代码,如何使用 BLE:
1.
BluetoothAdapter mBluetoothAdapter = mBluetoothManager.getAdapter();
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(DEVICE_ADDR);
这是设备初始化,和简单的蓝牙一样,其中 DEVICE_ADDR 是你的 BLE 的 MAC(如何找到这个地址你可以在 google 或堆栈溢出中找到,很简单)
2.
BluetoothGattService mBluetoothGattService;
BluetoothGatt mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
mBluetoothGatt.discoverServices();
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
List<BluetoothGattService> gattServices = mBluetoothGatt.getServices();
for(BluetoothGattService gattService : gattServices) {
if("0000ffe0-0000-1000-8000-00805f9b34fb".equals(gattService.getUuid().toString()))
{
mBluetoothGattService = gattService;
}
}
} else {
Log.d(TAG, "onServicesDiscovered received: " + status);
}
}
};
那么,这段代码是什么意思:如果你可以从这部分代码中看到,我描述了 GATT 服务是如何找到的。 “属性”通信需要此服务。 gattService.getUuid() 很少有用于通信的 uuid(我的模块中有 4 个),其中一些用于 RX,一些用于 TX 等。“0000ffe0-0000-1000-8000-00805f9b34fb”是用于通信的 uuid 之一为什么我检查它。
代码的最后部分是消息发送:
BluetoothGattCharacteristic gattCharacteristic = mBluetoothGattService.getCharacteristic(UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb"));
String msg = "HELLO BLE =)";
byte b = 0x00;
byte[] temp = msg.getBytes();
byte[] tx = new byte[temp.length + 1];
tx[0] = b;
for(int i = 0; i < temp.length; i++)
tx[i+1] = temp[i];
gattCharacteristic.setValue(tx);
mBluetoothGatt.writeCharacteristic(gattCharacteristic);
发送消息后包含等待,您可以发送另一条消息或关闭连接。
更多信息,您可以在https://developer.android.com/guide/topics/connectivity/bluetooth-le.html 上找到。
PS:您的模块的MAC地址可以通过ble扫描码或AT cmd找到:
在我的固件 AT+ADDR 或 AT+LADDR
关于 UUID 的使用:不确定,但在我的情况下,我发现它带有下一个 AT+UUID [Get/Set system SERVER_UUID] -> Response +UUID=0xFFE0, AT+CHAR [Get/Set system CHAR_UUID] - Response +CHAR= 0xFFE1。这就是为什么我得出结论,我必须使用 fe "0000[ffe0/is 0xFFE0 from AT response]-0000-1000-8000-00805f9b34fb"