Flutter: How to receive data from bluetooth manager class

64 Views Asked by At

I'm building an app to communicate the mobile device with the external device over Bluetooth classic. I'm using the flutter_bluetooth_serial package. I'm able to connect to the device and also I'm receiving the data back. I created a Bluetooth manager class with a notifier, all the Bluetooth operations are handled in this class. Now, when I send a command/message from the "device firmware" class, data is received in the Bluetooth manager class, but I want data to be received in the "device operation" class. Likewise, If I send a command/message from "some other class", I should receive data on "some other class". Below is part of my code. Can somebody tell me how to achieve this?

BluetoothManager Class:

 class BluetoothManager extends ChangeNotifier {
      static final BluetoothManager _singleton = BluetoothManager._internal();
    
      factory BluetoothManager() {
        return _singleton;
      }
    
      BluetoothManager._internal();
      List<dynamic> globalFinalList = [];
    
    connectToExternalDevice() async {
        try {
          await BluetoothConnection.toAddress(device.address).then((result) {
           
            connection?.input?.listen(_onDataReceived).onDone(() { // _onDataReceived metod will receive data
             
            });
          });
        } catch (exception) {
          // TODO
        }
      }
    
    Future<List> _onDataReceived(Uint8List data) async { // This method received the output
        List<dynamic> finalList = data
        Uint8List uintList = Uint8List.fromList(receivedDecimalData);
        globalFinalList = finalList;
        return finalList;
      }
}

Device Firmware class:

void sendMessage() async { //This method sends command to the external device
    var commandhelper = CommandsHelper();
    var finalCommandWithCRC = await commandhelper
        .getCommandWithCRC(commandhelper.mainFirmwareCommand);
    var finalHexValues =
        await commandhelper.convertCommandToHexTwoBytes(finalCommandWithCRC);

    var finalCommandtoSend =
        await commandhelper.convertCommandToSignedDecimal(finalHexValues);
    Uint8List bytes = Uint8List.fromList(finalCommandtoSend);
    connection.output.add(bytes);
    await connection.output.allSent;
  }

Once the sendMessage()method is executed, _onDataReceived method in Bluettooth manager class will receive the data. But I want this message in the Device Firmware class

0

There are 0 best solutions below