const SerialPortLib = require("serialport");
const Readline = require("@serialport/parser-readline");
const http = require("http"),
    WebSocketServer = require("ws").Server,
    port = 8080;
const portArduino = new SerialPortLib("/dev/ttyACM0", { baudRate: 9600 });
const parser = portArduino.pipe(new Readline({ delimiter: "\n" }));


portArduino.on("open", () => {
  console.log("Serial port ouvert");
});

parser.on("data", (data) => {
    console.log(data);
});




const server = http.createServer();
// create a WebSocket Server on top of the HTTP server to deal with the WebSocket protocol
const wss = new WebSocketServer({
  server,
});

wss.on("connection", (client) => {
  console.log("Client connected");

  console.log("client " + ++count);
  // Register a listener on each message of each connection
  client.on("message", (message) => {
    console.log(message.toString());
    console.log("message from");
  });
});

// http sever starts listening on given host and port.
server.listen(port, () => {
  console.log(
    "Listening on " + server.address().address + ":" + server.address().port
  );
});