var express = require('express');
var router = express.Router();
var ws = null;

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

const SerialPort = require('serialport');
const Readline = require('@serialport/parser-readline');
let state = 0;

var port = new SerialPort('COM9', {
  baudRate: 9600,
});

const parser = port.pipe(new Readline({delimiter: '\n'}));

// Read the port data
port.on("open", function () {
  console.log('open');
});

var WebSocketServer = require('ws').Server,
    wss = new WebSocketServer({port: 40510})
    wss.on('connection', function (wsp) {

        ws = wsp;

        ws.on('message', function (message) {
            if(!isNaN(parseInt(message)))
            {
                port.write(message)
            }
            console.log('received: %s', message)
        });
});

parser.on("data", data =>{
  /*if (state!==data)
  {
      state = data;
      console.log(state);
  }*/
  if(ws != null)
    ws.send(data.toString());
  port.write(data+"\n");
});



module.exports = router;
