You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

119 lines
3.4 KiB

//-----------------------------------------------------------------------------
// 2022 Ahoy, https://www.mikrocontroller.net/topic/525778
// Creative Commons - http://creativecommons.org/licenses/by-nc-sa/3.0/de/
//-----------------------------------------------------------------------------
2 years ago
#ifndef __MQTT_H__
#define __MQTT_H__
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include "defines.h"
class mqtt {
public:
mqtt() {
mClient = new PubSubClient(mEspClient);
mAddressSet = false;
memset(mAddr, 0, MQTT_ADDR_LEN);
2 years ago
memset(mUser, 0, MQTT_USER_LEN);
memset(mPwd, 0, MQTT_PWD_LEN);
memset(mTopic, 0, MQTT_TOPIC_LEN);
}
~mqtt() { }
2 years ago
void setup(const char *addr, const char *topic, const char *user, const char *pwd, uint16_t port) {
DPRINTLN(DBG_VERBOSE, F("mqtt.h:setup"));
2 years ago
mAddressSet = true;
mClient->setServer(addr, port);
mClient->setBufferSize(MQTT_MAX_PACKET_SIZE);
2 years ago
mPort = port;
snprintf(mAddr, MQTT_ADDR_LEN, "%s", addr);
2 years ago
snprintf(mUser, MQTT_USER_LEN, "%s", user);
snprintf(mPwd, MQTT_PWD_LEN, "%s", pwd);
snprintf(mTopic, MQTT_TOPIC_LEN, "%s", topic);
}
void sendMsg(const char *topic, const char *msg) {
//DPRINTLN(DBG_VERBOSE, F("mqtt.h:sendMsg"));
char top[64];
snprintf(top, 64, "%s/%s", mTopic, topic);
sendMsg2(top, msg, false);
}
2 years ago
void sendMsg2(const char *topic, const char *msg, boolean retained) {
if(mAddressSet) {
2 years ago
if(!mClient->connected())
reconnect();
if(mClient->connected())
mClient->publish(topic, msg, retained);
2 years ago
}
}
bool isConnected(bool doRecon = false) {
//DPRINTLN(DBG_VERBOSE, F("mqtt.h:isConnected"));
2 years ago
if(doRecon)
reconnect();
return mClient->connected();
}
char *getAddr(void) {
//DPRINTLN(DBG_VERBOSE, F("mqtt.h:getAddr"));
return mAddr;
}
2 years ago
char *getUser(void) {
//DPRINTLN(DBG_VERBOSE, F("mqtt.h:getUser"));
2 years ago
return mUser;
}
char *getPwd(void) {
//DPRINTLN(DBG_VERBOSE, F("mqtt.h:getPwd"));
return mPwd;
2 years ago
}
char *getTopic(void) {
//DPRINTLN(DBG_VERBOSE, F("mqtt.h:getTopic"));
2 years ago
return mTopic;
}
uint16_t getPort(void) {
return mPort;
}
2 years ago
void loop() {
//DPRINT(F("m"));
2 years ago
//if(!mClient->connected())
// reconnect();
2 years ago
mClient->loop();
}
private:
void reconnect(void) {
//DPRINTLN(DBG_VERBOSE, F("mqtt.h:reconnect"));
2 years ago
if(!mClient->connected()) {
if(strlen(mAddr) > 0) {
if((strlen(mUser) > 0) && (strlen(mPwd) > 0))
mClient->connect(mAddr, mUser, mPwd);
else
mClient->connect(mAddr);
}
2 years ago
}
}
WiFiClient mEspClient;
PubSubClient *mClient;
bool mAddressSet;
uint16_t mPort;
char mAddr[MQTT_ADDR_LEN];
2 years ago
char mUser[MQTT_USER_LEN];
char mPwd[MQTT_PWD_LEN];
char mTopic[MQTT_TOPIC_LEN];
};
#endif /*__MQTT_H_*/