refactor tyoes + added callbacks
This commit is contained in:
30
src/mqtt.cpp
30
src/mqtt.cpp
@@ -44,7 +44,7 @@ const bool MQTTwrapper::disconnect()
|
||||
return true;
|
||||
}
|
||||
|
||||
const bool MQTTwrapper::subscribe(const topic_t &topic, const action_t action)
|
||||
const bool MQTTwrapper::subscribe(const Topic &topic, const ActionCallback action)
|
||||
{
|
||||
if (m_actionMap.contains(topic))
|
||||
{
|
||||
@@ -61,7 +61,7 @@ const bool MQTTwrapper::subscribe(const topic_t &topic, const action_t action)
|
||||
return false;
|
||||
}
|
||||
|
||||
const bool MQTTwrapper::unsubscribe(const topic_t &topic)
|
||||
const bool MQTTwrapper::unsubscribe(const Topic &topic)
|
||||
{
|
||||
if (!m_actionMap.contains(topic))
|
||||
{
|
||||
@@ -83,7 +83,7 @@ const bool MQTTwrapper::connected()
|
||||
return m_loopHandle != NULL;
|
||||
}
|
||||
|
||||
const bool MQTTwrapper::publish(const topic_t &topic, const ArduinoJson::JsonDocument obj)
|
||||
const bool MQTTwrapper::publish(const Topic &topic, const ArduinoJson::JsonDocument obj)
|
||||
{
|
||||
std::string message;
|
||||
if (!m_client.connected())
|
||||
@@ -99,12 +99,32 @@ const bool MQTTwrapper::publish(const topic_t &topic, const ArduinoJson::JsonDoc
|
||||
if (m_client.publish(topic.c_str(), message.c_str()))
|
||||
{
|
||||
LOG_DEBUG("MQTT published topic [", topic.c_str(), "] - message [", message.c_str(), "]");
|
||||
if (m_onPublish)
|
||||
{
|
||||
m_onPublish(topic, message);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
LOG_ERROR("MQTT failed to publish topic [", topic.c_str(), "] - message [", message.c_str(), "]");
|
||||
return false;
|
||||
}
|
||||
|
||||
void MQTTwrapper::setOnMessageCb(MessageCallback cb)
|
||||
{
|
||||
if (cb)
|
||||
m_onReceive = cb;
|
||||
else
|
||||
LOG_ERROR("MQTT invalid onReceive Callback");
|
||||
}
|
||||
|
||||
void MQTTwrapper::setOnPublishCb(MessageCallback cb)
|
||||
{
|
||||
if (cb)
|
||||
m_onPublish = cb;
|
||||
else
|
||||
LOG_ERROR("MQTT invalid onPublish Callback");
|
||||
}
|
||||
|
||||
void MQTTwrapper::callback(char *topic, uint8_t *payload, unsigned int length)
|
||||
{
|
||||
std::string pl;
|
||||
@@ -120,13 +140,15 @@ void MQTTwrapper::callback(char *topic, uint8_t *payload, unsigned int length)
|
||||
return;
|
||||
}
|
||||
|
||||
void MQTTwrapper::onMessage(const std::string topic, const std::string message)
|
||||
void MQTTwrapper::onMessage(const Topic topic, const Message message)
|
||||
{
|
||||
ArduinoJson::JsonDocument obj;
|
||||
LOG_DEBUG("MQTT received topic [", topic.c_str(), "] - message [", message.c_str(), "]");
|
||||
if (ArduinoJson::deserializeJson(obj, message) == ArduinoJson::DeserializationError::Ok)
|
||||
{
|
||||
m_actionMap[topic](obj);
|
||||
if (m_onReceive)
|
||||
m_onReceive(topic, message);
|
||||
return;
|
||||
}
|
||||
LOG_ERROR("MQTT failed to deserialize message\n", message.c_str());
|
||||
|
||||
Reference in New Issue
Block a user