-
Notifications
You must be signed in to change notification settings - Fork 3
/
mqtt.h
73 lines (61 loc) · 2.1 KB
/
mqtt.h
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
71
72
73
#ifndef mqtt_h
#define mqtt_h
/*
* light-duino v2
* MQTT <-> DMX controller with hw switches, based on ESP8266
* See attached Readme.md for details
*
* This is based on the work of Jorgen (aka Juergen Skrotzky, [email protected]), buy him a beer. ;-)
* Rest if not noted otherwise by Peter Froehlich, [email protected] - Munich Maker Lab e.V. (January 2016)
*
* Published under Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)
* You'll find a copy of the licence text in this repo.
*/
#include <WiFiClient.h>
#include <PubSubClient.h>
#include "config.h"
bool mqttNewMessage = false;
String mqttTopic = "";
String mqttPayload = "";
IPAddress server(0, 0, 0, 0);
WiFiClientSecure client; // with TLS
//WiFiClient client; // without TLS
PubSubClient mqttClient(client, server);
// handle received serial data
void publishMQTTMessage(String strTopic, String strMessage, bool bRetain=false) {
// publish mqtt message with given topic
if (bRetain)
mqttClient.publish(MQTT::Publish(strTopic, strMessage).set_retain().set_qos(1));
else
mqttClient.publish(strTopic, strMessage);
DEBUG_PRINT("send MQTT: topic='" + strTopic + "', message='" + strMessage + "', retain=");
DEBUG_PRINTLN(bRetain);
}
void subscribeMQTTTopic(String strTopic) {
mqttClient.subscribe(strTopic);
Serial.println("subscribe MQTT: topic='" + strTopic + "'");
}
bool connectMQTT(String strUser, String strPass, String strHost, uint16_t port = mqtt_port) {
// connect to mqtt broker
mqttClient.set_server(strHost, port);
bool MQTTconnected = false;
int retries = 0;
while(!MQTTconnected && retries < 10) {
retries++;
//String strClientID = String(mqtt_client_id);
if (mqttClient.connect(MQTT::Connect(mqtt_client_id).set_auth(strUser, strPass).set_will(strTopicPrefixID + "controller", "", 1, true))) {
MQTTconnected = true;
}
delay(10);
}
return MQTTconnected;
}
bool processMQTTLoop() {
// handle mqtt messages and wifi connection
if (mqttClient.connected()) {
mqttClient.loop();
return true;
}
return false;
}
#endif //mqtt_h