mirror of
https://github.com/jomjol/AI-on-the-edge-device.git
synced 2025-12-08 20:46:52 +03:00
Streamlined MQTT interlock when not activated & interlock MQTT when WIFI is not connected (#1556)
* streamlined mqtt interlock when disabled * Disconnect mqtt client before reboot * Interlock MQTT with WIFI * Update * loglevel to DEBUG * Update * mqtt msg id incremental * new ENABLE_MQTT includes * Loglevel to DEBUG * Loglevel * Update interface_mqtt.cpp
This commit is contained in:
@@ -1,8 +1,8 @@
|
||||
#ifdef ENABLE_MQTT
|
||||
#include "interface_mqtt.h"
|
||||
|
||||
//#define LOG_LOCAL_LEVEL ESP_LOG_DEBUG
|
||||
#include "esp_log.h"
|
||||
#include "connect_wlan.h"
|
||||
#include "mqtt_client.h"
|
||||
#include "ClassLogFile.h"
|
||||
#include "server_tflite.h"
|
||||
@@ -18,86 +18,93 @@ std::map<std::string, std::function<bool(std::string, char*, int)>>* subscribeFu
|
||||
|
||||
|
||||
int failedOnRound = -1;
|
||||
|
||||
bool MQTT_Enabled = true;
|
||||
|
||||
esp_mqtt_event_id_t esp_mmqtt_ID = MQTT_EVENT_ANY;
|
||||
esp_mqtt_event_id_t esp_mqtt_ID = MQTT_EVENT_ANY;
|
||||
// ESP_EVENT_ANY_ID
|
||||
|
||||
bool mqtt_enabled = false;
|
||||
bool mqtt_configOK = false;
|
||||
bool mqtt_initialized = false;
|
||||
bool mqtt_connected = false;
|
||||
|
||||
esp_mqtt_client_handle_t client = NULL;
|
||||
std::string uri, client_id, lwt_topic, lwt_connected, lwt_disconnected, user, password, maintopic;
|
||||
int keepalive, SetRetainFlag;
|
||||
void (*callbackOnConnected)(std::string, int) = NULL;
|
||||
|
||||
|
||||
void MQTTdisable()
|
||||
bool MQTTPublish(std::string _key, std::string _content, int retained_flag)
|
||||
{
|
||||
MQTT_Enabled = false;
|
||||
}
|
||||
|
||||
bool MQTTPublish(std::string _key, std::string _content, int retained_flag) {
|
||||
int msg_id;
|
||||
std::string zw;
|
||||
|
||||
if (failedOnRound == getCountFlowRounds()) { // we already failed in this round, do not retry until the next round
|
||||
return true; // Fail quietly
|
||||
if (!mqtt_enabled) { // MQTT sevice not started / configured (MQTT_Init not called before)
|
||||
return false;
|
||||
}
|
||||
|
||||
if (failedOnRound == getCountFlowRounds()) { // we already failed in this round, do not retry until the next round
|
||||
return true; // Fail quietly
|
||||
}
|
||||
|
||||
#ifdef DEBUG_DETAIL_ON
|
||||
LogFile.WriteHeapInfo("MQTT Publish");
|
||||
#endif
|
||||
|
||||
if (!mqtt_initialized) {
|
||||
if (!MQTT_Init()) {
|
||||
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Init failed, skipping all MQTT publishings in this round!");
|
||||
failedOnRound = getCountFlowRounds();
|
||||
return false;
|
||||
MQTT_Init(); // Re-Init client if not initialized yet/anymore
|
||||
|
||||
if (mqtt_initialized && mqtt_connected) {
|
||||
#ifdef DEBUG_DETAIL_ON
|
||||
long long int starttime = esp_timer_get_time();
|
||||
#endif
|
||||
int msg_id = esp_mqtt_client_publish(client, _key.c_str(), _content.c_str(), 0, 1, retained_flag);
|
||||
#ifdef DEBUG_DETAIL_ON
|
||||
ESP_LOGD(TAG, "Publish msg_id %d in %lld ms", msg_id, (esp_timer_get_time() - starttime)/1000);
|
||||
#endif
|
||||
if (msg_id == -1) {
|
||||
LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Failed to publish topic '" + _key + "', re-trying...");
|
||||
#ifdef DEBUG_DETAIL_ON
|
||||
starttime = esp_timer_get_time();
|
||||
#endif
|
||||
msg_id = esp_mqtt_client_publish(client, _key.c_str(), _content.c_str(), 0, 1, retained_flag);
|
||||
#ifdef DEBUG_DETAIL_ON
|
||||
ESP_LOGD(TAG, "Publish msg_id %d in %lld ms", msg_id, (esp_timer_get_time() - starttime)/1000);
|
||||
#endif
|
||||
if (msg_id == -1) {
|
||||
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to publish topic '" + _key + "', skipping all MQTT publishings in this round!");
|
||||
failedOnRound = getCountFlowRounds();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
msg_id = esp_mqtt_client_publish(client, _key.c_str(), _content.c_str(), 0, 1, retained_flag);
|
||||
if (msg_id < 0) {
|
||||
LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Failed to publish topic '" + _key + "', re-trying...");
|
||||
esp_mqtt_client_reconnect(client);
|
||||
|
||||
msg_id = esp_mqtt_client_publish(client, _key.c_str(), _content.c_str(), 0, 1, retained_flag);
|
||||
if (msg_id < 0) {
|
||||
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to publish topic '" + _key + "', skipping all MQTT publishings in this round!");
|
||||
failedOnRound = getCountFlowRounds();
|
||||
return false;
|
||||
if (_content.length() > 80) { // Truncate message if too long
|
||||
_content.resize(80);
|
||||
_content.append("..");
|
||||
}
|
||||
|
||||
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Published topic: " + _key + ", content: " + _content + " (msg_id=" + std::to_string(msg_id) + ")");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (_content.length() > 80) { // Truncate message if too long
|
||||
_content.resize(80);
|
||||
_content.append("..");
|
||||
else {
|
||||
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Publish skipped. Client not initalized or not connected. (topic: " + _key + ")");
|
||||
return false;
|
||||
}
|
||||
|
||||
zw = "Published topic: " + _key + ", content: " + _content + " (msg_id=" + std::to_string(msg_id) + ")";
|
||||
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, zw);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
static esp_err_t mqtt_event_handler_cb(esp_mqtt_event_handle_t event)
|
||||
{
|
||||
static esp_err_t mqtt_event_handler_cb(esp_mqtt_event_handle_t event) {
|
||||
int msg_id;
|
||||
std::string topic = "";
|
||||
switch (event->event_id) {
|
||||
case MQTT_EVENT_BEFORE_CONNECT:
|
||||
ESP_LOGD(TAG, "MQTT_EVENT_BEFORE_CONNECT");
|
||||
mqtt_initialized = true;
|
||||
break;
|
||||
case MQTT_EVENT_CONNECTED:
|
||||
ESP_LOGD(TAG, "MQTT_EVENT_CONNECTED");
|
||||
mqtt_initialized = true;
|
||||
mqtt_connected = true;
|
||||
MQTTconnected();
|
||||
break;
|
||||
case MQTT_EVENT_DISCONNECTED:
|
||||
ESP_LOGD(TAG, "MQTT_EVENT_DISCONNECTED");
|
||||
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Disconnected from broker");
|
||||
mqtt_connected = false;
|
||||
break;
|
||||
case MQTT_EVENT_SUBSCRIBED:
|
||||
@@ -126,8 +133,15 @@ static esp_err_t mqtt_event_handler_cb(esp_mqtt_event_handle_t event)
|
||||
}
|
||||
break;
|
||||
case MQTT_EVENT_ERROR:
|
||||
ESP_LOGD(TAG, "MQTT_EVENT_ERROR");
|
||||
mqtt_initialized = false; // Force re-init on next publish call
|
||||
#ifdef DEBUG_DETAIL_ON
|
||||
ESP_LOGD(TAG, "MQTT_EVENT_ERROR - esp_mqtt_error_codes:");
|
||||
ESP_LOGD(TAG, "error_type:%d", event->error_handle->error_type);
|
||||
ESP_LOGD(TAG, "connect_return_code:%d", event->error_handle->connect_return_code);
|
||||
ESP_LOGD(TAG, "esp_transport_sock_errno:%d", event->error_handle->esp_transport_sock_errno);
|
||||
ESP_LOGD(TAG, "esp_tls_last_esp_err:%d", event->error_handle->esp_tls_last_esp_err);
|
||||
ESP_LOGD(TAG, "esp_tls_stack_err:%d", event->error_handle->esp_tls_stack_err);
|
||||
ESP_LOGD(TAG, "esp_tls_cert_verify_flags:%d", event->error_handle->esp_tls_cert_verify_flags);
|
||||
#endif
|
||||
mqtt_connected = false;
|
||||
break;
|
||||
default:
|
||||
@@ -143,16 +157,14 @@ static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_
|
||||
}
|
||||
|
||||
|
||||
void MQTT_Configure(std::string _mqttURI, std::string _clientid, std::string _user, std::string _password,
|
||||
bool MQTT_Configure(std::string _mqttURI, std::string _clientid, std::string _user, std::string _password,
|
||||
std::string _maintopic, std::string _lwt, std::string _lwt_connected, std::string _lwt_disconnected,
|
||||
int _keepalive, int _SetRetainFlag, void *_callbackOnConnected){
|
||||
#ifdef __HIDE_PASSWORD
|
||||
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "URI: " + _mqttURI + ", clientname: " + _clientid +
|
||||
", user: " + _user + ", password: XXXXXXXX, maintopic: " + _maintopic + ", last-will-topic: " + _maintopic + "/" + _lwt + ", keepAlive: " + std::to_string(_keepalive));
|
||||
#else
|
||||
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "URI: " + _mqttURI + ", clientname: " + _clientid +
|
||||
", user: " + _user + ", password: " + _password + ", maintopic: " + _maintopic + ", last-will-topic: " + _maintopic + "/" + _lwt + ", keepAlive: " + std::to_string(_keepalive));
|
||||
#endif
|
||||
int _keepalive, int _SetRetainFlag, void *_callbackOnConnected) {
|
||||
if ((_mqttURI.length() == 0) || (_maintopic.length() == 0) || (_clientid.length() == 0))
|
||||
{
|
||||
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Init aborted! Config error (URI, MainTopic or ClientID missing)");
|
||||
return false;
|
||||
}
|
||||
|
||||
uri = _mqttURI;
|
||||
client_id = _clientid;
|
||||
@@ -168,42 +180,60 @@ void MQTT_Configure(std::string _mqttURI, std::string _clientid, std::string _us
|
||||
user = _user;
|
||||
password = _password;
|
||||
}
|
||||
|
||||
#ifdef __HIDE_PASSWORD
|
||||
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "URI: " + uri + ", clientname: " + client_id + ", user: " + user + ", password: XXXXXXXX, maintopic: "
|
||||
+ maintopic + ", last-will-topic: " + lwt_topic + ", keepAlive: " + std::to_string(keepalive) + ", RetainFlag: " + std::to_string(SetRetainFlag));
|
||||
#else
|
||||
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "URI: " + uri + ", clientname: " + client_id + ", user: " + user + ", password: " + password + ", maintopic: "
|
||||
+ maintopic + ", last-will-topic: " + lwt_topic + ", keepAlive: " + std::to_string(keepalive) + ", RetainFlag: " + std::to_string(SetRetainFlag));
|
||||
#endif
|
||||
|
||||
mqtt_configOK = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MQTT_Init() {
|
||||
|
||||
if (MQTT_Enabled == false)
|
||||
return false;
|
||||
|
||||
if ((client_id.length() == 0) || (lwt_topic.length() == 0))
|
||||
{
|
||||
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, std::string("Init with no Client_ID (" + client_id + ") or Last Will Topic (" + lwt_topic + "). Abort Init!"));
|
||||
return false;
|
||||
int MQTT_Init() {
|
||||
if (mqtt_initialized) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
esp_err_t ret;
|
||||
LogFile.WriteToFile(ESP_LOG_INFO, TAG, std::string("Init"));
|
||||
|
||||
if (mqtt_configOK) {
|
||||
mqtt_enabled = true;
|
||||
} else {
|
||||
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Init called, but client is not yet configured.");
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (!getWIFIisConnected()) {
|
||||
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Init called, but WIFI is not yet connected.");
|
||||
return 0;
|
||||
}
|
||||
|
||||
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Init");
|
||||
MQTTdestroy_client();
|
||||
|
||||
std::string lw = lwt_disconnected;
|
||||
|
||||
esp_mqtt_client_config_t mqtt_cfg = {
|
||||
.uri = uri.c_str(),
|
||||
.client_id = client_id.c_str(),
|
||||
.lwt_topic = lwt_topic.c_str(),
|
||||
.lwt_msg = lw.c_str(),
|
||||
.lwt_msg = lwt_disconnected.c_str(),
|
||||
.lwt_retain = 1,
|
||||
.lwt_msg_len = (int)(lw.length()),
|
||||
.lwt_msg_len = (int)(lwt_disconnected.length()),
|
||||
.keepalive = keepalive,
|
||||
.disable_auto_reconnect = false, // Reconnection routine active
|
||||
.reconnect_timeout_ms = 10000 // Try to reconnect to broker every 10s
|
||||
.disable_auto_reconnect = false, // Reconnection routine active (Default: false)
|
||||
.buffer_size = 1536, // size of MQTT send/receive buffer (Default: 1024)
|
||||
.reconnect_timeout_ms = 15000, // Try to reconnect to broker (Default: 10000ms)
|
||||
.network_timeout_ms = 20000, // Network Timeout (Default: 10000ms)
|
||||
.message_retransmit_timeout = 3000 // Tiem after message resent when broker not acknowledged (QoS1, QoS2)
|
||||
|
||||
};
|
||||
|
||||
if (user.length() && password.length()){
|
||||
mqtt_cfg.username = user.c_str();
|
||||
mqtt_cfg.password = password.c_str();
|
||||
};
|
||||
}
|
||||
|
||||
#ifdef DEBUG_DETAIL_ON
|
||||
LogFile.WriteHeapInfo("MQTT Client Init");
|
||||
@@ -212,12 +242,12 @@ bool MQTT_Init() {
|
||||
client = esp_mqtt_client_init(&mqtt_cfg);
|
||||
if (client)
|
||||
{
|
||||
ret = esp_mqtt_client_register_event(client, esp_mmqtt_ID, mqtt_event_handler, client);
|
||||
esp_err_t ret = esp_mqtt_client_register_event(client, esp_mqtt_ID, mqtt_event_handler, client);
|
||||
if (ret != ESP_OK)
|
||||
{
|
||||
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Could not register event (ret=" + std::to_string(ret) + ")!");
|
||||
mqtt_initialized = false;
|
||||
return false;
|
||||
return -1;
|
||||
}
|
||||
|
||||
#ifdef DEBUG_DETAIL_ON
|
||||
@@ -226,40 +256,44 @@ bool MQTT_Init() {
|
||||
ret = esp_mqtt_client_start(client);
|
||||
if (ret != ESP_OK)
|
||||
{
|
||||
LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Could not start client (ret=" + std::to_string(ret) + "), retrying...");
|
||||
ret = esp_mqtt_client_start(client);
|
||||
if (ret != ESP_OK)
|
||||
{
|
||||
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Could not start client (ret=" + std::to_string(ret) + ")!");
|
||||
mqtt_initialized = false;
|
||||
return false;
|
||||
}
|
||||
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Client start failed (retval=" + std::to_string(ret) + ")!");
|
||||
mqtt_initialized = false;
|
||||
return -1;
|
||||
}
|
||||
else {
|
||||
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Client started, waiting for established connection...");
|
||||
mqtt_initialized = true;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Init failed, no handle created!");
|
||||
mqtt_initialized = false;
|
||||
return false;
|
||||
return -1;
|
||||
}
|
||||
|
||||
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Client started, waiting for established connection...");
|
||||
mqtt_initialized = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
void MQTTdestroy_client() {
|
||||
if (client) {
|
||||
if (mqtt_connected) {
|
||||
esp_mqtt_client_disconnect(client);
|
||||
mqtt_connected = false;
|
||||
}
|
||||
esp_mqtt_client_stop(client);
|
||||
esp_mqtt_client_destroy(client);
|
||||
client = NULL;
|
||||
mqtt_initialized = false;
|
||||
mqtt_connected = false;
|
||||
}
|
||||
}
|
||||
|
||||
bool MQTTisConnected() {
|
||||
bool getMQTTisEnabled() {
|
||||
return mqtt_enabled;
|
||||
}
|
||||
|
||||
bool getMQTTisConnected() {
|
||||
return mqtt_connected;
|
||||
}
|
||||
|
||||
@@ -347,4 +381,4 @@ void MQTTdestroySubscribeFunction(){
|
||||
subscribeFunktionMap = NULL;
|
||||
}
|
||||
}
|
||||
#endif //ENABLE_MQTT
|
||||
#endif //ENABLE_MQTT
|
||||
|
||||
Reference in New Issue
Block a user