我现在已经使用了Flutter Blue,但我坚持以下几点: 我使用的是我在https://github.com/pauldemarco/flutter_blue上下载的示例应用程序,通过这里的基本思想是,一旦我连接到蓝牙设备,它就会开始检查服务“ FFE0”是否存在以及特征“ FFE1”是否存在。 这个特性吐出了我的项目所需的随机字符串。
Image of screen with characteristic open
通过屏幕,我可以看到上面的内容是正确的,我只需要以某种方式在特征连接到蓝牙设备后就自动为其设置通知。
这是我正在_Connect函数中测试的一些当前代码。
_connect(BluetoothDevice d) async {
device = d;
// Connect to device
deviceConnection = _flutterBlue
.connect(device, timeout: const Duration(seconds: 4))
.listen(
null,
onDone: _disconnect,
);
// Update the connection state immediately
device.state.then((s) {
setState(() {
deviceState = s;
});
});
// Subscribe to connection changes
deviceStateSubscription = device.onStateChanged().listen((s) {
setState(() {
deviceState = s;
});
if (s == BluetoothDeviceState.connected) {
device.discoverServices().then((service) {
service.forEach((_service){
var characteristics = _service.characteristics;
_service.characteristics.map((c) {
print(c);
});
for(BluetoothCharacteristic _characteristic in characteristics) {
device.readCharacteristic(_characteristic).then((_value){
print(_value);
if (_value.contains("FFE0")) {
print("Found!!");
// do something
}
});
}
});
setState(() {
services = service;
});
_getServices();
});
}
});
}
我也许有人对如何解决我的问题提出了建议。
罗宾
答案 0 :(得分:0)
我找到了https://github.com/Sensirion/smart-gadget-flutter/tree/master/lib,并且可以使用以下代码解决问题:
for(BluetoothService service in services) {
for(BluetoothCharacteristic c in service.characteristics) {
if(c.uuid == new Guid("0000ffe1-0000-1000-8000-00805f9b34fb")) {
_setNotification(c);
} else {
print("Nope");
}
}
}
这已添加到_connect函数中。
_connect(BluetoothDevice d) async {
device = d;
// Connect to device
deviceConnection = _flutterBlue
.connect(device, timeout: const Duration(seconds: 4))
.listen(
null,
onDone: _disconnect,
);
// Update the connection state immediately
device.state.then((s) {
setState(() {
deviceState = s;
});
});
// Subscribe to connection changes
deviceStateSubscription = device.onStateChanged().listen((s) {
setState(() {
deviceState = s;
});
if (s == BluetoothDeviceState.connected) {
device.discoverServices().then((s) {
services = s;
for(BluetoothService service in services) {
for(BluetoothCharacteristic c in service.characteristics) {
if(c.uuid == new Guid("0000ffe1-0000-1000-8000-00805f9b34fb")) {
_setNotification(c);
} else {
print("Nope");
}
}
}
setState(() {
services = s;
});
_getServices();
});
}
});
}
答案 1 :(得分:-1)
如果我设置多个通知并聆听更改,我会遇到麻烦