diff --git a/.github/workflows/workflow.yml b/.github/workflows/workflow.yml index 1ab24ae..2759361 100644 --- a/.github/workflows/workflow.yml +++ b/.github/workflows/workflow.yml @@ -52,8 +52,10 @@ jobs: id: get_commit_message run: | currentTag=${GITHUB_REF#refs/tags/} - badgeText="![GitHub Downloads](https://img.shields.io/github/downloads/xyzroe/XZG/$currentTag/total)%0A" - commitMessage=$(git log -1 --pretty=%B | tail -n +3) + badgeText=`![GitHub Downloads](https://img.shields.io/github/downloads/xyzroe/XZG/$currentTag/total} + + ` + commitMessage=$(git log -1 --pretty=%B | tail -n +2) fullCommitMessage="$badgeText$commitMessage" echo "commitMessage<> $GITHUB_ENV echo "$fullCommitMessage" >> $GITHUB_ENV diff --git a/LICENSE b/LICENSE index f288702..5989653 100644 --- a/LICENSE +++ b/LICENSE @@ -178,19 +178,19 @@ makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - No covered work shall be deemed part of an effective technological + No covered work shall be deemed part of an effective technoLOGDcal measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention +circumvention of technoLOGDcal measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of -technological measures. +technoLOGDcal measures. 4. Conveying Verbatim Copies. diff --git a/README.md b/README.md index 0795150..1c28b2c 100644 --- a/README.md +++ b/README.md @@ -71,7 +71,7 @@ Firmware is opensource, so feel free to improve it
by making a commit to th - Change Ethernet/USB adapter mode through firmware or by physical button short press (Red LED On = USB mode, RED LED Off = Ethernet mode); - Adapter mode selector through web-interface: `Zigbee-to-Network` or `Zigbee-to-USB`; - Support mDNS autodiscovery in your network (go in the browser to `xzg.local`), in Zigbee2MQTT (set `port: mdns://xzg`), and in ZHA; -- Secure login through username and password; +- Secure LOGDn through username and password; - Zigbee2MQTT and ZHA config helper; - ESP32 (peripheral) and CC2652P (Zigbee) OTA updates, ESP32 and CC2652P restart; @@ -136,14 +136,14 @@ Special thanks to all third-party library authors. Their work has significantly - [esprfid / esp-rfid](https://github.com/esprfid/esp-rfid), - [fairecasoimeme / zigate-ethernet](https://github.com/fairecasoimeme/ZiGate-Ethernet), - [bblanchon / arduinojson](https://github.com/bblanchon/ArduinoJson), -- [rlogiacco / circularbuffer](https://github.com/rlogiacco/CircularBuffer), +- [rLOGDacco / circularbuffer](https://github.com/rLOGDacco/CircularBuffer), - [sstaub / ticker](https://github.com/sstaub/Ticker), - [vurtun / lib](https://github.com/vurtun/lib), - [Tinkerforge / WireGuard-ESP32-Arduino](https://github.com/Tinkerforge/WireGuard-ESP32-Arduino), - [sstaub / Ticker](https://github.com/sstaub/Ticker), -- [knolleary / PubSubClient](https://github.com/knolleary/pubsubclient), - [Martin-Laclaustra / CronAlarms](https://github.com/Martin-Laclaustra/CronAlarms), -- [xreef / WebServer-Esp8266-ESP32-Tutorial](https://github.com/xreef/WebServer-Esp8266-ESP32-Tutorial) +- [xreef / WebServer-Esp8266-ESP32-Tutorial](https://github.com/xreef/WebServer-Esp8266-ESP32-Tutorial), +- [marvinroger / async-mqtt-client](https://github.com/marvinroger/async-mqtt-client) ## 📄 License diff --git a/bin/XZG_20240415.full.bin b/bin/XZG_20240415.full.bin deleted file mode 100644 index 8fcf129..0000000 Binary files a/bin/XZG_20240415.full.bin and /dev/null differ diff --git a/bin/XZG_20240415.ota.bin b/bin/XZG_20240415.ota.bin deleted file mode 100644 index 1ca3f01..0000000 Binary files a/bin/XZG_20240415.ota.bin and /dev/null differ diff --git a/bin/XZG_20240417.full.bin b/bin/XZG_20240417.full.bin new file mode 100644 index 0000000..c7e4216 Binary files /dev/null and b/bin/XZG_20240417.full.bin differ diff --git a/bin/XZG_20240417.ota.bin b/bin/XZG_20240417.ota.bin new file mode 100644 index 0000000..2dbe2c6 Binary files /dev/null and b/bin/XZG_20240417.ota.bin differ diff --git a/platformio.ini b/platformio.ini index 653131b..aa35429 100644 --- a/platformio.ini +++ b/platformio.ini @@ -29,9 +29,9 @@ lib_deps = bblanchon/ArduinoJson@6.21.3 rlogiacco/CircularBuffer@>=1.4.0 sstaub/Ticker@>=4.4.0 - knolleary/PubSubClient@^2.8 Martin-Laclaustra/CronAlarms husarnet/Husarnet ESP32 @ 1.2.0-5 ;husarnet example + marvinroger/AsyncMqttClient@^0.9.0 ;plerup/EspSoftwareSerial@8.1.0 ;marian-craciunescu/ESP32Ping@>=1.7 ;me-no-dev/ESPAsyncWebServer@1.2.3 diff --git a/src/config.cpp b/src/config.cpp index 4d8e764..673e28c 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -10,7 +10,7 @@ #include "config.h" #include "etc.h" #include "web.h" -#include "keys.h" +#include "const/keys.h" Preferences preferences; @@ -38,23 +38,23 @@ void printNVSFreeSpace() { int total, used; getNvsStats(&total, &used); - LOGI(tag, "Total Entries: %d, Used Entries: %d, Free Entries: %d", total, used, (total - used)); + LOGD("Total Entries: %d, Used Entries: %d, Free Entries: %d", total, used, (total - used)); } void eraseNVS() { - LOGI(tag, "Going to erase NVS. It will factory reset device."); + LOGD("Going to erase NVS. It will factory reset device."); int timeDelay = 3; for (int i = 0; i < timeDelay; i++) { - LOGI(tag, "%d seconds left..", (timeDelay - i)); + LOGD("%d seconds left..", (timeDelay - i)); delay(1000); } - LOGI(tag, "Erasing NVS. It will factory reset device!"); + LOGD("Erasing NVS. It will factory reset device!"); ESP_ERROR_CHECK(nvs_flash_erase()); esp_err_t ret = nvs_flash_init(); ESP_ERROR_CHECK(ret); - LOGI(tag, "Erase complete!"); + LOGD("Erase complete!"); } void initNVS() @@ -62,7 +62,7 @@ void initNVS() esp_err_t ret = nvs_flash_init(); if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { - LOGI(tag, "ESP_ERR_NVS_NO_FREE_PAGES || ESP_ERR_NVS_NEW_VERSION_FOUND . DOWNGRADE and BACKUP CONFIG"); + LOGD("ESP_ERR_NVS_NO_FREE_PAGES || ESP_ERR_NVS_NEW_VERSION_FOUND . DOWNGRADE and BACKUP CONFIG"); while (true) { delay(1); // stop any work @@ -387,15 +387,15 @@ void updateConfiguration(WebServer &serverWeb, SystemConfigStruct &configSys, Ne if (serverWeb.hasArg(nmStartHourKey)) { - LOGI(tag, "nmStartHourKey %s", String(serverWeb.arg(nmStartHourKey))); - //Serial.println(convertTimeToCron(serverWeb.arg(nmStartHourKey))); + LOGD("nmStartHourKey %s", String(serverWeb.arg(nmStartHourKey))); + // Serial.println(convertTimeToCron(serverWeb.arg(nmStartHourKey))); strncpy(configSys.nmStart, serverWeb.arg(nmStartHourKey).c_str(), sizeof(configSys.nmStart) - 1); configSys.nmStart[sizeof(configSys.nmStart) - 1] = '\0'; // Guarantee a null terminator at the end } if (serverWeb.hasArg(nmEndHourKey)) { - LOGI(tag, "nmEndHourKey %s", String(serverWeb.arg(nmEndHourKey))); - //Serial.println(convertTimeToCron(serverWeb.arg(nmEndHourKey))); + LOGD("nmEndHourKey %s", String(serverWeb.arg(nmEndHourKey))); + // Serial.println(convertTimeToCron(serverWeb.arg(nmEndHourKey))); strncpy(configSys.nmEnd, serverWeb.arg(nmEndHourKey).c_str(), sizeof(configSys.nmEnd) - 1); configSys.nmEnd[sizeof(configSys.nmEnd) - 1] = '\0'; // Guarantee a null terminator at the end } @@ -581,6 +581,12 @@ void updateConfiguration(WebServer &serverWeb, SystemConfigStruct &configSys, Ne configMqtt.updateInt = serverWeb.arg(MqttIntervalKey).toInt(); } + const char *mqttReconnectKey = "mqttReconnect"; + if (serverWeb.hasArg(mqttReconnectKey)) + { + configMqtt.reconnectInt = serverWeb.arg(mqttReconnectKey).toInt(); + } + const char *MqttDiscoveryKey = "MqttDiscovery"; configMqtt.discovery = serverWeb.hasArg(MqttDiscoveryKey) == true; @@ -742,7 +748,7 @@ void serializeSysVarsToJson(const SysVarsStruct &vars, JsonObject obj) obj[hwZigbeeIsKey] = vars.hwZigbeeIs; // Assuming WORK_MODE_t can be directly cast to int for serialization - // obj[workModeKey] = static_cast(systemCfg.workMode); + // obj[workModeKey] = static_cast(systemCfg.workMode); // Serializing an array of connectedSocket /*JsonArray connectedSocketArray = obj.createNestedArray(connectedSocket); @@ -828,12 +834,12 @@ bool loadFileConfigHW() if (hwConfig.board[0] != '\0' && strlen(hwConfig.board) > 0) { - LOGI(tag, "LOAD - OK"); + LOGD("LOAD - OK"); return true; } else { - LOGE(tag, "LOAD - ERROR"); + LOGP("LOAD - ERROR"); int searchId = 0; if (config["searchId"]) @@ -843,7 +849,7 @@ bool loadFileConfigHW() BrdConfigStruct *newConfig = findBrdConfig(searchId); if (newConfig) { - LOGI(tag, "Find. Saving config"); + LOGD("Find. Saving config"); DynamicJsonDocument config(512); config[board] = newConfig->board; @@ -864,13 +870,13 @@ bool loadFileConfigHW() config[zbBslPin] = newConfig->zb.bslPin; writeDefaultConfig(configFileHw, config); - LOGI(tag, "Calc and save temp offset"); + LOGD("Calc and save temp offset"); float CPUtemp = getCPUtemp(true); int offset = CPUtemp - 30; systemCfg.tempOffset = int(offset); saveSystemConfig(systemCfg); - LOGI(tag, "Restarting..."); + LOGD("Restarting..."); ESP.restart(); } } @@ -888,18 +894,18 @@ void fileReadError(String tag, DeserializationError error, const char *fileName) File configFile = LittleFS.open(fileName, FILE_READ); if (!configFile) { - LOGE(tag, "Failed to open file: %s", fileName); + LOGP("Failed to open file: %s", fileName); return; } while (configFile.available()) { fileContent += (char)configFile.read(); } - LOGE(tag, "%s - %s - %s", fileName, error.f_str(), fileContent.c_str()); + LOGP("%s - %s - %s", fileName, error.f_str(), fileContent.c_str()); configFile.close(); if (error == DeserializationError::EmptyInput) { - LOGI(tag, "%s %s", fileName, msg_file_rm); + LOGD("%s %s", fileName, msg_file_rm); LittleFS.remove(fileName); } } @@ -911,7 +917,7 @@ bool loadFileSystemVar() File configFile = LittleFS.open(configFileSystem, FILE_READ); if (!configFile) { - LOGI(tag, "%s %s", configFileSystem, msg_open_f); + LOGD("%s %s", configFileSystem, msg_open_f); return false; } @@ -928,7 +934,7 @@ bool loadFileSystemVar() systemCfg.tempOffset = (int)doc[tempOffsetKey]; configFile.close(); - LOGI(tag, "%s %s", configFileSystem, msg_file_rm); + LOGD("%s %s", configFileSystem, msg_file_rm); saveSystemConfig(systemCfg); LittleFS.remove(configFileSystem); return true; @@ -948,7 +954,7 @@ bool loadFileConfigWifi() File configFile = LittleFS.open(configFileWifi, FILE_READ); if (!configFile) { - LOGI(tag, "%s %s", configFileWifi, msg_open_f); + LOGD("%s %s", configFileWifi, msg_open_f); return false; } @@ -971,7 +977,7 @@ bool loadFileConfigWifi() networkCfg.wifiGate.fromString(doc[gw] | ""); configFile.close(); - LOGI(tag, "%s %s", configFileWifi, msg_file_rm); + LOGD("%s %s", configFileWifi, msg_file_rm); saveNetworkConfig(networkCfg); LittleFS.remove(configFileWifi); return true; @@ -989,7 +995,7 @@ bool loadFileConfigEther() File configFile = LittleFS.open(configFileEther, FILE_READ); if (!configFile) { - LOGI(tag, "%s %s", configFileEther, msg_open_f); + LOGD("%s %s", configFileEther, msg_open_f); return false; } @@ -1009,7 +1015,7 @@ bool loadFileConfigEther() networkCfg.ethGate.fromString(doc[gw] | ""); configFile.close(); - LOGI(tag, "%s %s", configFileEther, msg_file_rm); + LOGD("%s %s", configFileEther, msg_file_rm); saveNetworkConfig(networkCfg); LittleFS.remove(configFileEther); return true; @@ -1024,7 +1030,7 @@ bool loadFileConfigGeneral() File configFile = LittleFS.open(configFileGeneral, FILE_READ); if (!configFile) { - LOGI(tag, "%s %s", configFileGeneral, msg_open_f); + LOGD("%s %s", configFileGeneral, msg_open_f); return false; } @@ -1052,9 +1058,9 @@ bool loadFileConfigGeneral() strlcpy(systemCfg.hostname, doc[hostnameKey] | "", sizeof(systemCfg.hostname)); systemCfg.workMode = static_cast((uint8_t)doc[coordMode]); - //systemCfg.prevWorkMode = static_cast((uint8_t)doc[prevCoordMode]); - // DEBUG_PRINT(F("[loadFileConfigGeneral] 'vars.workMode' res is: ")); - // DEBUG_PRINTLN(String(vars.workMode)); + // systemCfg.prevWorkMode = static_cast((uint8_t)doc[prevCoordMode]); + // DEBUG_PRINT(F("[loadFileConfigGeneral] 'vars.workMode' res is: ")); + // DEBUG_PRINTLN(String(vars.workMode)); systemCfg.disableLedPwr = (uint8_t)doc[disableLedPwrKey]; // DEBUG_PRINTLN(F("[loadFileConfigGeneral] disableLedPwr")); @@ -1067,7 +1073,7 @@ bool loadFileConfigGeneral() strlcpy(systemCfg.timeZone, doc[timeZoneKey] | "", sizeof(systemCfg.timeZone)); configFile.close(); - LOGI(tag, "%s %s", configFileGeneral, msg_file_rm); + LOGD("%s %s", configFileGeneral, msg_file_rm); saveSystemConfig(systemCfg); LittleFS.remove(configFileGeneral); return true; @@ -1080,7 +1086,7 @@ bool loadFileConfigSecurity() File configFile = LittleFS.open(configFileSecurity, FILE_READ); if (!configFile) { - LOGI(tag, "%s %s", configFileSecurity, msg_open_f); + LOGD("%s %s", configFileSecurity, msg_open_f); return false; } @@ -1102,7 +1108,7 @@ bool loadFileConfigSecurity() systemCfg.fwIp.fromString(doc[fwIpKey] | "0.0.0.0"); configFile.close(); - LOGI(tag, "%s %s", configFileSecurity, msg_file_rm); + LOGD("%s %s", configFileSecurity, msg_file_rm); saveSystemConfig(systemCfg); LittleFS.remove(configFileSecurity); return true; @@ -1117,7 +1123,7 @@ bool loadFileConfigSerial() File configFile = LittleFS.open(configFileSerial, FILE_READ); if (!configFile) { - LOGI(tag, "%s %s", configFileSerial, msg_open_f); + LOGD("%s %s", configFileSerial, msg_open_f); return false; } @@ -1135,7 +1141,7 @@ bool loadFileConfigSerial() systemCfg.socketPort = (int)doc[portKey]; configFile.close(); - LOGI(tag, "%s %s", configFileSerial, msg_file_rm); + LOGD("%s %s", configFileSerial, msg_file_rm); saveSystemConfig(systemCfg); LittleFS.remove(configFileSerial); return true; @@ -1148,7 +1154,7 @@ bool loadFileConfigMqtt() File configFile = LittleFS.open(configFileMqtt, FILE_READ); if (!configFile) { - LOGI(tag, "%s %s", configFileMqtt, msg_open_f); + LOGD("%s %s", configFileMqtt, msg_open_f); return false; } @@ -1170,9 +1176,10 @@ bool loadFileConfigMqtt() strlcpy(mqttCfg.topic, doc[topicKey] | "", sizeof(mqttCfg.topic)); mqttCfg.updateInt = (int)doc[intervalKey]; mqttCfg.discovery = (int)doc[discoveryKey]; + mqttCfg.reconnectInt = (int)doc[reconnectIntKey]; configFile.close(); - LOGI(tag, "%s %s", configFileMqtt, msg_file_rm); + LOGD("%s %s", configFileMqtt, msg_file_rm); saveMqttConfig(mqttCfg); LittleFS.remove(configFileMqtt); return true; @@ -1191,7 +1198,7 @@ bool loadFileConfigWg() File configFile = LittleFS.open(configFileWg, FILE_READ); if (!configFile) { - LOGI(tag, "%s %s", configFileWg, msg_open_f); + LOGD("%s %s", configFileWg, msg_open_f); return false; } @@ -1215,7 +1222,7 @@ bool loadFileConfigWg() vpnCfg.wgEndPort = (int)doc[endPort]; configFile.close(); - LOGI(tag, "%s %s", configFileWg, msg_file_rm); + LOGD("%s %s", configFileWg, msg_file_rm); saveVpnConfig(vpnCfg); LittleFS.remove(configFileWg); return true; diff --git a/src/config.h b/src/config.h index b89949a..0dc4ce2 100644 --- a/src/config.h +++ b/src/config.h @@ -81,7 +81,7 @@ struct SysVarsStruct bool hwUartSelIs = false; bool hwZigbeeIs = false; - //WORK_MODE_t workMode; // for button // WORK_MODE_t + // WORK_MODE_t workMode; // for button // WORK_MODE_t bool connectedSocket[MAX_SOCKET_CLIENTS]; //[10] int connectedClients; @@ -210,8 +210,8 @@ struct SystemConfigStruct char nmStart[6]; char nmEnd[6]; - //WORK_MODE_t prevWorkMode; // for button // WORK_MODE_t - WORK_MODE_t workMode; // for button // WORK_MODE_t + // WORK_MODE_t prevWorkMode; // for button // WORK_MODE_t + WORK_MODE_t workMode; // for button // WORK_MODE_t }; // Function prototypes for SystemConfigStruct @@ -281,29 +281,47 @@ uint8_t temprature_sens_read(); // #define min(a, b) ((a) < (b) ? (a) : (b)) +// Define log levels +#define LOG_LEVEL_NONE 0 +#define LOG_LEVEL_PROD 1 +#define LOG_LEVEL_DEBUG 2 + #ifdef DEBUG + +// Set the current logging level here +#define CURRENT_LOG_LEVEL LOG_LEVEL_DEBUG + #define DEBUG_PRINT(x) Serial.print(String(x)) #define DEBUG_PRINTLN(x) Serial.println(String(x)) -#define LOGE(tag, format, ...) Serial.printf("[%s] " format " (%s:%d)\n", tag, ##__VA_ARGS__, __FILE__, __LINE__) -#define LOGI(tag, format, ...) Serial.printf("[%s] " format "\n", tag, ##__VA_ARGS__) +#else -/* - LOGE("ZB", "%u - %s", 1, "test"); - LOGI("ZB", "%u - %s", 1, "test"); +// Set the current logging level here +#define CURRENT_LOG_LEVEL LOG_LEVEL_PROD +#define DEBUG_PRINT(x) +#define DEBUG_PRINTLN(x) +#endif - [ZB] 1 - test (src/main.cpp:1374) - [ZB] 1 - test -*/ +#endif + +// Define ANSI color codes +#define ANSI_COLOR_PURPLE "\x1b[35m" +#define ANSI_COLOR_YELLOW "\x1b[33m" +#define ANSI_COLOR_GREEN "\x1b[32m" +#define ANSI_COLOR_RESET "\x1b[0m" +// Conditional logging macros +#if CURRENT_LOG_LEVEL >= LOG_LEVEL_PROD +#define LOGP(format, ...) Serial.printf(ANSI_COLOR_PURPLE "%d " ANSI_COLOR_RESET ANSI_COLOR_YELLOW "[%s] "ANSI_COLOR_RESET ANSI_COLOR_GREEN format ANSI_COLOR_RESET "\n", millis(), __func__, ##__VA_ARGS__) #else -#define DEBUG_PRINT(x) -#define DEBUG_PRINTLN(x) -#define LOGE(f_, ...) -#define LOGI(f_, ...) +#define LOGP(format, ...) // Nothing #endif +#if CURRENT_LOG_LEVEL >= LOG_LEVEL_DEBUG +#define LOGD(format, ...) Serial.printf(ANSI_COLOR_PURPLE "%d " ANSI_COLOR_RESET ANSI_COLOR_YELLOW "[%s] "ANSI_COLOR_RESET format "\n", millis(), __func__, ##__VA_ARGS__) +#else +#define LOGD(format, ...) // Nothing #endif /* ----- Define functions | END -----*/ @@ -329,7 +347,8 @@ struct LEDSettings bool active; }; -struct LEDControl { - LEDSettings modeLED; - LEDSettings powerLED; +struct LEDControl +{ + LEDSettings modeLED; + LEDSettings powerLED; }; diff --git a/src/hw.cpp b/src/const/hw.cpp similarity index 98% rename from src/hw.cpp rename to src/const/hw.cpp index 7f2136e..14815de 100644 --- a/src/hw.cpp +++ b/src/const/hw.cpp @@ -1,4 +1,4 @@ -#include "hw.h" +#include "const/hw.h" BrdConfigStruct brdConfigs[BOARD_CFG_CNT] = { diff --git a/src/hw.h b/src/const/hw.h similarity index 100% rename from src/hw.h rename to src/const/hw.h diff --git a/src/keys.cpp b/src/const/keys.cpp similarity index 96% rename from src/keys.cpp rename to src/const/keys.cpp index fe1bca8..28a0ed7 100644 --- a/src/keys.cpp +++ b/src/const/keys.cpp @@ -1,4 +1,4 @@ -#include "keys.h" +#include "const/keys.h" const char *networkConfigKey = "network-config"; const char *wifiEnblKey = "wifiEnbl"; @@ -40,9 +40,7 @@ const char *topicKey = "topic"; const char *intervalKey = "interval"; const char *updateIntKey = "updateInt"; const char *discoveryKey = "discovery"; -// const char *reconnectTimeKey = "reconnectTime"; const char *reconnectIntKey = "reconnectInt"; -// const char *heartbeatTimeKey = "heartbeatTime"; const char *systemConfigKey = "system-config"; const char *keepWebKey = "keepWeb"; diff --git a/src/keys.h b/src/const/keys.h similarity index 97% rename from src/keys.h rename to src/const/keys.h index 4793e57..2e1da21 100644 --- a/src/keys.h +++ b/src/const/keys.h @@ -40,9 +40,7 @@ extern const char *topicKey; extern const char *intervalKey; extern const char *updateIntKey; extern const char *discoveryKey; -extern const char *reconnectTimeKey; extern const char *reconnectIntKey; -extern const char *heartbeatTimeKey; extern const char *systemConfigKey; extern const char *keepWebKey; extern const char *disableWebKey; diff --git a/src/zones.h b/src/const/zones.h similarity index 100% rename from src/zones.h rename to src/const/zones.h diff --git a/src/etc.cpp b/src/etc.cpp index 08be9e9..2a0aa52 100644 --- a/src/etc.cpp +++ b/src/etc.cpp @@ -13,8 +13,8 @@ #include "web.h" #include "log.h" #include "etc.h" -#include "zones.h" -// #include "hw.h" +#include "const/zones.h" +// #include "const/hw.h" #include "zb.h" #include @@ -283,20 +283,20 @@ void factoryReset() { String tag = "FactoryReset"; - LOGI(tag, "start"); + LOGD("start"); ledControl.powerLED.mode = LED_FLASH_3Hz; ledControl.modeLED.mode = LED_FLASH_3Hz; for (uint8_t i = 0; i < 5; i++) { - LOGI(tag, "%d, sec", 5 - i); + LOGD("%d, sec", 5 - i); delay(1000); } if (!LittleFS.begin(FORMAT_LITTLEFS_IF_FAILED, "/lfs2", 10)) { - LOGI(tag, "Error with LITTLEFS"); + LOGD("Error with LITTLEFS"); } LittleFS.remove(configFileSerial); LittleFS.remove(configFileSecurity); @@ -307,9 +307,9 @@ void factoryReset() LittleFS.remove(configFileWg); LittleFS.remove(configFileHw); LittleFS.remove(configFileMqtt); - LOGI(tag, "FS Done"); + LOGD("FS Done"); eraseNVS(); - LOGI(tag, "NVS Done"); + LOGD("NVS Done"); ledControl.powerLED.mode = LED_OFF; ledControl.modeLED.mode = LED_OFF; @@ -324,7 +324,7 @@ void setClock(void *pvParameters) const time_t targetTime = 946684800; // 946684800 - is 01.01.2000 in timestamp - LOGI(tag, "Waiting for NTP time sync: "); + LOGD("Waiting for NTP time sync: "); unsigned long startTryingTime = millis(); time_t nowSecs = time(nullptr); @@ -342,7 +342,7 @@ void setClock(void *pvParameters) struct tm timeinfo; if (localtime_r(&nowSecs, &timeinfo)) { - LOGI(tag, "Current GMT time: %s", String(asctime(&timeinfo))); + LOGD("Current GMT time: %s", String(asctime(&timeinfo)).c_str()); char *zoneToFind = const_cast("Europe/Kiev"); if (systemCfg.timeZone) @@ -355,20 +355,20 @@ void setClock(void *pvParameters) if (gmtOffset != nullptr) { - LOGI(tag, "GMT Offset for %s is %s", zoneToFind, gmtOffset); + LOGD("GMT Offset for %s is %s", zoneToFind, gmtOffset); timezone = gmtOffset; setTimezone(timezone); } else { - LOGI(tag, "GMT Offset for %s not found.", zoneToFind); + LOGD("GMT Offset for %s not found.", zoneToFind); } setupCron(); } else { - LOGI(tag, "Failed to get time from NTP server."); + LOGD("Failed to get time from NTP server."); } vTaskDelete(NULL); } @@ -377,7 +377,7 @@ void setLedsDisable(bool all) { if (vars.hwLedPwrIs || vars.hwLedUsbIs) { - LOGI("setLedsDisable", "%s", String(all)); + LOGD("setLedsDisable", "%s", String(all)); if (all) { ledControl.powerLED.active = false; @@ -393,13 +393,13 @@ void setLedsDisable(bool all) void nmActivate() { - LOGI("NM", "start"); + LOGD("NM", "start"); setLedsDisable(true); } void nmDeactivate() { - LOGI("NM", "end"); + LOGD("NM", "end"); setLedsDisable(); } @@ -451,8 +451,8 @@ void setupCron() char endCron[30]; strcpy(startCron, convertTimeToCron(String(systemCfg.nmStart))); strcpy(endCron, convertTimeToCron(String(systemCfg.nmEnd))); - LOGI("cron", "NM start %s", startCron); - LOGI("cron", "NM end %s", endCron); + LOGD("cron", "NM start %s", startCron); + LOGD("cron", "NM end %s", endCron); Cron.create(const_cast(startCron), nmActivate, false); Cron.create(const_cast(endCron), nmDeactivate, false); @@ -462,7 +462,7 @@ void setupCron() void setTimezone(String timezone) { String tag = "TZ"; - LOGI(tag, "Setting Timezone"); + LOGD("Setting Timezone"); setenv("TZ", timezone.c_str(), 1); // Now adjust the TZ. Clock settings are adjusted to show the new local time tzset(); time_t nowSecs = time(nullptr); @@ -471,7 +471,7 @@ void setTimezone(String timezone) String timeNow = asctime(&timeinfo); timeNow.remove(timeNow.length() - 1); - LOGI(tag, "Local time: %s", timeNow.c_str()); + LOGD("Local time: %s", timeNow.c_str()); printLogMsg("Local time: " + timeNow); } @@ -544,12 +544,12 @@ BrdConfigStruct *findBrdConfig(int searchId = 0) if (ETH.begin(brdConfigs[i].eth.addr, brdConfigs[i].eth.pwrPin, brdConfigs[i].eth.mdcPin, brdConfigs[i].eth.mdiPin, brdConfigs[i].eth.phyType, brdConfigs[i].eth.clkMode, brdConfigs[i].eth.pwrAltPin)) { - LOGI(tag, "Config found: %s", brdConfigs[i].board); + LOGD("Config found: %s", brdConfigs[i].board); brdOk = true; if (brdConfigs[i].zb.rxPin > 0 && brdConfigs[i].zb.txPin > 0 && brdConfigs[i].zb.rstPin > 0 && brdConfigs[i].zb.bslPin > 0) { - LOGI(tag, "Zigbee pins OK. Try to connect..."); + LOGD("Zigbee pins OK. Try to connect..."); esp_task_wdt_reset(); Serial2.begin(systemCfg.serialSpeed, SERIAL_8N1, brdConfigs[i].zb.rxPin, brdConfigs[i].zb.txPin); // start zigbee serial @@ -557,12 +557,12 @@ BrdConfigStruct *findBrdConfig(int searchId = 0) int BSL_MODE = 0; if (zbInit(brdConfigs[i].zb.rstPin, brdConfigs[i].zb.bslPin, BSL_MODE)) { - LOGI(tag, "Zigbee find - OK"); + LOGD("Zigbee find - OK"); brdOk = true; } else { - LOGE(tag, "Zigbee find - ERROR"); + LOGP("Zigbee find - ERROR"); brdOk = false; } } @@ -573,12 +573,12 @@ BrdConfigStruct *findBrdConfig(int searchId = 0) } else { - LOGE(tag, "Config error with: %s", brdConfigs[i].board); + LOGP("Config error with: %s", brdConfigs[i].board); DynamicJsonDocument config(300); config["searchId"] = i + 1; writeDefaultConfig(configFileHw, config); - LOGI(tag, "Restarting..."); + LOGD("Restarting..."); delay(500); ESP.restart(); @@ -688,14 +688,14 @@ void wgLoop() { if (vars.vpnWgCheckTime <= millis()) { - // LOGI(tag, "check"); + // LOGD("check"); vars.vpnWgCheckTime = millis() + 1000 * checkPeriod; if (wg.is_peer_up(&lwip_ip, &localport)) { vars.vpnWgPeerIp = (lwip_ip.u_addr.ip4.addr); if (!vars.vpnWgConnect) { - LOGI(tag, "Peer with IP %s connect", vars.vpnWgPeerIp.toString().c_str()); + LOGD("Peer with IP %s connect", vars.vpnWgPeerIp.toString().c_str()); } vars.vpnWgConnect = true; } @@ -703,7 +703,7 @@ void wgLoop() { if (vars.vpnWgConnect) { - LOGI(tag, "Peer disconnect"); + LOGD("Peer disconnect"); } vars.vpnWgPeerIp.clear(); vars.vpnWgConnect = false; @@ -735,7 +735,7 @@ void ledTask(void *parameter) // String tag = "ledTask"; while (1) { - // LOGI(tag, "%d | led %s | m %d", millis(), led->name, led->mode); + // LOGD("%d | led %s | m %d", millis(), led->name, led->mode); if (led->pin == -1) continue; if (!led->active) diff --git a/src/etc.h b/src/etc.h index a42f1c5..6977be5 100644 --- a/src/etc.h +++ b/src/etc.h @@ -1,5 +1,5 @@ #include -#include "hw.h" +#include "const/hw.h" void getReadableTime(String &readableTime, unsigned long beginTime); diff --git a/src/main.cpp b/src/main.cpp index c8ecad0..5334383 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -22,7 +22,7 @@ #include "mqtt.h" #include "zb.h" #include "version.h" -// #include "hw.h" +// #include "const/hw.h" #include "esp_system.h" #include "esp_task_wdt.h" @@ -78,21 +78,21 @@ CCTools CCTool(Serial2); void initLan() { + String tag = "initLan"; + LOGD("Some ETH config found. Try to use %s", hwConfig.board); - DEBUG_PRINT(F("Some ETH config found. Try to use ")); - DEBUG_PRINTLN(hwConfig.board); if (ETH.begin(hwConfig.eth.addr, hwConfig.eth.pwrPin, hwConfig.eth.mdcPin, hwConfig.eth.mdiPin, hwConfig.eth.phyType, hwConfig.eth.clkMode, hwConfig.eth.pwrAltPin)) { - DEBUG_PRINTLN(F("LAN start ok")); + LOGD("LAN start ok"); if (!networkCfg.ethDhcp) { - DEBUG_PRINTLN(F("ETH STATIC")); + LOGD("ETH STATIC"); ETH.config(networkCfg.ethIp, networkCfg.ethGate, networkCfg.ethMask, networkCfg.ethDns1, networkCfg.ethDns2); // ConfigSettings.disconnectEthTime = millis(); } else { - DEBUG_PRINTLN(F("ETH DHCP")); + LOGD("ETH DHCP"); } } else @@ -326,18 +326,18 @@ void NetworkEvent(WiFiEvent_t event) switch (event) { case ARDUINO_EVENT_ETH_START: // 18: // SYSTEM_EVENT_ETH_START: - LOGI(ethKey, "Started"); + LOGD("%s Started", ethKey); // DEBUG_PRINTLN(F("ETH Started")); // ConfigSettings.disconnectEthTime = millis(); ETH.setHostname(systemCfg.hostname); break; case ARDUINO_EVENT_ETH_CONNECTED: // 20: // SYSTEM_EVENT_ETH_CONNECTED: // DEBUG_PRINTLN(F("ETH Connected")); - LOGI(ethKey, "Connected"); + LOGD("%s Connected", ethKey); break; case ARDUINO_EVENT_ETH_GOT_IP: // 22: // SYSTEM_EVENT_ETH_GOT_IP: - LOGI(ethKey, "MAC: %s, IP: %s, Mask: %s, Gw: %s, %dMbps", + LOGD("%s MAC: %s, IP: %s, Mask: %s, Gw: %s, %dMbps", ethKey, ETH.macAddress().c_str(), ETH.localIP().toString().c_str(), ETH.subnetMask().toString().c_str(), @@ -351,7 +351,7 @@ void NetworkEvent(WiFiEvent_t event) break; case ARDUINO_EVENT_ETH_DISCONNECTED: // 21: //SYSTEM_EVENT_ETH_DISCONNECTED: // DEBUG_PRINTLN(F("ETH Disconnected")); - LOGI(ethKey, "Disconnected"); + LOGD("%s Disconnected", ethKey); vars.connectedEther = false; // ConfigSettings.disconnectEthTime = millis(); if (tmrNetworkOverseer.state() == STOPPED && systemCfg.workMode == WORK_MODE_NETWORK) @@ -361,7 +361,7 @@ void NetworkEvent(WiFiEvent_t event) break; case SYSTEM_EVENT_ETH_STOP: // 27: case ARDUINO_EVENT_ETH_STOP: - LOGI(ethKey, "Stopped"); + LOGD("%s Stopped", ethKey); // DEBUG_PRINTLN(F("ETH Stopped")); vars.connectedEther = false; // ConfigSettings.disconnectEthTime = millis(); @@ -383,7 +383,7 @@ void NetworkEvent(WiFiEvent_t event) DEBUG_PRINTLN(WiFi.gatewayIP().toString()); */ - LOGI(wifiKey, "MAC: %s, IP: %s, Mask: %s, Gw: %s", + LOGD("%s MAC: %s, IP: %s, Mask: %s, Gw: %s", wifiKey, WiFi.macAddress().c_str(), WiFi.localIP().toString().c_str(), WiFi.subnetMask().toString().c_str(), @@ -392,7 +392,7 @@ void NetworkEvent(WiFiEvent_t event) // setClock(); break; case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: // SYSTEM_EVENT_STA_DISCONNECTED: - LOGI(wifiKey, "STA DISCONNECTED"); + LOGD("%s STA DISCONNECTED", wifiKey); // DEBUG_PRINTLN(F("WIFI ")); if (tmrNetworkOverseer.state() == STOPPED) { @@ -407,7 +407,7 @@ void NetworkEvent(WiFiEvent_t event) void startAP(const bool start) { String tag = "sAP"; - LOGI(tag, "begin s=%d, v=%d", start, vars.apStarted); + LOGD("begin s=%d, v=%d", start, vars.apStarted); if (vars.apStarted) { @@ -432,7 +432,7 @@ void startAP(const bool start) { if (!start) return; - LOGI(tag, "WIFI_AP_STA"); + LOGD("WIFI_AP_STA"); WiFi.mode(WIFI_AP_STA); // WIFI_AP_STA for possible wifi scan in wifi mode WiFi.disconnect(); // String AP_NameString; @@ -455,7 +455,7 @@ void startAP(const bool start) dnsServer.start(53, "*", apIP); WiFi.setSleep(false); // ConfigSettings.wifiAPenblTime = millis(); - LOGI(tag, "startServers()"); + LOGD("startServers()"); startServers(); vars.apStarted = true; } @@ -534,13 +534,13 @@ void mDNS_start() if (!MDNS.begin(systemCfg.hostname)) { String msg = "Error setting up MDNS responder!"; - LOGI(tag, "%s", msg.c_str()); + LOGD("%s", msg.c_str()); // printLogMsg(msg); } else { String msg = "mDNS responder started"; - LOGI(tag, "%s", msg.c_str()); + LOGD("%s", msg.c_str()); // printLogMsg(msg); MDNS.addService(http, tcp, 80); // web //--zeroconf zha-- @@ -551,7 +551,7 @@ void mDNS_start() MDNS.addServiceTxt(host, tcp, "data_flow_control", "software"); MDNS.addServiceTxt(host, tcp, "board", String(hwConfig.board)); // msg = "setup finish"; - // LOGI(tag, "%s", msg); + // LOGD("%s", msg); } } @@ -582,7 +582,7 @@ void handleLongBtn() String tag = "lBTN"; if (!digitalRead(hwConfig.mist.btnPin)) { - LOGI(tag, "press +, %d s", btnFlag); + LOGD("press +, %d s", btnFlag); btnFlag++; if (btnFlag >= 3) @@ -592,7 +592,7 @@ void handleLongBtn() } else { - LOGI(tag, "press -, %d s", btnFlag); + LOGD("press -, %d s", btnFlag); if (btnFlag >= 3) { @@ -624,7 +624,7 @@ void toggleUsbMode() { String tag = "tUSB"; - LOGI(tag, "start"); + LOGD("start"); delay(250); if (systemCfg.workMode != WORK_MODE_USB) { @@ -635,7 +635,7 @@ void toggleUsbMode() systemCfg.workMode = WORK_MODE_NETWORK; } saveSystemConfig(systemCfg); - LOGI(tag, "Change mode to %s", String(systemCfg.workMode)); + LOGD("Change mode to %s", String(systemCfg.workMode)); if (vars.hwLedUsbIs) { @@ -652,7 +652,7 @@ void setupCoordinatorMode() DEBUG_PRINTLN(F("WRONG MODE DETECTED, set to LAN")); systemCfg.workMode = WORK_MODE_NETWORK; } - LOGI("setupCoordinatorMode", "Mode is: %d", systemCfg.workMode); + LOGD("setupCoordinatorMode", "Mode is: %d", systemCfg.workMode); if (systemCfg.workMode != WORK_MODE_USB || systemCfg.keepWeb) { // start network overseer @@ -730,7 +730,7 @@ void setup() loadMqttConfig(mqttCfg); /* - LOGI(tag, "After NVS load config\n"); + LOGD("After NVS load config\n"); delay(500); printConfig(networkCfg, vpnCfg, mqttCfg, systemCfg); */ @@ -738,7 +738,7 @@ void setup() // LOAD System vars and create FS / start if (!LittleFS.begin(FORMAT_LITTLEFS_IF_FAILED, "/lfs2", 10)) { - LOGI(tag, "Error with LITTLEFS"); + LOGD("Error with LITTLEFS"); return; } @@ -767,7 +767,7 @@ void setup() ledControl.modeLED.active = true; ledControl.modeLED.mode = LED_OFF; - LOGI(tag, "%d", ledControl.modeLED.mode); + LOGD("%d", ledControl.modeLED.mode); xTaskCreate(ledTask, "MODE LED Task", 2048, &ledControl.modeLED, 6, NULL); } @@ -782,7 +782,7 @@ void setup() ledControl.powerLED.active = true; ledControl.powerLED.mode = LED_OFF; - LOGI(tag, "%d", ledControl.powerLED.mode); + LOGD("%d", ledControl.powerLED.mode); xTaskCreate(ledTask, "PWR LED Task", 2048, &ledControl.powerLED, 6, NULL); } @@ -848,7 +848,7 @@ void setup() loadFileConfigWg(); // READ file to support migrate from old firmware - LOGI(tag, "After full load config"); + LOGD("After full load config"); // printConfig(networkCfg, vpnCfg, mqttCfg, systemCfg); String cfg = makeJsonConfig(&networkCfg, &vpnCfg, &mqttCfg, &systemCfg, &vars); DEBUG_PRINTLN(cfg); @@ -872,7 +872,7 @@ void setup() printNVSFreeSpace(); /* - LOGI(tag, "Saving config to NVS"); + LOGD("Saving config to NVS"); saveNetworkConfig(networkCfg); saveVpnConfig(vpnCfg); saveMqttConfig(mqttCfg); @@ -1122,7 +1122,7 @@ void loop(void) if (mqttCfg.enable) { - mqttLoop(); + //mqttLoop(); } } if (vpnCfg.wgEnable && vars.vpnWgInit) diff --git a/src/mqtt.cpp b/src/mqtt.cpp index 2d72815..014d65f 100644 --- a/src/mqtt.cpp +++ b/src/mqtt.cpp @@ -5,8 +5,7 @@ #include #include #include -#include -#include +#include #include "config.h" #include "web.h" @@ -14,9 +13,7 @@ #include "etc.h" #include "mqtt.h" -// extern struct ConfigSettingsStruct ConfigSettings; extern struct zbVerStruct zbVer; -// extern struct MqttSettingsStruct MqttSettings; extern struct SystemConfigStruct systemCfg; extern struct NetworkConfigStruct networkCfg; @@ -24,9 +21,9 @@ extern struct MqttConfigStruct mqttCfg; extern struct SysVarsStruct vars; -WiFiClient clientMqtt; - -PubSubClient clientPubSub(clientMqtt); +AsyncMqttClient mqttClient; +TimerHandle_t mqttReconnectTimer; +TimerHandle_t mqttPubStateTimer; String tagMQTT = "MQTT"; @@ -38,243 +35,158 @@ const char *willMessage = "offline"; void mqttConnectSetup() { - LOGI(tagMQTT, "Try to connect %s:%d", mqttCfg.server, mqttCfg.port); - if (strlen(mqttCfg.server) > 0 && mqttCfg.port > 0) + LOGD("mqttConnectSetup"); + + mqttReconnectTimer = xTimerCreate("mqttReconnectTimer", pdMS_TO_TICKS(mqttCfg.reconnectInt * 1000), pdFALSE, (void *)0, reinterpret_cast(connectToMqtt)); + mqttPubStateTimer = xTimerCreate("mqttPubStateTimer", pdMS_TO_TICKS(mqttCfg.updateInt * 1000), pdFALSE, (void *)0, reinterpret_cast(mqttPublishState)); + + if (mqttReconnectTimer == NULL) { - clientPubSub.setServer(mqttCfg.server, mqttCfg.port); // - LOGI(tagMQTT, "Try to setCallback"); - clientPubSub.setCallback(mqttCallback); + LOGD("Failed to create timer"); } else { - LOGE(tagMQTT, "Error in config"); + LOGD("Timer created successfully"); } -} + mqttClient.setServer(mqttCfg.server, mqttCfg.port); + mqttClient.setCredentials(mqttCfg.user, mqttCfg.pass); -bool mqttReconnect() -{ - LOGI(tagMQTT, "Attempting MQTT connection..."); + mqttClient.onConnect(onMqttConnect); + mqttClient.onDisconnect(onMqttDisconnect); - byte willQoS = 0; - String willTopic = String(mqttCfg.topic) + "/avty"; + mqttClient.onMessage(onMqttMessage); - boolean willRetain = false; - //char deviceIdArr[MAX_DEV_ID_LONG]; - //getDeviceID(deviceIdArr); - - if (clientPubSub.connect(vars.deviceId, mqttCfg.user, mqttCfg.pass, willTopic.c_str(), willQoS, willRetain, willMessage)) + if (xTimerStart(mqttReconnectTimer, 0) != pdPASS) { - vars.mqttReconnectTime = 0; - mqttOnConnect(); - LOGI(tagMQTT, "OK, %d", clientPubSub.state()); - return true; + LOGD("Failed to start timer"); } - else - { - LOGI(tagMQTT, "failed, rc= %d try again in %d seconds", clientPubSub.state(), mqttCfg.reconnectInt); +} - return false; - } +void connectToMqtt() +{ + Serial.println("Connecting to MQTT..."); + mqttClient.connect(); } -void mqttOnConnect() +void onMqttConnect(bool sessionPresent) { - //LOGI(tagMQTT, "connected"); - vars.mqttConn = true; - mqttSubscribe("cmd"); - LOGI(tagMQTT, "mqtt Subscribed"); - if (mqttCfg.discovery) - { - mqttPublishDiscovery(); - LOGI(tagMQTT, "mqtt Published Discovery"); - } + LOGD("Connected to MQTT. Session present: %s", String(sessionPresent).c_str()); + + mqttClient.subscribe((String(mqttCfg.topic) + "/cmd").c_str(), 2); + mqttPublishDiscovery(); + mqttPublishIo("rst_esp", "OFF"); mqttPublishIo("rst_zig", "OFF"); mqttPublishIo("enbl_bsl", "OFF"); mqttPublishIo("socket", "OFF"); - LOGI(tagMQTT, "mqtt Published IOs"); + mqttPublishState(); + mqttPublishAvail(); - LOGI(tagMQTT, "mqtt Published Avty"); - if (mqttCfg.updateInt > 0) +} + +void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) +{ + LOGP("Disconnected from MQTT: %d", reason); + xTimerStart(mqttReconnectTimer, 0); +} + +void onMqttMessage(char *topic, char *payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) +{ + String topicStr(topic); + if (topicStr.endsWith("/cmd")) { - mqttPublishState(); - LOGI(tagMQTT, "mqtt Published State"); + char json[len + 1]; + memcpy(json, payload, len); + json[len] = '\0'; + + DynamicJsonDocument doc(512); + deserializeJson(doc, json); + const char *command = doc["cmd"]; + + LOGD("cmd - %s", String(json)); + + if (command) + { + executeCommand(command); + } } } -void mqttPublishMsg(String topic, String msg, bool retain) +void executeCommand(const char *command) { - clientPubSub.beginPublish(topic.c_str(), msg.length(), retain); - clientPubSub.print(msg.c_str()); - clientPubSub.endPublish(); + LOGD("mqtt cmd - %s", String(command)); + if (strcmp(command, "rst_esp") == 0) + { + printLogMsg("ESP restart MQTT"); + ESP.restart(); + } + + if (strcmp(command, "rst_zig") == 0) + { + printLogMsg("Zigbee restart MQTT"); + zigbeeRestart(); + } + + if (strcmp(command, "enbl_bsl") == 0) + { + printLogMsg("Zigbee BSL enable MQTT"); + zigbeeEnableBSL(); + } } void mqttPublishAvail() { - String topic(mqttCfg.topic); - topic = topic + "/avty"; - String mqttBuffer = "online"; - clientPubSub.publish(topic.c_str(), mqttBuffer.c_str(), true); + String topic = String(mqttCfg.topic) + "/avty"; + mqttClient.publish(topic.c_str(), 1, true, "online"); +} + +void mqttPublishIo(const String &io, const String &state) +{ + if (mqttClient.connected()) + { + String topic = String(mqttCfg.topic) + "/io/" + io; + LOGD("Pub Io %s at %s", state.c_str(), topic.c_str()); + mqttClient.publish(topic.c_str(), 0, true, state.c_str()); + } } void mqttPublishState() { - String topic(mqttCfg.topic); - topic = topic + "/state"; + String topic = String(mqttCfg.topic) + "/state"; DynamicJsonDocument root(1024); + String readableTime; getReadableTime(readableTime, 0); root["uptime"] = readableTime; float CPUtemp = getCPUtemp(); root["temperature"] = String(CPUtemp); - root["connections"] = vars.connectedClients; - if (vars.connectedEther) - { - if (networkCfg.ethDhcp) - { - root["ip"] = ETH.localIP().toString(); - } - else - { - root["ip"] = networkCfg.ethIp; - } - } - else - { - if (networkCfg.wifiDhcp) - { - root["ip"] = WiFi.localIP().toString(); - } - else - { - root["ip"] = networkCfg.wifiIp; - } - } - // if (ConfigSettings.emergencyWifi) - //{ - // root["emergencyMode"] = "ON"; - // } - // else - //{ - // root["emergencyMode"] = "OFF"; - // } + String ip = networkCfg.wifiDhcp ? WiFi.localIP().toString() : networkCfg.wifiIp.toString(); + root["ip"] = ip; switch (systemCfg.workMode) { case WORK_MODE_USB: root["mode"] = "Zigbee-to-USB"; break; - /*case COORDINATOR_MODE_WIFI: - root["mode"] = "Zigbee-to-WiFi"; - break;*/ case WORK_MODE_NETWORK: root["mode"] = "Zigbee-to-Network"; break; - default: - break; } + root["zbfw"] = String(zbVer.zbRev); root["hostname"] = systemCfg.hostname; + String mqttBuffer; serializeJson(root, mqttBuffer); - // DEBUG_PRINTLN(mqttBuffer); - clientPubSub.publish(topic.c_str(), mqttBuffer.c_str(), true); - vars.mqttHeartbeatTime = millis() + (mqttCfg.updateInt * 1000); -} -void mqttPublishIo(String const &io, String const &state) -{ - if (clientPubSub.connected()) - { - String topic(mqttCfg.topic); - topic = topic + "/io/" + io; - clientPubSub.publish(topic.c_str(), state.c_str(), true); - } -} - -void mqttCallback(char *topic, byte *payload, unsigned int length) -{ - char jjson[length + 1]; - memcpy(jjson, payload, length); - //jjson[length + 1] = '\0'; - jjson[length] = '\0'; - - DynamicJsonDocument jsonBuffer(512); - - deserializeJson(jsonBuffer, jjson); - - const char *command = jsonBuffer["cmd"]; + mqttClient.publish(topic.c_str(), 0, true, mqttBuffer.c_str()); - LOGI(tagMQTT, "mqtt Callback - %s", String(jjson)); - if (command) - { - LOGI(tagMQTT, "mqtt cmd - %s", String(command)); - if (strcmp(command, "rst_esp") == 0) - { - printLogMsg("ESP restart MQTT"); - ESP.restart(); - } - - if (strcmp(command, "rst_zig") == 0) - { - printLogMsg("Zigbee restart MQTT"); - zigbeeRestart(); - } - - if (strcmp(command, "enbl_bsl") == 0) - { - printLogMsg("Zigbee BSL enable MQTT"); - zigbeeEnableBSL(); - } - } - return; -} - -void mqttSubscribe(String topic) -{ - String mtopic(mqttCfg.topic); - mtopic = mtopic + "/" + topic; - clientPubSub.subscribe(mtopic.c_str()); -} - -void mqttLoop() -{ - if (!clientPubSub.connected()) - { - vars.mqttConn = false; - if (vars.mqttReconnectTime == 0) - { - // mqttReconnect(); - LOGI(tagMQTT, "Connect in %d seconds", mqttCfg.reconnectInt); - vars.mqttReconnectTime = millis() + mqttCfg.reconnectInt*1000; - } - else - { - if (vars.mqttReconnectTime <= millis()) - { - bool conn = mqttReconnect(); - //LOGI(tagMQTT, "mqttReconnect exit with %s", conn ? "true" : "false"); - vars.mqttReconnectTime = millis() + mqttCfg.reconnectInt*1000; - } - } - } - else - { - clientPubSub.loop(); - if (mqttCfg.updateInt > 0) - { - if (vars.mqttHeartbeatTime <= millis()) - { - mqttPublishState(); - } - } - } - // LOGI(tagMQTT, "loop end"); + xTimerStart(mqttPubStateTimer, 0); } void mqttPublishDiscovery() @@ -287,8 +199,8 @@ void mqttPublishDiscovery() String mqttBuffer; DynamicJsonDocument via(150); - //char deviceIdArr[MAX_DEV_ID_LONG]; - //getDeviceID(deviceIdArr); + // char deviceIdArr[MAX_DEV_ID_LONG]; + // getDeviceID(deviceIdArr); via["ids"] = String(vars.deviceId); String sensor_topic = String(homeAssistant) + "/" + String(haSensor) + "/"; @@ -304,8 +216,8 @@ void mqttPublishDiscovery() case 0: { DynamicJsonDocument dev(256); - //char deviceIdArr[MAX_DEV_ID_LONG]; - //getDeviceID(deviceIdArr); + // char deviceIdArr[MAX_DEV_ID_LONG]; + // getDeviceID(deviceIdArr); dev["ids"] = String(vars.deviceId); dev["name"] = systemCfg.hostname; @@ -480,8 +392,8 @@ void mqttPublishDiscovery() if (topic != "error") { serializeJson(buffJson, mqttBuffer); - // DEBUG_PRINTLN(mqttBuffer); - mqttPublishMsg(topic, mqttBuffer, true); + mqttClient.publish(topic.c_str(), 1, true, mqttBuffer.c_str()); + buffJson.clear(); mqttBuffer = ""; } diff --git a/src/mqtt.h b/src/mqtt.h index c87a21c..6bcdfc4 100644 --- a/src/mqtt.h +++ b/src/mqtt.h @@ -1,12 +1,13 @@ +#include + void mqttConnectSetup(); -bool mqttReconnect(); -void mqttCallback(char *topic, byte *payload, unsigned int length); -void mqttLoop(); -void mqttPublishState(); -void mqttOnConnect(); +void connectToMqtt(); +void onMqttConnect(bool sessionPresent); +void onMqttDisconnect(AsyncMqttClientDisconnectReason reason); +void onMqttMessage(char *topic, char *payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total); +void executeCommand(const char *command); void mqttPublishAvail(); -void mqttPublishDiscovery(); -void mqttPublishMsg(String topic, String msg, bool retain); -void mqttPublishIo(String const &io, String const &state); -void mqttSubscribe(String topic); \ No newline at end of file +void mqttPublishIo(const String &io, const String &state); +void mqttPublishState(); +void mqttPublishDiscovery(); \ No newline at end of file diff --git a/src/version.h b/src/version.h index bbd6cd6..e988268 100644 --- a/src/version.h +++ b/src/version.h @@ -1,4 +1,4 @@ // AUTO GENERATED FILE #ifndef VERSION - #define VERSION "20240415" + #define VERSION "20240417" #endif diff --git a/src/web.cpp b/src/web.cpp index b43668a..54650ca 100644 --- a/src/web.cpp +++ b/src/web.cpp @@ -15,9 +15,9 @@ #include "log.h" #include "etc.h" #include "zb.h" -#include "zones.h" -#include "keys.h" -// #include "hw.h" +#include "const/zones.h" +#include "const/keys.h" +// #include "const/hw.h" #include "webh/html/PAGE_VPN.html.gz.h" #include "webh/html/PAGE_MQTT.html.gz.h" @@ -122,9 +122,9 @@ void checkFwHexTask(void *param) vTaskDelete(NULL); } -void redirectLogin(String msg = "") +void redirectLOGDn(String msg = "") { - String path = "/login"; + String path = "/LOGDn"; if (msg != "") { path = path + "?msg=" + msg; @@ -143,7 +143,7 @@ void handleLoader() } if (!is_authenticated()) { - redirectLogin(); + redirectLOGDn(); return; } sendGzip(contTypeTextHtml, PAGE_LOADER_html_gz, PAGE_LOADER_html_gz_len); @@ -218,11 +218,11 @@ void initWebServer() serverWeb.on("/tools", handleLoader); serverWeb.on("/mqtt", handleLoader); serverWeb.on("/vpn", handleLoader); - serverWeb.on("/login", []() + serverWeb.on("/LOGDn", []() { if (serverWeb.method() == HTTP_GET) { - handleLoginGet(); + handleLOGDnGet(); } else if (serverWeb.method() == HTTP_POST) { - handleLoginPost(); + handleLOGDnPost(); } }); serverWeb.on("/logout", HTTP_GET, handleLogout); /* ----- PAGES | END -----*/ @@ -645,7 +645,7 @@ void handleApi() if (!is_authenticated()) { - redirectLogin("Need to login"); + redirectLOGDn("Need to LOGDn"); return; } @@ -681,7 +681,7 @@ void handleApi() delay(25); evWaitCount++; } - // sendEvent(tag, eventLen, String("FW Url: ") + fwUrl); + // sendEvent(eventLen, String("FW Url: ") + fwUrl); // setClock(); HTTPClient https; WiFiClientSecure client; @@ -689,7 +689,7 @@ void handleApi() https.begin(client, fwUrl); // https://raw.githubusercontent.com/Tarik2142/devHost/main/coordinator_20211217.bin https.addHeader("Content-Type", "application/octet-stream"); const int16_t httpsCode = https.GET(); - // sendEvent(tag, eventLen, String("REQ result: ") + httpsCode); + // sendEvent(eventLen, String("REQ result: ") + httpsCode); if (httpsCode == HTTP_CODE_OK) { const uint32_t fwSize = https.getSize(); @@ -830,12 +830,12 @@ void handleApi() serverWeb.send(HTTP_CODE_OK, contTypeText, result); if (ledNum == MODE_LED) { - LOGI(tag, "%s led %d", ledControl.modeLED.name, actNum); + LOGD("%s led %d", ledControl.modeLED.name, actNum); ledControl.modeLED.mode = static_cast(actNum); } else if (ledNum == POWER_LED) { - LOGI(tag, "%s led %d", ledControl.powerLED.name, actNum); + LOGD("%s led %d", ledControl.powerLED.name, actNum); ledControl.powerLED.mode = static_cast(actNum); } } @@ -1155,7 +1155,7 @@ void updateWebTask(void *parameter) printEachKeyValuePair(root_data); // sendEvent("root_update", eventLen, String(root_data)); - // LOGI("web_task", "%s", root_data); + // LOGD("web_task", "%s", root_data); // DEBUG_PRINTLN(root_data); vTaskDelayUntil(&lastWakeTime, pdMS_TO_TICKS(systemCfg.refreshLogs * 1000)); } @@ -1484,7 +1484,7 @@ else } }*/ -void handleLoginGet() +void handleLOGDnGet() { if (!is_authenticated()) { @@ -1493,16 +1493,16 @@ void handleLoginGet() } else { - // DEBUG_PRINTLN("handleLoginGet else"); + // DEBUG_PRINTLN("handleLOGDnGet else"); serverWeb.sendHeader("Location", "/"); serverWeb.sendHeader("Cache-Control", "no-cache"); serverWeb.send(301); // sendGzip(contTypeTextHtml, PAGE_LOADER_html_gz, PAGE_LOADER_html_gz_len); } } -void handleLoginPost() +void handleLOGDnPost() { - // Serial.println("Handle login"); + // Serial.println("Handle LOGDn"); // String msg; /*if (serverWeb.hasHeader("Cookie")) @@ -1531,7 +1531,7 @@ void handleLoginPost() } // msg = ; // Serial.println("Log in Failed"); - redirectLogin("Wrong credentials! Try again."); + redirectLOGDn("Wrong credentials! Try again."); return; } } @@ -1541,7 +1541,7 @@ void handleLogout() // Serial.println("Disconnection"); serverWeb.sendHeader("Set-Cookie", "XZG_UID=0"); serverWeb.sendHeader("Authentication", "fail"); - redirectLogin("Logged out"); + redirectLOGDn("Logged out"); // serverWeb.send_P(401, contTypeTextHtml, (const char *)PAGE_LOGOUT_html_gz, PAGE_LOGOUT_html_gz_len); });*/ @@ -1789,6 +1789,7 @@ void handleMqtt() doc["passMqtt"] = mqttCfg.pass; doc["topicMqtt"] = mqttCfg.topic; doc["intervalMqtt"] = mqttCfg.updateInt; + doc["mqttReconnect"] = mqttCfg.reconnectInt; if (mqttCfg.discovery) { @@ -1835,73 +1836,38 @@ String getRootData(bool update) getReadableTime(readableTime, vars.socketTime); const char *connectedSocketStatus = "connectedSocketStatus"; const char *connectedSocket = "connectedSocket"; - // const char *notConnected = "Not connected"; - // const char *yes = "Yes"; - // const char *no = "No"; - // const char *on = "On"; - // const char *off = "Off"; const char *noConn = "noConn"; - /* - if (vars.connectedClients > 0) - { - if (vars.connectedClients > 1) - { - doc[connectedSocketStatus] = "Yes, " + String(vars.connectedClients) + "connection"; - doc[connectedSocket] = readableTime; - } - else - { - doc[connectedSocketStatus] = "Yes, " + String(vars.connectedClients) + " connections"; - doc[connectedSocket] = readableTime; - } - } - else - { - doc[connectedSocketStatus] = no; - doc[connectedSocket] = notConnected; - } - */ doc[connectedSocketStatus] = vars.connectedClients; doc[connectedSocket] = vars.socketTime; doc["localTime"] = getTime(); - // DEBUG_PRINTLN(getTime()); + if (!update) { char verArr[25]; const char *env = STRINGIFY(BUILD_ENV_NAME); - // sprintf(verArr, "%s (%s)", VERSION, env); - if (strcasestr(env, "debug") != NULL) { - // env содержит "debug" в любом регистре, выводим VERSION и env sprintf(verArr, "%s (%s)", VERSION, env); } else { - // env не содержит "debug", выводим только VERSION sprintf(verArr, "%s", VERSION); } doc["VERSION"] = String(verArr); const char *operationalMode = "operationalMode"; - doc[operationalMode] = systemCfg.workMode; } // ETHERNET TAB - // const char *ethDhcp = "ethDhcp"; - const char *ethConn = "ethConn"; - const char *ethMac = "ethMac"; const char *ethSpd = "ethSpd"; - // const char *ethIp = "ethIp"; - const char *ethDns = "ethDns"; - // + if (networkCfg.ethEnable) { if (!update) @@ -1912,7 +1878,7 @@ String getRootData(bool update) doc[ethDhcpKey] = networkCfg.ethDhcp ? 1 : 0; if (vars.connectedEther) { - doc[ethSpd] = ETH.linkSpeed(); // + String(" Mbps"); + doc[ethSpd] = ETH.linkSpeed(); doc[ethIpKey] = ETH.localIP().toString(); doc[ethMaskKey] = ETH.subnetMask().toString(); doc[ethGateKey] = ETH.gatewayIP().toString(); @@ -1928,7 +1894,6 @@ String getRootData(bool update) } } - // getReadableTime(readableTime, 0); doc["uptime"] = millis(); // readableTime; float CPUtemp = getCPUtemp(); @@ -1947,11 +1912,11 @@ String getRootData(bool update) const char *espFlashType = "espFlashType"; if (chip_info.features & CHIP_FEATURE_EMB_FLASH) { - doc[espFlashType] = 1; //"embedded"; + doc[espFlashType] = 1; } else { - doc[espFlashType] = 2; //"external"; + doc[espFlashType] = 2; } doc["espFlashSize"] = ESP.getFlashChipSize() / (1024 * 1024); @@ -1991,17 +1956,9 @@ String getRootData(bool update) doc["espNvsUsed"] = used; // wifi - // const char *wifiSsid = "wifiSsid"; const char *wifiRssi = "wifiRssi"; - // const char *wifiIp = "wifiIp"; const char *wifiConn = "wifiConn"; - // const char *wifiMask = "wifiMask"; - // const char *wifiGate = "wifiGate"; - // const char *wifiEnabled = "wifiEnabled"; const char *wifiMode = "wifiMode"; - // const char *wifiModeAPStatus = "wifiModeAPStatus"; - // const char *wifiModeAP = "wifiModeAP"; - // const char *wifiDhcp = "wifiDhcp"; const char *wifiDns = "wifiDns"; if (!update) @@ -2011,15 +1968,13 @@ String getRootData(bool update) if (networkCfg.wifiEnable) { - // doc[wifiEnabled] = yes; doc[wifiMode] = 1; //"Client"; doc[wifiDhcpKey] = networkCfg.wifiDhcp ? 1 : 0; if (WiFi.status() == WL_CONNECTED) { // STA connected - // String rssiWifi = String(WiFi.RSSI()) + String(" dBm"); doc[wifiSsidKey] = WiFi.SSID(); - doc[wifiRssi] = WiFi.RSSI(); // rssiWifi; - doc[wifiConn] = 1; // "Connected to " + WiFi.SSID(); + doc[wifiRssi] = WiFi.RSSI(); + doc[wifiConn] = 1; doc[wifiIpKey] = WiFi.localIP().toString(); doc[wifiMaskKey] = WiFi.subnetMask().toString(); doc[wifiGateKey] = WiFi.gatewayIP().toString(); @@ -2027,7 +1982,6 @@ String getRootData(bool update) } else { - // const char *noConn = "Connecting..."; doc[wifiSsidKey] = networkCfg.wifiSsid; doc[wifiRssi] = noConn; doc[wifiConn] = 0; @@ -2037,27 +1991,11 @@ String getRootData(bool update) doc[wifiDns] = networkCfg.wifiDhcp ? noConn : WiFi.dnsIP().toString(); } } - /*else - { - doc[wifiEnabled] = no; - doc[wifiConnected] = notConnected; - doc[wifiMode] = off; - doc[wifiSsid] = off; - doc[wifiIp] = off; - doc[wifiMask] = off; - doc[wifiGate] = off; - doc[wifiRssi] = off; - doc[wifiDhcp] = off; - }*/ + if (vars.apStarted) { // AP active String AP_NameString; - // char apSsid[MAX_DEV_ID_LONG]; - // getDeviceID(apSsid); - // char wifiSsidBuf[MAX_DEV_ID_LONG + 25]; - // sprintf(wifiSsidBuf, "%s (no password)", vars.deviceId); - // doc[wifiSsidKey] = wifiSsidBuf; doc[wifiMode] = 2; doc[wifiConn] = 1; doc[wifiSsidKey] = vars.deviceId; @@ -2065,17 +2003,9 @@ String getRootData(bool update) doc[wifiMaskKey] = "255.255.255.0 (Access point)"; doc[wifiGateKey] = "192.168.1.1 (this device)"; doc[wifiDhcpKey] = "On (Access point)"; - // doc[wifiModeAPStatus] = "AP started"; doc[wifiMode] = 2; //"AP"; - // doc[wifiModeAP] = yes; doc[wifiRssi] = noConn; //"N/A"; } - // else - //{ - // doc[wifiModeAP] = no; - // doc[wifiModeAPStatus] = "Not started"; - // doc[wifiMode] = "Client"; - //} // MQTT if (mqttCfg.enable) diff --git a/src/web.h b/src/web.h index 0d89b3e..853a394 100644 --- a/src/web.h +++ b/src/web.h @@ -2,8 +2,8 @@ void handleEvents(); void initWebServer(); void webServerHandleClient(); -void handleLoginGet(); -void handleLoginPost(); +void handleLOGDnGet(); +void handleLOGDnPost(); void handleLogout(); bool is_authenticated(); void handleGeneral(); diff --git a/src/websrc/css/custom.css b/src/websrc/css/custom.css index d36aeb9..92a8c05 100644 --- a/src/websrc/css/custom.css +++ b/src/websrc/css/custom.css @@ -450,8 +450,8 @@ body { color: #f39c12; } -/*Login page*/ -#loginForm { +/*LOGDn page*/ +#LOGDnForm { display: flex; height: 100vh; align-items: center; @@ -504,7 +504,7 @@ body { font-size: medium; } -/*Login page*/ +/*LOGDn page*/ .two_cols_checkbox { padding-left: 2.5rem !important; diff --git a/src/websrc/html/PAGE_GENERAL.html b/src/websrc/html/PAGE_GENERAL.html index 0be237c..624ec4e 100644 --- a/src/websrc/html/PAGE_GENERAL.html +++ b/src/websrc/html/PAGE_GENERAL.html @@ -2,24 +2,24 @@
-
+
- +
- +
@@ -27,24 +27,24 @@ diff --git a/src/websrc/html/PAGE_LOGIN.html b/src/websrc/html/PAGE_LOGIN.html index b12b0ad..e230821 100644 --- a/src/websrc/html/PAGE_LOGIN.html +++ b/src/websrc/html/PAGE_LOGIN.html @@ -4,7 +4,7 @@ - + @@ -17,7 +17,7 @@
Logo XZG -

+

@@ -29,7 +29,7 @@

- +
-

xyzroe © 2024

diff --git a/src/websrc/html/PAGE_MQTT.html b/src/websrc/html/PAGE_MQTT.html index a838295..2db7de1 100644 --- a/src/websrc/html/PAGE_MQTT.html +++ b/src/websrc/html/PAGE_MQTT.html @@ -6,43 +6,43 @@
- +
- + + data-i18n="p.mq.broker.ph[placeholder];p.mq.broker.tt[title]" required>
- + + data-i18n="p.mq.port.ph[placeholder];p.mq.port.tt[title]" required>
- + + data-i18n="p.mq.user.ph[placeholder];p.mq.user.tt[title]">
- +
+ data-i18n="p.mq.pass.ph[placeholder];p.mq.pass.tt[title]">
- + + data-i18n="p.mq.topic.ph[placeholder];p.mq.topic.tt[title]" required>
- + + data-i18n="p.mq.interval.ph[placeholder];p.mq.interval.tt[title]" required> +
+
+ +

+ class="btn btn-outline-primary col-6" name='save' data-i18n="c.save">
diff --git a/src/websrc/html/PAGE_NETWORK.html b/src/websrc/html/PAGE_NETWORK.html index fdad7f6..3b05d1e 100644 --- a/src/websrc/html/PAGE_NETWORK.html +++ b/src/websrc/html/PAGE_NETWORK.html @@ -5,7 +5,7 @@
- +
@@ -13,36 +13,36 @@
- +
- +
- +
- +
- +
- +
- +
@@ -54,7 +54,7 @@
- +
@@ -64,36 +64,36 @@
- +
- +
- +
- +
- +
- +
- +
@@ -103,10 +103,10 @@ - - - - + + + + @@ -125,12 +125,12 @@
+ data-i18n="p.ne.wifi.btn.scan">
+ data-i18n="p.ne.wifi.btn.man">
@@ -139,12 +139,12 @@
- +
- +
- +
\ No newline at end of file diff --git a/src/websrc/html/PAGE_ROOT.html b/src/websrc/html/PAGE_ROOT.html index 7f6d599..e149444 100644 --- a/src/websrc/html/PAGE_ROOT.html +++ b/src/websrc/html/PAGE_ROOT.html @@ -6,13 +6,13 @@
- +
- + - + - + - + - + @@ -61,25 +61,25 @@
- +
- + - + - + - + - - + - + - + - + - + - + - + @@ -167,41 +167,41 @@
- +
@ + @ - +
/ - +
, + data-i18n="p.st.dic.mb">,
/ - +
/ - +
- + - + - + - + - + - + - + - + @@ -214,41 +214,41 @@
- +
- + - + - + - + - + - + - + - + - + @@ -274,17 +274,17 @@
- +
- + - + @@ -297,29 +297,29 @@
- +
- + - + - + - + - + @@ -332,17 +332,17 @@
- +
- + - +