'use strict'; var MongoClient = require('mongodb').MongoClient; var assert = require('assert'); var url = 'mongodb://localhost:27017/arduino'; // db should be created if not exists const serialport = require('serialport');// include the library const SerialPort = serialport.SerialPort; // make a local instance of it var portName = "/dev/ttyACM0"; var portNameCLI = process.argv[2]; if ( portNameCLI > "") { portName = portNameCLI; } else { serialport.list(function (err, ports) { ports.forEach(function(port) { console.log("port: " + port.comName + " manuf: " + port.manufacturer ); }); }); } var myPort = new SerialPort(portName, { baudRate: 9600, parser: serialport.parsers.readline("\n") } ); // look for return and newline at the end of each data packet myPort.on('open', showPortOpen); myPort.on('data', saveLatestData); myPort.on('close', showPortClose); myPort.on('error', showError); function showPortOpen() { console.log('port open:' + portName +' Data rate: ' + myPort.options.baudRate); myPort.flush(); } function saveLatestData(data) { if (isValidJSON(data)) { let serialData = JSON.parse(data); // convert to JSON //console.log("time:"+ serialData.time); // there must be a "time":"yyyymmddhhmmss" in the serial string MongoClient.connect(url, function(err, db) { assert.equal(null, err); db.collection("AINS").insert(serialData); db.close(); }); } else { console.log(data); } // show the garbage for diagnostic } function showPortClose() { console.log('port closed.'); } function showError(error) { console.log('Serial port error: ' + error); } function isValidJSON(jsonOBJ) { try { JSON.parse(jsonOBJ); return true; } catch (e) { return false; } }