connect static method
Implementation
static Future<bool> connect({required String macAddress}) async {
if (_macAddressConnect.isNotEmpty) return true; // Ya está conectado.
Completer<bool> connectionCompleter = Completer<bool>();
if (_connectionStream != null) _connectionStream!.cancel();
_connectionStream = WinBle.connectionStreamOf(macAddress).listen((bool status) async {
if (status) {
//_macAddressConnect = macAddress;
connectionCompleter.complete(true);
print("connect status: $status");
} else {
//print("Finalizó el stream $event");
if (!connectionCompleter.isCompleted) connectionCompleter.complete(true); // Completar con error la Future en caso de desconexión.
}
});
// Realizar la conexión
await WinBle.connect(macAddress);
// Esperar que la conexion finalice
await connectionCompleter.future;
//cancelar el stream
if (_connectionStream != null) _connectionStream?.cancel();
//print("complete ${DateTime.now().toString()}");
//buscar el servicio y caracteristica para imprimir
List<String> services = await WinBle.discoverServices(macAddress);
//print("Services: ${services.length}");
for (String service in services) {
//print("service: $service");
List<BleCharacteristic> bleCharacteristics = await WinBle.discoverCharacteristics(address: macAddress, serviceId: service);
//print("bleCharacteristics: ${bleCharacteristics.length}");
for (BleCharacteristic characteristic in bleCharacteristics) {
//print("service: $service -> bleCharacteristic: ${characteristic.properties.toJson()}");
if (characteristic.properties.write ?? false) {
_serviceSelect = service;
_bleCharacteristicSelect = characteristic;
_macAddressConnect = macAddress;
print("macAddress: $macAddress service: $service");
break;
}
}
}
//return if not empty si success connection
return _macAddressConnect.isNotEmpty;
}