scan static method
搜索|连接
Implementation
static Stream<List<ClingDevice>> scan(
ClingDeviceType type, {
int seconds = 15,
String? connectDevice,
}) {
cfg.type = type;
final controller = StreamController<List<ClingDevice>>();
if (!_sdkInitSuccess) {
() async {
controller
.addError(ClingBleError(code: -1, message: 'sdk has not init'));
controller.close();
}();
return controller.stream;
}
if (connectDevice != null) {
slog('scan and connect device: $connectDevice');
}
if (state != ClingBleState.disconnect) {
() async {
controller.addError(ClingBleError(
code: -3, message: 'can not search, current state: $state'));
controller.close();
}();
} else {
final name = _deviceFromType(type);
_devices.clear();
controller.add(_devices);
if (name.isNotEmpty) {
_changeState(ClingBleState.searching);
StreamSubscription<BleDevice>? sub;
void stopScan() {
_changeState(ClingBleState.connecting);
// QuickBlue.stopScan();
WinBle.stopScanning();
sub?.cancel();
controller.close();
}
sub = WinBle.scanStream.where((e) => e.name.startsWith(name)).listen(
(event) {
final d = ClingDevice(
name: event.name, rssi: event.rssi, id: event.address);
if (!_devices.contains(d)) {
_devices.add(d);
if (!controller.isClosed) {
controller.add(_devices);
}
}
if (state == ClingBleState.disconnect) {
stopScan();
}
if (connectDevice != null) {
if (event.name.contains(connectDevice)) {
stopScan();
connect(d);
}
}
slog(
'name: ${event.name}, rssi: ${event.rssi}, id: ${event.address}');
}, onError: (v) {
controller.addError(ClingBleError(code: -2, message: 'search error'));
sub?.cancel();
_changeState(ClingBleState.disconnect);
});
// Future.delayed(Duration(seconds: seconds)).then((value) {
// stopScan();
// });
slog('start scanning...');
WinBle.startScanning();
} else {
controller.addError(
ClingBleError(code: -1, message: 'device type unavailable'));
}
}
return controller.stream;
}