This repository has been archived by the owner on Oct 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathMQTTPublisher.cpp
106 lines (82 loc) · 2.06 KB
/
MQTTPublisher.cpp
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include "MQTTPublisher.h"
#include "Settings.h"
#pragma once
WiFiClient espClient;
PubSubClient client(espClient);
MQTTPublisher::MQTTPublisher(String identifier)
{
_identifier = identifier;
randomSeed(micros());
logger = Logger("MQTTPublisher");
}
MQTTPublisher::MQTTPublisher() {}
bool MQTTPublisher::reconnect()
{
lastConnectionAttempt = millis();
logger.debug("Attempt connection to server: " + String(MQTT_BROKER));
// Attempt to connect
bool clientConnected;
if (String(MQTT_USER_NAME).length())
{
logger.info("Connecting with credientials");
clientConnected = client.connect(_identifier.c_str(), MQTT_USER_NAME, MQTT_PASSWORD);
}
else
{
logger.info("Connecting without credentials");
clientConnected = client.connect(_identifier.c_str());
}
if (clientConnected)
{
logger.debug("connected");
hasMQTT = true;
// Once connected, publish an announcement...
client.publish(String(_identifier + "/status").c_str(), String("online").c_str());
return true;
}
else
{
logger.warn("failed, rc=" + client.state());
}
return false;
}
void MQTTPublisher::start()
{
if (String(MQTT_BROKER).length() == 0 || MQTT_PORT == 0)
{
logger.warn("disabled. No hostname or port set.");
return; //not configured
}
logger.debug("enabled. Connecting.");
client.setServer(MQTT_BROKER, MQTT_PORT);
client.setKeepAlive(10);
client.setBufferSize(2048);
reconnect();
isStarted = true;
}
void MQTTPublisher::stop()
{
isStarted = false;
}
void MQTTPublisher::handle()
{
if (!isStarted)
return;
if (!client.connected() && millis() - lastConnectionAttempt > RECONNECT_TIMEOUT)
{
hasMQTT = false;
if (!reconnect())
return;
}
}
bool MQTTPublisher::publish(String topic, String msg, bool addIdentifier)
{
if (addIdentifier)
topic = _identifier + "/" + topic;
logger.debug("Publish to: " + topic + ": " + msg);
auto retVal = client.publish(topic.c_str(), msg.c_str(), true);
yield();
if (!retVal)
logger.debug("!error : " + String(client.state()));
return retVal;
}