57 lines
1.6 KiB
JavaScript
57 lines
1.6 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) {
|
|
// console.log('topic:', topic.toString(), 'message:', message.toString())
|
|
let topicElements = topic.split('/');
|
|
const type = topicElements.pop();
|
|
const id = topicElements.pop();
|
|
//console.log(id, type);
|
|
|
|
let doc = {
|
|
device_id: id,
|
|
timestamp: new Date,
|
|
}
|
|
try {
|
|
doc = _.merge(doc, JSON.parse(message));
|
|
//doc.sensordata = 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...");
|
|
})
|
|
}
|
|
}
|