问题
I'm using nodeJS's SerialPort
Package for connecting to computer ports.
About Package's close
event here.
I have created this code, I would like to know why close
/disconnect
event never fire when I disconnect the COM
const express = require('express');
const router = express.Router();
//
const cors = require('cors');
router.use(cors());
//
const SerialPort = require('serialport');
const Readline = SerialPort.parsers.Readline;
const port = new SerialPort('COM7',function (err) {
if (err) {
return console.log('Error: ', err.message);
}
});
const parser = port.pipe(new Readline());
/*
var lastresult = '';
var count = 0;
*/
port.on('open', function() {
console.log('~Port is open.');
parser.on('data', console.log);
});
port.on('disconnect', function () {
console.log('disconnected');
});
port.on('close', function () {
console.log('closed');
});
router.get('/', function (req, res) {
res.send('index');
});
module.exports = router;
I'm trying to think if I use it wrong because I havn't saw example for using this event.
Thanks for the help :)
回答1:
I have created timestamp every time I recive data from the COM
,
And check it with interval()
every time.
setInterval(function () {
if (Date.now() - lastDataTime > 1000 || !comStatus) {
comStatus = false;
port.close();
port = new SerialPort(comPort, function (err) {
if (err) {
error = 'Error: ' + err.message;
return console.log(error);
}
});
}
}, 1000);
来源:https://stackoverflow.com/questions/46164051/serialport-close-event-never-fire