forked from Brunas/esp32_p1meter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mqtt.ino
48 lines (43 loc) · 1.41 KB
/
mqtt.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
void sendMQTTMessage(const char *topic, const char *payload) {
bool result = mqttClient.publish(topic, payload, false);
}
void makeSureMqttConnected() {
uint _retries = MQTT_MAX_RECONNECT_TRIES;
while (!mqttClient.connected() && _retries > 0) {
if (mqttClient.connect(String(HOSTNAME).c_str(), MQTT_USER, MQTT_PASS)) {
char *message = new char[16 + strlen(HOSTNAME) + 1];
strcpy(message, "p1 meter alive: ");
strcat(message, HOSTNAME);
mqttClient.publish(String(MQTT_STATUS_TOPIC).c_str(), message);
}
else {
debug("MQTT Connection Failed! Retries left: " + String(_retries));
_retries--;
delay(5000);
}
}
if (!mqttClient.connected()) {
blinkLed(20, 200); // Blink moderately fast to indicate failed connection
debug ("Connection to MQTT Failed!");
#ifdef MQTT_RESTART_ON_ERROR
debug ("Rebooting...");
ESP.restart();
#endif
}
}
void sendMetric(String name, String metric) {
String topic = String(MQTT_ROOT_TOPIC) + "/" + name;
#ifdef DEBUG
debug(topic);
#endif
sendMQTTMessage(topic.c_str(), metric.c_str());
}
void sendDataToBroker() {
for (int i = 0; i < telegramObjects.size(); i++) {
if (telegramObjects[i].sendData) {
debug("Sending: " + telegramObjects[i].name + " value: " + telegramObjects[i].value);
sendMetric(telegramObjects[i].name, telegramObjects[i].value);
telegramObjects[i].sendData = false;
}
}
}