refactor tyoes + added callbacks
This commit is contained in:
29
src/mqtt.h
29
src/mqtt.h
@@ -13,12 +13,16 @@
|
||||
#include <mutex>
|
||||
#include <functional>
|
||||
|
||||
typedef std::string topic_t;
|
||||
typedef std::function<void(const ArduinoJson::JsonDocument &)> action_t; // the actions receive a JsonObject containing the received message
|
||||
typedef std::map<topic_t, action_t> action_map_t;
|
||||
|
||||
class MQTTwrapper
|
||||
{
|
||||
public:
|
||||
using Topic = std::string;
|
||||
using Message = std::string;
|
||||
using MessageCallback = std::function<void(const Topic &topic, const Message &message)>;
|
||||
using ActionCallback = std::function<void(const ArduinoJson::JsonDocument &)>; // the actions receive a JsonObject containing the received message
|
||||
using StateChangeCallback = std::function<void(void)>;
|
||||
|
||||
using ActionMap = std::map<Topic, ActionCallback>;
|
||||
|
||||
private:
|
||||
const std::map<int, std::string> stateMap = {
|
||||
@@ -31,8 +35,7 @@ private:
|
||||
{2, "MQTT_CONNECT_BAD_CLIENT_ID"},
|
||||
{3, "MQTT_CONNECT_UNAVAILABLE"},
|
||||
{4, "MQTT_CONNECT_BAD_CREDENTIALS"},
|
||||
{5, "MQTT_CONNECT_UNAUTHORIZED"}
|
||||
};
|
||||
{5, "MQTT_CONNECT_UNAUTHORIZED"}};
|
||||
|
||||
private:
|
||||
static MQTTwrapper *
|
||||
@@ -54,10 +57,13 @@ public:
|
||||
const bool disconnect();
|
||||
const bool connected();
|
||||
|
||||
const bool subscribe(const topic_t &topic, const action_t action);
|
||||
const bool unsubscribe(const topic_t &topic);
|
||||
const bool subscribe(const Topic &topic, const ActionCallback action);
|
||||
const bool unsubscribe(const Topic &topic);
|
||||
|
||||
const bool publish(const topic_t &topic, const ArduinoJson::JsonDocument obj);
|
||||
const bool publish(const Topic &topic, const ArduinoJson::JsonDocument obj);
|
||||
|
||||
void setOnMessageCb(MessageCallback cb);
|
||||
void setOnPublishCb(MessageCallback cb);
|
||||
|
||||
private:
|
||||
static void callback(char *topic, uint8_t *payload, unsigned int length); // C-style callback only to invoke onMessage
|
||||
@@ -68,8 +74,11 @@ private:
|
||||
|
||||
private:
|
||||
const Config &m_config;
|
||||
action_map_t m_actionMap;
|
||||
ActionMap m_actionMap;
|
||||
NetworkClient m_tcp;
|
||||
PubSubClient m_client;
|
||||
TaskHandle_t m_loopHandle;
|
||||
|
||||
MessageCallback m_onPublish;
|
||||
MessageCallback m_onReceive;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user