-
-
Notifications
You must be signed in to change notification settings - Fork 124
/
mqtt-advanced.ino
65 lines (48 loc) · 1.73 KB
/
mqtt-advanced.ino
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
#include <Ethernet.h>
#include <ArduinoHA.h>
#define BROKER_ADDR IPAddress(192,168,0,17)
byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};
EthernetClient client;
HADevice device(mac, sizeof(mac));
HAMqtt mqtt(client, device);
void onMqttMessage(const char* topic, const uint8_t* payload, uint16_t length) {
// This callback is called when message from MQTT broker is received.
// Please note that you should always verify if the message's topic is the one you expect.
// For example: if (memcmp(topic, "myCustomTopic") == 0) { ... }
Serial.print("New message on topic: ");
Serial.println(topic);
Serial.print("Data: ");
Serial.println((const char*)payload);
mqtt.publish("myPublishTopic", "hello");
}
void onMqttConnected() {
Serial.println("Connected to the broker!");
// You can subscribe to custom topic if you need
mqtt.subscribe("myCustomTopic");
}
void onMqttDisconnected() {
Serial.println("Disconnected from the broker!");
}
void onMqttStateChanged(HAMqtt::ConnectionState state) {
Serial.print("MQTT state changed to: ");
Serial.println(static_cast<int8_t>(state));
}
void setup() {
Serial.begin(9600);
Ethernet.begin(mac);
mqtt.onMessage(onMqttMessage);
mqtt.onConnected(onMqttConnected);
mqtt.onDisconnected(onMqttDisconnected);
mqtt.onStateChanged(onMqttStateChanged);
// If you use custom discovery prefix you can change it as following:
// mqtt.setDiscoveryPrefix("customPrefix");
// If you want to change prefix only for non-discovery prefix:
// mqtt.setDataPrefix("data");
// Obtaining state of the MQTT connection:
// mqtt.getState();
mqtt.begin(BROKER_ADDR);
}
void loop() {
Ethernet.maintain();
mqtt.loop();
}