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;
Answer from Aikon Mogwai on Stack OverflowVideos
I cannot test this end to end (no arduino anywhere near), but since serialport seems to implement a Readable stream, I'd try using scramjet like this:
const {StringStream} = require('scramjet');
serialport.on('open', () => console.log('open');
serialport.pipe(new StringStream) // pipe the stream to scramjet StringStream
.lines('\n') // split per line
.each( // send message per every line
data => io.sockets.emit('message',data)
);
Scramjet would sort the readline issue for you.
I tested this code with the serial port device that uses RS-232 protocol. Its advantage is that you don't need install the third package from npm.
var recVal = '';
mySerial.on('data', function(data) {
if(data.indexOf('\n') != -1) {
io.emit('serial:data', {
value: recVal
});
console.log("Data: ", recVal.toString());
recVal = '';
} else {
recVal = recVal.concat(data);
}
});
» npm install serialport
Author of node-serialport. I have tracked down the issue and it is due to a compilation issue with IOWatcher in node.js. I have revised the strategy for reading from the serial port and it now should function as designed in all cases. Please ensure you are using node-serialport 0.2.6 and greater.
Now go out and build JS controlled robots!!!
I also experienced problems with the serial port read. This is due to a bug in node.js v4.7 (see this issue)
However it worked after switching to an older version of Node.js (v4.0).
It might work with versions up to v4.6 also, but I haven't verified that yet.