SerialPort 'close' event never fire

心已入冬 提交于 2019-12-08 17:32:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!