Writing Characteristics on Bluetooth Device

1.2k Views Asked by At

For those who have already worked on Bluetooth Low Energy on Flutter:

I am developing a mobile application. Simply, every time the user clicks on the "Read Data" button, I want to discoverServices and receive data:

          onTap: () async {
                  deviceStateSubscription = bluetoothDevice.state.listen((s) {
                    if (s == BluetoothDeviceState.connected) {
                      _discoverServices();
                    } else  {
                      bluetoothDevice.connect();
                      _discoverServices();
                    }
                  });
                },

I have realized that connection is sometimes dropping for no reason. That is why I use an 'if/else' to check the connection.

Here is my discoverServices method:

_discoverServices() async {
  List<BluetoothService> services = await bluetoothDevice.discoverServices();
  if (bluetoothServices != null && bluetoothServices.isNotEmpty) {
    bluetoothServices.forEach((service) {
      if (service.uuid.toString().toLowerCase() == Configuration.nusUUID) {
        service.characteristics.forEach((c) async {
          if (c.uuid.toString() == Configuration.txUUID) {
            txChar = c;
            try {
              await txChar!.write(Configuration.config, withoutResponse: true); // Sending the configuration 
              await txChar!.write(Configuration.rfCmdStart, withoutResponse: true); // Sending the start configuration
              await txChar!.write(Configuration.rfCmdStop, withoutResponse: true); // Sending the stop configuration to say that I am done, so send me data now
            } catch (e) {
                print(e.toString());
              }
            } else if (c.uuid.toString() == Configuration.rxUUID) {
              rxChar = c;
              rxChar!.setNotifyValue(true);
              rxChar!.value.listen((value) async {
                if (value.isEmpty) {
                  print('No data received');
                } else {
                  print(value);
                }
              });
            }
          });
        }
      });
    }
  }

The problem is, the button sometimes works and sometimes doesn't... It is not stable at all. Sometimes when I click, I receive data; and sometimes I receive Unhandled Exception: PlatformException(set_notification_error, error when writing the descriptor, null, null). I couldn't find any logical answers for that. To fix it, I am simply clicking on the button a few more times so that it sends me the data.

Any thoughts about how to fix this descriptor error?

1

There are 1 best solutions below

2
Risto On

writing the txChar characteristic with withoutResponse: true three times in a row is a problem. As the documentation for the write method states:

Writes the value of a characteristic. CharacteristicWriteType.withoutResponse: the write is not guaranteed and will return immediately with success.