0

Description: I'm trying to use the Flutter Bluetooth Serial plugin to communicate with an HC-05 Bluetooth module. I'm able to connect to the device and send/receive data successfully on the first attempt. However, when I try to send/receive data again, I encounter the following issues:

  • I receive a "E/flutter ( 9883): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Bad state: Future already completed" error on the second attempt to send/receive data./ .... /I/flutter (10663): Error: TimeoutException after 0:00:03.000000: Future not completed/

  • There data sent on the second attempt is sent correctly to HC-05 but no received data, and i get the errors above

  • i configured my HC05 module correctly and i have tested it in bluetooth terminal app ( available on playstore).

  • If I disconnect and reconnect to the Bluetooth device, I'm able to send/receive data once before encountering the same issues.

Code : Flutter "Handling send/received data"

  Future<String> sendAndReceive(String message) async {
    if (!isConnected) {
      return ('BLUETOOTH NOT CONNECTED');
    }
    try {
      // Send the message
      connection.output.add(utf8.encode(message));
      await connection.output.allSent;

      // Wait for the response
      final completer = Completer<String>();
      final buffer = StringBuffer();
      _inputSubscription ??= connection.input.listen((data) {
        buffer.write(utf8.decode(data));
        final message = buffer.toString();
        if (message.endsWith('\n')) {
          completer.complete(message.trim());
          buffer.clear();
        }
      });

      final response = await completer.future;  //.timeout(Duration(seconds: 3));
      print(response);
      return response;
    } catch (e) {
      print('Error: $e');
      return ('Error');
    }
  }

Code Arduino : "Handling received data"

 if(bthc05.available()) // Looking for Bluetooth Received Data
    {
      
    BT_String = bthc05.readStringUntil('\n'); 
    // BT_uid = BT_String;
    BT_String.trim(); // Remove any leading or trailing white space
    if(BT_String == "status"){
      sendStatusAndRecords();
    }
    else if (BT_String == "clear") // clear table from previous added uids
    {
    allowedUIDs="";
    bthc05.println("Cleared\n");
    Serial.println("Cleared");
     allowedUIDs_count =0;
    }

Code Flutter: (Executing functions)

 final BluetoothService bluetoothService = BluetoothService();
Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Bluetooth Status'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.bluetooth, color: Colors.blue),
              SizedBox(width: 8),
              Text(bluetoothStatus),
              ElevatedButton(
                  onPressed: () async {
                    await bluetoothService.startScan(pin);
                  },
                  child: Text('connect')),
              ElevatedButton(
                onPressed: () async {
                  String bt_bt =
                      await bluetoothService.sendAndReceive('status\n');
                  setState(() {
                    bt = bt_bt;
                  });
                },
                child: Text('send status'),
              ),
              ElevatedButton(
                onPressed: () async {
                  String bt_bt = await bluetoothService.sendAndReceive('clear\n');
                  setState(() {
                    bt = bt_bt;
                  });
                },
                child: Text('clear'),
              ),
              ElevatedButton(
                  onPressed: bluetoothService.disconnect,
                  child: Text('Disconnect')),
              Text(bt),
            ],
          ),
        ),
      ),
    );
  }
}

its not the full code because its long

I've tried the following to troubleshoot the issue:

  • Testing the Bluetooth connection with another app (Bluetooth Terminal), and it works correctly and quickly.

  • Adding a connection check before sending/receiving data and a timeout to the receive function.

  • Updating the Flutter Bluetooth Serial plugin to the latest version.

  • Running the code on a different device.

IMPORTANT : i added \n when calling function because while writing this stackoverflow question i remembered that my arduino code i have a function that keeps reading bluetooth data until it encounters \n

so by adding it is receiving data correctly and fast because before it it either not sending at all or delayed or concatenated with last data.

0 Answers0