Read/Write data returns null - Unable to perform any operations - node serialport

耗尽温柔 提交于 2020-05-17 07:04:45

问题


I am working with serialport for the first time and trying to establish a read and write connection with an UART device which is a controller of a height adjustment desk by using the below method. The application is a desktop application using electron.

const SerialPort = require('serialport')
const Readline = require('@serialport/parser-readline')
const parser = new Readline()


const port = new SerialPort("COM4",  { 
                baudRate: 9600
 })

This is the code I have used and port.read() always returns null value.

For the write operation I have used the code like below:

var buf = new Buffer([ 0XF1, 0XF1, 0X01, 0X00, 0X01, 0X7E]);
    port.write(buf, function(err,n) {
    if (err) {
    return console.log('Error on write: ', err.message)
    }
    console.log(n)
    console.log('message written')
})

The buffer values are the ones for moving the desk up but no operation takes place and it returns no error or returns undefined value in callback.

More details on the device and setup: Using an RJ45 to USB connector to connect with the control box of the table.

The definition of the SCI is as below:
(Baud Rate):9600
(Data Mode):8
(Stop Bit):1
(Parity Type):None
Path: COM3

Handset is what is being referred to my system.

Basic write operation buffer vals:

Move Up=0XF1 0XF1 0X01 0X00 0X01 0X7E

Move Down=0XF1 0XF1 0X02 0X00 0X02 0X7E

Stop Action=0XF1 0XF1 0X0c 0X00 0X0c 0X7E

Read functionality example:

Current height(1000mm-0x03E8) 0XF2 0XF2 0X01 0X02 0X03 0XE8 0XEE 0X7E

(there is two bytes in ‘Data’,so ‘Data Length’ is 0x02;‘Checksum’= 0x01 + 0x02 +0x03 +0xE8 = 0xEE)

Expecting the read functionality to give the current height info and write functionality to be able to control the device.

Versions, Operating System and Hardware:

SerialPort@ ^8.0.7

Node.js v10.16.0

Windows

Hardware and chipset? COM4

FTDIBUS\VID_0403+PID_6001+AB0JIYQTA\0000

FTDI


回答1:


Creating a read-line parser suggests that messages are terminated by \n, but your write does not include one, so that could explain why commands are not getting to the device.

For the reads, if you want to use the read-line parser, you need to pipe the serialPort to it, then listen for data from the parser, e.g.:

serialPort.pipe(parser);

parser.on('data', (data) => {
  console.log(data)
})

Note: data will be a Buffer

You could skip the parser and call read directly. I assume you tried that. Docs say:

If no data is available to be read, null is returned.

https://serialport.io/docs/api-stream#serialport-read

So, it could be that the desk only outputs data after a message is received.



来源:https://stackoverflow.com/questions/61486104/read-write-data-returns-null-unable-to-perform-any-operations-node-serialpor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!