69 lines
1.9 KiB
JavaScript
69 lines
1.9 KiB
JavaScript
const mqtt = require('mqtt')
|
|
const { MongoClient } = require('mongodb')
|
|
const _ = require('lodash')
|
|
|
|
const dbClient = new MongoClient("mongodb://garden:99009911@cloud.timovolkmann.de:27017/Smart_Garden", { useUnifiedTopology: true })
|
|
|
|
startMqttObserver()
|
|
|
|
async function startMqttObserver() {
|
|
console.log("setup connections...")
|
|
// setup mongodb
|
|
dbClient.connect(err => {
|
|
if (err) {console.log("mongodb connection error")} else {console.log("mongodb connected.")}
|
|
const db = dbClient.db("Smart_Garden")
|
|
const sensorData = db.collection('sensorData');
|
|
console.log("collection retrieved.")
|
|
// setup mqtt client
|
|
mqttClient = mqtt.connect('mqtt://mqtt.timovolkmann.de')
|
|
mqttClient.on('connect', onMqttConnect(mqttClient))
|
|
mqttClient.on('message', messageCallback(sensorData))
|
|
})
|
|
}
|
|
|
|
function messageCallback(collection) {
|
|
return function (topic, message) {
|
|
let topicElements = topic.split('/');
|
|
const type = topicElements.pop();
|
|
const id = topicElements.pop();
|
|
|
|
var date = new Date;
|
|
var time;
|
|
|
|
if (date.getHours() <= 9) {time = "0" + date.getHours();} else {
|
|
time = date.getHours();
|
|
}
|
|
if (date.getMinutes() <= 9) {time = time + ":0" + date.getMinutes();} else {
|
|
time = time + ":" + date.getMinutes();
|
|
}
|
|
/*
|
|
if (date.getSeconds() <= 9) {time = time + ":0" + date.getSeconds();} else {
|
|
time = time + ":" + date.getSeconds();
|
|
}
|
|
*/
|
|
|
|
let doc = {
|
|
device_id: id,
|
|
timestamp: date,
|
|
timeAsString: time,
|
|
}
|
|
try {
|
|
doc = _.merge(doc, JSON.parse(message));
|
|
} catch {
|
|
|
|
}
|
|
if (type === 'data') {
|
|
console.log(doc);
|
|
collection.insertOne(doc)
|
|
}
|
|
}
|
|
}
|
|
|
|
function onMqttConnect(mqttClient) {
|
|
return function () {
|
|
mqttClient.subscribe('smartgarden/updates/#', function (err) {
|
|
if (err) console.log(err);
|
|
console.log("Sucessfully subscribed...");
|
|
})
|
|
}
|
|
} |