John John - 3 months ago 47
Node.js Question

Reading data from NodeJs Serialport

I would like to be able to read data received by the ascii command sent.

Below is the code that sends command to my lock controller

var express = require('express');
var router = express.Router();
var SerialPort = require('serialport');


/* GET home page */
router.get('/', function(request, response){


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


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

port.on('open', function() {
// NodeJS v4 and earlier
port.write(new Buffer('status1', 'ascii'), function(err) {
if (err) {
return console.log('Error on write: ', err.message);
}
console.log('message written');

});
});

// open errors will be emitted as an error event
port.on('error', function(err) {
console.log('Error: ', err.message);
});

});

// Important
module.exports = router;


In the doc, it mentions the use of parsers to try and read data, https://github.com/EmergingTechnologyAdvisors/node-serialport#serialportparsers--object but I am not sure how to implement it, and I would want to execute after the command
status1
has been written.

Essentially logs the response of the command succesfully written to the console

Answer

There are some peculiarities.
You can open port on application start and reconnect on port close or open port on each request. It defines how work with data flow. If you send request to port then answer can contain data of previous requests (more than one). You can ignore this problem (if answer is short and request interval is enough large) or send request with assign id and search answer with this id.

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

router.get('/', function(req, res){
    function sendData(code, msg) {
        res.statusCode = 500;
        res.write(msg);
        console.log(msg);   
    }

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

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

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

    var buffer = '';
    port.on('data', function(chunk) {
        buffer += chunk;
        var answers = buffer.split(/\r?\n/); \\ Split data by new line character or smth-else
        buffer = answers.pop(); \\ Store unfinished data

        if (answer.length > 0) 
            sendData(200, answer[0]);
    });

    port.on('error', function(err) {
        sendData(500, err.message);
    });
});

module.exports = router;