-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.js
33 lines (27 loc) · 932 Bytes
/
test.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
const mqtt = require('mqtt')
// MQTT connects to Adafruit IO
const client = mqtt.connect('mqtt://io.adafruit.com', {
username: 'thuanlebk473',
password: process.env.AIO_KEY
});
// Optionally publish messages to a topic
client.publish('thuanlebk473/feeds/fan-control', '0');
client.on('connect', function () {
console.log("Connected to MQTT");
// Subscribe to a topic
client.subscribe('thuanlebk473/feeds/fan-control', function (err) {
if (!err) {
console.log("Subscription successful");
} else {
console.error("Subscription failed:", err);
}
});
});
// Handle incoming messages
client.on('message', function (topic, message) {
console.log(`Message received on topic ${topic}: ${message.toString()}`);
});
// Handle errors
client.on('error', function (error) {
console.error("Error from MQTT client:", error);
});