I am trying to write Node.js script that uses the serialport
npm package to read and write data to COM5
serial port, which is connected to a device using RS-232 cable. This device is automatically transmitting the data it has.
To retrieve the data stored inside the device, I need to send, first, one byte 0x80 (uInt8
) to the device and expect to receive 81 as a hex number from the device. Second, I need to send another byte 0x81 (uInt8
) and then expect to receive all stored data (around 130000 bytes) as lines.
There is no way how to retrieve the whole stored data only by two bytes, one after another. Communication with the device can only be done by bytes.
I tried the following code:
import SerialPort from 'serialport';
const sp = new SerialPort.SerialPort({path: "COM5", baudRate: 115200});
const buff = Buffer.allocUnsafe(1);
buff.writeUInt8(0x80, 0);
sp.write(buff, function (err){
if (err){
return console.log("Error on write: ", err.message);
}
console.log("Port.write: ", buff);
});
sp.on('readable', function () {
var arr = new Uint8Array(sp._pool);
console.log('Data:', arr);
});
When running my script (using node myScript.mjs
), I see the following:
PortWrite: <Buffer 80>
Data: Uint8Array(65536) [
0, 30, 167, 106, 127, 2, 0, 0, 32, 31, 170, 106,
127, 2, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0,
16, 84, 18, 76, 196, 0, 0, 0, 100, 84, 18, 76,
196, 0, 0, 0, 184, 84, 18, 76, 196, 0, 0, 0,
160, 84, 18, 76, 196, 0, 0, 0, 244, 84, 18, 76,
196, 0, 0, 0, 72, 85, 18, 76, 196, 0, 0, 0,
240, 120, 18, 76, 196, 0, 0, 0, 68, 121, 18, 76,
196, 0, 0, 0, 152, 121, 18, 76, 196, 0, 0, 0,
240, 120, 18, 76,
... 65436 more items
]
The program doesn't exit until I hit Ctrl+c
. I am not sure what ps._pool
does but it seems the output is not correct but looks like giving something at random.
I am new to Node.js. I am also not sure how to add an argument TimeOut
of 10 seconds in the sp
object.
I tried to use Matlab, for testing, and I could retrieve the data successfully.
I tried Python too but didn't work for me - PySerial package is reading serial data before writing?.