Added MQTT last will and testament

This commit is contained in:
Dirk Jahnke 2020-12-28 17:18:19 +01:00
parent 1d065e580d
commit 83fc1e357f
1 changed files with 13 additions and 2 deletions

View File

@ -40,6 +40,12 @@ IPAddress mqttServerIP(192, 168, 89, 95);
const char *mqttUser = "default";
const char *mqttPassword = "12345678";
const char *lwtTopic = "doorBellGW/LWT";
const char *lwtMessage = "Offline";
const char *onlineMessage = "Online";
const bool lwtRetain = true;
const int lwtQos = 2;
const char *doorBellTopic = "doorBellGW/doorbell";
const char *postboxFlapTopic = "doorBellGW/mailboxFlap";
const char *postboxDoorTopic = "doorBellGW/mailboxDoor";
@ -91,6 +97,11 @@ struct {
};
#define NUM_OUTPUTS (sizeof(myOutputs) / sizeof(myOutputs[0]))
// Forward function declarations:
void reconnect();
void sendMqttMessage(const char *topic, const char *message);
uint8_t getOutputIndexByPin(uint8_t pin) {
for (unsigned int i=0; i<NUM_OUTPUTS; ++i) {
if (myOutputs[i].pin == pin) {
@ -193,9 +204,10 @@ void reconnect() {
while (!mqttClient.connected()) {
Serial.print(F("Attempting MQTT connection..."));
// Attempt to connect
if (mqttClient.connect("doorBellGateway", mqttUser, mqttPassword)) {
if (mqttClient.connect("doorBellGateway", mqttUser, mqttPassword, lwtTopic, lwtQos, lwtRetain, lwtMessage)) {
Serial.println(F("connected"));
// Once connected, publish an announcement...
mqttClient.publish_P(lwtTopic, onlineMessage, lwtRetain);
// mqttClient.publish("hello","hello world");
// ... and resubscribe
Serial.println(F("MQTT subscribe doorbell"));
@ -208,7 +220,6 @@ void reconnect() {
Serial.println(F("ERROR: Failed to subscribe"));
}
}
} else {
Serial.print(F("failed, rc="));
Serial.print(mqttClient.state());