-
Notifications
You must be signed in to change notification settings - Fork 1
/
SubscriberMQTT.js
executable file
·75 lines (63 loc) · 2.48 KB
/
SubscriberMQTT.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('IOTProjectDB.db');
var mqtt = require('mqtt');
var count = 0;
var settings = {
port: 1883
};
var client = mqtt.connect('mqtt://127.0.0.1', settings);
// the client subscribe some new topic, the one realtive to tthe Database
client.subscribe('/db/#');
console.log('Subscriber started...');
// fired when new message is received
client.on('message', function(topic, message) {
if(topic === '/db/waterSensor'){
let jsonObj = JSON.parse(message)
db.run(`INSERT INTO WaterSensor(SalinityValue, SalinityType, SodiumType, SodiumValue, Time ) VALUES(?,?,?,?,?)`, jsonObj['SalinityValue'], jsonObj['SalinityType'],jsonObj['SodiumType'],jsonObj['SodiumValue'],jsonObj['Timestamp'], function(err) {
if (err) {
return console.log(err.message);
}
// get the last insert id
console.log(`A row has been inserted with rowid ${this.lastID}`);
});
}else if(topic === '/db/airSensor'){
let jsonObj = JSON.parse(message)
db.run(`INSERT INTO AirSensor(AQI, Time, Condition ) VALUES(?,?,?)`, jsonObj['AQI'], jsonObj['Timestamp'],jsonObj['Condition'], function(err) {
if (err) {
return console.log(err.message);
}
// get the last insert id
console.log(`A row has been inserted with rowid ${this.lastID}`);
});
}
else if(topic === '/db/tempSensor'){
let jsonObj = JSON.parse(message)
db.run(`INSERT INTO TemperatureSensor(Temperature, Date, Hour ) VALUES(?,?,?)`, jsonObj['Temperature'], jsonObj['Date'],jsonObj['Hour'], function(err) {
if (err) {
return console.log(err.message);
}
// get the last insert id
console.log(`A row has been inserted with rowid ${this.lastID}`);
});
}
else if(topic === '/db/soilMoistureSensor'){
let jsonObj = JSON.parse(message)
db.run(`INSERT INTO SoilMoistureSensor(SoilMoisture, SoilMoistureType, Time ) VALUES(?,?,?)`, jsonObj['soilMoisture'], jsonObj['soilMoistureType'],jsonObj['Time'], function(err) {
if (err) {
return console.log(err.message);
}
// get the last insert id
console.log(`A row has been inserted with rowid ${this.lastID}`);
});
}
else if(topic === '/db/irrigator'){
let jsonObj = JSON.parse(message)
db.run(`INSERT INTO Irrigator(State, Pressure ) VALUES(?,?)`, jsonObj['state'], jsonObj['pressure'], function(err) {
if (err) {
return console.log(err.message);
}
// get the last insert id
console.log(`A row has been inserted with rowid ${this.lastID}`);
});
}
});