altera2015 / usbserial

Flutter Android USB Serial plugin
BSD 3-Clause "New" or "Revised" License
121 stars 83 forks source link

How can i perform a write soon as i read some string from my device? #56

Closed sanidhya-r closed 2 years ago

sanidhya-r commented 2 years ago

I have a microcontroller that sends a string 'Device Boot' on restart. I am using a regex to parse it, but soon as it does find it, i wish to perform a write - to send a $ signal which makes the microcontroller send logs.

I am using USB_SERIAL for Flutter.

This is the current setup:

Future<bool> _connectTo(device) async {

    if (device == null) {
      setState(() {
        _status = "DISCONNECTED";
      });
      return true;
    }

    _port = await device.create();

    if (!await _port!.open()) {
      setState(() {
        _status = "FAILED";
      });
      return false;
    }

    await _port!.setDTR(true);
    await _port!.setRTS(true);
    await _port!.setPortParameters(
        115200, UsbPort.DATABITS_8, UsbPort.STOPBITS_1, UsbPort.PARITY_NONE);

    _transaction = Transaction.stringTerminated(
        _port!.inputStream!, Uint8List.fromList([13, 10]));

    _subscription = _transaction!.stream.listen((String line) {
      //Set in progress flag for first time read.
      if (line.contains('Device Boot')) {
        setState(() {
          Wakelock.enable();
        });

        //Set timer for timeout
        _timer = Timer(const Duration(seconds: 300), () {
          Wakelock.disable();
          _saveData(); // to save logs
        });
      }
    return true;
  }

And i wish to perform a write soon as it finds the first line Device Boot.

The USB_SERIAL's document suggests to use

await port.write(Uint8List.fromList('\$'.codeunits));

So i used the above code right after it found the boot line, like below

.....
    _subscription = _transaction!.stream.listen((String line) {
      //Set in progress flag for first time read.
      if (line.contains('Device Boot')) {

        // writing to device
        await _port.write(Uint8List.fromList('\$'.codeunits));

        setState(() {
          Wakelock.enable();
        });

.....

But this doesn't work for me, so i am really confused if this is where i should be performing the write, this is first time i am working with usb package. Any help is appreciated.

sanidhya-r commented 2 years ago

Found the issue in flow.