-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.js
63 lines (51 loc) · 1.85 KB
/
client.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
require('dotenv').config();
const mqtt = require('mqtt');
(async () => {
if (!process.env.MOSQUITTO_SERVER) {
throw Error('You should first fill the .env-example file and rename it to .env');
}
let client;
// Connect to the MQTT server
console.log('Connecting...');
client = await mqtt.connectAsync(
// Note: you can replace 'mqtts' per 'wss' to connect to Mosquitto using websockets (you need to activate the option on Stackhero console and to configure "Security shield" to allow your IPs).
`mqtts://${process.env.MOSQUITTO_SERVER}:${process.env.MOSQUITTO_PORT}`,
{
username: process.env.MOSQUITTO_USERNAME,
password: process.env.MOSQUITTO_PASSWORD,
clean: true
}
);
console.log('Connected');
// This callback will be executed when a message is received on topics you subscribed (see client.subscribe below).
client.on(
'message',
(topic, message) => console.log(`Message received on topic "${topic}": ${message.toString()}`)
);
// Subscribe to the topic "global"
console.log('Subscribing to "global" topic...');
await client.subscribeAsync('global');
console.log('Subscribed to "global" topic');
// Publish to the topic "global"
console.log('Publishing to "global" topic...');
await client.publishAsync(
'global',
'Hello everyone!',
{ qos: 2 }
);
console.log('Published to "global" topic');
// Publish to a user topic
console.log('Publishing to "users/testUser/sensor1" topic...');
await client.publishAsync(
'users/testUser/sensor1',
'123',
{ qos: 2 }
);
console.log('Published to "users/testUser/sensor1" topic');
// Note: we can publish to a topic without "write" rights. MQTT will ignore the message without informing us.
})().catch(error => {
console.error('');
console.error('🐞 An error occurred!');
console.error(error);
process.exit(1);
});