updates
This commit is contained in:
@@ -0,0 +1,104 @@
|
||||
#include <Arduino.h>
|
||||
#include <WiFi.h>
|
||||
#include <PubSubClient.h>
|
||||
|
||||
#include "MqttManager.h"
|
||||
#include "Config.h"
|
||||
|
||||
|
||||
WiFiClient wifiClient;
|
||||
|
||||
PubSubClient mqttClient(wifiClient);
|
||||
|
||||
|
||||
|
||||
void MqttManager::begin()
|
||||
{
|
||||
mqttClient.setServer(
|
||||
Config::MQTT_HOST,
|
||||
Config::MQTT_PORT
|
||||
);
|
||||
|
||||
mqttClient.setCallback(
|
||||
[this](char* topic, byte* payload, unsigned int length)
|
||||
{
|
||||
callback(topic, payload, length);
|
||||
}
|
||||
);
|
||||
|
||||
reconnect();
|
||||
}
|
||||
|
||||
|
||||
|
||||
void MqttManager::loop()
|
||||
{
|
||||
if (!mqttClient.connected())
|
||||
{
|
||||
reconnect();
|
||||
}
|
||||
|
||||
mqttClient.loop();
|
||||
}
|
||||
|
||||
|
||||
|
||||
void MqttManager::reconnect()
|
||||
{
|
||||
Serial.println("MQTT verbinden...");
|
||||
|
||||
while (!mqttClient.connected())
|
||||
{
|
||||
if (mqttClient.connect(Config::MQTT_CLIENT))
|
||||
{
|
||||
Serial.println("MQTT verbunden");
|
||||
|
||||
mqttClient.publish(
|
||||
Config::MQTT_STATUS_TOPIC,
|
||||
"online"
|
||||
);
|
||||
|
||||
mqttClient.subscribe(
|
||||
Config::MQTT_COMMAND_TOPIC
|
||||
);
|
||||
|
||||
_connected = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
Serial.print(".");
|
||||
|
||||
delay(3000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
void MqttManager::callback(
|
||||
char* topic,
|
||||
byte* payload,
|
||||
unsigned int length
|
||||
)
|
||||
{
|
||||
Serial.print("MQTT Nachricht: ");
|
||||
Serial.println(topic);
|
||||
|
||||
Serial.print("Payload: ");
|
||||
|
||||
for (unsigned int i = 0; i < length; i++)
|
||||
{
|
||||
Serial.print(
|
||||
(char)payload[i]
|
||||
);
|
||||
}
|
||||
|
||||
Serial.println();
|
||||
}
|
||||
|
||||
|
||||
|
||||
bool MqttManager::connected()
|
||||
{
|
||||
return mqttClient.connected();
|
||||
}
|
||||
Reference in New Issue
Block a user