From fcffa95dcaa43136cf1060ed9bbc40737a0adcf0 Mon Sep 17 00:00:00 2001 From: root Date: Sat, 1 Oct 2022 20:38:06 +0200 Subject: [PATCH] BL0937 - implemented energy counter. TODO: save to flash. http server - buffer size change, added MQTT status information. MQTT - connect event counter for debug purpose. MQTT - debug outputs. MQTT - ERR-ISCONN result bug fix. MQTT - Wifi connection check added. MQTT - connect/reconnect patch Formatting changes. Reading code was sometimes hard. bug fix new device. bug fix http server --- src/driver/drv_bl_shared.c | 70 +++++++++--- src/hal/bk7231/hal_wifi_bk7231.c | 40 ++++--- src/httpserver/http_fns.c | 6 +- src/httpserver/http_tcp_server.c | 2 +- src/mqtt/new_mqtt.c | 188 ++++++++++++++++++++++--------- src/mqtt/new_mqtt.h | 1 + src/new_builtin_devices.c | 1 + src/new_common.h | 1 + src/obk_config.h | 4 +- src/user_main.c | 128 ++++++++++++++------- 10 files changed, 310 insertions(+), 131 deletions(-) diff --git a/src/driver/drv_bl_shared.c b/src/driver/drv_bl_shared.c index 45e663232..627aedd3c 100644 --- a/src/driver/drv_bl_shared.c +++ b/src/driver/drv_bl_shared.c @@ -25,8 +25,13 @@ float lastReadings[OBK_NUM_MEASUREMENTS]; // // what are the last values we sent over the MQTT? float lastSentValues[OBK_NUM_MEASUREMENTS]; +float energyCounter = 0.0f; +portTickType energyCounterStamp; + // how much update frames has passed without sending MQTT update of read values? int noChangeFrames[OBK_NUM_MEASUREMENTS]; +int noChangeFrameEnergyCounter; + // how much of value have to change in order to be send over MQTT again? int changeSendThresholds[OBK_NUM_MEASUREMENTS] = { 0.25f, // voltage - OBK_VOLTAGE @@ -40,7 +45,7 @@ const char *mqttNames[OBK_NUM_MEASUREMENTS] = { "power" }; -int changeSendAlwaysFrames = 60; +int changeSendAlwaysFrames = 5; // 60; void BL09XX_AppendInformationToHTTPIndexPage(http_request_t *request) { char tmp[128]; @@ -59,23 +64,37 @@ void BL09XX_AppendInformationToHTTPIndexPage(http_request_t *request) { hprintf128(request,tmp); } -void BL_ProcessUpdate(float voltage, float current, float power) { - int i; -// those are final values, like 230V +void BL_ProcessUpdate(float voltage, float current, float power) +{ + int i; + float energy; + int xPassedTicks; + + // those are final values, like 230V lastReadings[OBK_POWER] = power; lastReadings[OBK_VOLTAGE] = voltage; lastReadings[OBK_CURRENT] = current; + + xPassedTicks = (int)(xTaskGetTickCount() - energyCounterStamp); + if (xPassedTicks <= 0) + xPassedTicks = 1; + energy = (float)xPassedTicks; + energy *= power; + energy /= (3600000.0f / (float)portTICK_PERIOD_MS); - for(i = 0; i < OBK_NUM_MEASUREMENTS; i++) { + energyCounter += energy; + energyCounterStamp = xTaskGetTickCount(); + + for(i = 0; i < OBK_NUM_MEASUREMENTS; i++) + { // send update only if there was a big change or if certain time has passed - if( - (abs(lastSentValues[i]-lastReadings[i]) > changeSendThresholds[i]) - || - noChangeFrames[i] > changeSendAlwaysFrames - ){ + if ( (abs(lastSentValues[i]-lastReadings[i]) > changeSendThresholds[i]) || + (noChangeFrames[i] > changeSendAlwaysFrames) ) + { noChangeFrames[i] = 0; - if(i == OBK_CURRENT) { + if(i == OBK_CURRENT) + { int prev_mA, now_mA; prev_mA = lastSentValues[i] * 1000; now_mA = lastReadings[i] * 1000; @@ -91,22 +110,37 @@ void BL_ProcessUpdate(float voltage, float current, float power) { noChangeFrames[i]++; stat_updatesSkipped++; } - } -} -void BL_Shared_Init() { + } + if ( (energy > 0.0f) || + (noChangeFrameEnergyCounter > changeSendAlwaysFrames) ) + { + MQTT_PublishMain_StringFloat("energycounter", energyCounter); + noChangeFrameEnergyCounter = 0; + stat_updatesSent++; + } else { + noChangeFrameEnergyCounter++; + stat_updatesSkipped++; + } +} + +void BL_Shared_Init() +{ int i; - for(i = 0; i < OBK_NUM_MEASUREMENTS; i++) { + for(i = 0; i < OBK_NUM_MEASUREMENTS; i++) + { noChangeFrames[i] = 0; lastReadings[i] = 0; } + noChangeFrameEnergyCounter = 0; + energyCounterStamp = xTaskGetTickCount(); } + // OBK_POWER etc -float DRV_GetReading(int type) { +float DRV_GetReading(int type) +{ return lastReadings[type]; } - - diff --git a/src/hal/bk7231/hal_wifi_bk7231.c b/src/hal/bk7231/hal_wifi_bk7231.c index ba88bf733..3de3693be 100644 --- a/src/hal/bk7231/hal_wifi_bk7231.c +++ b/src/hal/bk7231/hal_wifi_bk7231.c @@ -40,7 +40,9 @@ const char *HAL_GetMyIPString(){ void getMAC(unsigned char *mac){ net_get_if_macaddr(mac, net_get_sta_handle()); } -int WiFI_SetMacAddress(char *mac) { + +int WiFI_SetMacAddress(char *mac) +{ #if WINDOWS return 0; #elif PLATFORM_BL602 @@ -54,17 +56,21 @@ int WiFI_SetMacAddress(char *mac) { #endif } -void WiFI_GetMacAddress(char *mac) { +void WiFI_GetMacAddress(char *mac) +{ wifi_get_mac_address((char *)mac, CONFIG_ROLE_STA); } -const char *HAL_GetMACStr(char *macstr){ + +const char *HAL_GetMACStr(char *macstr) +{ unsigned char mac[6]; getMAC(mac); sprintf(macstr, MACSTR, MAC2STR(mac)); return macstr; } -void HAL_PrintNetworkInfo(){ +void HAL_PrintNetworkInfo() +{ IPStatusTypedef ipStatus; os_memset(&ipStatus, 0x0, sizeof(IPStatusTypedef)); @@ -160,7 +166,8 @@ void HAL_PrintNetworkInfo(){ } -int HAL_GetWifiStrength() { +int HAL_GetWifiStrength() +{ LinkStatusTypeDef linkStatus; os_memset(&linkStatus, 0x0, sizeof(LinkStatusTypeDef)); bk_wlan_get_link_status(&linkStatus); @@ -169,7 +176,8 @@ int HAL_GetWifiStrength() { // receives status change notifications about wireless - could be useful // ctxt is pointer to a rw_evt_type -void wl_status( void *ctxt ){ +void wl_status( void *ctxt ) +{ rw_evt_type stat = *((rw_evt_type*)ctxt); ADDLOGF_INFO("wl_status %d\r\n", stat); @@ -227,11 +235,13 @@ void wl_status( void *ctxt ){ void bk_wlan_status_register_cb(FUNC_1PARAM_PTR cb); -void HAL_WiFi_SetupStatusCallback(void (*cb)(int code)) { +void HAL_WiFi_SetupStatusCallback(void (*cb)(int code)) +{ g_wifiStatusCallback = cb; bk_wlan_status_register_cb(wl_status); } + void HAL_ConnectToWiFi(const char *oob_ssid,const char *connect_key) { g_bOpenAccessPointMode = 0; @@ -303,14 +313,16 @@ int HAL_SetupWiFiOpenAccessPoint(const char *ssid) wNetConfig.dhcp_mode = DHCP_SERVER; wNetConfig.wifi_retry_interval = 100; - if(1) { + if(1) + { ADDLOGF_INFO("set ip info: %s,%s,%s\r\n", wNetConfig.local_ip_addr, wNetConfig.net_mask, wNetConfig.dns_server_ip_addr); } - if(1) { + if(1) + { ADDLOGF_INFO("ssid:%s key:%s mode:%d\r\n", wNetConfig.wifi_ssid, wNetConfig.wifi_key, wNetConfig.wifi_mode); } //{ @@ -319,10 +331,10 @@ int HAL_SetupWiFiOpenAccessPoint(const char *ssid) // os_memset(&ipStatus, 0x0, sizeof(IPStatusTypedef)); // bk_wlan_get_ip_status(&ipStatus, STATION); // ipStatus.dhcp = 1; - // os_strcpy((char *)ipStatus.ip, APP_DRONE_DEF_NET_IP); - // os_strcpy((char *)ipStatus.mask, APP_DRONE_DEF_NET_MASK); - // os_strcpy((char *)ipStatus.gate, APP_DRONE_DEF_NET_GW); - // os_strcpy((char *)ipStatus.dns, APP_DRONE_DEF_NET_IP); + // os_strcpy((char *)ipStatus.ip, APP_DRONE_DEF_NET_IP); + // os_strcpy((char *)ipStatus.mask, APP_DRONE_DEF_NET_MASK); + // os_strcpy((char *)ipStatus.gate, APP_DRONE_DEF_NET_GW); + // os_strcpy((char *)ipStatus.dns, APP_DRONE_DEF_NET_IP); // bk_wlan_set_ip_status(&ipStatus, STATION); //} @@ -332,6 +344,6 @@ int HAL_SetupWiFiOpenAccessPoint(const char *ssid) //dhcp_server_start(0); //dhcp_server_stop(void); - return 0; + return 0; } diff --git a/src/httpserver/http_fns.c b/src/httpserver/http_fns.c index ec87ba0b9..56d1c1713 100644 --- a/src/httpserver/http_fns.c +++ b/src/httpserver/http_fns.c @@ -15,6 +15,7 @@ #include "../devicegroups/deviceGroups_public.h" #include "../mqtt/new_mqtt.h" #include "hass.h" +#include "../cJSON/cJSON.h" #ifdef WINDOWS // nothing @@ -526,6 +527,7 @@ int http_fn_index(http_request_t *request) { hprintf128(request,"
Ping watchdog - %i lost, %i ok!
", PingWatchDog_GetTotalLost(),PingWatchDog_GetTotalReceived()); + hprintf128(request,"
MQTT State: %s
", (Main_HasMQTTConnected()==1)?"connected":"disconnected"); // for normal page loads, show the rest of the HTML if(!http_getArg(request->url,"state",tmpA,sizeof(tmpA))) { @@ -1232,7 +1234,9 @@ int http_fn_ha_discovery(http_request_t *request) { sprintf(topic, "homeassistant"); //default discovery topic is `homeassistant` } - cJSON_Hooks hooks = {os_malloc, os_free}; + struct cJSON_Hooks hooks; + hooks.malloc_fn = os_malloc; + hooks.free_fn = os_free; cJSON_InitHooks(&hooks); if(relayCount > 0) { diff --git a/src/httpserver/http_tcp_server.c b/src/httpserver/http_tcp_server.c index e55c81b89..2c7aeb567 100644 --- a/src/httpserver/http_tcp_server.c +++ b/src/httpserver/http_tcp_server.c @@ -7,7 +7,7 @@ #include "new_http.h" #define HTTP_SERVER_PORT 80 -#define REPLY_BUFFER_SIZE 1000 +#define REPLY_BUFFER_SIZE 2048 #define INCOMING_BUFFER_SIZE 1024 diff --git a/src/mqtt/new_mqtt.c b/src/mqtt/new_mqtt.c index f0945ec70..547bf8b36 100644 --- a/src/mqtt/new_mqtt.c +++ b/src/mqtt/new_mqtt.c @@ -57,6 +57,7 @@ ip_addr_t mqtt_ip LWIP_MQTT_EXAMPLE_IPADDR_INIT; mqtt_client_t* mqtt_client; static int g_timeSinceLastMQTTPublish = 0; static int mqtt_initialised = 0; +static int mqtt_connect_events = 0; typedef struct mqtt_callback_tag { char *topic; @@ -119,25 +120,27 @@ static bool MQTT_Mutex_Take(int del) { } return false; } -static void MQTT_Mutex_Free() { +static void MQTT_Mutex_Free() +{ xSemaphoreGive( g_mutex ); } -void MQTT_PublishWholeDeviceState() { - g_bPublishAllStatesNow = 1; - +void MQTT_PublishWholeDeviceState() +{ + g_bPublishAllStatesNow = 1; //Publish all status items once. Publish only dynamic items after that. g_publishItemIndex = g_firstFullBroadcast == true ? PUBLISHITEM_ALL_INDEX_FIRST:PUBLISHITEM_DYNAMIC_INDEX_FIRST; } -void MQTT_PublishOnlyDeviceChannelsIfPossible() { - if(g_bPublishAllStatesNow == 1) - return; - g_bPublishAllStatesNow = 1; - +void MQTT_PublishOnlyDeviceChannelsIfPossible() +{ + if(g_bPublishAllStatesNow == 1) + return; + g_bPublishAllStatesNow = 1; //Start with channels g_publishItemIndex = 0; } + static struct mqtt_connect_client_info_t mqtt_client_info = { "test", @@ -159,7 +162,49 @@ int channelSet(mqtt_request_t* request); static void MQTT_do_connect(mqtt_client_t *client); static void mqtt_connection_cb(mqtt_client_t *client, void *arg, mqtt_connection_status_t status); +int MQTT_GetConnectEvents(void) +{ + return mqtt_connect_events; +} +static const char *get_error_name(int err) +{ + switch(err) + { + case ERR_MEM: return "ERR_MEM"; + /** Buffer error. */ + case ERR_BUF: return "ERR_BUF"; + /** Timeout. */ + case ERR_TIMEOUT: return "ERR_TIMEOUT"; + /** Routing problem. */ + case ERR_RTE: return "ERR_RTE"; + /** Operation in progress */ + case ERR_INPROGRESS: return "ERR_INPROGRESS"; + /** Illegal value. */ + case ERR_VAL: return "ERR_VAL"; + /** Operation would block. */ + case ERR_WOULDBLOCK: return "ERR_WOULDBLOCK"; + /** Address in use. */ + case ERR_USE: return "ERR_USE"; + /** Already connecting. */ + case ERR_ALREADY: return "ERR_ALREADY"; + /** Conn already established.*/ + case ERR_ISCONN: return "ERR_ISCONN"; + /** Not connected. */ + case ERR_CONN: return "ERR_CONN"; + /** Low-level netif error */ + case ERR_IF: return "ERR_IF"; + /** Connection aborted. */ + case ERR_ABRT: return "ERR_ABRT"; + /** Connection reset. */ + case ERR_RST: return "ERR_RST"; + /** Connection closed. */ + case ERR_CLSD: return "ERR_CLSD"; + /** Illegal argument. */ + case ERR_ARG: return "ERR_ARG"; + } + return ""; +} // this can REPLACE callbacks, since we MAY wish to change the root topic.... // in which case we would re-resigster all callbacks? int MQTT_RegisterCallback( const char *basetopic, const char *subscriptiontopic, int ID, mqtt_callback_fn callback){ @@ -389,8 +434,9 @@ static void MQTT_disconnect(mqtt_client_t *client) /* Called when publish is complete either with sucess or failure */ static void mqtt_pub_request_cb(void *arg, err_t result) { - if(result != ERR_OK) { - addLogAdv(LOG_INFO,LOG_FEATURE_MQTT,"Publish result: %d\n", result); + if(result != ERR_OK) + { + addLogAdv(LOG_INFO,LOG_FEATURE_MQTT,"Publish result: %d(%s)\n", result, get_error_name(result)); } } @@ -435,6 +481,8 @@ static OBK_Publish_Result MQTT_PublishTopicToClient(mqtt_client_t *client, const char *pub_topic = (char *)os_malloc(strlen(sTopic) + 1 + strlen(sChannel) + 5 + 1); //5 for /get sprintf(pub_topic, "%s/%s%s", sTopic, sChannel, (appendGet == true ? "/get" : "")); addLogAdv(LOG_INFO,LOG_FEATURE_MQTT,"Publishing to %s retain=%i",pub_topic, retain); + addLogAdv(LOG_INFO,LOG_FEATURE_MQTT,"Published '%s' \n", sVal); + err = mqtt_publish(client, pub_topic, sVal, strlen(sVal), qos, retain, mqtt_pub_request_cb, 0); os_free(pub_topic); @@ -550,7 +598,8 @@ static void mqtt_connection_cb(mqtt_client_t *client, void *arg, mqtt_connection // addLogAdv(LOG_INFO,LOG_FEATURE_MQTT,"MQTT client < removed name > connection cb: status %d\n", (int)status); // addLogAdv(LOG_INFO,LOG_FEATURE_MQTT,"MQTT client \"%s\" connection cb: status %d\n", client_info->client_id, (int)status); - if (status == MQTT_CONNECT_ACCEPTED) { + if (status == MQTT_CONNECT_ACCEPTED) + { addLogAdv(LOG_INFO,LOG_FEATURE_MQTT,"mqtt_connection_cb: Successfully connected\n"); mqtt_set_inpub_callback(mqtt_client, @@ -669,15 +718,21 @@ static void MQTT_do_connect(mqtt_client_t *client) to establish a connection with the server. For now MQTT version 3.1.1 is always used */ - res = mqtt_client_connect(mqtt_client, + res = mqtt_client_connect(mqtt_client, &mqtt_ip, mqtt_port, mqtt_connection_cb, LWIP_CONST_CAST(void*, &mqtt_client_info), &mqtt_client_info); - if(res != ERR_OK) { + if(res != ERR_OK) + { addLogAdv(LOG_INFO,LOG_FEATURE_MQTT,"Connect error in mqtt_client_connect - code: %d\n", res); - + if (res == ERR_ISCONN) + { + if (mqtt_client != 0) + { + mqtt_disconnect(mqtt_client); + } + } } - } else { addLogAdv(LOG_INFO,LOG_FEATURE_MQTT,"mqtt_host %s not found by gethostbyname\r\n", mqtt_host); } @@ -752,34 +807,38 @@ OBK_Publish_Result MQTT_PublishCommand(const void *context, const char *cmd, con } // initialise things MQTT // called from user_main -void MQTT_init(){ - char cbtopicbase[64]; - char cbtopicsub[64]; +void MQTT_init() +{ + char cbtopicbase[64]; + char cbtopicsub[64]; const char *clientId; - clientId = CFG_GetMQTTClientId(); + + clientId = CFG_GetMQTTClientId(); // register the main set channel callback - sprintf(cbtopicbase,"%s/",clientId); + sprintf(cbtopicbase,"%s/",clientId); sprintf(cbtopicsub,"%s/+/set",clientId); // note: this may REPLACE an existing entry with the same ID. ID 1 !!! MQTT_RegisterCallback( cbtopicbase, cbtopicsub, 1, channelSet); // register the TAS cmnd callback - sprintf(cbtopicbase,"cmnd/%s/",clientId); + sprintf(cbtopicbase,"cmnd/%s/",clientId); sprintf(cbtopicsub,"cmnd/%s/+",clientId); // note: this may REPLACE an existing entry with the same ID. ID 2 !!! MQTT_RegisterCallback( cbtopicbase, cbtopicsub, 2, tasCmnd); mqtt_initialised = 1; - CMD_RegisterCommand("publish","",MQTT_PublishCommand, "Sqqq", NULL); - + CMD_RegisterCommand("publish","",MQTT_PublishCommand, "Sqqq", NULL); } -OBK_Publish_Result MQTT_DoItemPublishString(const char *sChannel, const char *valueStr) { +OBK_Publish_Result MQTT_DoItemPublishString(const char *sChannel, const char *valueStr) +{ return MQTT_PublishMain(mqtt_client, sChannel, valueStr, OBK_PUBLISH_FLAG_MUTEX_SILENT, false); } -OBK_Publish_Result MQTT_DoItemPublish(int idx) { + +OBK_Publish_Result MQTT_DoItemPublish(int idx) +{ char dataStr[3*6+1]; //This is sufficient to hold mac value switch(idx) { @@ -852,35 +911,45 @@ OBK_Publish_Result MQTT_DoItemPublish(int idx) { static int g_secondsBeforeNextFullBroadcast = 30; // called from user timer. -int MQTT_RunEverySecondUpdate() { - +int MQTT_RunEverySecondUpdate() +{ if (!mqtt_initialised) return 0; + if (Main_HasWiFiConnected() == 0) + return 0; + // take mutex for connect and disconnect operations - if(MQTT_Mutex_Take(100)==0) { + if(MQTT_Mutex_Take(100)==0) + { return 0; } - // reconnect if went into MQTT library ERR_MEM forever loop - if(g_memoryErrorsThisSession >= 5) { + // reconnect if went into MQTT library ERR_MEM forever loop + if(g_memoryErrorsThisSession >= 5) + { addLogAdv(LOG_INFO,LOG_FEATURE_MQTT, "MQTT will reconnect soon to fix ERR_MEM errors\n"); g_memoryErrorsThisSession = 0; mqtt_reconnect = 5; } + // if asked to reconnect (e.g. change of topic(s)) - if (mqtt_reconnect > 0){ + if (mqtt_reconnect > 0) + { mqtt_reconnect --; - if (mqtt_reconnect == 0){ + if (mqtt_reconnect == 0) + { // then if connected, disconnect, and then it will reconnect automatically in 2s - if (mqtt_client && mqtt_client_is_connected(mqtt_client)) { + if (mqtt_client && mqtt_client_is_connected(mqtt_client)) + { MQTT_disconnect(mqtt_client); loopsWithDisconnected = 8; } } } - if(mqtt_client == 0 || mqtt_client_is_connected(mqtt_client) == 0) { + if(mqtt_client == 0 || mqtt_client_is_connected(mqtt_client) == 0) + { //addLogAdv(LOG_INFO,LOG_FEATURE_MAIN, "Timer discovers disconnected mqtt %i\n",loopsWithDisconnected); loopsWithDisconnected++; if(loopsWithDisconnected > 10) @@ -888,8 +957,11 @@ int MQTT_RunEverySecondUpdate() { if(mqtt_client == 0) { mqtt_client = mqtt_client_new(); - } + } else { + mqtt_client_cleanup(mqtt_client); + } MQTT_do_connect(mqtt_client); + mqtt_connect_events++; loopsWithDisconnected = 0; } MQTT_Mutex_Free(); @@ -905,35 +977,42 @@ int MQTT_RunEverySecondUpdate() { // Do it slowly in order not to overload the buffers // The item indexes start at negative values for special items // and then covers Channel indexes up to CHANNEL_MAX - - //Handle only queued items. Don't need to do this separately if entire state is being published. - if ((g_MqttPublishItemsQueued > 0) && !g_bPublishAllStatesNow){ - PublishQueuedItems(); - return 1; - } - else if(g_bPublishAllStatesNow) { + //Handle only queued items. Don't need to do this separately if entire state is being published. + if ((g_MqttPublishItemsQueued > 0) && !g_bPublishAllStatesNow) + { + PublishQueuedItems(); + return 1; + } + else if(g_bPublishAllStatesNow) + { // Doing step by a step a full publish state - if(g_timeSinceLastMQTTPublish > 2) { + if(g_timeSinceLastMQTTPublish > 2) + { OBK_Publish_Result publishRes; int g_sent_thisFrame = 0; - while(g_publishItemIndex < CHANNEL_MAX) { + while(g_publishItemIndex < CHANNEL_MAX) + { publishRes = MQTT_DoItemPublish(g_publishItemIndex); - if(publishRes != OBK_PUBLISH_WAS_NOT_REQUIRED){ + if(publishRes != OBK_PUBLISH_WAS_NOT_REQUIRED) + { addLogAdv(LOG_INFO,LOG_FEATURE_MQTT, "[g_bPublishAllStatesNow] item %i result %i\n",g_publishItemIndex,publishRes); } // There are several things that can happen now // OBK_PUBLISH_OK - it was required and was published - if(publishRes == OBK_PUBLISH_OK) { + if(publishRes == OBK_PUBLISH_OK) + { g_sent_thisFrame++; - if(g_sent_thisFrame>=1){ + if(g_sent_thisFrame>=1) + { g_publishItemIndex++; break; } } // OBK_PUBLISH_MUTEX_FAIL - MQTT is busy if(publishRes == OBK_PUBLISH_MUTEX_FAIL - || publishRes == OBK_PUBLISH_WAS_DISCONNECTED) { + || publishRes == OBK_PUBLISH_WAS_DISCONNECTED) + { // retry the same later break; } @@ -941,23 +1020,26 @@ int MQTT_RunEverySecondUpdate() { // The item is not used for this device g_publishItemIndex++; } - if(g_publishItemIndex >= CHANNEL_MAX) { + + if(g_publishItemIndex >= CHANNEL_MAX) + { // done g_bPublishAllStatesNow = 0; } } } else { // not doing anything - if(CFG_HasFlag(OBK_FLAG_MQTT_BROADCASTSELFSTATEPERMINUTE)) { + if(CFG_HasFlag(OBK_FLAG_MQTT_BROADCASTSELFSTATEPERMINUTE)) + { // this is called every second g_secondsBeforeNextFullBroadcast--; - if(g_secondsBeforeNextFullBroadcast <= 0) { + if(g_secondsBeforeNextFullBroadcast <= 0) + { g_secondsBeforeNextFullBroadcast = 60; MQTT_PublishWholeDeviceState(); } } } - } return 1; } diff --git a/src/mqtt/new_mqtt.h b/src/mqtt/new_mqtt.h index ac19b0f24..a230c6ac2 100644 --- a/src/mqtt/new_mqtt.h +++ b/src/mqtt/new_mqtt.h @@ -65,6 +65,7 @@ typedef int (*mqtt_callback_fn)(mqtt_request_t *request); // topics must be unique (i.e. you can't have /about and /aboutme or /about/me) // ALL topics currently must start with main device topic root. // ID is unique and non-zero - so that callbacks can be replaced.... +int MQTT_GetConnectEvents(void); int MQTT_RegisterCallback( const char *basetopic, const char *subscriptiontopic, int ID, mqtt_callback_fn callback); int MQTT_RemoveCallback(int ID); diff --git a/src/new_builtin_devices.c b/src/new_builtin_devices.c index 9d702e0ab..a87747f49 100644 --- a/src/new_builtin_devices.c +++ b/src/new_builtin_devices.c @@ -867,3 +867,4 @@ void Setup_Device_Zemismart_Light_Switch_KS_811_3() { CFG_Save_SetupTimer(); } + diff --git a/src/new_common.h b/src/new_common.h index c6a67e249..2715b76a1 100644 --- a/src/new_common.h +++ b/src/new_common.h @@ -277,6 +277,7 @@ int Main_IsOpenAccessPointMode(); void Main_Init(); void Main_OnEverySecond(); int Main_HasMQTTConnected(); +int Main_HasWiFiConnected(); int Main_GetLastRebootBootFailures(); void Main_OnPingCheckerReply(int ms); diff --git a/src/obk_config.h b/src/obk_config.h index 5296e0c7b..c23f63190 100644 --- a/src/obk_config.h +++ b/src/obk_config.h @@ -2,7 +2,7 @@ // specify which parts of the app we wish to be active // #ifndef OBK_CONFIG_H - #define OBK_CONFIG_H +#define OBK_CONFIG_H #if PLATFORM_XR809 ///#define DEBUG_USE_SIMPLE_LOGGER @@ -22,7 +22,7 @@ #else // comment out to remove component - + #undef OBK_DISABLE_ALL_DRIVERS // comment out to remove littlefs #define BK_LITTLEFS diff --git a/src/user_main.c b/src/user_main.c index c919ebe01..a6899bb7a 100644 --- a/src/user_main.c +++ b/src/user_main.c @@ -119,10 +119,11 @@ static void ScheduleDriverStart(const char *name, int delay) { strcpy(scheduledDriverName,name); } -void Main_OnWiFiStatusChange(int code){ +void Main_OnWiFiStatusChange(int code) +{ - - switch(code){ + switch(code) + { case WIFI_STA_CONNECTING: g_bHasWiFiConnected = 0; g_connectToWiFi = 120; @@ -165,19 +166,29 @@ void Main_OnWiFiStatusChange(int code){ } -void CFG_Save_SetupTimer() { +void CFG_Save_SetupTimer() +{ g_saveCfgAfter = 3; } -void Main_OnPingCheckerReply(int ms) { + +void Main_OnPingCheckerReply(int ms) +{ g_timeSinceLastPingReply = 0; } + int g_bBootMarkedOK = 0; - - static int bMQTTconnected = 0; -int Main_HasMQTTConnected(){ + +int Main_HasMQTTConnected() +{ return bMQTTconnected; } + +int Main_HasWiFiConnected() +{ + return g_bHasWiFiConnected; +} + void Main_OnEverySecond() { const char *safe; @@ -191,20 +202,25 @@ void Main_OnEverySecond() // some users say that despite our simple reconnect mechanism // there are some rare cases when devices stuck outside network // That is why we can also reconnect them by basing on ping - if(g_timeSinceLastPingReply != -1 && g_secondsElapsed > 60) { + if(g_timeSinceLastPingReply != -1 && g_secondsElapsed > 60) + { g_timeSinceLastPingReply++; - if(g_timeSinceLastPingReply == CFG_GetPingDisconnectedSecondsToRestart()) { + if(g_timeSinceLastPingReply == CFG_GetPingDisconnectedSecondsToRestart()) + { ADDLOGF_INFO("[Ping watchdog] No ping replies within %i seconds. Will try to reconnect.\n",g_timeSinceLastPingReply); g_bHasWiFiConnected = 0; g_connectToWiFi = 10; } } - if(bSafeMode == 0) { + if(bSafeMode == 0) + { int i; - for(i = 0; i < PLATFORM_GPIO_MAX; i++) { - if(g_cfg.pins.roles[i] == IOR_ADC) { + for(i = 0; i < PLATFORM_GPIO_MAX; i++) + { + if(g_cfg.pins.roles[i] == IOR_ADC) + { int value; value = HAL_ADC_Read(i); @@ -215,9 +231,11 @@ void Main_OnEverySecond() } } - if(scheduledDelay > 0) { + if(scheduledDelay > 0) + { scheduledDelay--; - if(scheduledDelay<=0){ + if(scheduledDelay<=0) + { scheduledDelay = -1; #ifndef OBK_DISABLE_ALL_DRIVERS DRV_StopDriver(scheduledDriverName); @@ -236,22 +254,25 @@ void Main_OnEverySecond() { //int mqtt_max, mqtt_cur, mqtt_mem; //MQTT_GetStats(&mqtt_cur, &mqtt_max, &mqtt_mem); - // ADDLOGF_INFO("mqtt req %i/%i, free mem %i\n", mqtt_cur,mqtt_max,mqtt_mem); - ADDLOGF_INFO("%sTime %i, free %d, MQTT %i, bWifi %i, secondsWithNoPing %i, socks %i/%i\n", - safe, g_secondsElapsed, xPortGetFreeHeapSize(),bMQTTconnected, g_bHasWiFiConnected,g_timeSinceLastPingReply, - LWIP_GetActiveSockets(),LWIP_GetMaxSockets()); + //ADDLOGF_INFO("mqtt req %i/%i, free mem %i\n", mqtt_cur,mqtt_max,mqtt_mem); + ADDLOGF_INFO("%sTime %i, free %d, MQTT %i(%i), bWifi %i, secondsWithNoPing %i, socks %i/%i\n", + safe, g_secondsElapsed, xPortGetFreeHeapSize(),bMQTTconnected, MQTT_GetConnectEvents(), + g_bHasWiFiConnected, g_timeSinceLastPingReply, LWIP_GetActiveSockets(), LWIP_GetMaxSockets()); } // print network info - if (!(g_secondsElapsed % 10)){ + if (!(g_secondsElapsed % 10)) + { HAL_PrintNetworkInfo(); } // when we hit 30s, mark as boot complete. - if(g_bBootMarkedOK==false) { + if(g_bBootMarkedOK==false) + { int bootCompleteSeconds = CFG_GetBootOkSeconds(); - if (g_secondsElapsed > bootCompleteSeconds){ + if (g_secondsElapsed > bootCompleteSeconds) + { ADDLOGF_INFO("Boot complete time reached (%i seconds)\n",bootCompleteSeconds); HAL_FlashVars_SaveBootComplete(); g_bootFailures = HAL_FlashVars_GetBootFailures(); @@ -259,16 +280,21 @@ void Main_OnEverySecond() } } - if (g_openAP){ + if (g_openAP) + { g_openAP--; - if (0 == g_openAP){ + if (0 == g_openAP) + { HAL_SetupWiFiOpenAccessPoint(CFG_GetDeviceName()); g_bOpenAccessPointMode = 1; } } - if(g_startPingWatchDogAfter) { + + if(g_startPingWatchDogAfter) + { g_startPingWatchDogAfter--; - if(0==g_startPingWatchDogAfter) { + if(0==g_startPingWatchDogAfter) + { const char *pingTargetServer; ///int pingInterval; int restartAfterNoPingsSeconds; @@ -279,10 +305,11 @@ void Main_OnEverySecond() //pingInterval = CFG_GetPingIntervalSeconds(); restartAfterNoPingsSeconds = CFG_GetPingDisconnectedSecondsToRestart(); - if(*pingTargetServer /* && pingInterval > 0*/ && restartAfterNoPingsSeconds > 0) { + if(*pingTargetServer /* && pingInterval > 0*/ && restartAfterNoPingsSeconds > 0) + { // mark as enabled g_timeSinceLastPingReply = 0; - // Main_SetupPingWatchDog(pingTargetServer,pingInterval); + //Main_SetupPingWatchDog(pingTargetServer,pingInterval); Main_SetupPingWatchDog(pingTargetServer /*,1*/ ); @@ -292,9 +319,11 @@ void Main_OnEverySecond() } } } - if(g_connectToWiFi){ + if(g_connectToWiFi) + { g_connectToWiFi --; - if(0 == g_connectToWiFi && g_bHasWiFiConnected == 0) { + if(0 == g_connectToWiFi && g_bHasWiFiConnected == 0) + { const char *wifi_ssid, *wifi_pass; g_bOpenAccessPointMode = 0; @@ -337,19 +366,25 @@ void Main_OnEverySecond() void app_on_generic_dbl_click(int btnIndex) { - if(g_secondsElapsed < 5) { + if(g_secondsElapsed < 5) + { CFG_SetOpenAccessPoint(); } } -int Main_IsOpenAccessPointMode() { +int Main_IsOpenAccessPointMode() +{ return g_bOpenAccessPointMode; } -int Main_IsConnectedToWiFi() { + +int Main_IsConnectedToWiFi() +{ return g_bHasWiFiConnected; } -int Main_GetLastRebootBootFailures() { + +int Main_GetLastRebootBootFailures() +{ return g_bootFailures; } @@ -363,7 +398,8 @@ void Main_Init() HAL_FlashVars_IncreaseBootCount(); g_bootFailures = HAL_FlashVars_GetBootFailures(); - if (g_bootFailures > RESTARTS_REQUIRED_FOR_SAFE_MODE){ + if (g_bootFailures > RESTARTS_REQUIRED_FOR_SAFE_MODE) + { bSafeMode = 1; ADDLOGF_INFO("###### safe mode activated - boot failures %d", g_bootFailures); } @@ -382,12 +418,18 @@ void Main_Init() bForceOpenAP = 1; #endif - if(*wifi_ssid == 0 || *wifi_pass == 0 || bSafeMode) { + if((*wifi_ssid == 0) || (*wifi_pass == 0)) + { // start AP mode in 5 seconds g_openAP = 5; //HAL_SetupWiFiOpenAccessPoint(); } else { - g_connectToWiFi = 5; + if (bSafeMode) + { + g_openAP = 5; + } else { + g_connectToWiFi = 5; + } } ADDLOGF_INFO("Using SSID [%s]\r\n",wifi_ssid); @@ -399,8 +441,8 @@ void Main_Init() HTTPServer_Start(); ADDLOGF_DEBUG("Started http tcp server\r\n"); // only initialise certain things if we are not in AP mode - if (!bSafeMode){ - + if (!bSafeMode) + { #ifndef OBK_DISABLE_ALL_DRIVERS DRV_Generic_Init(); #endif @@ -446,12 +488,14 @@ void Main_Init() CMD_Init(); // autostart drivers - if(PIN_FindPinIndexForRole(IOR_SM2135_CLK,-1) != -1 && PIN_FindPinIndexForRole(IOR_SM2135_DAT,-1) != -1) { + if(PIN_FindPinIndexForRole(IOR_SM2135_CLK,-1) != -1 && PIN_FindPinIndexForRole(IOR_SM2135_DAT,-1) != -1) + { #ifndef OBK_DISABLE_ALL_DRIVERS DRV_StartDriver("SM2135"); #endif } - if(PIN_FindPinIndexForRole(IOR_BP5758D_CLK,-1) != -1 && PIN_FindPinIndexForRole(IOR_BP5758D_DAT,-1) != -1) { + if(PIN_FindPinIndexForRole(IOR_BP5758D_CLK,-1) != -1 && PIN_FindPinIndexForRole(IOR_BP5758D_DAT,-1) != -1) + { #ifndef OBK_DISABLE_ALL_DRIVERS DRV_StartDriver("BP5758D"); #endif @@ -478,5 +522,5 @@ void Main_Init() NewLED_RestoreSavedStateIfNeeded(); } - } +