-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemp-log-simple.js
40 lines (31 loc) · 917 Bytes
/
temp-log-simple.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
const SerialPort = require('serialport');
// Add your USB port name
const port = new SerialPort('/dev/xy', {
parser: SerialPort.parsers.readline('\n')
});
const fs = require('fs');
const logIntervalMinutes = 0.1;
let lastMoment = new Date();
function tryParseJson (str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return JSON.parse(str);
}
console.log('Initialising...');
port.on('open', function () {
console.log('Opened port...');
port.on('data', function (data) {
const sensorData = tryParseJson(data);
const moment = new Date();
if (moment.getTime() - lastMoment.getTime() > logIntervalMinutes * 60 * 1000) {
lastMoment = moment;
fs.appendFile('log.txt', `\n${sensorData.temperature} , ${sensorData.humidity} , ${moment}`, function (err) {
if (err) return console.log(err);
console.log('Logged data: ', moment);
});
}
});
});