-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_subscriber.js
46 lines (38 loc) · 1.11 KB
/
test_subscriber.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
// This file creates an MQTT client and connects to the HiveMQ Cloud Broker
// Example of subscribing to a topic and receiving messages
const mqtt = require('mqtt');
/*
const options = {
// Clean session
clean: true,
connectTimeout: 4000,
// Auth
clientId: 'emqx_test',
username: 'emqx_test',
password: 'emqx_test',
}
*/
var client = mqtt.connect('mqtt://broker.hivemq.com');
// connect to broker
client.on('connect', function () {
client.subscribe("cameronhowley888");
console.log("Client has subscribed successfully");
});
/* parse string message
client.on('message', function (topic, message) {
if (topic === 'cameronhowley888') {
console.log(message.toString());
}
});
*/
// parse json file - message is json, packet contains data about transmission
client.on('message', function (topic, message, packet) {
// ensure message from correct topic
if (topic === 'cameronhowley888') {
const obj = JSON.parse(message.toString())
// store data in database
let data = obj.Data
let meterNum = obj.MeterNum
console.log(obj)
}
})