-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmqtt_server.js
70 lines (60 loc) · 1.79 KB
/
mqtt_server.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
// THIS IS AN EXAMPLE JS FILE SHOWING HOW TO USE MQTT
// For more details check http://www.steves-internet-guide.com/using-node-mqtt-client/
const mqtt = require('mqtt');
//const fs = require('fs');
//const caFile = fs.readFileSync("ca.crt"); //Works without this
const clientOptions = {
clientId:"mqttjs01",
username:"webapp",
password:"=ZCJ=4uzfZZZ#36f",
rejectUnauthorized : false // I need to do this for it to work
//ca:caFile
}
const client = mqtt.connect("mqtts://debonair.duckdns.org", clientOptions);
// Runs on connection to the broker
client.on("connect", () => {
console.log("connected " + client.connected);
// Subscribes to topics on startup
let topic = 'fromESP32/#';
client.subscribe(topic, (err, granted) => {
if (err) {
console.log(err);
return;
}
console.log('Subscribed to topic: ' + topic);
});
// Testing publishing ability
publish('toESP32/test','hello',options);
})
// Runs if unable to connect to broker
client.on("error", error => {
console.log("cannot connect " + error);
process.exit(1)
});
//client.subscribe(topic/topic array/topic object, [options], [callback])
/*
client.subscribe(topic, (err, granted) => {
if (err) {
console.log(err);
return;
}
console.log('Subscribed to topic: ' + topic);
});
*/
// Triggered when receiving messages, need to be subscribed first
client.on('message', (topic, message, packet) => {
console.log("message is "+ message);
console.log("topic is "+ topic);
});
//client.publish(topic, message, [options], [callback]);
// You can call this function to publish to things
function publish(topic,msg,options){
console.log("publishing",msg);
if (client.connected == true){
client.publish(topic,msg,options);
}
}
const options={
retain:true,
qos:1
};