connect method

  1. @override
Future<void> connect(
  1. String deviceId, {
  2. bool autoConnect = false,
  3. Duration? timeout,
})
override

实现 FlutterBluetoothPluginPlatform.connect

Web 只能连接已通过选择器授权给当前站点的 BLE GATT 设备。

Implementation

@override
Future<void> connect(
  String deviceId, {
  bool autoConnect = false,
  Duration? timeout,
}) async {
  final device = await _requireDevice(deviceId);
  final gatt = _requireGatt(device);
  if (gatt.connected) {
    _gattServers[deviceId] = gatt;
    _sendConnectionState(deviceId, BluetoothConnectionState.connected);
    return;
  }

  _sendConnectionState(deviceId, BluetoothConnectionState.connecting);
  try {
    final connectFuture = gatt.connect().toDart;
    final server = timeout == null
        ? await connectFuture
        : await connectFuture.timeout(timeout, onTimeout: () {
            gatt.disconnect();
            throw TimeoutException('Web Bluetooth connection timed out.');
          });
    _gattServers[deviceId] = server;
    _sendConnectionState(deviceId, BluetoothConnectionState.connected);
  } catch (_) {
    _sendConnectionState(deviceId, BluetoothConnectionState.disconnected);
    rethrow;
  }
}