Search code examples
node.jsmongodbmongoosearduinonode-serialport

MongoDB saving one correct one wrong


This is my first project with these technologies and English is not my native language forgive me for all mistakes.

I am making Real-time Arduino NodeJS MongoDB project. My main goal is getting humidity, temperature and gas values from arduino. Storing them in Mongodb and publish these values on web site (localhost for now). Here is my NodeJS file. Couple variables are Turkish but its not that important i assume.

// Express bir server kurduk
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 8000;
// 8000. Porttan bağlantıyı sağlıyoruz
// mongoose kullandığımız veri tabanı kısmımız
var mongoose = require('mongoose');
var promise = mongoose.connect('mongodb://localhost/deneme2', {
  useMongoClient: true,

});
promise.then(function(db) {
console.log('database e baglanildi')

});

// mongoose şeması tanımlaması
var Schema = mongoose.Schema;

var Veri = new Schema({
    nem:  String,
    sicaklik: String,
    sicaklik2: String,
    sicaklik3: String,
    gas: String,
    body:   String,
    date: { type: Date,default: Date.now }});
var Veriler = mongoose.model('veri', Veri);

// server dinleniyor fonksiyonu
server.listen(port, function () {
    console.log('Server listening at port %d', port);
});

// yönlendirme

app.use(express.static(__dirname + '/public'));

var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort("/dev/ttyACM0", { //Arduino bağlantısını sağladığımız USB portumuz
    autoOpen: false,
    parser: SerialPort.parsers.readline('\r\n'),
    baudrate:115200 // bitrate'imiz
}); 
//serialporttan okuyan ve datayı ekranımıza yazan fonksiyon
serialPort.open(function () {
    console.log('NodeJS Arduino Projemiz Hazır');
    serialPort.on('data', function(data) {
        console.log(data);
        io.sockets.emit('message', data.toString());
        var test=data.toString();
        var temp=test.split(",");
        var veritabani=new Veriler({
          nem: temp[0],
          sicaklik: temp[1],
          sicaklik2: temp[2],
          sicaklik3: temp[3],
          gas: temp[4]
        }); 
        veritabani.save(function(err){
         if(err) throw err
        });
});   

   }); 


app.get('/', function (req, res) {
    res.sendFile(__dirname + '/index.html');
});

io.on('connection', function (socket) {

});

Everything is fine. I am getting my data from Arduino like this way 31.0,24.0,297.0,185 I am saving it to the database but this is the first object which is wrong

{
    "_id" : ObjectId("5a5285dd36e0c007967c3f66"),
    "nem" : "",
    "date" : ISODate("2018-01-07T20:41:01.168Z"),
    "__v" : 0
}

And this is the second object which is correct.

{
    "_id" : ObjectId("5a5285dd36e0c007967c3f67"),
    "nem" : "32.0",
    "sicaklik" : "24.0",
    "sicaklik2" : "297.0",
    "sicaklik3" : "56.0",
    "gas" : "228",
    "date" : ISODate("2018-01-07T20:41:01.193Z"),
    "__v" : 0
}

It goes on and on againg like this one correct one wrong. I am using 800ms delay but i am going to try to change delay. I have no idea what is the problem. Also my html file :

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Ev Otomasyonu</title>
    <script src="/socket.io/socket.io.js"></script>
    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <script>
        var socket = io.connect('http://localhost');
        socket.on('message',function(data){
            test=data.toString(); 
            temp=test.split(',');
            $('#nem').temp[0];
            $('#sicaklik').text(temp[1]);
            $('#sicaklik2').text(temp[2]);
            $('#sicaklik3').text(temp[3]);
            $('#gas').text(temp[4]);
        });
    </script>
</head>
<body>
<div>
    <h1>Nem</h1>
    <h1 id='nem'></h1>
</div>

<div>
    <h1>Celcius</h1>
    <h1 id='sicaklik'></h1>
</div>
<div>
    <h1>Fahrenheit</h1>
    <h1 id='sicaklik2'></h1>
</div>
<div>
    <h1>Kelvin</h1>
    <h1 id='sicaklik3'></h1>
</div>
<div>
    <h1>Gaz</h1>
    <h1 id='gas'></h1>
</div>

</body>
</html>

Which does not give me my values just writing the headers. I assume its because the first object in database that saved before.


Solution

  • According to the sample code in serialport package, you are listening with the 'flowing mode' which can introduce such behaviour. Have you try using the non flowing mode?

    see sample code:

    // Switches the port into "flowing mode"
    port.on('data', function (data) {
      console.log('Data:', data);
    });
    
    // Read data that is available but keep the stream from entering "flowing mode"
    port.on('readable', function () {
      console.log('Data:', port.read());
    });