react-native-usbserial icon indicating copy to clipboard operation
react-native-usbserial copied to clipboard

Read data from serial

Open nightmareindustries opened this issue 8 years ago • 7 comments

Hello,

Are you planning on implementing serial read as well? It would make the library extremely useful and complete.

Thanks for your great work

nightmareindustries avatar Sep 22 '17 06:09 nightmareindustries

How about just giving the port.read() method a fixed buffer? Or we specify the buffersize via param. The following code is completely untested:

    private static final int READ_BUFFER_SIZE = 256;
    ...
    public void readAsync(Promise promise) {
        if (port != null) {
            byte[] buffer = new byte[READ_BUFFER_SIZE];
            try {
                int bytesRead = port.read(buffer, SERIAL_TIMEOUT);
                String byteString = new String(buffer, 0, bytesRead);
                promise.resolve(byteString);
            } catch (IOException e) {
                promise.reject(e);
            }
        } else {
            promise.resolve(getNoPortErrorMessage());
        }
    }

stefan-beyer avatar Mar 13 '18 18:03 stefan-beyer

I studied the source code of this project a little bit and it looks like, for writing data, it just calls this:

return this.UsbSerialModule.writeInDeviceAsync(this.id, value);

Is it much harder to change this to 'read'? What exactly needs to be done to support reading from serial?

wil93 avatar Jun 08 '18 09:06 wil93

Hi guys, have anyone implemented it already? I'm willing to pay for it if needed.

gabrielhpugliese avatar Jul 30 '18 08:07 gabrielhpugliese

Hey, yeah, we have a working fork for reading data. Nothing pretty, but it gets the job done: https://github.com/edvijaka/react-native-usbserial

GreenGI avatar Jul 31 '18 06:07 GreenGI

Hey @GreenGI thank you. Is this usage correct?

        DeviceEventEmitter.addListener('newData', (e) => {
          console.log('newData', e);
        });

gabrielhpugliese avatar Jul 31 '18 09:07 gabrielhpugliese

Basically - yes. This is how I use it on a component after mounting it:

componentWillMount() {
  this.getDeviceAsync().then(device => {
    if (device) {
      DeviceEventEmitter.addListener('newData', (e) => {
        console.log('newData', e);
      });
      this.readDevice(device.id);
    }
  });
}

getDeviceListAsync = () => {
  return UsbSerialModule.getDeviceListAsync();
};

readDevice = (id) => {
  UsbSerialModule.readDeviceAsync(id);
};

GreenGI avatar Aug 01 '18 12:08 GreenGI

Hi @GreenGI ! Is the code above still working in your fork? Could you provide the code for getDeviceAsync()? Thanks in advance.

omatrot avatar Aug 26 '19 08:08 omatrot