Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SerialPort 'close' event never fire

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 :)

like image 594
Itzik.B Avatar asked Sep 11 '17 20:09

Itzik.B


1 Answers

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);
like image 136
Itzik.B Avatar answered Oct 22 '22 03:10

Itzik.B