-
Notifications
You must be signed in to change notification settings - Fork 0
/
mqttserver.js
46 lines (37 loc) · 1.13 KB
/
mqttserver.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
var mqtt = require('mqtt');
var mongoClient = require('mongodb').MongoClient;
var uuid = require('uuid');
var mqttClient = mqtt.connect('ws://atliot.com:8080', {clientId: 'mongoClient_' + uuid.v1()});
var insertDocument = function(db, document, callback) {
var collection = db.collection('rawdata');
collection.insert(document, function(err, result) {
callback(result);
})
}
function tryParseJSON (jsonString){
try {
var o = JSON.parse(jsonString);
if (o && typeof o === "object" && o !== null) {
return o;
}
}
catch (e) { }
return false;
};
mqttClient.on('connect', function () {
console.log('mongoClient connected to mosquitto broker.')
mqttClient.subscribe('/motion');
});
mqttClient.on('message', function (topic, message) {
var jsonDoc = tryParseJSON(message);
if (jsonDoc) {
mongoClient.connect('mongodb://localhost:27017/motionsensor', function(err, db) {
insertDocument(db, jsonDoc, function(result){
db.close();
});
});
}
});
mqttClient.on('close', function() {
console.log('mongoClient disconnected from mosquitto broker')
});