diff --git a/.gitignore b/.gitignore index bd718a8..d2887ab 100644 --- a/.gitignore +++ b/.gitignore @@ -3,7 +3,7 @@ .vscode .gcc-flags.json .clang_complete -commit +commit* test.html gzipped webh diff --git a/README.md b/README.md index 0cd66a7..f76dafa 100644 --- a/README.md +++ b/README.md @@ -20,8 +20,10 @@ This repository contains the latest firmware for the ESP32 peripheral module of - ESP32 (peripheral) and CC2652P (Zigbee) OTA updates, ESP32 and CC2652P restart; - Switch CC2652P (Zigbee) to flash mode; - Pairing mode for the adapter in router mode; -- Firewall for incoming connections to secure your network; +- Filter IP addresses for incoming connections to secure your network; - Fully responsive web interface based on the latest Bootstrap 5.3. +- WireGuard VPN +- MQTT client for gateway monitoring and control ## Installation and Configuration Please refer to the installation and configuration articles in our [documentation](https://uzg.zig-star.com). @@ -31,20 +33,11 @@ Please follow this link for web-flasher - just plug-and-flash: [ZigStar WebFlash If you made changes to the code and want to compile you own firmware, please do the following: -### You did not change web-interface appearance - Download repository; - Install Microsoft Visual Code (MVC); - Install PlatformIO extension to MVC; - Press "PlatformIO: Build" and wait until firmware.bin is generated; -### You made changes to web-interface - -In such case - you have to rebuild web-interface fisrt before building the firmware. -- Go to the folder tools/webfilesbuilder; -- Run: npm install -- Run: npx gulp - - ## Contribute You can contribute to UZG-01 Firmware by @@ -55,25 +48,24 @@ You can contribute to UZG-01 Firmware by ## Credits People helping to keep the show on the road - **developers and contributors**: -- [@smlight-dev](https://github.com/smlight-dev/) - for improvement and refactoring of [ZigStarGW-FW](https://github.com/xyzroe/ZigStarGW-FW) -- [@Tarik2142](https://github.com/Tarik2142) for refactoring, code optimizations done under [smlight-dev](https://github.com/mercenaruss/uzg-firmware) -- [@xyzroe](https://github.com/xyzroe/) for initial firmware released for ZigStar devices + +- [@xyzroe](https://github.com/xyzroe/) for initial firmware released for ZigStar devices and all work being doing till now +- [@Tarik2142](https://github.com/Tarik2142) for refactoring, code optimizations done under [smlight-dev](https://github.com/smlight-dev/) + Special thanks goes also to all authors of 3rd party libraries which are used in this project: - [bblanchon / arduinojson](https://github.com/bblanchon/ArduinoJson), -- [esp8266 / arduino](https://github.com/esp8266/Arduino), - [espressif / arduino-esp32](https://github.com/espressif/arduino-esp32), - [esprfid / esp-rfid](https://github.com/esprfid/esp-rfid), - [fairecasoimeme / zigate-ethernet](https://github.com/fairecasoimeme/ZiGate-Ethernet), - [rlogiacco / circularbuffer](https://github.com/rlogiacco/CircularBuffer), - [sstaub / ticker](https://github.com/sstaub/Ticker), -- [vurtun / lib](https://github.com/vurtun/lib) +- [vurtun / lib](https://github.com/vurtun/lib), +- [ciniml / WireGuard-ESP32-Arduino] (https://github.com/ciniml/WireGuard-ESP32-Arduino) ## License and attribution -UZG-01-Firmware is a fork of [smlight-dev](https://github.com/mercenaruss/uzg-firmware),what was refactored from our original firmware[ZigStarGW-FW](https://github.com/xyzroe/ZigStarGW-FW) - UZG-01-Firmware is licensed under GNU General Public License v3. 3rd party libraries that are used by this project are licensed under different license schemes, please check them out as well. Copyright (c) 2023 ZigStar. diff --git a/bin/UZG-01.bin b/bin/UZG-01.bin index 6cf92cb..cd9d259 100644 Binary files a/bin/UZG-01.bin and b/bin/UZG-01.bin differ diff --git a/bin/UZG-01_v0.2.3.full.bin b/bin/UZG-01_v0.2.3.full.bin deleted file mode 100644 index 943b92e..0000000 Binary files a/bin/UZG-01_v0.2.3.full.bin and /dev/null differ diff --git a/bin/UZG-01_v0.2.4.full.bin b/bin/UZG-01_v0.2.4.full.bin new file mode 100644 index 0000000..ca8bc4c Binary files /dev/null and b/bin/UZG-01_v0.2.4.full.bin differ diff --git a/lib/CC26XX/library.properties b/lib/CC26XX/library.properties new file mode 100644 index 0000000..70f9163 --- /dev/null +++ b/lib/CC26XX/library.properties @@ -0,0 +1,8 @@ +name=CC26XX-ESP32 +version=0.0.1 +author=xyzroe +maintainer=xyzroe +sentence=TI CC26XX dev tools on ESP32 +paragraph= +includes=CC26XX.h +architectures=esp32 diff --git a/lib/CC26XX/src/CC26XX.cpp b/lib/CC26XX/src/CC26XX.cpp index 484f3b9..4e15cdc 100644 --- a/lib/CC26XX/src/CC26XX.cpp +++ b/lib/CC26XX/src/CC26XX.cpp @@ -146,6 +146,17 @@ void CommandInterface::_sendNAck() _stream.write(cmd2); } +void CommandInterface::_eraseFlash() { + const u_int32_t cmd1 = 0x2C; + _stream.write(cmd1); +} + +bool CommandInterface::_ping() { + const u_int32_t cmd1 = 0x20; + _stream.write(cmd1); + return _wait_for_ack(1); +} + byte *CommandInterface::_cmdMemRead(uint32_t address) { const u_int32_t cmd = 0x2A; @@ -355,3 +366,11 @@ String CC26XX_detect::detectChipInfo() return chip_str; } + +bool CC26XX_detect::eraseFlash() +{ + _ping(); + _eraseFlash(); + + return true; +} \ No newline at end of file diff --git a/lib/CC26XX/src/CC26XX.h b/lib/CC26XX/src/CC26XX.h index 88099ab..81cb55e 100644 --- a/lib/CC26XX/src/CC26XX.h +++ b/lib/CC26XX/src/CC26XX.h @@ -94,6 +94,8 @@ class CommandInterface bool _checkLastCmd(); void _sendAck(); void _sendNAck(); + void _eraseFlash(); + bool _ping(); void _encodeAddr(unsigned long addr, byte encodedAddr[4]); unsigned long _decodeAddr(byte byte0, byte byte1, byte byte2, byte byte3); byte _calcChecks(byte cmd, unsigned long addr, unsigned long size); @@ -110,6 +112,8 @@ class CC26XX_detect : public CommandInterface public: CC26XX_detect(Stream &serial); bool begin(int CC_RST_PIN, int CC_BSL_PIN, int BSL_MODE = 0); + bool eraseFlash(); + bool ping(); String detectChipInfo(); }; diff --git a/lib/intelhex/library.properties b/lib/intelhex/library.properties new file mode 100644 index 0000000..ead0ede --- /dev/null +++ b/lib/intelhex/library.properties @@ -0,0 +1,8 @@ +name=IntelHEX-ESP32 +version=0.0.2 +author="OpenAI's ChatGPT with contributions from xyzroe" +maintainer=xyzroe +sentence=IntelHEX file actions on ESP32 +paragraph= +includes=intelhex.h +architectures=esp32 diff --git a/lib/intelhex/src/intelhex.cpp b/lib/intelhex/src/intelhex.cpp index cf7a04a..0caad35 100644 --- a/lib/intelhex/src/intelhex.cpp +++ b/lib/intelhex/src/intelhex.cpp @@ -1,4 +1,6 @@ #include "intelhex.h" +#include + /* * IntelHex Arduino Library * @@ -15,15 +17,8 @@ If you want library to control LittleFS you need to uncomment some lines. - -TO-DO List - -1. Line length check -2. Error if not IntelHEX line after start till end - */ - #ifndef DEBUG_PRINT #ifdef DEBUG #define DEBUG_PRINT(x) Serial.print(String(x)) @@ -34,9 +29,6 @@ TO-DO List #endif #endif - - - IntelHex::IntelHex(const char *filename) : _filename(filename) {} IntelHex::~IntelHex() @@ -63,13 +55,16 @@ void IntelHex::close() // LittleFS.end(); } -bool IntelHex::parse(void (*preCallback)(), void (*parseCallback)(uint32_t address, uint8_t len, uint8_t *data), void (*postCallback)()) +bool IntelHex::parse(void (*preCallback)(), void (*parseCallback)(uint32_t address, uint8_t len, uint8_t *data, size_t currentPosition, size_t totalSize), void (*postCallback)()) { if (!open()) { return false; } + _totalSize = _file.size(); + DEBUG_PRINTLN(String("_file.size() = ") + String(_totalSize)); + preCallback(); bool status = true; @@ -96,8 +91,115 @@ bool IntelHex::parse(void (*preCallback)(), void (*parseCallback)(uint32_t addre return status; } -bool IntelHex::_munchLine(void (*parseCallback)(uint32_t address, uint8_t len, uint8_t *data)) +/* +bool IntelHex::validateChecksum() +{ + DEBUG_PRINTLN("Starting checksum validation"); + + if (!open()) + { + DEBUG_PRINTLN("Failed to open file"); + return false; + } + + String line; + while (_file.available()) + { + line = _file.readStringUntil('\n'); + line.trim(); + + if (line.length() < 11 || line[0] != ':') + { + DEBUG_PRINTLN("Skipping non-data line or line too short"); + continue; + } + + // Проверяем на строку окончания файла Intel HEX + if (line == ":00000001FF") + { + DEBUG_PRINTLN("Intel HEX file end line found, checksum validation passed"); + close(); + return true; + } + + uint8_t sum = 0; + // Считаем сумму всех байтов строки, за исключением начального ':' + for (int i = 1; i < line.length(); i += 2) + { + uint8_t byteValue = strtol(line.substring(i, i + 2).c_str(), nullptr, 16); + sum += byteValue; + } + + // Проверка контрольной суммы + if (sum != 0) + { + DEBUG_PRINTLN("Checksum validation failed"); + close(); + return false; + } + } + + DEBUG_PRINTLN("Checksum validation passed, but no end line found - file might be incomplete"); + close(); + return false; // Если мы достигли этой точки, значит, строка окончания файла не была найдена. +} +*/ + +/* +bool IntelHex::checkBSLConfiguration() { + DEBUG_PRINTLN("checkBSLConfiguration: Starting BSL configuration check"); + + if (!open()) { + DEBUG_PRINTLN("checkBSLConfiguration: Failed to open file"); + return false; + } + + const uint32_t addresses[] = {ALL_CHIP_ADDRESS, P7_CHIP_ADDRESS}; + bool foundBSL = false; + + for (auto address : addresses) { + DEBUG_PRINT("checkBSLConfiguration: Checking address: "); + DEBUG_PRINTLN(String(address, HEX)); + + // Предполагаем, что BSL конфигурация начинается непосредственно с этого адреса. + // Важно отметить, что в файле Intel Hex адреса не обязательно идут последовательно и могут быть разбросаны. + // Это может потребовать специфической логики для перемещения по файлу. + + // Чтение данных из файла, предполагая, что они могут находиться по этому адресу. + _file.seek(address, SeekSet); + uint8_t data[4]; // Предполагаем, что для проверки BSL конфигурации достаточно 4 байтов. + if (_file.read(data, 4) != 4) { + DEBUG_PRINTLN("checkBSLConfiguration: Failed to read data"); + continue; // Если не удается прочитать 4 байта, переходим к следующему адресу. + } + + // Добавляем логирование прочитанных данных, чтобы увидеть, что было считано. + DEBUG_PRINT("checkBSLConfiguration: Read data: "); + for (int i = 0; i < 4; ++i) { + DEBUG_PRINT(String(data[i], HEX)); + DEBUG_PRINT(" "); + } + DEBUG_PRINTLN(); + + foundBSL = _checkBSLconfig(address, 4, data); + if (foundBSL) { + DEBUG_PRINTLN("checkBSLConfiguration: BSL configuration found and valid"); + break; // Если нашли и проверили конфигурацию BSL, прерываем цикл. + } + } + + if (!foundBSL) { + DEBUG_PRINTLN("checkBSLConfiguration: BSL configuration not found or invalid"); + } + + close(); + return foundBSL; +} +*/ + +bool IntelHex::_munchLine(void (*parseCallback)(uint32_t address, uint8_t len, uint8_t *data, size_t currentPosition, size_t totalSize)) { + String line = _file.readStringUntil('\n'); line.trim(); @@ -135,11 +237,6 @@ bool IntelHex::_munchLine(void (*parseCallback)(uint32_t address, uint8_t len, u // DEBUG_PRINTLN("Record Type: " + String(recordType, HEX) + ", Offset Low: " + String(offset_low, HEX) + ", Length: " + String(len, HEX)); // Print record info uint8_t data[255]; - for (uint8_t i = 0; i < len; i++) - { - data[i] = strtol(line.substring(9 + i * 2, 11 + i * 2).c_str(), nullptr, 16); - } - uint32_t address = offset_low; // https://jimmywongiot.com/2021/04/20/format-of-intelhex/ if (recordType == 4) @@ -153,11 +250,36 @@ bool IntelHex::_munchLine(void (*parseCallback)(uint32_t address, uint8_t len, u address += _offset_high; - if (!_bsl_valid) + esp_task_wdt_reset(); +//#ifdef DEBUG +// delay(5); // to avoid reboot +//#endif + + for (int i = 0; i < ELEMENTCOUNT(CCFG_ADDRESS); i++) { - _bsl_valid = _checkBSLconfig(address, len, data); + // DEBUG_PRINT(CCFG_ADDRESS[i]); + // DEBUG_PRINT(" "); + if (address <= CCFG_ADDRESS[i] && address + len > CCFG_ADDRESS[i] + 4) + { + //DEBUG_PRINTLN(" "); + //DEBUG_PRINTLN("CCFG_ADDRESS[" + String(i) + "] in range"); + + + for (uint8_t i = 0; i < len; i++) + { + data[i] = strtol(line.substring(9 + i * 2, 11 + i * 2).c_str(), nullptr, 16); + } + + if (!_bsl_valid) + { + _bsl_valid = _checkBSLconfig(address, len, data); + } + } } - parseCallback(address, len, data); + + size_t currentPosition = _file.position(); + + parseCallback(address, len, data, currentPosition, _totalSize); return true; } @@ -165,16 +287,14 @@ bool IntelHex::_munchLine(void (*parseCallback)(uint32_t address, uint8_t len, u bool IntelHex::_checkBSLconfig(uint32_t address, uint8_t len, uint8_t *data) { // Check if CCFG is within the buffer - //DEBUG_PRINTLN(" "); - //DEBUG_PRINT(ELEMENTCOUNT(CCFG_ADDRESS)); - //DEBUG_PRINT(" "); + // DEBUG_PRINTLN(" "); + // DEBUG_PRINT(ELEMENTCOUNT(CCFG_ADDRESS)); + // DEBUG_PRINT(" "); - // DEBUG_PRINTLN(ESP.getFreeHeap() / 1024); - delay(5); for (int i = 0; i < ELEMENTCOUNT(CCFG_ADDRESS); i++) { - //DEBUG_PRINT(CCFG_ADDRESS[i]); - //DEBUG_PRINT(" "); + // DEBUG_PRINT(CCFG_ADDRESS[i]); + // DEBUG_PRINT(" "); if (address <= CCFG_ADDRESS[i] && address + len > CCFG_ADDRESS[i] + 4) { DEBUG_PRINTLN(" "); diff --git a/lib/intelhex/src/intelhex.h b/lib/intelhex/src/intelhex.h index 172af0f..e132956 100644 --- a/lib/intelhex/src/intelhex.h +++ b/lib/intelhex/src/intelhex.h @@ -12,8 +12,7 @@ class IntelHex IntelHex(const char *filename); ~IntelHex(); - bool parse(void (*preCallback)(), void (*parseCallback)(uint32_t address, uint8_t len, uint8_t *data), void (*postCallback)()); - + bool parse(void (*preCallback)(), void (*parseCallback)(uint32_t address, uint8_t len, uint8_t *data, size_t currentPosition, size_t totalSize), void (*postCallback)()); void setFileValidated(bool value) { _file_validated = value; } bool fileParsed() const { return _file_parsed; } @@ -24,6 +23,11 @@ class IntelHex bool bslLevel() const { return _bsl_level - 1; } // 0 error, 1 low, 2 high bool bslAddr() const { return _bsl_addr; } // 0 - all seriers, 1 - P/R 7 series + + bool validateChecksum(); // Построчная валидация контрольной суммы + bool checkBSLConfiguration(); // Проверка конфигурации BSL + + private: const char *_filename; File _file; @@ -39,13 +43,15 @@ class IntelHex bool _bsl_valid = false; int _bsl_addr = 0; + size_t _totalSize = 0; + // const uint32_t CCFG_ADDRESS = 0x057FD8; // all others const uint32_t ALL_CHIP_ADDRESS = 0x057FD8; const uint32_t P7_CHIP_ADDRESS = 0x0AFFD8; const uint32_t CCFG_ADDRESS[2] = {ALL_CHIP_ADDRESS, P7_CHIP_ADDRESS}; - #define ALL_CHIP_ID 0 - #define P7_CHIP_ID 1 +#define ALL_CHIP_ID 0 +#define P7_CHIP_ID 1 // const uint32_t CCFG_ADDRESS = 0x0AFFD8; //CC2652R7 and CC1352P7 @@ -63,7 +69,7 @@ class IntelHex bool open(); void close(); - bool _munchLine(void (*parseCallback)(uint32_t address, uint8_t len, uint8_t *data)); + bool _munchLine(void (*parseCallback)(uint32_t address, uint8_t len, uint8_t *data, size_t currentPosition, size_t totalSize)); bool _checkBSLconfig(uint32_t address, uint8_t len, uint8_t *data); }; diff --git a/platformio.ini b/platformio.ini index 3a3b4a8..91e447a 100644 --- a/platformio.ini +++ b/platformio.ini @@ -33,7 +33,7 @@ lib_deps = sstaub/Ticker@>=4.4.0 knolleary/PubSubClient@^2.8 ESP Async WebServer -monitor_filters = esp32_exception_decoder, default, log2file +monitor_filters = esp32_exception_decoder, default ;, log2file monitor_speed = 115200 upload_speed = 460800 extra_scripts = diff --git a/src/config.h b/src/config.h index 1f7e18f..cb9fe88 100644 --- a/src/config.h +++ b/src/config.h @@ -22,12 +22,12 @@ #define BTN 35 #define MODE_SWITCH 33 #define DEBOUNCE_TIME 70 -#define PRODUCTION 1 + #define TCP_LISTEN_PORT 9999 #define FORMAT_LITTLEFS_IF_FAILED true -// CC2652 settings -#define BSL_PIN 15 // CC2652 pin number +// CC2652 settings (FOR BSL VALIDATION!) +#define BSL_PIN 15 // CC2652 pin number (FOR BSL VALIDATION!) #define BSL_LEVEL 0 // 0-LOW 1-HIGH const int16_t overseerInterval = 5 * 1000; // check lan or wifi connection every 5sec @@ -43,6 +43,18 @@ enum COORDINATOR_MODE_t : uint8_t COORDINATOR_MODE_USB }; +extern const char *coordMode;// coordMode node name +extern const char *prevCoordMode;// prevCoordMode node name +extern const char *configFileSystem; +extern const char *configFileWifi; +extern const char *configFileEther; +extern const char *configFileGeneral; +extern const char *configFileSecurity; +extern const char *configFileSerial; +extern const char *configFileMqtt; +extern const char *configFileWg; +extern const char *deviceModel; + // struct JsonConsts_t{ // char* str; // }; @@ -86,37 +98,48 @@ struct ConfigSettingsStruct bool wifiWebSetupInProgress; bool fwEnabled; IPAddress fwIp; - bool mqttEnable; - char mqttServer[50]; - IPAddress mqttServerIP; - int mqttPort; - char mqttUser[50]; - char mqttPass[50]; - char mqttTopic[50]; - // bool mqttRetain; - int mqttInterval; - bool mqttDiscovery; - unsigned long mqttReconnectTime; - unsigned long mqttHeartbeatTime; + bool zbLedState; bool zbFlashing; + char timeZone[50]; +}; - bool wgEnable; - char wgLocalAddr[20]; - IPAddress wgLocalIP; - char wgLocalPrivKey[45]; - char wgEndAddr[45]; - char wgEndPubKey[45]; - int wgEndPort; - bool wgInit = 0; +struct MqttSettingsStruct +{ + bool enable; + char server[50]; + IPAddress serverIP; + int port; + char user[50]; + char pass[50]; + char topic[50]; + // bool retain; + int interval; + bool discovery; + unsigned long reconnectTime; + unsigned long heartbeatTime; +}; + +struct WgSettingsStruct +{ + bool enable; + bool init = 0; + char localAddr[20]; + IPAddress localIP; + char localPrivKey[45]; + char endAddr[45]; + char endPubKey[45]; + int endPort; }; +/* struct InfosStruct { char device[8]; char mac[8]; char flash[8]; }; +*/ struct zbVerStruct { diff --git a/src/etc.cpp b/src/etc.cpp index 0fa4880..2808be3 100644 --- a/src/etc.cpp +++ b/src/etc.cpp @@ -9,9 +9,21 @@ #include "web.h" #include "log.h" #include "etc.h" +#include "zones.h" extern struct ConfigSettingsStruct ConfigSettings; -extern const char *deviceModel; + +const char *coordMode = "coordMode"; // coordMode node name +const char *prevCoordMode = "prevCoordMode"; // prevCoordMode node name +const char *configFileSystem = "/config/system.json"; +const char *configFileWifi = "/config/configWifi.json"; +const char *configFileEther = "/config/configEther.json"; +const char *configFileGeneral = "/config/configGeneral.json"; +const char *configFileSecurity = "/config/configSecurity.json"; +const char *configFileSerial = "/config/configSerial.json"; +const char *configFileMqtt = "/config/configMqtt.json"; +const char *configFileWg = "/config/configWg.json"; +const char *deviceModel = "UZG-01"; void getReadableTime(String &readableTime, unsigned long beginTime) { @@ -211,7 +223,7 @@ void getDeviceID(char *arr) // arr = buf; } -// void writeDefultConfig(const char *path, String StringConfig) +// void writeDefaultConfig(const char *path, String StringConfig) // { // DEBUG_PRINTLN(path); // DEBUG_PRINTLN(F("failed open. try to write defaults")); @@ -233,7 +245,7 @@ void getDeviceID(char *arr) // configFile.close(); // } -void writeDefultConfig(const char *path, DynamicJsonDocument &doc) +void writeDefaultConfig(const char *path, DynamicJsonDocument &doc) { DEBUG_PRINTLN(path); DEBUG_PRINTLN(F("Write defaults")); @@ -291,12 +303,86 @@ void resetSettings() { DEBUG_PRINTLN(F("Error with LITTLEFS")); } - LittleFS.remove("/config/configSerial.json"); // todo move 2 define or global const - LittleFS.remove("/config/configSecurity.json"); // todo move 2 define or global const - LittleFS.remove("/config/configGeneral.json"); // todo move 2 define or global const - LittleFS.remove("/config/configEther.json"); // todo move 2 define or global const - LittleFS.remove("/config/configWifi.json"); // todo move 2 define or global const - LittleFS.remove("/config/system.json"); // todo move 2 define or global const + LittleFS.remove(configFileSerial); + LittleFS.remove(configFileSecurity); + LittleFS.remove(configFileGeneral); + LittleFS.remove(configFileEther); + LittleFS.remove(configFileWifi); + LittleFS.remove(configFileSystem); + LittleFS.remove(configFileWg); DEBUG_PRINTLN(F("[resetSettings] Config del done")); ESP.restart(); -} \ No newline at end of file +} + +void setClock() +{ + configTime(0, 0, "pool.ntp.org", "time.google.com"); + + DEBUG_PRINT(F("Waiting for NTP time sync: ")); + time_t nowSecs = time(nullptr); + while ((nowSecs < 60)) + { + delay(500); + DEBUG_PRINT(F(".")); + yield(); + nowSecs = time(nullptr); + DEBUG_PRINT(nowSecs); + } + + DEBUG_PRINTLN(); + struct tm timeinfo; + localtime_r(&nowSecs, &timeinfo); + DEBUG_PRINT(F("Current GMT time: ")); + DEBUG_PRINT(asctime(&timeinfo)); + + char *zoneToFind = "Europe/Kiev"; + if (ConfigSettings.timeZone) + { + zoneToFind = ConfigSettings.timeZone; + } + const char *gmtOffset = getGmtOffsetForZone(zoneToFind); + + String timezone = "EET-2EEST,M3.5.0/3,M10.5.0/4"; + + if (gmtOffset != nullptr) + { + DEBUG_PRINT("GMT Offset for "); + DEBUG_PRINT(zoneToFind); + DEBUG_PRINT(" is "); + DEBUG_PRINTLN(gmtOffset); + timezone = gmtOffset; + setTimezone(timezone); + } + else + { + DEBUG_PRINT("GMT Offset for "); + DEBUG_PRINT(zoneToFind); + DEBUG_PRINTLN(" not found."); + } +} + +void setTimezone(String timezone) +{ + DEBUG_PRINTLN(F("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); + struct tm timeinfo; + localtime_r(&nowSecs, &timeinfo); + DEBUG_PRINT(F("Local time: ")); + DEBUG_PRINTLN(asctime(&timeinfo)); +} + +const char *getGmtOffsetForZone(const char *zone) +{ + for (int i = 0; i < timeZoneCount; i++) + { + if (strcmp(zone, timeZones[i].zone) == 0) + { + // Зона найдена, возвращаем GMT Offset + return timeZones[i].gmtOffset; + } + } + // Зона не найдена + return nullptr; +} diff --git a/src/etc.h b/src/etc.h index 34893ba..c69fbd1 100644 --- a/src/etc.h +++ b/src/etc.h @@ -28,10 +28,14 @@ void ledPowerToggle(); void ledUSBToggle(); void getDeviceID(char * arr); -void writeDefultConfig(const char *path, DynamicJsonDocument& doc); +void writeDefaultConfig(const char *path, DynamicJsonDocument& doc); void resetSettings(); String hexToDec(String hexString); +void setClock(); +void setTimezone(String timezone); +const char* getGmtOffsetForZone(const char* zone); + //#define min(a, b) ((a) < (b) ? (a) : (b)) \ No newline at end of file diff --git a/src/main.cpp b/src/main.cpp index 88e3f87..b081700 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -30,41 +30,31 @@ ConfigSettingsStruct ConfigSettings; zbVerStruct zbVer; -InfosStruct Infos; +// InfosStruct Infos; +MqttSettingsStruct MqttSettings; +WgSettingsStruct WgSettings; // volatile bool btnFlag = false; int btnFlag = false; bool updWeb = false; -const char *coordMode = "coordMode"; // coordMode node name -const char *prevCoordMode = "prevCoordMode"; // prevCoordMode node name -const char *configFileSystem = "/config/system.json"; -const char *configFileWifi = "/config/configWifi.json"; -const char *configFileEther = "/config/configEther.json"; -const char *configFileGeneral = "/config/configGeneral.json"; -const char *configFileSecurity = "/config/configSecurity.json"; -const char *configFileSerial = "/config/configSerial.json"; -const char *configFileMqtt = "/config/configMqtt.json"; -const char *configFileWg = "/config/configWg.json"; -const char *deviceModel = "UZG-01"; - void mDNS_start(); void connectWifi(); -void handlelongBtn(); -void handletmrNetworkOverseer(); +void handleLongBtn(); +void handleTmrNetworkOverseer(); void setupCoordinatorMode(); void startAP(const bool start); IPAddress parse_ip_address(const char *str); -Ticker tmrBtnLongPress(handlelongBtn, 1000, 0, MILLIS); -Ticker tmrNetworkOverseer(handletmrNetworkOverseer, overseerInterval, 0, MILLIS); +Ticker tmrBtnLongPress(handleLongBtn, 1000, 0, MILLIS); +Ticker tmrNetworkOverseer(handleTmrNetworkOverseer, overseerInterval, 0, MILLIS); IPAddress apIP(192, 168, 1, 1); DNSServer dnsServer; WiFiServer server(TCP_LISTEN_PORT, MAX_SOCKET_CLIENTS); static WireGuard wg; -// MDNSResponder MDNS; +// MDNSResponder MDNS; don't need? void initLan() { @@ -89,7 +79,7 @@ void initLan() } } -void startSoketServer() +void startSocketServer() { server.begin(ConfigSettings.socketPort); server.setNoDelay(true); @@ -98,26 +88,27 @@ void startSoketServer() void wgBegin() { printLogMsg(String("Adjusting system time...")); - configTime(9 * 60 * 60, 0, "0.pool.ntp.org", "time.google.com"); + // configTime(2 * 60 * 60, 0, "0.pool.ntp.org", "time.google.com"); + setClock(); if (!wg.is_initialized()) { printLogMsg(String("Initializing WireGuard interface...")); if (!wg.begin( - ConfigSettings.wgLocalIP, // IP address of the local interface - ConfigSettings.wgLocalPrivKey, // Private key of the local interface - ConfigSettings.wgEndAddr, // Address of the endpoint peer. - ConfigSettings.wgEndPubKey, // Public key of the endpoint peer. - ConfigSettings.wgEndPort)) // Port pf the endpoint peer. ) + WgSettings.localIP, // IP address of the local interface + WgSettings.localPrivKey, // Private key of the local interface + WgSettings.endAddr, // Address of the endpoint peer. + WgSettings.endPubKey, // Public key of the endpoint peer. + WgSettings.endPort)) // Port pf the endpoint peer. ) { printLogMsg(String("Failed to initialize WG interface.")); - ConfigSettings.wgInit = false; - //printLogMsg(String(ConfigSettings.wgLocalIP) + " " + String(ConfigSettings.wgLocalPrivKey) + " " + String(ConfigSettings.wgEndAddr) + " " + String(ConfigSettings.wgEndPubKey) + " " + String(ConfigSettings.wgEndPort)); + WgSettings.init = false; + // printLogMsg(String(WgSettings.localIP) + " " + String(WgSettings.localPrivKey) + " " + String(WgSettings.endAddr) + " " + String(WgSettings.endPubKey) + " " + String(WgSettings.endPort)); } else { printLogMsg(String("WireGuard interface initialized.")); - ConfigSettings.wgInit = true; + WgSettings.init = true; } } } @@ -126,30 +117,26 @@ void startServers(bool usb = false) { initWebServer(); if (!usb) - startSoketServer(); + startSocketServer(); startAP(false); mDNS_start(); getZbVer(); - if (ConfigSettings.wgEnable) + if (WgSettings.enable) { wgBegin(); } } -void handletmrNetworkOverseer() +void handleTmrNetworkOverseer() { switch (ConfigSettings.coordinator_mode) { case COORDINATOR_MODE_WIFI: - DEBUG_PRINTLN(F("WiFi.status()")); + DEBUG_PRINT(F("WiFi.status = ")); DEBUG_PRINTLN(WiFi.status()); if (WiFi.isConnected()) { DEBUG_PRINTLN(F("WIFI CONNECTED")); - DEBUG_PRINTLN(F(" ")); - DEBUG_PRINTLN(WiFi.localIP()); - DEBUG_PRINTLN(WiFi.subnetMask()); - DEBUG_PRINTLN(WiFi.gatewayIP()); startServers(); tmrNetworkOverseer.stop(); } @@ -212,9 +199,9 @@ void handletmrNetworkOverseer() } } -void WiFiEvent(WiFiEvent_t event) +void NetworkEvent(WiFiEvent_t event) { - DEBUG_PRINT(F("WiFiEvent ")); + DEBUG_PRINT(F("NetworkEvent ")); DEBUG_PRINTLN(event); switch (event) { @@ -242,9 +229,7 @@ void WiFiEvent(WiFiEvent_t event) // ConfigSettings.disconnectEthTime = 0; // mDNS_start(); break; - case SYSTEM_EVENT_STA_GOT_IP: - DEBUG_PRINTLN(F("SYSTEM_EVENT_STA_GOT_IP")); - case 21: // SYSTEM_EVENT_ETH_DISCONNECTED: + case 21: //SYSTEM_EVENT_ETH_DISCONNECTED: DEBUG_PRINTLN(F("ETH Disconnected")); ConfigSettings.connectedEther = false; // ConfigSettings.disconnectEthTime = millis(); @@ -262,6 +247,14 @@ void WiFiEvent(WiFiEvent_t event) tmrNetworkOverseer.start(); } break; + case SYSTEM_EVENT_STA_GOT_IP: + DEBUG_PRINTLN(F("SYSTEM_EVENT_STA_GOT_IP")); + DEBUG_PRINT(F("IPv4: ")); + DEBUG_PRINT(WiFi.localIP().toString()); + DEBUG_PRINT(F(", ")); + DEBUG_PRINT(WiFi.subnetMask().toString()); + DEBUG_PRINT(F(", ")); + DEBUG_PRINTLN(WiFi.gatewayIP().toString()); case SYSTEM_EVENT_STA_DISCONNECTED: DEBUG_PRINTLN(F("WIFI STA DISCONNECTED")); if (tmrNetworkOverseer.state() == STOPPED) @@ -350,7 +343,6 @@ bool loadSystemVar() DEBUG_PRINTLN(F("saved tempOffset in system.json")); ConfigSettings.tempOffset = int(tempOffset.toInt()); } - // ConfigSettings.restarts = (int)doc["restarts"]; configFile.close(); return true; } @@ -376,7 +368,7 @@ bool loadConfigWifi() doc[ip] = ""; doc[mask] = ""; doc[gw] = ""; - writeDefultConfig(configFileWifi, doc); + writeDefaultConfig(configFileWifi, doc); } configFile = LittleFS.open(configFileWifi, FILE_READ); @@ -422,7 +414,7 @@ bool loadConfigEther() doc[gw] = ""; // doc["disablePingCtrl"] = 0; // String StringConfig = "{\"dhcp\":1,\"ip\":\"\",\"mask\":\"\",\"gw\":\"\",\"disablePingCtrl\":0}"; - writeDefultConfig(configFileEther, doc); + writeDefaultConfig(configFileEther, doc); } configFile = LittleFS.open(configFileEther, FILE_READ); @@ -458,6 +450,7 @@ bool loadConfigGeneral() const char *disableLedUSB = "disableLedUSB"; const char *prevCoordMode = "prevCoordMode"; const char *keepWeb = "keepWeb"; + const char *timeZoneName = "timeZoneName"; File configFile = LittleFS.open(configFileGeneral, FILE_READ); DEBUG_PRINTLN(configFile.readString()); if (!configFile) @@ -475,7 +468,7 @@ bool loadConfigGeneral() doc[coordMode] = 0; doc[prevCoordMode] = 0; doc[keepWeb] = 0; - writeDefultConfig(configFileGeneral, doc); + writeDefaultConfig(configFileGeneral, doc); } configFile = LittleFS.open(configFileGeneral, FILE_READ); @@ -508,12 +501,14 @@ bool loadConfigGeneral() DEBUG_PRINTLN(F("[loadConfigGeneral] 'static_cast' res is:")); DEBUG_PRINTLN(String(ConfigSettings.coordinator_mode)); ConfigSettings.disableLedPwr = (uint8_t)doc[disableLedPwr]; - DEBUG_PRINTLN(F("[loadConfigGeneral] disableLedPwr")); + //DEBUG_PRINTLN(F("[loadConfigGeneral] disableLedPwr")); ConfigSettings.disableLedUSB = (uint8_t)doc[disableLedUSB]; - DEBUG_PRINTLN(F("[loadConfigGeneral] disableLedUSB")); + //DEBUG_PRINTLN(F("[loadConfigGeneral] disableLedUSB")); ConfigSettings.disableLeds = (uint8_t)doc[disableLeds]; - DEBUG_PRINTLN(F("[loadConfigGeneral] disableLeds")); + //DEBUG_PRINTLN(F("[loadConfigGeneral] disableLeds")); ConfigSettings.keepWeb = (uint8_t)doc[keepWeb]; + //DEBUG_PRINTLN(F("[loadConfigGeneral] disableLeds")); + strlcpy(ConfigSettings.timeZone, doc[timeZoneName] | "", sizeof(ConfigSettings.timeZone)); configFile.close(); DEBUG_PRINTLN(F("[loadConfigGeneral] config load done")); return true; @@ -538,7 +533,7 @@ bool loadConfigSecurity() doc[webPass] = ""; doc[fwEnabled] = 0; doc[fwIp] = ""; - writeDefultConfig(configFileSecurity, doc); + writeDefaultConfig(configFileSecurity, doc); } configFile = LittleFS.open(configFileSecurity, FILE_READ); @@ -577,7 +572,7 @@ bool loadConfigSerial() DynamicJsonDocument doc(1024); doc[baud] = 115200; doc[port] = 6638; - writeDefultConfig(configFileSerial, doc); + writeDefaultConfig(configFileSerial, doc); } configFile = LittleFS.open(configFileSerial, FILE_READ); @@ -630,7 +625,7 @@ bool loadConfigMqtt() doc[topic] = String(deviceIdArr); doc[interval] = 60; doc[discovery] = 0; - writeDefultConfig(configFileMqtt, doc); + writeDefaultConfig(configFileMqtt, doc); } configFile = LittleFS.open(configFileMqtt, FILE_READ); @@ -646,15 +641,15 @@ bool loadConfigMqtt() return false; } - ConfigSettings.mqttEnable = (int)doc[enable]; - strlcpy(ConfigSettings.mqttServer, doc[server] | "", sizeof(ConfigSettings.mqttServer)); - ConfigSettings.mqttServerIP = parse_ip_address(ConfigSettings.mqttServer); - ConfigSettings.mqttPort = (int)doc[port]; - strlcpy(ConfigSettings.mqttUser, doc[user] | "", sizeof(ConfigSettings.mqttUser)); - strlcpy(ConfigSettings.mqttPass, doc[pass] | "", sizeof(ConfigSettings.mqttPass)); - strlcpy(ConfigSettings.mqttTopic, doc[topic] | "", sizeof(ConfigSettings.mqttTopic)); - ConfigSettings.mqttInterval = (int)doc[interval]; - ConfigSettings.mqttDiscovery = (int)doc[discovery]; + MqttSettings.enable = (int)doc[enable]; + strlcpy(MqttSettings.server, doc[server] | "", sizeof(MqttSettings.server)); + MqttSettings.serverIP = parse_ip_address(MqttSettings.server); + MqttSettings.port = (int)doc[port]; + strlcpy(MqttSettings.user, doc[user] | "", sizeof(MqttSettings.user)); + strlcpy(MqttSettings.pass, doc[pass] | "", sizeof(MqttSettings.pass)); + strlcpy(MqttSettings.topic, doc[topic] | "", sizeof(MqttSettings.topic)); + MqttSettings.interval = (int)doc[interval]; + MqttSettings.discovery = (int)doc[discovery]; configFile.close(); return true; @@ -664,7 +659,7 @@ bool loadConfigWg() { const char *enable = "enable"; const char *localAddr = "localAddr"; - const char *localPrivKey = "localPrivKey"; + const char *localIP = "localIP"; const char *endAddr = "endAddr"; const char *endPubKey = "endPubKey"; const char *endPort = "endPort"; @@ -675,11 +670,11 @@ bool loadConfigWg() DynamicJsonDocument doc(1024); doc[enable] = 0; doc[localAddr] = ""; - doc[localPrivKey] = ""; + doc[localIP] = ""; doc[endAddr] = ""; doc[endPubKey] = ""; doc[endPort] = ""; - writeDefultConfig(configFileWg, doc); + writeDefaultConfig(configFileWg, doc); } configFile = LittleFS.open(configFileWg, FILE_READ); @@ -695,15 +690,15 @@ bool loadConfigWg() return false; } - ConfigSettings.wgEnable = (int)doc[enable]; + WgSettings.enable = (int)doc[enable]; - strlcpy(ConfigSettings.wgLocalAddr, doc[localAddr] | "", sizeof(ConfigSettings.wgLocalAddr)); - ConfigSettings.wgLocalIP = parse_ip_address(ConfigSettings.wgLocalAddr); + strlcpy(WgSettings.localAddr, doc[localAddr] | "", sizeof(WgSettings.localAddr)); + WgSettings.localIP = parse_ip_address(WgSettings.localAddr); - strlcpy(ConfigSettings.wgLocalPrivKey, doc[localPrivKey] | "", sizeof(ConfigSettings.wgLocalPrivKey)); - strlcpy(ConfigSettings.wgEndAddr, doc[endAddr] | "", sizeof(ConfigSettings.wgEndAddr)); - strlcpy(ConfigSettings.wgEndPubKey, doc[endPubKey] | "", sizeof(ConfigSettings.wgEndPubKey)); - ConfigSettings.wgEndPort = (int)doc[endPort]; + strlcpy(WgSettings.localPrivKey, doc[localIP] | "", sizeof(WgSettings.localPrivKey)); + strlcpy(WgSettings.endAddr, doc[endAddr] | "", sizeof(WgSettings.endAddr)); + strlcpy(WgSettings.endPubKey, doc[endPubKey] | "", sizeof(WgSettings.endPubKey)); + WgSettings.endPort = (int)doc[endPort]; configFile.close(); return true; @@ -903,7 +898,7 @@ void setLedsDisable(bool mode, bool setup) DEBUG_PRINTLN(F("[setLedsDisable] done")); } -void handlelongBtn() +void handleLongBtn() { if (!digitalRead(BTN)) { // long press @@ -982,7 +977,7 @@ void setupCoordinatorMode() { tmrNetworkOverseer.start(); } - WiFi.onEvent(WiFiEvent); + WiFi.onEvent(NetworkEvent); } switch (ConfigSettings.coordinator_mode) { @@ -1079,7 +1074,7 @@ void setup() // chipDetector.cmdGetChipId(); String zb_chip = chipDetector.detectChipInfo(); - Serial.println(zb_chip); + DEBUG_PRINTLN(zb_chip); printLogMsg(String("[ZBCHIP] ") + zb_chip); zbVer.chipID = zb_chip; zigbeeRestart(); @@ -1091,7 +1086,7 @@ void setup() { String msg = "No connection with Zigbee"; printLogMsg(String("[ZBCHIP] ") + msg); - Serial.println(msg); + DEBUG_PRINTLN(msg); } //----------------- @@ -1123,10 +1118,6 @@ void setup() else { DEBUG_PRINTLN(F("System vars load OK")); - // ConfigSettings.restarts++; - // DEBUG_PRINT(F("Restarts count ")); - // DEBUG_PRINTLN(ConfigSettings.restarts); - // saveRestartCount(ConfigSettings.restarts); } if (!loadConfigSerial()) @@ -1154,7 +1145,7 @@ void setup() setupCoordinatorMode(); ConfigSettings.connectedClients = 0; - if (ConfigSettings.mqttEnable) + if (MqttSettings.enable) { mqttConnectSetup(); } @@ -1391,7 +1382,7 @@ void loop(void) serial_bytes_read = 0; } - if (ConfigSettings.mqttEnable) + if (MqttSettings.enable) { mqttLoop(); } diff --git a/src/mqtt.cpp b/src/mqtt.cpp index 00d03ad..b76fa4a 100644 --- a/src/mqtt.cpp +++ b/src/mqtt.cpp @@ -15,14 +15,21 @@ extern struct ConfigSettingsStruct ConfigSettings; extern struct zbVerStruct zbVer; +extern struct MqttSettingsStruct MqttSettings; WiFiClient clientMqtt; PubSubClient clientPubSub(clientMqtt); + +const char *homeAssistant = "homeassistant"; +const char *haSensor = "sensor"; +const char *haButton = "button"; +const char *haBinarySensor = "binary_sensor"; + void mqttConnectSetup() { - clientPubSub.setServer(ConfigSettings.mqttServerIP, ConfigSettings.mqttPort); + clientPubSub.setServer(MqttSettings.serverIP, MqttSettings.port); clientPubSub.setCallback(mqttCallback); } @@ -31,15 +38,15 @@ void mqttReconnect() DEBUG_PRINT(F("Attempting MQTT connection...")); byte willQoS = 0; - String willTopic = String(ConfigSettings.mqttTopic) + "/avty"; + String willTopic = String(MqttSettings.topic) + "/avty"; const char *willMessage = "offline"; boolean willRetain = false; char deviceIdArr[20]; getDeviceID(deviceIdArr); - if (clientPubSub.connect(String(deviceIdArr).c_str(), ConfigSettings.mqttUser, ConfigSettings.mqttPass, willTopic.c_str(), willQoS, willRetain, willMessage)) + if (clientPubSub.connect(String(deviceIdArr).c_str(), MqttSettings.user, MqttSettings.pass, willTopic.c_str(), willQoS, willRetain, willMessage)) { - ConfigSettings.mqttReconnectTime = 0; + MqttSettings.reconnectTime = 0; mqttOnConnect(); } else @@ -47,10 +54,10 @@ void mqttReconnect() DEBUG_PRINT(F("failed, rc=")); DEBUG_PRINT(clientPubSub.state()); DEBUG_PRINT(F(" try again in ")); - DEBUG_PRINT(ConfigSettings.mqttInterval); + DEBUG_PRINT(MqttSettings.interval); DEBUG_PRINTLN(F(" seconds")); - ConfigSettings.mqttReconnectTime = millis() + ConfigSettings.mqttInterval * 1000; + MqttSettings.reconnectTime = millis() + MqttSettings.interval * 1000; } } @@ -59,7 +66,7 @@ void mqttOnConnect() DEBUG_PRINTLN(F("connected")); mqttSubscribe("cmd"); DEBUG_PRINTLN(F("mqtt Subscribed")); - if (ConfigSettings.mqttDiscovery) + if (MqttSettings.discovery) { mqttPublishDiscovery(); DEBUG_PRINTLN(F("mqtt Published Discovery")); @@ -70,9 +77,9 @@ void mqttOnConnect() mqttPublishIo("enbl_bsl", "OFF"); mqttPublishIo("socket", "OFF"); DEBUG_PRINTLN(F("mqtt Published IOs")); - mqttPublishAvty(); + mqttPublishAvail(); DEBUG_PRINTLN(F("mqtt Published Avty")); - if (ConfigSettings.mqttInterval > 0) + if (MqttSettings.interval > 0) { mqttPublishState(); DEBUG_PRINTLN(F("mqtt Published State")); @@ -86,9 +93,9 @@ void mqttPublishMsg(String topic, String msg, bool retain) clientPubSub.endPublish(); } -void mqttPublishAvty() +void mqttPublishAvail() { - String topic(ConfigSettings.mqttTopic); + String topic(MqttSettings.topic); topic = topic + "/avty"; String mqttBuffer = "online"; clientPubSub.publish(topic.c_str(), mqttBuffer.c_str(), true); @@ -96,7 +103,7 @@ void mqttPublishAvty() void mqttPublishState() { - String topic(ConfigSettings.mqttTopic); + String topic(MqttSettings.topic); topic = topic + "/state"; DynamicJsonDocument root(1024); String readableTime; @@ -158,14 +165,14 @@ void mqttPublishState() serializeJson(root, mqttBuffer); DEBUG_PRINTLN(mqttBuffer); clientPubSub.publish(topic.c_str(), mqttBuffer.c_str(), true); - ConfigSettings.mqttHeartbeatTime = millis() + (ConfigSettings.mqttInterval * 1000); + MqttSettings.heartbeatTime = millis() + (MqttSettings.interval * 1000); } void mqttPublishIo(String const &io, String const &state) { if (clientPubSub.connected()) { - String topic(ConfigSettings.mqttTopic); + String topic(MqttSettings.topic); topic = topic + "/io/" + io; clientPubSub.publish(topic.c_str(), state.c_str(), true); } @@ -212,7 +219,7 @@ void mqttCallback(char *topic, byte *payload, unsigned int length) void mqttSubscribe(String topic) { - String mtopic(ConfigSettings.mqttTopic); + String mtopic(MqttSettings.topic); mtopic = mtopic + "/" + topic; clientPubSub.subscribe(mtopic.c_str()); } @@ -221,15 +228,15 @@ void mqttLoop() { if (!clientPubSub.connected()) { - if (ConfigSettings.mqttReconnectTime == 0) + if (MqttSettings.reconnectTime == 0) { //mqttReconnect(); DEBUG_PRINTLN(F("mqttReconnect in 5 seconds")); - ConfigSettings.mqttReconnectTime = millis() + 5000; + MqttSettings.reconnectTime = millis() + 5000; } else { - if (ConfigSettings.mqttReconnectTime <= millis()) + if (MqttSettings.reconnectTime <= millis()) { mqttReconnect(); } @@ -238,9 +245,9 @@ void mqttLoop() else { clientPubSub.loop(); - if (ConfigSettings.mqttInterval > 0) + if (MqttSettings.interval > 0) { - if (ConfigSettings.mqttHeartbeatTime <= millis()) + if (MqttSettings.heartbeatTime <= millis()) { mqttPublishState(); } @@ -250,7 +257,7 @@ void mqttLoop() void mqttPublishDiscovery() { - String mtopic(ConfigSettings.mqttTopic); + String mtopic(MqttSettings.topic); String deviceName = mtopic; //ConfigSettings.hostname; String topic; @@ -262,6 +269,9 @@ void mqttPublishDiscovery() getDeviceID(deviceIdArr); via["ids"] = String(deviceIdArr); + String sensor_topic = String(homeAssistant) + "/" + String(haSensor) + "/"; + String button_topic = String(homeAssistant) + "/" + String(haButton) + "/"; + String binary_sensor_topic = String(homeAssistant) + "/" + String(haBinarySensor) + "/"; //int lastAutoMsg = 9; //if (ConfigSettings.board == 2) lastAutoMsg--; @@ -285,7 +295,7 @@ void mqttPublishDiscovery() sprintf(verArr, "%s (%s)", VERSION, env); dev["sw"] = String(verArr); - topic = "homeassistant/button/" + deviceName + "/rst_esp/config"; + topic = button_topic + deviceName + "/rst_esp/config"; buffJson["name"] = "Restart ESP"; buffJson["uniq_id"] = deviceName + "/rst_esp"; buffJson["stat_t"] = mtopic + "/io/rst_esp"; @@ -298,7 +308,7 @@ void mqttPublishDiscovery() } case 1: { - topic = "homeassistant/button/" + deviceName + "/rst_zig/config"; + topic = button_topic + deviceName + "/rst_zig/config"; buffJson["name"] = "Restart Zigbee"; buffJson["uniq_id"] = deviceName + "/rst_zig"; buffJson["stat_t"] = mtopic + "/io/rst_zig"; @@ -311,7 +321,7 @@ void mqttPublishDiscovery() } case 2: { - topic = "homeassistant/button/" + deviceName + "/enbl_bsl/config"; + topic = button_topic + deviceName + "/enbl_bsl/config"; buffJson["name"] = "Enable BSL"; buffJson["uniq_id"] = deviceName + "/enbl_bsl"; buffJson["stat_t"] = mtopic + "/io/enbl_bsl"; @@ -324,7 +334,7 @@ void mqttPublishDiscovery() } case 3: { - topic = "homeassistant/binary_sensor/" + deviceName + "/socket/config"; + topic = binary_sensor_topic + deviceName + "/socket/config"; buffJson["name"] = "Socket"; buffJson["uniq_id"] = deviceName + "/socket"; buffJson["stat_t"] = mtopic + "/io/socket"; @@ -335,7 +345,7 @@ void mqttPublishDiscovery() } //case 4: //{ - // topic = "homeassistant/binary_sensor/" + deviceName + "/emrgncMd/config"; + // topic = binary_sensor_topic + deviceName + "/emrgncMd/config"; // buffJson["name"] = "Emergency mode"; // buffJson["uniq_id"] = deviceName + "/emrgncMd"; // buffJson["stat_t"] = mtopic + "/state"; @@ -349,7 +359,7 @@ void mqttPublishDiscovery() //} case 4: { - topic = "homeassistant/sensor/" + deviceName + "/uptime/config"; + topic = sensor_topic + deviceName + "/uptime/config"; buffJson["name"] = "Uptime"; buffJson["uniq_id"] = deviceName + "/uptime"; buffJson["stat_t"] = mtopic + "/state"; @@ -362,7 +372,7 @@ void mqttPublishDiscovery() } case 5: { - topic = "homeassistant/sensor/" + deviceName + "/ip/config"; + topic = sensor_topic + deviceName + "/ip/config"; buffJson["name"] = "IP"; buffJson["uniq_id"] = deviceName + "/ip"; buffJson["stat_t"] = mtopic + "/state"; @@ -375,7 +385,7 @@ void mqttPublishDiscovery() } case 6: { - topic = "homeassistant/sensor/" + deviceName + "/temperature/config"; + topic = sensor_topic + deviceName + "/temperature/config"; buffJson["name"] = "ESP temperature"; buffJson["uniq_id"] = deviceName + "/temperature"; buffJson["stat_t"] = mtopic + "/state"; @@ -391,7 +401,7 @@ void mqttPublishDiscovery() } case 7: { - topic = "homeassistant/sensor/" + deviceName + "/hostname/config"; + topic = sensor_topic + deviceName + "/hostname/config"; buffJson["name"] = "Hostname"; buffJson["uniq_id"] = deviceName + "/hostname"; buffJson["stat_t"] = mtopic + "/state"; @@ -404,7 +414,7 @@ void mqttPublishDiscovery() } case 8: { - topic = "homeassistant/sensor/" + deviceName + "/connections/config"; + topic = sensor_topic + deviceName + "/connections/config"; buffJson["name"] = "Socket connections"; buffJson["uniq_id"] = deviceName + "/connections"; buffJson["stat_t"] = mtopic + "/state"; @@ -417,7 +427,7 @@ void mqttPublishDiscovery() } case 9: { - topic = "homeassistant/sensor/" + deviceName + "/mode/config"; + topic = sensor_topic + deviceName + "/mode/config"; buffJson["name"] = "Mode"; buffJson["uniq_id"] = deviceName + "/mode"; buffJson["stat_t"] = mtopic + "/state"; @@ -430,7 +440,7 @@ void mqttPublishDiscovery() } case 10: { - topic = "homeassistant/sensor/" + deviceName + "/zbfw/config"; + topic = sensor_topic + deviceName + "/zbfw/config"; buffJson["name"] = "Zigbee fw rev"; buffJson["uniq_id"] = deviceName + "/zbfw"; buffJson["stat_t"] = mtopic + "/state"; diff --git a/src/mqtt.h b/src/mqtt.h index bbe2ebd..113700d 100644 --- a/src/mqtt.h +++ b/src/mqtt.h @@ -5,7 +5,7 @@ void mqttCallback(char *topic, byte *payload, unsigned int length); void mqttLoop(); void mqttPublishState(); void mqttOnConnect(); -void mqttPublishAvty(); +void mqttPublishAvail(); void mqttPublishDiscovery(); void mqttPublishMsg(String topic, String msg, bool retain); void mqttPublishIo(String const &io, String const &state); diff --git a/src/version.h b/src/version.h index fa184b7..97efc22 100644 --- a/src/version.h +++ b/src/version.h @@ -1,9 +1,9 @@ // AUTO GENERATED FILE, DO NOT EDIT #ifndef VERSION - #define VERSION "0.2.3" + #define VERSION "0.2.4" #endif #ifndef BUILD_TIMESTAMP - #define BUILD_TIMESTAMP "2024-03-16 22:23:51.598701" + #define BUILD_TIMESTAMP "2024-03-16 22:36:55.504633" #endif \ No newline at end of file diff --git a/src/web.cpp b/src/web.cpp index 40f5cf5..e80a036 100644 --- a/src/web.cpp +++ b/src/web.cpp @@ -15,6 +15,7 @@ #include "log.h" #include "etc.h" #include "zb.h" +#include "zones.h" #include "webh/PAGE_WG.html.gz.h" #include "webh/PAGE_MQTT.html.gz.h" @@ -50,6 +51,8 @@ extern struct ConfigSettingsStruct ConfigSettings; extern struct zbVerStruct zbVer; +extern struct MqttSettingsStruct MqttSettings; +extern struct WgSettingsStruct WgSettings; bool wifiWebSetupInProgress = false; extern const char *coordMode; @@ -67,6 +70,7 @@ const char *contTypeTextJs = "text/javascript"; const char *contTypeTextCss = "text/css"; const char *checked = "true"; const char *respHeaderName = "respValuesArr"; +const char *respTimeZonesName = "respTimeZones"; const char *contTypeJson = "application/json"; const char *contTypeText = "text/plain"; @@ -102,6 +106,15 @@ void webServerHandleClient() serverWeb.handleClient(); } +void checkFwHexTask(void *param) +{ + const char *tempFile = static_cast(param); + checkFwHex(tempFile); + + // Завершаем задачу, чтобы освободить выделенные для неё ресурсы + vTaskDelete(NULL); +} + void initWebServer() { serverWeb.on("/js/bootstrap.min.js", []() @@ -171,10 +184,10 @@ void initWebServer() if (!checkAuth()) return; - Serial.println("hostHeader: " + serverWeb.hostHeader()); - // Serial.println("header Content-Length: " + serverWeb.header("Content-Length")); + DEBUG_PRINTLN("hostHeader: " + serverWeb.hostHeader()); + // DEBUG_PRINTLN("header Content-Length: " + serverWeb.header("Content-Length")); contentLength = serverWeb.header("Content-Length").toInt(); - Serial.println("contentLength: " + String(contentLength)); + DEBUG_PRINTLN("contentLength: " + String(contentLength)); DEBUG_PRINTLN("Update ESP from file " + String(upload.filename.c_str()) + " size: " + String(upload.totalSize)); DEBUG_PRINTLN("upload.currentSize " + String(upload.currentSize)); @@ -252,8 +265,8 @@ void initWebServer() { if (!checkAuth()) return; - DEBUG_PRINTLN("Upload zigbee fw file: " + String(upload.filename.c_str())); - printLogMsg("[ZB_FW] upload:" + String(upload.filename.c_str())); + DEBUG_PRINTLN(String(millis()) + " Upload zigbee fw file: " + String(upload.filename.c_str())); + printLogMsg("[ZB_FW] upload: " + String(upload.filename.c_str())); // DEBUG_PRINTLN("size: " + String(String(upload.totalSize).c_str())); // printLogMsg("size:" + String(String(upload.totalSize).c_str())); } @@ -283,13 +296,19 @@ void initWebServer() delay(500); fwFile.close(); delay(500); - DEBUG_PRINTLN(F("UPLOAD_FILE_END")); + DEBUG_PRINTLN(String(millis()) + "UPLOAD_FILE_END"); printLogMsg("[ZB_FW] upload finish!"); opened = false; DEBUG_PRINTLN("Total file size: " + String(upload.totalSize)); - checkFwHex(tempFile); + // checkFwHex(tempFile); + xTaskCreate(checkFwHexTask, // Функция задачи + "CheckFWHex", // Имя задачи для удобства отладки + 8192, // Размер стека задачи (в байтах) + (void *)tempFile, // Параметр, передаваемый в задачу + 3, // Приоритет задачи + NULL); // Указатель на задачу (не используется) } }); @@ -491,13 +510,14 @@ void handleApi() CMD_LED_PWR_TOG, CMD_LED_USB_TOG, CMD_CLEAR_LOG, - CMD_ESP_UPD_GIT, + CMD_ESP_UPD_URL, CMD_ZB_CHK_REV, CMD_ZB_CHK_CON, CMD_ZB_LED_TOG }; String result = wrongArgs; const char *argCmd = "cmd"; + const char *argUrl = "url"; if (serverWeb.hasArg(argCmd)) { result = "ok"; @@ -531,9 +551,11 @@ void handleApi() case CMD_LED_USB_TOG: ledUSBToggle(); break; - case CMD_ESP_UPD_GIT: - getEspUpdate(UPD_FILE); - // downloadURLAndUpdateESP(UPD_FILE); + case CMD_ESP_UPD_URL: + if (serverWeb.hasArg(argUrl)) + getEspUpdate(serverWeb.arg(argUrl)); + else + getEspUpdate(UPD_FILE); break; case CMD_ZB_CHK_REV: getZbVer(); @@ -832,7 +854,6 @@ void handleSaveParams() { doc[disableLedUSB] = zero; } - configFile = LittleFS.open(configFileGeneral, FILE_WRITE); serializeJson(doc, configFile); configFile.close(); } @@ -914,7 +935,7 @@ void handleSaveParams() deserializeJson(doc, configFile); configFile.close(); doc["localAddr"] = serverWeb.arg("WgLocalAddr"); - doc["localPrivKey"] = serverWeb.arg("WgLocalPrivKey"); + doc["localIP"] = serverWeb.arg("WgLocalPrivKey"); doc["endAddr"] = serverWeb.arg("WgEndAddr"); doc["endPubKey"] = serverWeb.arg("WgEndPubKey"); doc["endPort"] = serverWeb.arg("WgEndPort"); @@ -1064,6 +1085,12 @@ void handleSaveParams() doc[hostname] = serverWeb.arg(hostname); strlcpy(ConfigSettings.hostname, serverWeb.arg(hostname).c_str(), sizeof(ConfigSettings.hostname)); } + const char *timeZoneName = "timeZoneName"; + if (serverWeb.hasArg(timeZoneName)) + { + doc[timeZoneName] = serverWeb.arg(timeZoneName); + } + configFile = LittleFS.open(configFileGeneral, FILE_WRITE); configFile = LittleFS.open(configFileGeneral, FILE_WRITE); serializeJson(doc, configFile); configFile.close(); @@ -1245,18 +1272,18 @@ void handleMqtt() String result; DynamicJsonDocument doc(1024); - if (ConfigSettings.mqttEnable) + if (MqttSettings.enable) { doc["enableMqtt"] = checked; } - doc["serverMqtt"] = ConfigSettings.mqttServer; - doc["portMqtt"] = ConfigSettings.mqttPort; - doc["userMqtt"] = ConfigSettings.mqttUser; - doc["passMqtt"] = ConfigSettings.mqttPass; - doc["topicMqtt"] = ConfigSettings.mqttTopic; - doc["intervalMqtt"] = ConfigSettings.mqttInterval; - - if (ConfigSettings.mqttDiscovery) + doc["serverMqtt"] = MqttSettings.server; + doc["portMqtt"] = MqttSettings.port; + doc["userMqtt"] = MqttSettings.user; + doc["passMqtt"] = MqttSettings.pass; + doc["topicMqtt"] = MqttSettings.topic; + doc["intervalMqtt"] = MqttSettings.interval; + + if (MqttSettings.discovery) { doc["discoveryMqtt"] = checked; } @@ -1270,15 +1297,15 @@ void handleWg() String result; DynamicJsonDocument doc(1024); - if (ConfigSettings.wgEnable) + if (WgSettings.enable) { doc["enableWg"] = checked; } - doc["localAddrWg"] = ConfigSettings.wgLocalAddr; - doc["localPrivKeyWg"] = ConfigSettings.wgLocalPrivKey; - doc["endAddrWg"] = ConfigSettings.wgEndAddr; - doc["endPubKeyWg"] = ConfigSettings.wgEndPubKey; - doc["endPortWg"] = ConfigSettings.wgEndPort; + doc["localAddrWg"] = WgSettings.localAddr; + doc["localPrivKeyWg"] = WgSettings.localPrivKey; + doc["endAddrWg"] = WgSettings.endAddr; + doc["endPubKeyWg"] = WgSettings.endPubKey; + doc["endPortWg"] = WgSettings.endPort; serializeJson(doc, result); serverWeb.sendHeader(respHeaderName, result); @@ -1426,7 +1453,7 @@ DynamicJsonDocument getRootData() const char *wifiRssi = "wifiRssi"; const char *wifiIp = "wifiIp"; const char *wifiConnected = "wifiConnected"; - const char *wifiSubnet = "wifiSubnet"; + const char *wifiMask = "wifiMask"; const char *wifiGate = "wifiGate"; const char *wifiEnabled = "wifiEnabled"; const char *wifiMode = "wifiMode"; @@ -1445,7 +1472,7 @@ DynamicJsonDocument getRootData() doc[wifiRssi] = rssiWifi; doc[wifiConnected] = "Connected to " + WiFi.SSID(); doc[wifiIp] = WiFi.localIP().toString(); - doc[wifiSubnet] = WiFi.subnetMask().toString(); + doc[wifiMask] = WiFi.subnetMask().toString(); doc[wifiGate] = WiFi.gatewayIP().toString(); } else @@ -1455,7 +1482,7 @@ DynamicJsonDocument getRootData() doc[wifiRssi] = connecting; doc[wifiConnected] = connecting; doc[wifiIp] = ConfigSettings.dhcpWiFi ? WiFi.localIP().toString() : connecting; - doc[wifiSubnet] = ConfigSettings.dhcpWiFi ? WiFi.subnetMask().toString() : connecting; + doc[wifiMask] = ConfigSettings.dhcpWiFi ? WiFi.subnetMask().toString() : connecting; doc[wifiGate] = ConfigSettings.dhcpWiFi ? WiFi.gatewayIP().toString() : connecting; } if (ConfigSettings.dhcpWiFi) @@ -1474,7 +1501,7 @@ DynamicJsonDocument getRootData() doc[wifiMode] = off; doc[wifiSsid] = off; doc[wifiIp] = off; - doc[wifiSubnet] = off; + doc[wifiMask] = off; doc[wifiGate] = off; doc[wifiRssi] = off; doc[wifiDhcp] = off; @@ -1488,7 +1515,7 @@ DynamicJsonDocument getRootData() sprintf(wifiSsidBuf, "%s (no password)", apSsid); doc[wifiSsid] = wifiSsidBuf; doc[wifiIp] = "192.168.1.1 (UZG-01 web interface)"; - doc[wifiSubnet] = "255.255.255.0 (Access point)"; + doc[wifiMask] = "255.255.255.0 (Access point)"; doc[wifiGate] = "192.168.1.1 (this device)"; doc[wifiDhcp] = "On (Access point)"; doc[wifiModeAPStatus] = "AP started"; @@ -1503,15 +1530,15 @@ DynamicJsonDocument getRootData() // doc[wifiMode] = "Client"; } - //VPN + // VPN const char *wgInit = "wgInit"; const char *wgDeviceAddr = "wgDeviceAddr"; const char *wgRemoteAddr = "wgRemoteAddr"; - doc[wgDeviceAddr] = ConfigSettings.wgLocalAddr; - doc[wgRemoteAddr] = ConfigSettings.wgEndAddr; + doc[wgDeviceAddr] = WgSettings.localAddr; + doc[wgRemoteAddr] = WgSettings.endAddr; - if (ConfigSettings.wgInit) + if (WgSettings.init) { doc[wgInit] = yes; } @@ -1560,11 +1587,27 @@ void handleSysTools() { String result; DynamicJsonDocument doc(512); - // doc["pageName"] = "System and Tools"; + doc["hostname"] = ConfigSettings.hostname; doc["refreshLogs"] = ConfigSettings.refreshLogs; + if (ConfigSettings.timeZone) + { + doc["timeZoneName"] = ConfigSettings.timeZone; + } serializeJson(doc, result); serverWeb.sendHeader(respHeaderName, result); + + DynamicJsonDocument zones(10240); + String results; + + JsonArray zonesArray = zones.to(); + for (int i = 0; i < timeZoneCount; i++) + { + zonesArray.add(timeZones[i].zone); + } + + serializeJson(zones, results); + serverWeb.sendHeader(respTimeZonesName, results); } void handleSavefile() @@ -1658,12 +1701,14 @@ void progressFunc(unsigned int progress, unsigned int total) float percent = ((float)progress / total) * 100.0; sendEvent(tagESP_FW_progress, eventLen, String(percent)); - printLogMsg(String(percent)); + // printLogMsg(String(percent)); +#ifdef DEBUG if (int(percent) % 5 == 0) { DEBUG_PRINTLN("Update ESP32 progress: " + String(progress) + " of " + String(total) + " | " + String(percent) + "%"); } +#endif }; int totalLength; // total size of firmware @@ -1744,215 +1789,3 @@ void runEspUpdateFirmware(uint8_t *data, size_t len) // Restart ESP32 to see changes ESP.restart(); } - -/*void runESPUpdateFirmware(uint8_t *data, size_t len) -{ // todo del - // DEBUG_PRINT("-"); - // DEBUG_PRINT(len); - // size_t cur = - // DEBUG_PRINT("!"); - // DEBUG_PRINTLN(cur); - if (Update.write(data, len) != len) - { - DEBUG_PRINT(F("Write error: ")); - Update.printError(Serial); - } -} - -void downloadURLAndUpdateESP(String esp_fw_url) -{ - int totalLength; // total size of firmware - //int currentLength = 0; // current size of written firmware - setClock(); - HTTPClient https; - WiFiClientSecure client; - client.setInsecure(); // the magic line, use with caution - https.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS); - https.begin(client, esp_fw_url); - https.addHeader("Content-Type", "application/octet-stream"); - - // Get file, just to check if each reachable - int resp = https.GET(); - - DEBUG_PRINTLN(F("Response: ")); - DEBUG_PRINTLN(resp); - // If file is reachable, start downloading - if (resp == HTTP_CODE_OK) - { - // get length of document (is -1 when Server sends no Content-Length header) - totalLength = https.getSize(); - // transfer to local variable - int len = totalLength; - // this is required to start firmware update process - // Update.begin(UPDATE_SIZE_UNKNOWN); - Update.begin(totalLength); - Update.onProgress(progressFunc); - - DEBUG_PRINT("FW Size: "); - DEBUG_PRINTLN(totalLength); - - DEBUG_PRINTLN("Updating firmware..."); - - uint8_t buff[128]; - uint32_t downloaded = 0; - while (client.readBytes(buff, sizeof(buff))) - { - size_t size = client.available(); - - if (size) - { - runESPUpdateFirmware(buff, ((size > sizeof(buff)) ? sizeof(buff) : size)); - } - } - if (Update.end(true)) - { // true to set the size to the current progress - DEBUG_PRINTLN("Update Success"); - // Restart ESP32 to see changes - DEBUG_PRINTLN("Rebooting..."); - ESP.restart(); - // serverWeb.send(HTTP_CODE_OK, contTypeText, (Update.hasError()) ? "FAIL" : "OK"); - } - else - { - DEBUG_PRINT(F("Update error: ")); - Update.printError(Serial); - } - - } - else - { - DEBUG_PRINTLN(F("Cannot download firmware file. Only HTTP response 200: OK is supported. Double check firmware location #defined in UPD_FILE.")); - } - https.end(); -}*/ - -/* // debug - clean - delete -void getEspUpdate() -{ // todo del - - WiFiClientSecure *client0 = new WiFiClientSecure; - if (client0) - { - // set secure client without certificate - client0->setInsecure(); - // create an HTTPClient instance - setClock(); - HTTPClient https0; - - // Initializing an HTTPS communication using the secure client - DEBUG_PRINTLN(F("[HTTPS] begin...")); - if (https0.begin(*client0, "https://www.howsmyssl.com/a/check")) - { // HTTPS - DEBUG_PRINTLN(F("[HTTPS] GET...")); - // start connection and send HTTP header - int httpCode0 = https0.GET(); - // httpCode will be negative on error - if (httpCode0 > 0) - { - // HTTP header has been send and Server response header has been handled - DEBUG_PRINTLN("[HTTPS] GET... code: " + httpCode0); - // file found at server - if (httpCode0 == HTTP_CODE_OK || httpCode0 == HTTP_CODE_MOVED_PERMANENTLY) - { - // print server response payload - String payload = https0.getString(); - DEBUG_PRINTLN(payload); - } - } - else - { - DEBUG_PRINTLN("[HTTPS] GET... failed, error: " + String(https0.errorToString(httpCode0).c_str())); - } - https0.end(); - } - } - else - { - DEBUG_PRINTLN(F("[HTTPS] Unable to connect")); - } - - DEBUG_PRINTLN(F("Waiting 2s before the next round...")); - delay(2000); - setClock(); - HTTPClient https; - WiFiClientSecure client; - client.setInsecure(); - https.begin(client, "https://raw.githubusercontent.com/Tarik2142/devHost/main/router_20221102.bin"); // 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); - DEBUG_PRINTLN(String("REQ result: " + String(httpsCode))); - if (httpsCode == HTTP_CODE_OK) - { - const uint32_t fwSize = https.getSize(); - // sendEvent(tagZB_FW_info, eventLen, "[start]"); - DEBUG_PRINTLN(F("[start]")); - // sendEvent(tagZB_FW_info, eventLen, "Downloading firmware..."); - DEBUG_PRINTLN(F("Downloading firmware...")); - const char *tempFile3 = "/config/router.bin"; - LittleFS.remove(tempFile3); - File fwFile = LittleFS.open(tempFile3, "w", 1); - uint8_t buff[4]; - uint32_t downloaded = 0; - while (client.readBytes(buff, sizeof(buff))) - { - downloaded += fwFile.write(buff, sizeof(buff)); - if (!(downloaded % 8192)) - { - const uint8_t d = ((float)downloaded / fwSize) * 100; - // sendEvent(tagZB_FW_progress, eventLen, String(d)); - } - } - fwFile.close(); - // in development - } - else - { - // serverWeb.send(HTTP_CODE_BAD_REQUEST, contTypeText, String(httpsCode)); - DEBUG_PRINTLN(F(httpsCode)); - } - - /* DEBUG_PRINTLN(F()); - DEBUG_PRINTLN(F("Waiting 2min before the next round...")); - delay(120000); - - - - //WiFiClientSecure clientSSL; - - //const char * git_url = "https://github.com/"; - - //clientSSL.setInsecure(); //the magic line, use with caution - //clientSSL.connect(git_url, 443); - - //clientWeb.begin(UPD_FILE); - //clientWeb.begin(clientSSL, UPD_FILE); - - //clientWeb.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS); - //client.setCACert(test_root_ca); - - //clientWeb.begin(url); - - -} */ - -void setClock() -{ - configTime(0, 0, "pool.ntp.org"); - - Serial.print(F("Waiting for NTP time sync: ")); - time_t nowSecs = time(nullptr); - while ((nowSecs < 8 * 3600 * 2)) - { - delay(500); - Serial.print(F(".")); - yield(); - nowSecs = time(nullptr); - } - - Serial.println(); - struct tm timeinfo; - gmtime_r(&nowSecs, &timeinfo); - Serial.print(F("Current time: ")); - Serial.print(asctime(&timeinfo)); -} diff --git a/src/web.h b/src/web.h index 168ad83..9c81d46 100644 --- a/src/web.h +++ b/src/web.h @@ -22,14 +22,10 @@ void printLogMsg(String msg); void handleSaveParams(); bool checkAuth(); - +void sendEvent(const char *event, const uint8_t evsz, const String data); void progressFunc(unsigned int progress, unsigned int total); -//void getEspUpdate(); -//void runESPUpdateFirmware(uint8_t *data, size_t len); -//void downloadURLAndUpdateESP(String esp_fw_url); + void getEspUpdate(String esp_fw_url); void runEspUpdateFirmware(uint8_t *data, size_t len); -void setClock(); - #define UPD_FILE "https://github.com/mercenaruss/uzg-firmware/releases/latest/download/UZG-01.bin" \ No newline at end of file diff --git a/src/websrc/html/PAGE_ABOUT.html b/src/websrc/html/PAGE_ABOUT.html index acc7be7..e69de29 100644 --- a/src/websrc/html/PAGE_ABOUT.html +++ b/src/websrc/html/PAGE_ABOUT.html @@ -1,31 +0,0 @@ - \ No newline at end of file diff --git a/src/websrc/html/PAGE_LOADER.html b/src/websrc/html/PAGE_LOADER.html index 3609ba1..457267d 100644 --- a/src/websrc/html/PAGE_LOADER.html +++ b/src/websrc/html/PAGE_LOADER.html @@ -70,7 +70,7 @@

+ UZG-01 diff --git a/src/websrc/html/PAGE_ROOT.html b/src/websrc/html/PAGE_ROOT.html index 59ab3ce..afa6643 100644 --- a/src/websrc/html/PAGE_ROOT.html +++ b/src/websrc/html/PAGE_ROOT.html @@ -158,7 +158,7 @@ Subnet mask: - + Default gateway: diff --git a/src/websrc/html/PAGE_SYSTOOLS.html b/src/websrc/html/PAGE_SYSTOOLS.html index d16133c..cf5c3c8 100644 --- a/src/websrc/html/PAGE_SYSTOOLS.html +++ b/src/websrc/html/PAGE_SYSTOOLS.html @@ -44,6 +44,9 @@ + +
@@ -207,7 +210,7 @@
- + -