简体   繁体   中英

Reading in Multiple Serial Inputs with Node.Js

I have been working on a simple script to monitor 6 arduino units in my lab. I seem to have almost got it!

My current issue is getting each dataset nicely bundled all in one string. as it is, I am able to open a connection with all the serial ports, recieve their data, as they spew it out, but lack the code block to organize it into the bundles. I have considered attempting to make a temporary array to append the chunks to, or produce child processes. However, I have had difficulties with child processes, and am not sure how to structure an array in an appropriate way. Once I have a bundled string I will be sending to a database on my server. I do have the feeling I may be doing this in an innapropriate way, any and all advice is much apreciated!

PS: You may notice there are only 5 arduinos showing, that was just to make things a little less complicated due to the 6th arduino also showed up as com9.

Thank you

The Code

var serialport = require('serialport');
var SerialPort = serialport.SerialPort;

// list serial ports:
serialport.list(function (err, ports) {
    console.log(" Readout all availiable Com Ports and their pnpID:   ");
    ports.forEach(function(port) {

        console.log(port.comName);
        console.log(port.pnpId);
        console.log(port.manufacturer);

        var serialPort = new SerialPort(port.comName, {baudrate: 9600
        }, false);
        serialPort.open(function (error) {
        if ( error ) {
            console.log('failed to open: '+error);
        } else {
            console.log('open');
            serialPort.on('data', function(data) {
                console.log('data received: ' + port.comName+ '   ' + data);

                });
            }
        });
    })
})

The Output

Readout all availiable Com Ports and their pnpID:   
COM11
USB\VID_2341&PID_0043\75430333437351517211
Arduino LLC (www.arduino.cc)
COM9
USB\VID_2341&PID_0043\7543033343735151C020
Arduino LLC (www.arduino.cc)
COM8
USB\VID_2341&PID_0043\754363434303516181F0
Arduino LLC (www.arduino.cc)
COM7
USB\VID_2341&PID_0043\7543033313735140B152
Arduino LLC (www.arduino.cc)
COM4
USB\VID_2341&PID_0043\754303334373515162D0
Arduino LLC (www.arduino.cc)
open
open
open
open
open
data received: COM8   L03 
data received: COM4   L01
data received: COM8   , -0.00127 , 8.19188

data received: COM4    , -
data received: COM7   L02
data received: COM4   0.00127 , 8.
data received: COM7    , -0.00
data received: COM4   19188

data received: COM7   127 , 8.
data received: COM9   L
data received: COM7   19188

From the documentation of the serial port library https://www.npmjs.com/package/serialport

There is an option to read the data until a new line is encountered. This can be used instead of the baudRate in order to read whole lines of data.

Change the following line(s)

var serialPort = new serialport.SerialPort(port.comName, {
      baudrate: 9600
    }, false);

to

var serialPort = new serialport.SerialPort(port.comName, {
      parser: serialport.parsers.readline("\n")
    }, false);

Then in your callback the data will come as a full line instead of in pieces

EDIT:

You should make a collector then that handles the server communication part. Just place it in another file in the same directory called collector.js . Then the main script would work like that:

var serialport = require('serialport');
var collector = require('./collector');

// list serial ports:
serialport.list(function (err, ports) {
  console.log(" Readout all available Com Ports and their pnpID:   ");
  ports.forEach(function (port) {

    console.log(port.comName);
    console.log(port.pnpId);
    console.log(port.manufacturer);

    var serialPort = new serialport.SerialPort(port.comName, {
      baudrate: 9600
    }, false);

    serialPort.open(function (error) {
      if (error) {
        return console.log('failed to open: ' + error);
      }

      console.log('open');

      serialPort.on('data', function (data) {
        console.log('data received: ' + port.comName + '   ' + data);

        // add message to port message collection
        collector.add(port.comName, data);
      });
    });
  });
});

And the collector would work like:

var os = require('os');

var messages = {};

function checkAndSendData(key, data, message) {
  if (data === os.EOL || message.match(/^L\d\d , \d,\d\d\d\d\d , \d\.\d\d\d\d\d$/)) {
    // TODO: send data to server in formatted way, maybe need key?

    return true;
  }

  return false;
}

module.exports = {
  add: function(key, data) {
    if (typeof messages[key] === 'undefined') {
      messages[key] = '';
    }

    messages[key] += String(data);

    if (checkAndSendData(key, data, messages[key])) {
      messages[key] = '';
    }
  }
}

This got a bit long for a comment..

serialPort.on('data', function(data) {
  console.log('data received: ' + port.comName+ '   ' + data);
  // switch(JSON.parse(data).type) { // if that's a possibility  
  if ("BEGIN" === data) {
    console.log('begin data received: ' + port.comName+ '   ' + data);
  }
});

I think what you're looking for is a paradigm to copy (Factory, Reader/Writer?) but maybe Begin, Stuff, and End would work for you? Then you can generate events or call callbacks you've passed in.

serialPort.on('data', function(data) {
  console.log('data received: ' + port.comName+ '   ' + data);
  // var _data =  JSON.parse(data); // if that's a possibility
  // switch(_data.type) { 
  //  case "BEGIN": fnBegin(port.comName, _data.object); break;
  // or  
  if ("BEGIN" === data) {
    console.log('begin data received: ' + port.comName+ '   ' + data);
  }
  // or
  factory.fn(port.comName, data);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM