Connecting to a bluetooth device with pairing in iOS in Flutter

832 views Asked by At

In my Flutter app, I have a service that is supposed to connect to a Bluetooth device with pairing. I use flutter_blue_plus for Bluetooth functionality. Everything works perfectly on Android, but on iOS, it's impossible to initiate pairing manually. Therefore, I try to read a characteristic, and I even get a pop-up for PIN input, but after that, the connection always breaks, even though the device appears in the paired list. Is it even possible to implement using only flutter and flutter blue?

  Future<BluetoothDevice?> _connectToIOS(BluetoothDevice device) async {
    try {
      await device.connect(
        // autoConnect: true,
        timeout: const Duration(
          seconds: 30,
        ),
      );
      device.connectionState.listen(
        (event) async {
          print("event $event");
          if (event == BluetoothConnectionState.connected) {
            await _discoverServices(device);
          }
        },
        onError: (error) {
          print("connect error $error");
        },
        onDone: () {
          print("done");
        },
      );

      return device;
    } catch (e) {
      print("connect to IOS error $e");
      return null;
    }
  }
 Future<void> _discoverServices(BluetoothDevice device) async {
    try {
      print("discover");
      final services = await device.discoverServices();
      print("Services $services");
      for (BluetoothService service in services) {
        if (service.uuid.toString() == SERVICE_UUID) {
          BluetoothCharacteristic? writeCharacteristic;
          BluetoothCharacteristic? readCharacteristic;

          for (BluetoothCharacteristic characteristic
              in service.characteristics) {
            if (characteristic.uuid.toString() == WRITE_CHAR_UUID) {
              writeCharacteristic = characteristic;
            }
            if (characteristic.uuid.toString() == READ_CHAR_UUID) {
              readCharacteristic = characteristic;
            }
          }

          if (readCharacteristic != null) {
            _readCharacteristic = readCharacteristic;
            await _readCharacteristic!.setNotifyValue(true);
            _valueStream = readCharacteristic.lastValueStream;
          }

          if (writeCharacteristic != null) {
            _writeCharacteristic = writeCharacteristic;
          }
        }
      }
      print("finish");
    } catch (e) {
      print("error $e");
    }
  }
0

There are 0 answers