flutter_blue
flutter_blue copied to clipboard
Connecting to multiple ble devices
I'm using flutter to work on an bluetooth low energy app, via your library, in which we are potentially connecting to multiple peripherals at the same time. I am able to connect to multiple peripherals if I connect to them individually and send commands to all of them simultaneously. For state management, my BluetoothHelper is the Model for my ScopedModel.
`class BluetoothHelper extends Model {
bool isProcessing = false;
int val = 0;
FlutterBlue flutterBlue = FlutterBlue.instance; //bluetooth library instance
StreamSubscription scanSubscription;
Map<DeviceIdentifier, ScanResult> scanResults = new Map();
/// State
StreamSubscription stateSubscription;
BluetoothState state = BluetoothState.unknown;
/// Device
List<BluetoothDevice> devicesList = new List(); //todo
bool get isConnected => (deviceList.size != 0);
StreamSubscription deviceConnection;
StreamSubscription deviceStateSubscription;
List<BluetoothService> services = new List();
Map<Guid, StreamSubscription> valueChangedSubscriptions = {};
BluetoothDeviceState deviceState = BluetoothDeviceState.disconnected;
Future startScan(String uuid) async {
isProcessing = true;
if (val == 0) {
Future.delayed(Duration(milliseconds: 25), () => scanAndConnect(uuid));
val++;
} else {
Future.delayed(Duration(seconds: 4), () => scanAndConnect(uuid));
}
}
scanAndConnect(String uuid){
scanSubscription =
flutterBlue.scan(timeout: const Duration(seconds: 120), withServices: [
//new Guid('FB755D40-8DE5-481E-A369-21C0B3F39664')]
]).listen((scanResult) {
if (scanResult.device.id.toString() == uuid) {
scanResults[scanResult.device.id] = scanResult;
print("found! Attempting to connect" + scanResult.device.id.toString());
device = scanResult.device;
//connect(device);
connect(device);
}
}, onDone: stopScan);
}
Future connect(BluetoothDevice d) {
deviceConnection = flutterBlue.connect(d).listen(
null,
);
deviceStateSubscription = d.onStateChanged().listen((s) {
if (s == BluetoothDeviceState.connected) {
stopScan();
d.discoverServices().then((s) {
print("connected to ${device.id.toString()}");
services = s;
services.forEach((service) {
var characteristics = service.characteristics;
for (BluetoothCharacteristic c in characteristics) {
if (c.uuid.toString() == '') {//we look for the uuid we want to write to
String handshakeValue ; //value is initiliazed here in code
List<int> bytes = utf8.encode(handshakeValue);
d.writeCharacteristic(c, bytes,
type: CharacteristicWriteType.withResponse);
devicesList.add(d);
}
}
});
});
}
});
}
}`
I am trying to loop throw all peripheral Unique Identifier (UID) and then have them connect one after the other programmatically. This wasnt working out great. It would always end up connecting to the very last peripheral. Seems like the flutterblue instance can only scan for one uid at a time, and if it receives another request, it immediately drops the last request and moves to the new one. I applied this same logic to the connection of an individual peripheral logic where I'd tap one peripheral and the second immediately and it'd connect to the second one. (I'm not currently blocking the UI or anything while the connection process takes place) I need to wait till the first peripheral is connected before moving onto the next one. The code above is the only way I've gotten my peripherals but there are huge problems with this code. It can currently only connect to 2 devices. It's using delays instead of callbacks to achieve connection by giving enough time for the scan and connect to happen before moving onto the second peripheral. My first instinct was to make the convert the startScan and connect methods into async methods but this isnt working out well as I'd hope. {await connect(device); } => gives "The built in Identifier "await" cant be used as a type. I could just be setting up the asyncs incorrectly. I realize this might just be a synchronization error rather than any issues with your library at all. But any help would be appreciated!
UI SIDE :
I have the following method set for the ontap of a button wrapped within a scoped model descendant. This is going to reliably load peripheralUIDs list with a few uids and then connect to them one after the other.
connectAllPeripherals(BluetoothHelper model, List<String> peripheralUIDs) { for(var uuid in peripheralUIDs) { //list of strings containing the uuids for the peripherals I want to connect to model.startScan(uuid); } }
@Arham360 Did you ever resolve this? I'm working on the same issue.
@Arham360 You need these:
StreamSubscription deviceConnection;
StreamSubscription deviceStateSubscription;
List<BluetoothService> services = new List();
Map<Guid, StreamSubscription> valueChangedSubscriptions = {};
BluetoothDeviceState deviceState = BluetoothDeviceState.disconnected;
For every single device. Don't forget to get rid of them in the Dispose override. This issue could probably be closed...
Hi @akatriel , Is it possible to listen for notifications from multiple BLE devices simultaneously using flutter_blue?
嗨,@akatriel,是否可以使用flutter_blue同时收听来自多个BLE设备的通知?
I want to ask a question. Due to the company's business, there are 5 bluetooth devices. I need to connect 5 devices at the same time, and get the data and update data of the device at the same time. I checked the information on the Internet and found that Android needs to send data serially.
https://stackoverflow.com/questions/28016571/robustly-communicating-with-multiple-ble-devices-simultaneously-on-android
Is there a way to write and update the characteristics of multiple devices at the same time?
@Arham360你曾经解决这个问题吗?我正在处理同样的问题。
I want to ask a question. Due to the company's business, there are 5 bluetooth devices. I need to connect 5 devices at the same time, and get the data and update data of the device at the same time. I checked the information on the Internet and found that Android needs to send data serially.
https://stackoverflow.com/questions/28016571/robustly-communicating-with-multiple-ble-devices-simultaneously-on-android
Is there a way to write and update the characteristics of multiple devices at the same time?
我正在使用颤抖通过您的库开发蓝牙低功耗应用程序,其中我们可能会同时连接到多个外围设备。如果我单独连接到多个外围设备,并同时向所有外围设备发送命令,我就可以连接到它们。对于状态管理,我的蓝牙Helper是我的ScopeedModel的模型。
`class BluetoothHelper扩展了模型{
bool isProcessing = false; int val = 0; FlutterBlue flutterBlue = FlutterBlue.instance; //bluetooth library instance StreamSubscription scanSubscription; Map<DeviceIdentifier, ScanResult> scanResults = new Map(); /// State StreamSubscription stateSubscription; BluetoothState state = BluetoothState.unknown; /// Device List<BluetoothDevice> devicesList = new List(); //todo bool get isConnected => (deviceList.size != 0); StreamSubscription deviceConnection; StreamSubscription deviceStateSubscription; List<BluetoothService> services = new List(); Map<Guid, StreamSubscription> valueChangedSubscriptions = {}; BluetoothDeviceState deviceState = BluetoothDeviceState.disconnected; Future startScan(String uuid) async { isProcessing = true; if (val == 0) { Future.delayed(Duration(milliseconds: 25), () => scanAndConnect(uuid)); val++; } else { Future.delayed(Duration(seconds: 4), () => scanAndConnect(uuid)); } } scanAndConnect(String uuid){ scanSubscription = flutterBlue.scan(timeout: const Duration(seconds: 120), withServices: [ //new Guid('FB755D40-8DE5-481E-A369-21C0B3F39664')] ]).listen((scanResult) { if (scanResult.device.id.toString() == uuid) { scanResults[scanResult.device.id] = scanResult; print("found! Attempting to connect" + scanResult.device.id.toString()); device = scanResult.device; //connect(device); connect(device); } }, onDone: stopScan); } Future connect(BluetoothDevice d) { deviceConnection = flutterBlue.connect(d).listen( null, ); deviceStateSubscription = d.onStateChanged().listen((s) { if (s == BluetoothDeviceState.connected) { stopScan(); d.discoverServices().then((s) { print("connected to ${device.id.toString()}"); services = s; services.forEach((service) { var characteristics = service.characteristics; for (BluetoothCharacteristic c in characteristics) { if (c.uuid.toString() == '') {//we look for the uuid we want to write to String handshakeValue ; //value is initiliazed here in code List<int> bytes = utf8.encode(handshakeValue); d.writeCharacteristic(c, bytes, type: CharacteristicWriteType.withResponse); devicesList.add(d); } } }); }); } }); } }`
我正在尝试循环抛出所有外围唯一标识符(UID),然后让他们以编程方式一个接一个地连接。这效果不太好。它最终总是会连接到最后一个外围设备。似乎flutterblue实例一次只能扫描一个uid,如果它收到另一个请求,它会立即删除最后一个请求并移动到新的请求。我将同样的逻辑应用于单个外围逻辑的连接,在那里我会立即点击一个外围设备,然后立即点击第二个外围设备,然后连接到第二个外围设备。(在连接过程中,我目前没有阻止用户界面或任何东西)我需要等到第一个外围设备连接后再转到下一个外围设备。上面的代码是我获得外围设备的唯一方法,但这个代码存在巨大问题。它目前只能连接到2台设备。它使用延迟而不是回调来实现连接,在进入第二个外围设备之前为扫描和连接提供足够的时间。我的第一个本能是将startScan和连接方法转换为异步方法,但这并不像我希望的那样顺利。{await connect(device); } =>给出“内置标识符“await”不能用作类型。我可能只是设置了错误的异步。我知道这可能只是一个同步错误,而不是您的库的任何问题。但任何帮助都将不胜感激!
用户界面端:
我为在作用域模型后代中缠绕的按钮的点击设置了以下方法。这将可靠地加载带有几个uid的外围UID列表,然后一个接一个地连接到它们。
connectAllPeripherals(BluetoothHelper model, List<String> peripheralUIDs) { for(var uuid in peripheralUIDs) { //list of strings containing the uuids for the peripherals I want to connect to model.startScan(uuid); } }
I want to ask a question. Due to the company's business, there are 5 bluetooth devices. I need to connect 5 devices at the same time, and get the data and update data of the device at the same time. I checked the information on the Internet and found that Android needs to send data serially.
https://stackoverflow.com/questions/28016571/robustly-communicating-with-multiple-ble-devices-simultaneously-on-android
Is there a way to write and update the characteristics of multiple devices at the same time?
@Arham360你曾经解决这个问题吗?我正在处理同样的问题。
I want to ask a question. Due to the company's business, there are 5 bluetooth devices. I need to connect 5 devices at the same time, and get the data and update data of the device at the same time. I checked the information on the Internet and found that Android needs to send data serially.
https://stackoverflow.com/questions/28016571/robustly-communicating-with-multiple-ble-devices-simultaneously-on-android
Is there a way to write and update the characteristics of multiple devices at the same time?
stop sending repeated questions. very disturbing, man. @paintingStyle
Hi @akatriel , Is it possible to listen for notifications from multiple BLE devices simultaneously using flutter_blue?
anyone has the answer to this?
嗨@akatriel,是否可以使用flutter_blue同时监听来自多个BLE设备的通知?
有人知道这个问题的答案吗? This is achievable, because most of my bluetooth devices are actively sending data to mobile phones, rarely need to actively send data to bluetooth devices, I just need to listen to him, use different subscription objects