connect method

  1. @override
Stream<BleConnectionState> connect({
  1. required String deviceAddress,
})
override

Initiates a connection to a BLE peripheral and returns a Stream representing the connection state.

The deviceAddress parameter specifies the MAC address of the target device.

This method calls the 'connect' method on the native Android implementation via a method channel, and returns a Stream that emits ConnectionState enum values representing the status of the connection. Because an app could attempt to establish a connection to multiple different peripherals at once, the platform side differentiates connection status updates for each peripheral by appending the peripherals' Bluetooth addresses to the method channel names. For example, the connection states for a particular module with address, 10:91:A8:32:8C:BA would be communicated with the method channel name, "bleConnectionState_10:91:A8:32:8C:BA". In this way, a different Stream of BleConnectionState values is established for each Bluetooth peripheral.

Implementation

@override
Stream<BleConnectionState> connect({required String deviceAddress}) {
  /// A [StreamController] emitting values from the [ConnectionState] enum, which represent the connection state
  /// between the host mobile device and a Bluetooth peripheral.
  final StreamController<BleConnectionState> connectionStateStreamController =
      StreamController<BleConnectionState>.broadcast();

  // Listen to the platform side for connection state updates. The platform side differentiates connection state
  // updates for different Bluetooth peripherals by appending the device address to the method name.
  channel
    ..setMethodCallHandler((MethodCall call) async {
      if (call.method == 'bleConnectionState_$deviceAddress') {
        final String connectionStateString = call.arguments as String;
        final BleConnectionState state = BleConnectionState.values.firstWhere(
          (value) => value.identifier == connectionStateString.toLowerCase(),
        );
        connectionStateStreamController.add(state);
      } else if (call.method == 'error') {
        connectionStateStreamController.addError(BluetoothConnectionException(call.arguments as String));
      }
    })
    ..invokeMethod('connect', {'address': deviceAddress});
  return connectionStateStreamController.stream;
}