Luk*_*eyb 6 android bluetooth xamarin
我有一个Android应用程序,它可以连接到BLE设备(使用BMD-350),通过通知接收数据并在特征上传输数据.我不知道为什么,但过了一段时间BLE设备自行断开连接,在BondStateChanged回调中报告错误代码8.我可以看到数据直接进入手机,直到它断开连接.BLE设备以大约550字节/秒的速度向手机发送数据.此时手机不会向BLE设备发送任何数据.为什么要断开连接?
*注意:此代码是用C#(Xamarin)编写的,但它与Java对应的代码基本相同.
连接代码:
_bleGatt = device.ConnectGatt(context, false, this);
Run Code Online (Sandbox Code Playgroud)
连接回调:
if (newState == ProfileState.Connected)
{
if (status == GattStatus.Success)
{
gatt.DiscoverServices();
}
}
Run Code Online (Sandbox Code Playgroud)
服务发现:
public override void OnServicesDiscovered(BluetoothGatt gatt, GattStatus status)
{
base.OnServicesDiscovered(gatt, status);
BluetoothGattService mService;
try
{
mService = gatt.GetService(UART_UUID);
}
catch
{
BluetoothConnectionError("UART service not found", gatt.Device);
return;
}
_tx = mService.GetCharacteristic(TX_UUID);
_rx = mService.GetCharacteristic(RX_UUID);
if (_tx == null)
{
BluetoothConnectionError("Tx characteristic not found", gatt.Device);
return;
}
if ((_tx.Properties | GattProperty.WriteNoResponse) == 0 && (_tx.Properties | GattProperty.Write) == 0)
{
BluetoothConnectionError("Tx characteristic not not in 'write' or 'write - no response' mode", gatt.Device);
return;
}
if (_rx == null)
{
BluetoothConnectionError("Rx characteristic not found", gatt.Device);
return;
}
if ((_rx.Properties | GattProperty.Notify) == 0)
{
BluetoothConnectionError("Rx characteristic not in 'notify' mode", gatt.Device);
return;
}
BluetoothGattDescriptor mDescriptor = _rx.GetDescriptor(CLIENT_UUID);
if (mDescriptor == null)
{
BluetoothConnectionError("Could not get descriptor", gatt.Device);
return;
}
mDescriptor.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray());
try
{
gatt.WriteDescriptor(mDescriptor);
}
catch
{
BluetoothConnectionError("Could not write descriptor", gatt.Device);
return;
}
ConnectionStatusChanged(ProfileState.Connected, gatt.Device);
}
Run Code Online (Sandbox Code Playgroud)
启用接收通知:
_bleGatt.SetCharacteristicNotification(_rx, true);
Run Code Online (Sandbox Code Playgroud)
阅读特点:
public override void OnCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic)
{
base.OnCharacteristicChanged(gatt, characteristic);
PublishNewData(characteristic.GetValue());
}
Run Code Online (Sandbox Code Playgroud)
UUID的/ CCCD:
private readonly UUID UART_UUID = UUID.FromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e");
private readonly UUID RX_UUID = UUID.FromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e");
private readonly UUID TX_UUID = UUID.FromString("6e400002-b5a3-f393-e0a9-e50e24dcca9e");
private readonly UUID CLIENT_UUID = UUID.FromString("00002902-0000-1000-8000-00805f9b34fb");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
382 次 |
| 最近记录: |