Search code examples
androidflutterdartbluetooth

How do I receive Strings sent over Bluetooth in Flutter using Flutter Reactive Ble Plugin?


Ok, so I already found out these Uuids of the Bluetooth Device I want to receive Strings from:

 bleNusServiceUUID  = '6e400001-b5a3-f393-e0a9-e50e24dcca9e';
 bleNusCharRXUUID   = '6e400002-b5a3-f393-e0a9-e50e24dcca9e';
 bleNusCharTXUUID   = '6e400003-b5a3-f393-e0a9-e50e24dcca9e';

I've already written the boilerplate Code to connect to the Device etc. and that works fine but as soon as I add following code, which should (theoretically) just read the characteristic, nothing works anymore and my device gets disconnected.

(this Function gets called as soon as the (right) device is connected):

Future<void> foo(String id) async {

  FlutterReactiveBle flutterReactiveBle = FlutterReactiveBle();

  flutterReactiveBle.connectToDevice(
    id: id,
    servicesWithCharacteristicsToDiscover: {Uuid.parse('6e400001-b5a3-f393-e0a9-e50e24dcca9e'): [Uuid.parse('6e400002-b5a3-f393-e0a9-e50e24dcca9e'), Uuid.parse('6e400003-b5a3-f393-e0a9-e50e24dcca9e')]},
    connectionTimeout: const Duration(seconds: 2),
  ).listen((connectionState) async {

    final characteristic = QualifiedCharacteristic(
        serviceId: Uuid.parse('6e400001-b5a3-f393-e0a9-e50e24dcca9e'),
        characteristicId: Uuid.parse('6e400002-b5a3-f393-e0a9-e50e24dcca9e'),
        deviceId: id);
    final response = await flutterReactiveBle.readCharacteristic(characteristic);

    if (response != null) {
      print(response.toString());
    }
  }, onError: (Object error) {
    // Handle a possible error
  });
}

Thanks to every answer in advance.

I tried to get the String sent by a bluetooth device but didn't get anything but errors.


Solution

  • Ok I fixed it myself, here my Resolution for anyone who might have this problem in the future:

    (Call this after the device is connected succesfully):

    Future<void> _startNotifications() async {
      print("start getting Data");
      await flutterReactiveBle.subscribeToCharacteristic(characteristic).listen((data) {
        print(data);
        //Further Data Handling
      },
      onError: (dynamic error) {
        print('Error subscribing to Char.');
        print('Error: ' + error.toString());
      },
      onDone: () {
        print('Seemingly Done (Whatever that means.)');
      }
      );
    }