How to write commands to a serial port using NodeJ

2019-09-11 11:13发布

问题:

Good day everyone,

I am having issues writing commands to a lock connected to a USB controller which is connected to the laptop port using NodeJs. I have successfully achieved this in python, but is having issues in nodejs.

The reason why I am converting to nodejs is because the entire application is written in nodejs and runs has a desktop app via electron, and opening/closing port is just a small component of it.

The python equivalent and which works fine

ser = serial.Serial()
        ser.baudrate = 38400 #Suggested rate in Southco documentation, both locks and program MUST be at same rate
        // COMPORT  is a variable that stores an integer such as 6
        ser.port = "COM{}".format(COMPORT) 
        ser.timeout = 10
        ser.open()
        command = "open1"
        #call the serial_connection() function
        ser.write(("%s\r\n"%command).encode('ascii')) #Southco locks receives and sends commands in ASCII

Now in NodeJs, I am using the library serialport and I am trying to achieve this via nodejs that runs under the electron app.

var SerialPort = require('serialport');

   var port = new SerialPort("COM6", {
        baudRate: 38400
    });

    port.on('open', function() {
        port.write(Buffer.from('open1', 'ascii'), function(err) {
            if (err) 
                return sendData(500, err.message);

            console.log('message written');
        });
    });

I know nodejs is able to interact with the port because when I run serialport-list in command prompt or when i run it within the code

SerialPort.list(function (err, ports) {
    ports.forEach(function(port) {
        console.log(port.comName, port.pnpId, port.manufacturer); // or console.log(port)
    });
});

it shows the port information. Hence, nodejs is able to read the port, and issue information about the specific port, but I cant seem to issue command succesfully to it. It seems to get execute since no error message is thrown and it does display message written in console, but the lock does not react, whereas with the python code the lock does react by opening or closing demanding on the command that is written.

Any help would be appreciated.