From f38dcea1f1188eaa513074b217944f1658024f27 Mon Sep 17 00:00:00 2001 From: cjkas Date: Tue, 24 Mar 2026 20:08:17 +0100 Subject: [PATCH 1/3] add archive for last 10 builds --- .gitignore | 3 ++- archive_elf.py | 45 +++++++++++++++++++++++++++++++++++++++++++++ platformio.ini | 22 ++++++++++++++-------- 3 files changed, 61 insertions(+), 9 deletions(-) create mode 100644 archive_elf.py diff --git a/.gitignore b/.gitignore index 5609aab..d384d46 100644 --- a/.gitignore +++ b/.gitignore @@ -14,4 +14,5 @@ data/ build/ coredump_report.txt coredump.bin -logs/ \ No newline at end of file +logs/ +elf_archive/ \ No newline at end of file diff --git a/archive_elf.py b/archive_elf.py new file mode 100644 index 0000000..0e5416e --- /dev/null +++ b/archive_elf.py @@ -0,0 +1,45 @@ +""" +PlatformIO post-build script: archive firmware.elf files. + +Copies firmware.elf to elf_archive/ with a timestamp after each build. +Keeps only the last 10 files to avoid filling up disk space. + +Usage in platformio.ini +----------------------- + extra_scripts = post:archive_elf.py +""" + +Import("env") + +import os +import shutil +from datetime import datetime + +MAX_ARCHIVES = 10 +ARCHIVE_DIR = os.path.join(env.subst("$PROJECT_DIR"), "elf_archive") + + +def archive_elf(source, target, env): + elf_path = os.path.join(env.subst("$BUILD_DIR"), "firmware.elf") + if not os.path.isfile(elf_path): + print("[archive_elf] firmware.elf not found, skipping.") + return + + os.makedirs(ARCHIVE_DIR, exist_ok=True) + + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") + dest = os.path.join(ARCHIVE_DIR, f"firmware_{timestamp}.elf") + shutil.copy2(elf_path, dest) + print(f"[archive_elf] Saved {dest}") + + # Keep only the last MAX_ARCHIVES files + files = sorted( + [f for f in os.listdir(ARCHIVE_DIR) if f.endswith(".elf")], + ) + while len(files) > MAX_ARCHIVES: + old = os.path.join(ARCHIVE_DIR, files.pop(0)) + os.remove(old) + print(f"[archive_elf] Removed old archive {old}") + + +env.AddPostAction("$BUILD_DIR/firmware.elf", archive_elf) diff --git a/platformio.ini b/platformio.ini index 2141691..78f2179 100644 --- a/platformio.ini +++ b/platformio.ini @@ -1,30 +1,38 @@ ; PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples ; https://docs.platformio.org/page/projectconf.html [platformio] -default_envs = esp32dev +default_envs = esp32devdbg -; Shared settings for all environments [env] platform = espressif32 framework = arduino -lib_deps = +lib_deps = bblanchon/ArduinoJson@^7.2.2 lsatan/SmartRC-CC1101-Driver-Lib@^2.5.7 knolleary/PubSubClient@^2.8 esp32async/ESPAsyncWebServer@^3.10.3 esp32async/AsyncTCP@^3.4.10 -extra_scripts = pre:minify.py +extra_scripts = + pre:minify.py + post:archive_elf.py board_build.partitions = huge_app.csv board_build.filesystem = littlefs -build_flags = +build_flags = -DCONFIG_ESP_COREDUMP_ENABLE_TO_FLASH=1 -DCONFIG_ESP_COREDUMP_DATA_FORMAT_ELF=1 -DCONFIG_ESP_COREDUMP_CHECKSUM_CRC32=1 -DCONFIG_ESP_TASK_WDT_PANIC=1 -DCONFIG_ESP_COREDUMP_DECODE_INFO=1 monitor_speed = 115200 -monitor_filters = +monitor_filters = time esp32_exception_decoder log2file @@ -35,5 +43,3 @@ board = esp32dev [env:esp32devdbg] board = esp32dev build_type = debug - - From a220b9ecc2a63dfdd95b7b672d233622d74c22a8 Mon Sep 17 00:00:00 2001 From: cjkas Date: Tue, 24 Mar 2026 20:28:06 +0100 Subject: [PATCH 2/3] replace Serial.print with logger --- platformio.ini | 3 +- src/ConfigFile.cpp | 93 +++++------ src/ConfigSettings.cpp | 72 +++------ src/ConfigSettings.h | 2 +- src/GitOTA.cpp | 60 ++++--- src/MQTT.cpp | 33 ++-- src/Network.cpp | 133 ++++++---------- src/SSDP.cpp | 29 ++-- src/Sockets.cpp | 21 +-- src/Somfy.cpp | 338 ++++++++++++++++------------------------ src/SomfyController.ino | 57 ++++--- src/WResp.cpp | 6 +- src/Web.cpp | 112 +++++++------ 13 files changed, 397 insertions(+), 562 deletions(-) diff --git a/platformio.ini b/platformio.ini index 78f2179..6d0d8de 100644 --- a/platformio.ini +++ b/platformio.ini @@ -25,7 +25,8 @@ extra_scripts = post:archive_elf.py board_build.partitions = huge_app.csv board_build.filesystem = littlefs -build_flags = +build_flags = + -DCORE_DEBUG_LEVEL=3 -DCONFIG_ESP_COREDUMP_ENABLE_TO_FLASH=1 -DCONFIG_ESP_COREDUMP_DATA_FORMAT_ELF=1 -DCONFIG_ESP_COREDUMP_CHECKSUM_CRC32=1 diff --git a/src/ConfigFile.cpp b/src/ConfigFile.cpp index 43fcbb7..2454499 100644 --- a/src/ConfigFile.cpp +++ b/src/ConfigFile.cpp @@ -1,10 +1,13 @@ #include #include #include +#include "esp_log.h" #include "ConfigFile.h" #include "Utils.h" #include "ConfigSettings.h" +static const char *TAG = "ConfigFile"; + extern Preferences pref; #define SHADE_HDR_VER 24 @@ -68,7 +71,7 @@ bool ConfigFile::writeHeader(const config_header_t &hdr) { bool ConfigFile::readHeader() { if(!this->isOpen()) return false; //if(this->file.position() != 0) this->file.seek(0, SeekSet); - Serial.printf("Reading header at %u\n", this->file.position()); + ESP_LOGD(TAG, "Reading header at %u", this->file.position()); this->header.version = this->readUInt8(this->header.version); this->header.length = this->readUInt8(0); if(this->header.version >= 19) { @@ -93,7 +96,7 @@ bool ConfigFile::readHeader() { this->header.transRecordSize = this->readUInt16(this->header.transRecordSize); this->readString(this->header.serverId, sizeof(this->header.serverId)); } - Serial.printf("version:%u len:%u roomSize:%u roomRecs:%u shadeSize:%u shadeRecs:%u groupSize:%u groupRecs: %u pos:%d\n", this->header.version, this->header.length, this->header.roomRecordSize, this->header.roomRecords, this->header.shadeRecordSize, this->header.shadeRecords, this->header.groupRecordSize, this->header.groupRecords, this->file.position()); + ESP_LOGD(TAG, "version:%u len:%u roomSize:%u roomRecs:%u shadeSize:%u shadeRecs:%u groupSize:%u groupRecs: %u pos:%d", this->header.version, this->header.length, this->header.roomRecordSize, this->header.roomRecords, this->header.shadeRecordSize, this->header.shadeRecords, this->header.groupRecordSize, this->header.groupRecords, this->file.position()); return true; } /* @@ -403,39 +406,34 @@ bool ShadeConfigFile::backup(SomfyShadeController *s) { bool ShadeConfigFile::validate() { this->readHeader(); if(this->header.version < 1) { - Serial.print("Invalid Header Version:"); - Serial.println(this->header.version); + ESP_LOGE(TAG, "Invalid Header Version:%u", this->header.version); return false; } if(this->header.shadeRecordSize < 100) { - Serial.print("Invalid Shade Record Size:"); - Serial.println(this->header.shadeRecordSize); + ESP_LOGE(TAG, "Invalid Shade Record Size:%u", this->header.shadeRecordSize); return false; } /* if(this->header.shadeRecords != SOMFY_MAX_SHADES) { - Serial.print("Invalid Shade Record Count:"); - Serial.println(this->header.shadeRecords); + ESP_LOGE(TAG, "Invalid Shade Record Count:%u", this->header.shadeRecords); return false; } */ if(this->header.version > 10) { if(this->header.groupRecordSize < 100) { - Serial.print("Invalid Group Record Size:"); - Serial.println(this->header.groupRecordSize); + ESP_LOGE(TAG, "Invalid Group Record Size:%u", this->header.groupRecordSize); return false; } /* if(this->header.groupRecords != SOMFY_MAX_GROUPS) { - Serial.print("Invalid Group Record Count:"); - Serial.println(this->header.groupRecords); + ESP_LOGE(TAG, "Invalid Group Record Count:%u", this->header.groupRecords); return false; } */ } if(this->file.position() != this->header.length) { - Serial.printf("File not positioned at %u end of header: %d\n", this->header.length, this->file.position()); + ESP_LOGE(TAG, "File not positioned at %u end of header: %d", this->header.length, this->file.position()); return false; } @@ -452,7 +450,7 @@ bool ShadeConfigFile::validate() { fsize += (this->header.repeaterRecordSize * this->header.repeaterRecords); } if(this->file.size() != fsize) { - Serial.printf("File size is not correct should be %d and got %d\n", fsize, this->file.size()); + ESP_LOGE(TAG, "File size is not correct should be %d and got %d", fsize, this->file.size()); } // Next check to see if the records match the header length. uint8_t recs = 0; @@ -461,11 +459,11 @@ bool ShadeConfigFile::validate() { while(recs < this->header.roomRecords) { uint32_t pos = this->file.position(); if(!this->seekChar(CFG_REC_END)) { - Serial.printf("Failed to find the room record end %d\n", recs); + ESP_LOGE(TAG, "Failed to find the room record end %d", recs); return false; } if(this->file.position() - pos != this->header.roomRecordSize) { - Serial.printf("Room record length is %d and should be %d\n", this->file.position() - pos, this->header.roomRecordSize); + ESP_LOGE(TAG, "Room record length is %d and should be %d", this->file.position() - pos, this->header.roomRecordSize); return false; } recs++; @@ -475,11 +473,11 @@ bool ShadeConfigFile::validate() { while(recs < this->header.shadeRecords) { uint32_t pos = this->file.position(); if(!this->seekChar(CFG_REC_END)) { - Serial.printf("Failed to find the shade record end %d\n", recs); + ESP_LOGE(TAG, "Failed to find the shade record end %d", recs); return false; } if(this->file.position() - pos != this->header.shadeRecordSize) { - Serial.printf("Shade record length is %d and should be %d\n", this->file.position() - pos, this->header.shadeRecordSize); + ESP_LOGE(TAG, "Shade record length is %d and should be %d", this->file.position() - pos, this->header.shadeRecordSize); return false; } recs++; @@ -489,12 +487,12 @@ bool ShadeConfigFile::validate() { while(recs < this->header.groupRecords) { uint32_t pos = this->file.position(); if(!this->seekChar(CFG_REC_END)) { - Serial.printf("Failed to find the group record end %d\n", recs); + ESP_LOGE(TAG, "Failed to find the group record end %d", recs); return false; } recs++; if(this->file.position() - pos != this->header.groupRecordSize) { - Serial.printf("Group record length is %d and should be %d\n", this->file.position() - pos, this->header.groupRecordSize); + ESP_LOGE(TAG, "Group record length is %d and should be %d", this->file.position() - pos, this->header.groupRecordSize); return false; } } @@ -504,7 +502,7 @@ bool ShadeConfigFile::validate() { while(recs < this->header.repeaterRecords) { //uint32_t pos = this->file.position(); if(!this->seekChar(CFG_REC_END)) { - Serial.printf("Failed to find the repeater record end %d\n", recs); + ESP_LOGE(TAG, "Failed to find the repeater record end %d", recs); } recs++; @@ -534,30 +532,27 @@ bool ShadeConfigFile::restore(SomfyShadeController *s, const char *filename, res bool ShadeConfigFile::restoreFile(SomfyShadeController *s, const char *filename, restore_options_t &opts) { bool opened = false; if(!this->isOpen()) { - Serial.println("Opening shade restore file"); + ESP_LOGI(TAG, "Opening shade restore file"); this->begin(filename, true); opened = true; } if(!this->validate()) { - Serial.println("Shade restore file invalid!"); + ESP_LOGE(TAG, "Shade restore file invalid!"); if(opened) this->end(); return false; } if(opts.shades) { - Serial.println("Restoring Rooms..."); + ESP_LOGI(TAG, "Restoring Rooms..."); for(uint8_t i = 0; i < this->header.roomRecords; i++) { this->readRoomRecord(&s->rooms[i]); - if(i > 0) Serial.print(","); - Serial.print(s->rooms[i].roomId); + ESP_LOGD(TAG, "Room %u", s->rooms[i].roomId); } - Serial.println("Restoring Shades..."); + ESP_LOGI(TAG, "Restoring Shades..."); // We should be valid so start reading. for(uint8_t i = 0; i < this->header.shadeRecords; i++) { this->readShadeRecord(&s->shades[i]); - if(i > 0) Serial.print(","); - Serial.print(s->shades[i].getShadeId()); + ESP_LOGD(TAG, "Shade %u", s->shades[i].getShadeId()); } - Serial.println(""); if(this->header.shadeRecords < SOMFY_MAX_SHADES) { uint8_t ndx = this->header.shadeRecords; // Clear out any positions that are not in the shade file. @@ -565,13 +560,11 @@ bool ShadeConfigFile::restoreFile(SomfyShadeController *s, const char *filename, ((SomfyShade *)&s->shades[ndx++])->clear(); } } - Serial.println("Restoring Groups..."); + ESP_LOGI(TAG, "Restoring Groups..."); for(uint8_t i = 0; i < this->header.groupRecords; i++) { - if(i > 0) Serial.print(","); - Serial.print(s->groups[i].getGroupId()); + ESP_LOGD(TAG, "Group %u", s->groups[i].getGroupId()); this->readGroupRecord(&s->groups[i]); } - Serial.println(""); if(this->header.groupRecords < SOMFY_MAX_GROUPS) { uint8_t ndx = this->header.groupRecords; // Clear out any positions that are not in the shade file. @@ -581,14 +574,14 @@ bool ShadeConfigFile::restoreFile(SomfyShadeController *s, const char *filename, } } else { - Serial.println("Shade data ignored"); + ESP_LOGI(TAG, "Shade data ignored"); // FF past the shades and groups. this->file.seek(this->file.position() + (this->header.shadeRecords * this->header.shadeRecordSize) + (this->header.groupRecords * this->header.groupRecordSize), SeekSet); // Start at the beginning of the file after the header. } if(opts.repeaters) { - Serial.println("Restoring Repeaters..."); + ESP_LOGI(TAG, "Restoring Repeaters..."); if(this->header.repeaterRecords > 0) { memset(s->repeaters, 0x00, sizeof(uint32_t) * SOMFY_MAX_REPEATERS); for(uint8_t i = 0; i < this->header.repeaterRecords; i++) { @@ -632,7 +625,7 @@ bool ShadeConfigFile::readNetRecord(restore_options_t &opts) { if(this->header.netRecordSize > 0) { uint32_t startPos = this->file.position(); if(opts.network) { - Serial.println("Reading network settings from file..."); + ESP_LOGD(TAG, "Reading network settings from file..."); settings.connType = static_cast(this->readUInt8(static_cast(conn_types_t::unset))); settings.IP.dhcp = this->readBool(true); char ip[24]; @@ -678,7 +671,7 @@ bool ShadeConfigFile::readNetRecord(restore_options_t &opts) { // the ethernet phy settings. if(opts.network) { if(strncmp(settings.serverId, this->header.serverId, sizeof(settings.serverId)) == 0) { - Serial.println("Restoring Ethernet adapter settings"); + ESP_LOGI(TAG, "Restoring Ethernet adapter settings"); settings.Ethernet.boardType = this->readUInt8(1); settings.Ethernet.phyType = static_cast(this->readUInt8(0)); settings.Ethernet.CLKMode = static_cast(this->readUInt8(0)); @@ -689,7 +682,7 @@ bool ShadeConfigFile::readNetRecord(restore_options_t &opts) { } } if(this->file.position() != startPos + this->header.netRecordSize) { - Serial.println("Reading to end of network record"); + ESP_LOGD(TAG, "Reading to end of network record"); this->seekChar(CFG_REC_END); } } @@ -698,7 +691,7 @@ bool ShadeConfigFile::readNetRecord(restore_options_t &opts) { bool ShadeConfigFile::readTransRecord(transceiver_config_t &cfg) { if(this->header.transRecordSize > 0) { uint32_t startPos = this->file.position(); - Serial.println("Reading Transceiver settings from file..."); + ESP_LOGD(TAG, "Reading Transceiver settings from file..."); cfg.enabled = this->readBool(false); cfg.proto = static_cast(this->readUInt8(0)); cfg.type = this->readUInt8(56); @@ -713,7 +706,7 @@ bool ShadeConfigFile::readTransRecord(transceiver_config_t &cfg) { cfg.deviation = this->readFloat(cfg.deviation); cfg.txPower = this->readInt8(cfg.txPower); if(this->file.position() != startPos + this->header.transRecordSize) { - Serial.println("Reading to end of transceiver record"); + ESP_LOGD(TAG, "Reading to end of transceiver record"); this->seekChar(CFG_REC_END); } @@ -723,7 +716,7 @@ bool ShadeConfigFile::readTransRecord(transceiver_config_t &cfg) { bool ShadeConfigFile::readSettingsRecord() { if(this->header.settingsRecordSize > 0) { uint32_t startPos = this->file.position(); - Serial.println("Reading settings from file..."); + ESP_LOGD(TAG, "Reading settings from file..."); char ver[24]; this->readVarString(ver, sizeof(ver)); this->readVarString(settings.hostname, sizeof(settings.hostname)); @@ -732,7 +725,7 @@ bool ShadeConfigFile::readSettingsRecord() { settings.ssdpBroadcast = this->readBool(false); if(this->header.version >= 20) settings.checkForUpdate = this->readBool(true); if(this->file.position() != startPos + this->header.settingsRecordSize) { - Serial.println("Reading to end of settings record"); + ESP_LOGD(TAG, "Reading to end of settings record"); this->seekChar(CFG_REC_END); } } @@ -772,7 +765,7 @@ bool ShadeConfigFile::readGroupRecord(SomfyGroup *group) { pref.end(); if(this->file.position() != startPos + this->header.groupRecordSize) { - Serial.println("Reading to end of group record"); + ESP_LOGD(TAG, "Reading to end of group record"); this->seekChar(CFG_REC_END); } return true; @@ -784,7 +777,7 @@ bool ShadeConfigFile::readRepeaterRecord(SomfyShadeController *s) { s->linkRepeater(this->readUInt32(0)); } if(this->file.position() != startPos + this->header.repeaterRecordSize) { - Serial.println("Reading to end of repeater record"); + ESP_LOGD(TAG, "Reading to end of repeater record"); this->seekChar(CFG_REC_END); } return true; @@ -795,7 +788,7 @@ bool ShadeConfigFile::readRoomRecord(SomfyRoom *room) { this->readString(room->name, sizeof(room->name)); room->sortOrder = this->readUInt8(room->roomId - 1); if(this->file.position() != startPos + this->header.roomRecordSize) { - Serial.println("Reading to end of room record"); + ESP_LOGD(TAG, "Reading to end of room record"); this->seekChar(CFG_REC_END); } return true; @@ -881,7 +874,7 @@ bool ShadeConfigFile::readShadeRecord(SomfyShade *shade) { pinMode(shade->gpioMy, OUTPUT); if(this->header.version >= 19) shade->roomId = this->readUInt8(0); if(this->file.position() != startPos + this->header.shadeRecordSize) { - Serial.println("Reading to end of shade record"); + ESP_LOGD(TAG, "Reading to end of shade record"); this->seekChar(CFG_REC_END); } return true; @@ -889,12 +882,12 @@ bool ShadeConfigFile::readShadeRecord(SomfyShade *shade) { bool ShadeConfigFile::loadFile(SomfyShadeController *s, const char *filename) { bool opened = false; if(!this->isOpen()) { - Serial.println("Opening shade config file"); + ESP_LOGI(TAG, "Opening shade config file"); this->begin(filename, true); opened = true; } if(!this->validate()) { - Serial.println("Shade config file invalid!"); + ESP_LOGE(TAG, "Shade config file invalid!"); if(opened) this->end(); return false; } @@ -936,7 +929,7 @@ bool ShadeConfigFile::loadFile(SomfyShadeController *s, const char *filename) { this->readRepeaterRecord(s); } if(opened) { - Serial.println("Closing shade config file"); + ESP_LOGI(TAG, "Closing shade config file"); this->end(); } return true; diff --git a/src/ConfigSettings.cpp b/src/ConfigSettings.cpp index 3de3c4c..b981711 100644 --- a/src/ConfigSettings.cpp +++ b/src/ConfigSettings.cpp @@ -6,6 +6,9 @@ #include "ConfigSettings.h" #include "Utils.h" #include "esp_chip_info.h" +#include "esp_log.h" + +static const char *TAG = "Config"; Preferences pref; @@ -104,7 +107,7 @@ bool BaseSettings::loadFile(const char *filename) { char c = file.read(); data += c; } - DynamicJsonDocument doc(filesize); + JsonDocument doc; deserializeJson(doc, data); JsonObject obj = doc.as(); this->fromJSON(obj); @@ -114,7 +117,7 @@ bool BaseSettings::loadFile(const char *filename) { } bool BaseSettings::saveFile(const char *filename) { File file = LittleFS.open(filename, "w"); - DynamicJsonDocument doc(2048); + JsonDocument doc; JsonObject obj = doc.as(); this->toJSON(obj); serializeJson(doc, file); @@ -171,7 +174,7 @@ bool ConfigSettings::begin() { sprintf(this->chipModel, "UNK%d", static_cast(ci.model)); break; } - Serial.printf("Chip Model ESP32-%s\n", this->chipModel); + ESP_LOGD(TAG, "Chip Model ESP32-%s", this->chipModel); this->fwVersion.parse(FW_VERSION); uint64_t mac = ESP.getEfuseMac(); for(int i=0; i<17; i=i+8) { @@ -252,7 +255,7 @@ bool ConfigSettings::fromJSON(JsonObject &obj) { } void ConfigSettings::print() { this->Security.print(); - Serial.printf("Connection Type: %u\n", (unsigned int) this->connType); + ESP_LOGD(TAG, "Connection Type: %u", (unsigned int) this->connType); this->NTP.print(); if(this->connType == conn_types_t::wifi || this->connType == conn_types_t::unset) this->WIFI.print(); if(this->connType == conn_types_t::ethernet || this->connType == conn_types_t::ethernetpref) this->Ethernet.print(); @@ -346,7 +349,7 @@ bool MQTTSettings::load() { pref.end(); return true; } -bool ConfigSettings::toJSON(DynamicJsonDocument &doc) { +bool ConfigSettings::toJSON(JsonDocument &doc) { doc["fwVersion"] = this->fwVersion.name; JsonObject objWIFI = doc.createNestedObject("WIFI"); this->WIFI.toJSON(objWIFI); @@ -381,10 +384,7 @@ bool NTPSettings::load() { return true; } void NTPSettings::print() { - Serial.println("NTP Settings "); - Serial.print(this->ntpServer); - Serial.print(" TZ:"); - Serial.println(this->posixZone); + ESP_LOGD(TAG, "NTP Settings %s TZ:%s", this->ntpServer, this->posixZone); } bool NTPSettings::fromJSON(JsonObject &obj) { this->parseValueString(obj, "ntpServer", this->ntpServer, sizeof(this->ntpServer)); @@ -463,7 +463,7 @@ bool IPSettings::load() { pref.getString("dns2", buff, sizeof(buff)); this->dns2.fromString(buff); } - Serial.printf("Preference IP Free Entries: %d\n", pref.freeEntries()); + ESP_LOGD(TAG, "Preference IP Free Entries: %d", pref.freeEntries()); pref.end(); return true; } @@ -509,16 +509,8 @@ bool SecuritySettings::load() { return true; } void SecuritySettings::print() { - Serial.print("SECURITY Type:"); - Serial.print(static_cast(this->type)); - Serial.print(" Username:["); - Serial.print(this->username); - Serial.print("] Password:["); - Serial.print(this->password); - Serial.print("] Pin:["); - Serial.print(this->pin); - Serial.print("] Permissions:"); - Serial.println(this->permissions); + ESP_LOGD(TAG, "SECURITY Type:%u Username:[%s] Password:[%s] Pin:[%s] Permissions:%u", + static_cast(this->type), this->username, this->password, this->pin, this->permissions); } WifiSettings::WifiSettings() {} @@ -579,34 +571,17 @@ String WifiSettings::mapEncryptionType(int type) { return "Unknown"; } void WifiSettings::print() { - Serial.println("WIFI Settings"); - Serial.print(" SSID: ["); - Serial.print(this->ssid); - Serial.print("] PassPhrase: ["); - Serial.print(this->passphrase); - Serial.println("]"); + ESP_LOGD(TAG, "WIFI Settings SSID: [%s] PassPhrase: [%s]", this->ssid, this->passphrase); } void WifiSettings::printNetworks() { int n = WiFi.scanNetworks(false, false); - Serial.print("Scanned "); - Serial.print(n); - Serial.println(" Networks..."); + ESP_LOGI(TAG, "Scanned %d Networks...", n); String network; for(int i = 0; i < n; i++) { - if(WiFi.SSID(i).compareTo(this->ssid) == 0) Serial.print("*"); - else Serial.print(" "); - Serial.print(i); - Serial.print(": "); - Serial.print(WiFi.SSID(i)); - Serial.print(" ("); - Serial.print(WiFi.RSSI(i)); - Serial.print("dBm) CH:"); - Serial.print(WiFi.channel(i)); - Serial.print(" MAC:"); - Serial.print(WiFi.BSSIDstr(i)); - Serial.println(); + ESP_LOGI(TAG, "%s%d: %s (%ddBm) CH:%d MAC:%s", + (WiFi.SSID(i).compareTo(this->ssid) == 0) ? "*" : " ", + i, WiFi.SSID(i).c_str(), WiFi.RSSI(i), WiFi.channel(i), WiFi.BSSIDstr(i).c_str()); } - } bool WifiSettings::ssidExists(const char *ssid) { int n = WiFi.scanNetworks(false, true); @@ -675,14 +650,11 @@ bool EthernetSettings::load() { return true; } void EthernetSettings::print() { - Serial.println("Ethernet Settings"); - Serial.printf("Board:%d PHYType:%d CLK:%d ADDR:%d PWR:%d MDC:%d MDIO:%d\n", this->boardType, this->phyType, this->CLKMode, this->phyAddress, this->PWRPin, this->MDCPin, this->MDIOPin); + ESP_LOGD(TAG, "Ethernet Settings Board:%d PHYType:%d CLK:%d ADDR:%d PWR:%d MDC:%d MDIO:%d", + this->boardType, this->phyType, this->CLKMode, this->phyAddress, this->PWRPin, this->MDCPin, this->MDIOPin); } void ConfigSettings::printAvailHeap() { - Serial.print("Max Heap: "); - Serial.println(ESP.getMaxAllocHeap()); - Serial.print("Free Heap: "); - Serial.println(ESP.getFreeHeap()); - Serial.print("Min Heap: "); - Serial.println(ESP.getMinFreeHeap()); + ESP_LOGD(TAG, "Max Heap: %u", (unsigned int)ESP.getMaxAllocHeap()); + ESP_LOGD(TAG, "Free Heap: %u", (unsigned int)ESP.getFreeHeap()); + ESP_LOGD(TAG, "Min Heap: %u", (unsigned int)ESP.getMinFreeHeap()); } diff --git a/src/ConfigSettings.h b/src/ConfigSettings.h index 2bee8e2..d2f9c21 100644 --- a/src/ConfigSettings.h +++ b/src/ConfigSettings.h @@ -194,7 +194,7 @@ class ConfigSettings: BaseSettings { void print(); void emitSockets(); void emitSockets(uint8_t num); - bool toJSON(DynamicJsonDocument &doc); + bool toJSON(JsonDocument &doc); uint16_t calcSettingsRecSize(); uint16_t calcNetRecSize(); bool getAppVersion(); diff --git a/src/GitOTA.cpp b/src/GitOTA.cpp index 3b4e9a3..eada176 100644 --- a/src/GitOTA.cpp +++ b/src/GitOTA.cpp @@ -3,6 +3,7 @@ #include #include #include +#include "esp_log.h" #include "ConfigSettings.h" #include "GitOTA.h" #include "Utils.h" @@ -22,7 +23,7 @@ extern rebootDelay_t rebootDelay; extern Web webServer; extern Network net; - +static const char *TAG = "OTA"; #define MAX_BUFF_SIZE 4096 void GitRelease::setReleaseProperty(const char *key, const char *val) { @@ -95,10 +96,10 @@ int16_t GitRepo::getReleases(uint8_t num) { if(https.begin(sclient, url)) { esp_task_wdt_reset(); int httpCode = https.GET(); - Serial.printf("[HTTPS] GET... code: %d\n", httpCode); + ESP_LOGD(TAG, "[HTTPS] GET... code: %d", httpCode); if(httpCode > 0) { int len = https.getSize(); - Serial.printf("[HTTPS] GET... code: %d - %d\n", httpCode, len); + ESP_LOGD(TAG, "[HTTPS] GET... code: %d - %d", httpCode, len); if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { WiFiClient *stream = https.getStreamPtr(); uint8_t buff[128] = {0}; @@ -229,14 +230,14 @@ void GitUpdater::loop() { } } else if(this->status == GIT_AWAITING_UPDATE) { - Serial.println("Starting update process........."); + ESP_LOGI(TAG, "Starting update process........."); this->status = GIT_UPDATING; this->beginUpdate(this->targetRelease); this->status = GIT_STATUS_READY; this->emitUpdateCheck(); } else if(this->status == GIT_UPDATE_CANCELLING) { - Serial.println("Cancelling update process.........."); + ESP_LOGI(TAG, "Cancelling update process.........."); if(!this->lockFS) { this->status = GIT_UPDATE_CANCELLED; this->cancelled = true; @@ -246,8 +247,8 @@ void GitUpdater::loop() { } void GitUpdater::checkForUpdate() { if(this->status != 0) return; // If we are already checking. - Serial.println("Check github for updates..."); - + ESP_LOGI(TAG, "Check github for updates..."); + this->status = GIT_STATUS_CHECK; settings.printAvailHeap(); this->lastCheck = millis(); @@ -316,12 +317,12 @@ int GitUpdater::checkInternet() { esp_task_wdt_reset(); if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY || httpCode == HTTP_CODE_FOUND) { err = 0; - Serial.printf("Internet is Available: %ldms\n", millis() - t); + ESP_LOGI(TAG, "Internet is Available: %ldms", millis() - t); this->inetAvailable = true; } else { err = httpCode; - Serial.printf("Internet is Unavailable: %d: %ldms\n", err, millis() - t); + ESP_LOGE(TAG, "Internet is Unavailable: %d: %ldms", err, millis() - t); this->inetAvailable = false; } https.end(); @@ -371,7 +372,7 @@ void GitUpdater::setFirmwareFile() { } bool GitUpdater::beginUpdate(const char *version) { - Serial.println("Begin update called..."); + ESP_LOGI(TAG, "Begin update called..."); if(strcmp(version, "Main") == 0) strcpy(this->baseUrl, "https://raw.githubusercontent.com/rstrouse/ESPSomfy-RTS/master/"); else sprintf(this->baseUrl, "https://github.com/rstrouse/ESPSomfy-RTS/releases/download/%s/", version); @@ -392,7 +393,7 @@ bool GitUpdater::beginUpdate(const char *version) { if(this->error == 0) { settings.fwVersion.parse(version); delay(100); - Serial.println("Committing Configuration..."); + ESP_LOGI(TAG, "Committing Configuration..."); somfy.commit(); } rebootDelay.reboot = true; @@ -412,7 +413,7 @@ bool GitUpdater::recoverFilesystem() { this->lockFS = false; if(this->error == 0) { delay(100); - Serial.println("Committing Configuration..."); + ESP_LOGI(TAG, "Committing Configuration..."); somfy.commit(); } this->status = GIT_UPDATE_COMPLETE; @@ -422,28 +423,27 @@ bool GitUpdater::recoverFilesystem() { } bool GitUpdater::endUpdate() { return true; } int8_t GitUpdater::downloadFile() { - Serial.printf("Begin update %s\n", this->currentFile); + ESP_LOGI(TAG, "Begin update %s", this->currentFile); WiFiClientSecure sclient; sclient.setInsecure(); HTTPClient https; char url[196]; sprintf(url, "%s%s", this->baseUrl, this->currentFile); - Serial.println(url); + ESP_LOGD(TAG, "%s", url); esp_task_wdt_reset(); if(https.begin(sclient, url)) { https.setFollowRedirects(HTTPC_FORCE_FOLLOW_REDIRECTS); - Serial.print("[HTTPS] GET...\n"); + ESP_LOGD(TAG, "[HTTPS] GET..."); int httpCode = https.GET(); if(httpCode > 0) { size_t len = https.getSize(); size_t total = 0; uint8_t pct = 0; - Serial.printf("[HTTPS] GET... code: %d - %d\n", httpCode, len); + ESP_LOGD(TAG, "[HTTPS] GET... code: %d - %d", httpCode, len); if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY || httpCode == HTTP_CODE_FOUND) { WiFiClient *stream = https.getStreamPtr(); if(!Update.begin(len, this->partition)) { - Serial.println("Update Error detected!!!!!"); - Update.printError(Serial); + ESP_LOGE(TAG, "Update Error detected!!!!!"); https.end(); return -(Update.getError() + UPDATE_ERR_OFFSET); } @@ -466,8 +466,7 @@ int8_t GitUpdater::downloadFile() { total += c; //Serial.println(total); if (Update.write(buff, c) != c) { - Update.printError(Serial); - Serial.printf("Upload of %s aborted invalid size %d\n", url, c); + ESP_LOGE(TAG, "Upload of %s aborted invalid size %d", url, c); free(buff); https.end(); sclient.stop(); @@ -477,17 +476,16 @@ int8_t GitUpdater::downloadFile() { uint8_t p = (uint8_t)floor(((float)total / (float)len) * 100.0f); if(p != pct) { pct = p; - Serial.printf("LEN:%d TOTAL:%d %d%%\n", len, total, pct); + ESP_LOGD(TAG, "LEN:%d TOTAL:%d %d%%", len, total, pct); this->emitDownloadProgress(len, total); } delay(1); if(total >= len) { if(!Update.end(true)) { - Serial.println("Error downloading update..."); - Update.printError(Serial); + ESP_LOGE(TAG, "Error downloading update..."); } else { - Serial.println("Update.end Called..."); + ESP_LOGI(TAG, "Update.end Called..."); } https.end(); sclient.stop(); @@ -499,7 +497,7 @@ int8_t GitUpdater::downloadFile() { Update.abort(); https.end(); free(buff); - Serial.println("Stream timeout!!!"); + ESP_LOGE(TAG, "Stream timeout!!!"); return -43; } sockEmit.loop(); @@ -511,28 +509,28 @@ int8_t GitUpdater::downloadFile() { if(len > total) { Update.abort(); somfy.commit(); - Serial.println("Error downloading file!!!"); + ESP_LOGE(TAG, "Error downloading file!!!"); return -42; } else - Serial.printf("Update %s complete\n", this->currentFile); + ESP_LOGI(TAG, "Update %s complete", this->currentFile); } else { // TODO: memory allocation error. - Serial.println("Unable to allocate memory for update!!!"); + ESP_LOGE(TAG, "Unable to allocate memory for update!!!"); } } else { - Serial.printf("Invalid HTTP Code... %d", httpCode); + ESP_LOGE(TAG, "Invalid HTTP Code... %d", httpCode); return httpCode; } } else { - Serial.printf("Invalid HTTP Code: %d\n", httpCode); + ESP_LOGE(TAG, "Invalid HTTP Code: %d", httpCode); } https.end(); sclient.stop(); - Serial.printf("End update %s\n", this->currentFile); + ESP_LOGI(TAG, "End update %s", this->currentFile); } esp_task_wdt_reset(); return 0; diff --git a/src/MQTT.cpp b/src/MQTT.cpp index 55f693a..72c5607 100644 --- a/src/MQTT.cpp +++ b/src/MQTT.cpp @@ -2,12 +2,15 @@ #include #include #include +#include "esp_log.h" #include "ConfigSettings.h" #include "MQTT.h" #include "Somfy.h" #include "Network.h" #include "Utils.h" +static const char *TAG = "MQTT"; + WiFiClient tcpClient; PubSubClient mqttClient(tcpClient); @@ -45,12 +48,7 @@ bool MQTTClass::loop() { } void MQTTClass::receive(const char *topic, byte*payload, uint32_t length) { esp_task_wdt_reset(); // Make sure we do not reboot here. - Serial.print("MQTT Topic:"); - Serial.print(topic); - Serial.print(" payload:"); - for(uint32_t i=0; iclientId, settings.MQTT.username, settings.MQTT.password, lwtTopic, 0, true, "offline")) { - Serial.print("Successfully connected MQTT client "); - Serial.println(this->clientId); + ESP_LOGI(TAG, "Successfully connected MQTT client %s", this->clientId); this->publish("status", "online", true); this->publish("ipAddress", settings.IP.ip.toString().c_str(), true); this->publish("host", settings.hostname, true); @@ -228,14 +218,13 @@ bool MQTTClass::connect() { this->subscribe("groups/+/sunny/set"); this->subscribe("groups/+/windy/set"); mqttClient.setCallback(MQTTClass::receive); - Serial.println("MQTT Startup Completed"); + ESP_LOGI(TAG, "MQTT Startup Completed"); esp_task_wdt_reset(); this->lastConnect = millis(); return true; } else { - Serial.print("MQTT Connection failed for: "); - Serial.println(mqttClient.state()); + ESP_LOGE(TAG, "MQTT Connection failed for: %d", mqttClient.state()); this->lastConnect = millis(); return false; } @@ -273,8 +262,7 @@ bool MQTTClass::unsubscribe(const char *topic) { snprintf(top, sizeof(top), "%s/%s", settings.MQTT.rootTopic, topic); else strlcpy(top, topic, sizeof(top)); - Serial.print("MQTT Unsubscribed from:"); - Serial.println(top); + ESP_LOGD(TAG, "MQTT Unsubscribed from:%s", top); return mqttClient.unsubscribe(top); } return true; @@ -287,8 +275,7 @@ bool MQTTClass::subscribe(const char *topic) { snprintf(top, sizeof(top), "%s/%s", settings.MQTT.rootTopic, topic); else strlcpy(top, topic, sizeof(top)); - Serial.print("MQTT Subscribed to:"); - Serial.println(top); + ESP_LOGD(TAG, "MQTT Subscribed to:%s", top); return mqttClient.subscribe(top); } return true; diff --git a/src/Network.cpp b/src/Network.cpp index 914d4fd..b300e4e 100644 --- a/src/Network.cpp +++ b/src/Network.cpp @@ -2,6 +2,7 @@ #include #include #include +#include "esp_log.h" #include "ConfigSettings.h" #include "Network.h" #include "Web.h" @@ -10,6 +11,8 @@ #include "SSDP.h" #include "MQTT.h" +static const char *TAG = "Network"; + extern ConfigSettings settings; extern Web webServer; extern SocketEmitter sockEmit; @@ -41,8 +44,7 @@ bool Network::setup() { if(settings.connType == conn_types_t::wifi || settings.connType == conn_types_t::unset) { WiFi.persistent(false); if(settings.hostname[0] != '\0') WiFi.setHostname(settings.hostname); - Serial.print("WiFi Mode: "); - Serial.println(WiFi.getMode()); + ESP_LOGI(TAG, "WiFi Mode: %d", WiFi.getMode()); WiFi.mode(WIFI_STA); } sockEmit.begin(); @@ -87,7 +89,7 @@ void Network::loop() { (this->connected() && !settings.WIFI.roaming) || // We are already connected and should not be roaming. (this->softAPOpened && WiFi.softAPgetStationNum() != 0) || // The Soft AP is open and a user is connected. (ctype != conn_types_t::wifi)) { // The Ethernet link is up so we should ignore this scan. - Serial.println("Cancelling WiFi STA Scan..."); + ESP_LOGI(TAG, "Cancelling WiFi STA Scan..."); _apScanning = false; WiFi.scanDelete(); } @@ -99,11 +101,11 @@ void Network::loop() { if(this->getStrongestAP(settings.WIFI.ssid, bssid, &channel)) { if(!WiFi.BSSID() || memcmp(bssid, WiFi.BSSID(), sizeof(bssid)) != 0) { if(!this->connected()) { - Serial.printf("Connecting to AP %02X:%02X:%02X:%02X:%02X:%02X CH: %d\n", bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5], channel); + ESP_LOGD(TAG, "Connecting to AP %02X:%02X:%02X:%02X:%02X:%02X CH: %d", bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5], channel); this->connectWiFi(bssid, channel); } else { - Serial.printf("Found stronger AP %02X:%02X:%02X:%02X:%02X:%02X CH: %d\n", bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5], channel); + ESP_LOGD(TAG, "Found stronger AP %02X:%02X:%02X:%02X:%02X:%02X CH: %d", bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5], channel); this->changeAP(bssid, channel); } } @@ -225,7 +227,7 @@ void Network::setConnected(conn_types_t connType) { this->connType = connType; this->connectTime = millis(); connectRetries = 0; - Serial.println("Setting connected..."); + ESP_LOGI(TAG, "Setting connected..."); if(this->connType == conn_types_t::wifi) { if(this->softAPOpened && WiFi.softAPgetStationNum() == 0) { WiFi.softAPdisconnect(true); @@ -240,7 +242,7 @@ void Network::setConnected(conn_types_t connType) { } else if(this->connType == conn_types_t::ethernet) { if(this->softAPOpened) { - Serial.println("Disonnecting from SoftAP"); + ESP_LOGI(TAG, "Disconnecting from SoftAP"); WiFi.softAPdisconnect(true); WiFi.mode(WIFI_OFF); } @@ -253,13 +255,8 @@ void Network::setConnected(conn_types_t connType) { esp_task_wdt_reset(); if(this->connectAttempts == 1) { - Serial.println(); if(this->connType == conn_types_t::wifi) { - Serial.print("Successfully Connected to WiFi!!!!"); - Serial.print(WiFi.localIP()); - Serial.print(" ("); - Serial.print(this->strength); - Serial.println("dbm)"); + ESP_LOGI(TAG, "Successfully Connected to WiFi!!!! %s (%ddbm)", WiFi.localIP().toString().c_str(), this->strength); if(settings.IP.dhcp) { settings.IP.ip = WiFi.localIP(); settings.IP.subnet = WiFi.subnetMask(); @@ -269,14 +266,7 @@ void Network::setConnected(conn_types_t connType) { } } else { - Serial.print("Successfully Connected to Ethernet!!! "); - Serial.print(ETH.localIP()); - if(ETH.fullDuplex()) { - Serial.print(" FULL DUPLEX"); - } - Serial.print(" "); - Serial.print(ETH.linkSpeed()); - Serial.println("Mbps"); + ESP_LOGI(TAG, "Successfully Connected to Ethernet!!! %s%s %dMbps", ETH.localIP().toString().c_str(), ETH.fullDuplex() ? " FULL DUPLEX" : "", ETH.linkSpeed()); if(settings.IP.dhcp) { settings.IP.ip = ETH.localIP(); settings.IP.subnet = ETH.subnetMask(); @@ -296,32 +286,12 @@ void Network::setConnected(conn_types_t connType) { } } else { - Serial.println(); - Serial.print("Reconnected after "); - Serial.print(1.0 * (millis() - this->connectStart)/1000); - Serial.print("sec IP: "); if(this->connType == conn_types_t::wifi) { - Serial.print(WiFi.localIP()); - Serial.print(" "); - Serial.print(this->mac); - Serial.print(" CH:"); - Serial.print(this->channel); - Serial.print(" ("); - Serial.print(this->strength); - Serial.print(" dBm)"); + ESP_LOGI(TAG, "Reconnected after %.3fsec IP: %s %s CH:%d (%d dBm) Disconnected %d times", 1.0 * (millis() - this->connectStart)/1000, WiFi.localIP().toString().c_str(), this->mac.c_str(), this->channel, this->strength, this->connectAttempts - 1); } else { - Serial.print(ETH.localIP()); - if(ETH.fullDuplex()) { - Serial.print(" FULL DUPLEX"); - } - Serial.print(" "); - Serial.print(ETH.linkSpeed()); - Serial.print("Mbps"); + ESP_LOGI(TAG, "Reconnected after %.3fsec IP: %s%s %dMbps Disconnected %d times", 1.0 * (millis() - this->connectStart)/1000, ETH.localIP().toString().c_str(), ETH.fullDuplex() ? " FULL DUPLEX" : "", ETH.linkSpeed(), this->connectAttempts - 1); } - Serial.print(" Disconnected "); - Serial.print(this->connectAttempts - 1); - Serial.println(" times"); } SSDP.setHTTPPort(80); SSDP.setSchemaURL(0, "upnp.xml"); @@ -345,7 +315,7 @@ void Network::setConnected(conn_types_t connType) { SSDP.setActive(0, true); esp_task_wdt_reset(); if(MDNS.begin(settings.hostname)) { - Serial.printf("MDNS Responder Started: serverId=%s\n", settings.serverId); + ESP_LOGI(TAG, "MDNS Responder Started: serverId=%s", settings.serverId); MDNS.addService("http", "tcp", 80); //MDNS.addServiceTxt("http", "tcp", "board", "ESP32"); //MDNS.addServiceTxt("http", "tcp", "model", "ESPSomfyRTS"); @@ -382,11 +352,10 @@ bool Network::connectWired() { return this->connectWiFi(); } if(this->connectAttempts > 0) { - Serial.printf("Ethernet Connection Lost... %d Reconnecting ", this->connectAttempts); - Serial.println(this->mac); + ESP_LOGW(TAG, "Ethernet Connection Lost... %d Reconnecting %s", this->connectAttempts, this->mac.c_str()); } else - Serial.println("Connecting to Wired Ethernet"); + ESP_LOGI(TAG, "Connecting to Wired Ethernet"); this->_connecting = true; this->connTarget = conn_types_t::ethernet; this->connType = conn_types_t::unset; @@ -398,10 +367,9 @@ bool Network::connectWired() { ETH.setHostname(settings.hostname); else ETH.setHostname("ESPSomfy-RTS"); - Serial.print("Set hostname to:"); - Serial.println(ETH.getHostname()); - if(!ETH.begin(settings.Ethernet.phyAddress, settings.Ethernet.PWRPin, settings.Ethernet.MDCPin, settings.Ethernet.MDIOPin, settings.Ethernet.phyType, settings.Ethernet.CLKMode)) { - Serial.println("Ethernet Begin failed"); + ESP_LOGD(TAG, "Set hostname to: %s", ETH.getHostname()); + if(!ETH.begin(settings.Ethernet.phyAddress, settings.Ethernet.PWRPin, settings.Ethernet.MDCPin, settings.Ethernet.MDIOPin, settings.Ethernet.phyType, settings.Ethernet.CLKMode)) { + ESP_LOGE(TAG, "Ethernet Begin failed"); this->ethStarted = false; if(settings.connType == conn_types_t::ethernetpref) { this->wifiFallback = true; @@ -412,7 +380,7 @@ bool Network::connectWired() { else { if(!settings.IP.dhcp) { if(!ETH.config(settings.IP.ip, settings.IP.gateway, settings.IP.subnet, settings.IP.dns1, settings.IP.dns2)) { - Serial.println("Unable to configure static IP address...."); + ESP_LOGE(TAG, "Unable to configure static IP address...."); ETH.config(INADDR_NONE, INADDR_NONE, INADDR_NONE, INADDR_NONE); } } @@ -427,13 +395,13 @@ void Network::updateHostname() { if(settings.hostname[0] != '\0' && this->connected()) { if(this->connType == conn_types_t::ethernet && strcmp(settings.hostname, ETH.getHostname()) != 0) { - Serial.printf("Updating host name to %s...\n", settings.hostname); + ESP_LOGD(TAG, "Updating host name to %s...", settings.hostname); ETH.setHostname(settings.hostname); MDNS.setInstanceName(settings.hostname); SSDP.setName(0, settings.hostname); } else if(strcmp(settings.hostname, WiFi.getHostname()) != 0) { - Serial.printf("Updating host name to %s...\n", settings.hostname); + ESP_LOGD(TAG, "Updating host name to %s...", settings.hostname); WiFi.setHostname(settings.hostname); MDNS.setInstanceName(settings.hostname); SSDP.setName(0, settings.hostname); @@ -467,7 +435,7 @@ bool Network::connectWiFi(const uint8_t *bssid, const int32_t channel) { } this->connTarget = conn_types_t::wifi; this->connType = conn_types_t::unset; - Serial.println("WiFi begin..."); + ESP_LOGI(TAG, "WiFi begin..."); this->_connecting = true; WiFi.begin(settings.WIFI.ssid, settings.WIFI.passphrase, channel, bssid); this->connectStart = millis(); @@ -484,26 +452,19 @@ bool Network::connectWiFi(const uint8_t *bssid, const int32_t channel) { this->connTarget = conn_types_t::wifi; this->connType = conn_types_t::unset; if(this->connectAttempts > 0) { - Serial.print("Connection Lost..."); - Serial.print(this->mac); - Serial.print(" CH:"); - Serial.print(this->channel); - Serial.print(" ("); - Serial.print(this->strength); - Serial.println("dbm) "); + ESP_LOGW(TAG, "Connection Lost... %s CH:%d (%ddbm)", this->mac.c_str(), this->channel, this->strength); } - else Serial.println("Connecting to AP"); + else ESP_LOGI(TAG, "Connecting to AP"); delay(100); // There is also another method simply called hostname() but this is legacy for esp8266. if(settings.hostname[0] != '\0') WiFi.setHostname(settings.hostname); - Serial.print("Set hostname to:"); - Serial.println(WiFi.getHostname()); + ESP_LOGD(TAG, "Set hostname to: %s", WiFi.getHostname()); WiFi.setScanMethod(WIFI_ALL_CHANNEL_SCAN); WiFi.setSortMethod(WIFI_CONNECT_AP_BY_SIGNAL); uint8_t _bssid[6]; int32_t _channel = 0; if(!settings.WIFI.hidden && this->getStrongestAP(settings.WIFI.ssid, _bssid, &_channel)) { - Serial.printf("Found strongest AP %02X:%02X:%02X:%02X:%02X:%02X CH:%d\n", _bssid[0], _bssid[1], _bssid[2], _bssid[3], _bssid[4], _bssid[5], _channel); + ESP_LOGD(TAG, "Found strongest AP %02X:%02X:%02X:%02X:%02X:%02X CH:%d", _bssid[0], _bssid[1], _bssid[2], _bssid[3], _bssid[4], _bssid[5], _channel); WiFi.begin(settings.WIFI.ssid, settings.WIFI.passphrase, _channel, _bssid); } else @@ -571,8 +532,7 @@ bool Network::openSoftAP() { if(this->softAPOpened || this->openingSoftAP) return true; if(this->connected()) WiFi.disconnect(false); this->openingSoftAP = true; - Serial.println(); - Serial.println("Turning the HotSpot On"); + ESP_LOGI(TAG, "Turning the HotSpot On"); esp_task_wdt_reset(); // Make sure we do not reboot here. WiFi.softAP(strlen(settings.hostname) > 0 ? settings.hostname : "ESPSomfy RTS", ""); delay(200); @@ -593,38 +553,36 @@ bool Network::connecting() { void Network::clearConnecting() { this->_connecting = false; } void Network::networkEvent(WiFiEvent_t event) { switch(event) { - case ARDUINO_EVENT_WIFI_READY: Serial.println("(evt) WiFi interface ready"); break; + case ARDUINO_EVENT_WIFI_READY: ESP_LOGI(TAG, "(evt) WiFi interface ready"); break; case ARDUINO_EVENT_WIFI_SCAN_DONE: - Serial.printf("(evt) Completed scan for access points (%d)\n", WiFi.scanComplete()); + ESP_LOGI(TAG, "(evt) Completed scan for access points (%d)", WiFi.scanComplete()); //Serial.println("(evt) Completed scan for access points"); net.lastWifiScan = millis(); break; case ARDUINO_EVENT_WIFI_STA_START: - Serial.println("WiFi station mode started"); + ESP_LOGI(TAG, "WiFi station mode started"); if(settings.hostname[0] != '\0') WiFi.setHostname(settings.hostname); break; - case ARDUINO_EVENT_WIFI_STA_STOP: Serial.println("(evt) WiFi clients stopped"); break; - case ARDUINO_EVENT_WIFI_STA_CONNECTED: Serial.println("(evt) Connected to WiFi STA access point"); break; + case ARDUINO_EVENT_WIFI_STA_STOP: ESP_LOGI(TAG, "(evt) WiFi clients stopped"); break; + case ARDUINO_EVENT_WIFI_STA_CONNECTED: ESP_LOGI(TAG, "(evt) Connected to WiFi STA access point"); break; case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: - Serial.printf("(evt) Disconnected from WiFi STA access point. Connecting: %d\n", net.connecting()); + ESP_LOGI(TAG, "(evt) Disconnected from WiFi STA access point. Connecting: %d", net.connecting()); net.connType = conn_types_t::unset; net.disconnectTime = millis(); net.clearConnecting(); break; - case ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE: Serial.println("(evt) Authentication mode of STA access point has changed"); break; + case ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE: ESP_LOGI(TAG, "(evt) Authentication mode of STA access point has changed"); break; case ARDUINO_EVENT_WIFI_STA_GOT_IP: - Serial.print("(evt) Got WiFi STA IP: "); - Serial.println(WiFi.localIP()); + ESP_LOGI(TAG, "(evt) Got WiFi STA IP: %s", WiFi.localIP().toString().c_str()); net.connType = conn_types_t::wifi; net.connectTime = millis(); net.setConnected(conn_types_t::wifi); break; - case ARDUINO_EVENT_WIFI_STA_LOST_IP: Serial.println("Lost IP address and IP address is reset to 0"); break; + case ARDUINO_EVENT_WIFI_STA_LOST_IP: ESP_LOGW(TAG, "Lost IP address and IP address is reset to 0"); break; case ARDUINO_EVENT_ETH_GOT_IP: // If the Wifi is connected then drop that connection if(WiFi.status() == WL_CONNECTED) WiFi.disconnect(true); - Serial.print("Got Ethernet IP "); - Serial.println(ETH.localIP()); + ESP_LOGI(TAG, "Got Ethernet IP %s", ETH.localIP().toString().c_str()); net.connectTime = millis(); net.connType = conn_types_t::ethernet; if(settings.IP.dhcp) { @@ -637,36 +595,35 @@ void Network::networkEvent(WiFiEvent_t event) { net.setConnected(conn_types_t::ethernet); break; case ARDUINO_EVENT_ETH_CONNECTED: - Serial.print("(evt) Ethernet Connected "); + ESP_LOGI(TAG, "(evt) Ethernet Connected"); break; case ARDUINO_EVENT_ETH_DISCONNECTED: - Serial.println("(evt) Ethernet Disconnected"); + ESP_LOGI(TAG, "(evt) Ethernet Disconnected"); net.connType = conn_types_t::unset; net.disconnectTime = millis(); net.clearConnecting(); break; case ARDUINO_EVENT_ETH_START: - Serial.println("(evt) Ethernet Started"); + ESP_LOGI(TAG, "(evt) Ethernet Started"); net.ethStarted = true; break; case ARDUINO_EVENT_ETH_STOP: - Serial.println("(evt) Ethernet Stopped"); + ESP_LOGI(TAG, "(evt) Ethernet Stopped"); net.connType = conn_types_t::unset; net.ethStarted = false; break; case ARDUINO_EVENT_WIFI_AP_START: - Serial.print("(evt) WiFi SoftAP Started IP:"); - Serial.println(WiFi.softAPIP()); + ESP_LOGI(TAG, "(evt) WiFi SoftAP Started IP: %s", WiFi.softAPIP().toString().c_str()); net.openingSoftAP = false; net.softAPOpened = true; break; case ARDUINO_EVENT_WIFI_AP_STOP: - if(!net.openingSoftAP) Serial.println("(evt) WiFi SoftAP Stopped"); + if(!net.openingSoftAP) ESP_LOGI(TAG, "(evt) WiFi SoftAP Stopped"); net.softAPOpened = false; break; default: if(event > ARDUINO_EVENT_ETH_START) - Serial.printf("(evt) Unknown Ethernet Event %d\n", event); + ESP_LOGW(TAG, "(evt) Unknown Ethernet Event %d", event); break; } } diff --git a/src/SSDP.cpp b/src/SSDP.cpp index f866865..144b8ab 100644 --- a/src/SSDP.cpp +++ b/src/SSDP.cpp @@ -1,5 +1,6 @@ #include #include +#include "esp_log.h" #include "Utils.h" #include "ConfigSettings.h" #include "SSDP.h" @@ -12,6 +13,7 @@ #define SSDP_MULTICAST_ADDR 239, 255, 255, 250 //#define DEBUG_SSDP Serial //#define DEBUG_SSDP_PACKET Serial +static const char *TAG = "SSDP"; extern ConfigSettings settings; static const char _ssdp_uuid_template[] PROGMEM = "C2496952-5610-47E6-A968-2FC1%02X%02X%02X%02X"; @@ -193,12 +195,12 @@ bool SSDPClass::begin() { return false; } for(uint8_t i = 0; i < this->m_cdeviceTypes; i++) { - Serial.printf("SSDP: %s - %s\n", this->deviceTypes[i].deviceType, this->deviceTypes[i].isActive ? "true" : "false"); + ESP_LOGI(TAG, "SSDP: %s - %s", this->deviceTypes[i].deviceType, this->deviceTypes[i].isActive ? "true" : "false"); } this->isStarted = true; this->_sendByeBye(); this->_sendNotify(); - Serial.println("Connected to SSDP..."); + ESP_LOGI(TAG, "Connected to SSDP..."); return true; } void SSDPClass::end() { @@ -209,7 +211,7 @@ void SSDPClass::end() { if(this->_server.connected()) { this->_sendByeBye(); this->_server.close(); - Serial.println("Disconnected from SSDP..."); + ESP_LOGI(TAG, "Disconnected from SSDP..."); } this->isStarted = false; // Clear out the last notified so if the user starts us up again it will notify @@ -432,7 +434,7 @@ void SSDPClass::_sendResponse(IPAddress addr, uint16_t port, const char *buff) { void SSDPClass::_sendNotify() { for(uint8_t i = 0; i < this->m_cdeviceTypes; i++) { UPNPDeviceType *dev = &this->deviceTypes[i]; - if(i == 0 && (strlen(dev->deviceType) == 0 || !dev->isActive)) Serial.printf("The device type is empty: %s\n", dev->isActive ? "true" : "false"); + if(i == 0 && (strlen(dev->deviceType) == 0 || !dev->isActive)) ESP_LOGD(TAG, "The device type is empty: %s", dev->isActive ? "true" : "false"); if(strlen(dev->deviceType) > 0 && dev->isActive) { unsigned long elapsed = (millis() - dev->lastNotified); if(!dev->lastNotified || (elapsed * 5) > (this->_interval * 1000)) { @@ -653,28 +655,23 @@ void SSDPClass::_sendQueuedResponses() { } } void SSDPClass::_printPacket(ssdp_packet_t *pkt) { - Serial.printf("Rec: %lu\n", pkt->recvd); + ESP_LOGD(TAG, "Rec: %lu", pkt->recvd); switch(pkt->method) { case NONE: - Serial.println("Method: NONE"); + ESP_LOGD(TAG, "Method: NONE"); break; case SEARCH: - Serial.println("Method: SEARCH"); + ESP_LOGD(TAG, "Method: SEARCH"); break; case NOTIFY: - Serial.println("Method: NOTIFY"); + ESP_LOGD(TAG, "Method: NOTIFY"); break; default: - Serial.println("Method: UNKOWN"); + ESP_LOGD(TAG, "Method: UNKNOWN"); break; } - Serial.printf("ST: %s\n", pkt->st); - Serial.printf("MAN: %s\n", pkt->man); - Serial.printf("AGENT: %s\n", pkt->agent); - Serial.printf("HOST: %s\n", pkt->host); - Serial.printf("MX: %d\n", pkt->mx); - Serial.printf("type: %d\n", pkt->type); - Serial.printf("valid: %d\n", pkt->valid); + ESP_LOGD(TAG, "ST: %s MAN: %s AGENT: %s HOST: %s MX: %d type: %d valid: %d", + pkt->st, pkt->man, pkt->agent, pkt->host, pkt->mx, pkt->type, pkt->valid); } void SSDPClass::_processRequest(AsyncUDPPacket &p) { // This pending BS should probably be for unicast request only but we will play along for now. diff --git a/src/Sockets.cpp b/src/Sockets.cpp index fb371e1..3eadb77 100644 --- a/src/Sockets.cpp +++ b/src/Sockets.cpp @@ -1,12 +1,15 @@ #include #include #include +#include "esp_log.h" #include "Sockets.h" #include "ConfigSettings.h" #include "Somfy.h" #include "Network.h" #include "GitOTA.h" +static const char *TAG = "Sockets"; + extern ConfigSettings settings; extern Network net; extern SomfyShadeController somfy; @@ -86,7 +89,7 @@ void SocketEmitter::begin() { ws.onEvent(SocketEmitter::wsEvent); wsServer.addHandler(&ws); wsServer.begin(); - Serial.println("Socket Server Started..."); + ESP_LOGI(TAG, "Socket Server Started..."); } void SocketEmitter::loop() { ws.cleanupClients(); @@ -126,7 +129,7 @@ void SocketEmitter::initClients() { if(slot != 255) { uint32_t asyncId = getAsyncId(slot); if(asyncId != 0 && ws.hasClient(asyncId)) { - Serial.printf("Initializing Socket Client %u (asyncId=%lu)\n", slot, asyncId); + ESP_LOGD(TAG, "Initializing Socket Client %u (asyncId=%lu)", slot, asyncId); esp_task_wdt_reset(); settings.emitSockets(slot); if(!ws.hasClient(asyncId)) { this->newClients[i] = 255; continue; } @@ -168,12 +171,12 @@ void SocketEmitter::wsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client { uint8_t slot = addClient(asyncId); if(slot == 255) { - Serial.printf("Socket: No free client slots, closing %lu\n", asyncId); + ESP_LOGE(TAG, "Socket: No free client slots, closing %lu", asyncId); client->close(); return; } IPAddress ip = client->remoteIP(); - Serial.printf("Socket [%lu] Connected from %d.%d.%d.%d (slot %u)\n", asyncId, ip[0], ip[1], ip[2], ip[3], slot); + ESP_LOGD(TAG, "Socket [%lu] Connected from %d.%d.%d.%d (slot %u)", asyncId, ip[0], ip[1], ip[2], ip[3], slot); client->text("Connected"); client->setCloseClientOnQueueFull(false); sockEmit.delayInit(slot); @@ -182,7 +185,7 @@ void SocketEmitter::wsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client case WS_EVT_DISCONNECT: { uint8_t slot = mapClientId(asyncId); - Serial.printf("Socket [%lu] Disconnected (slot %u)\n", asyncId, slot); + ESP_LOGD(TAG, "Socket [%lu] Disconnected (slot %u)", asyncId, slot); if(slot != 255) { for(uint8_t i = 0; i < SOCK_MAX_ROOMS; i++) sockEmit.rooms[i].leave(slot); @@ -198,22 +201,22 @@ void SocketEmitter::wsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client data[len] = 0; if(strncmp((char*)data, "join:", 5) == 0) { uint8_t roomNum = atoi((char*)&data[5]); - Serial.printf("Client %u joining room %u\n", slot, roomNum); + ESP_LOGD(TAG, "Client %u joining room %u", slot, roomNum); if(roomNum < SOCK_MAX_ROOMS && slot != 255) sockEmit.rooms[roomNum].join(slot); } else if(strncmp((char*)data, "leave:", 6) == 0) { uint8_t roomNum = atoi((char*)&data[6]); - Serial.printf("Client %u leaving room %u\n", slot, roomNum); + ESP_LOGD(TAG, "Client %u leaving room %u", slot, roomNum); if(roomNum < SOCK_MAX_ROOMS && slot != 255) sockEmit.rooms[roomNum].leave(slot); } else { - Serial.printf("Socket [%lu] text: %s\n", asyncId, data); + ESP_LOGD(TAG, "Socket [%lu] text: %s", asyncId, data); } } } break; case WS_EVT_ERROR: - Serial.printf("Socket [%lu] Error\n", asyncId); + ESP_LOGE(TAG, "Socket [%lu] Error", asyncId); break; case WS_EVT_PONG: break; diff --git a/src/Somfy.cpp b/src/Somfy.cpp index 31b1aca..2ee950e 100644 --- a/src/Somfy.cpp +++ b/src/Somfy.cpp @@ -2,6 +2,7 @@ #include #include #include +#include "esp_log.h" #include "Utils.h" #include "ConfigSettings.h" #include "Somfy.h" @@ -10,6 +11,8 @@ #include "ConfigFile.h" #include "GitOTA.h" +static const char *TAG = "Somfy"; + extern Preferences pref; extern SomfyShadeController somfy; extern SocketEmitter sockEmit; @@ -216,37 +219,21 @@ void somfy_frame_t::decodeFrame(byte* frame) { } if(this->valid && this->encKey == 0) this->valid = false; if (!this->valid) { - Serial.print("INVALID FRAME "); - Serial.print("KEY:"); - Serial.print(this->encKey); - Serial.print(" ADDR:"); - Serial.print(this->remoteAddress); - Serial.print(" CMD:"); - Serial.print(translateSomfyCommand(this->cmd)); - Serial.print(" RCODE:"); - Serial.println(this->rollingCode); - Serial.println(" KEY 1 2 3 4 5 6 "); - Serial.println("--------------------------------"); - Serial.print("ENC "); + ESP_LOGW(TAG, "INVALID FRAME KEY:%d ADDR:%d CMD:%s RCODE:%d", + this->encKey, this->remoteAddress, + translateSomfyCommand(this->cmd).c_str(), this->rollingCode); + ESP_LOGD(TAG, " KEY 1 2 3 4 5 6 "); + ESP_LOGD(TAG, "--------------------------------"); + char enc_buf[64], dec_buf[64]; + int enc_pos = 0, dec_pos = 0; + enc_pos += snprintf(enc_buf + enc_pos, sizeof(enc_buf) - enc_pos, "ENC "); + dec_pos += snprintf(dec_buf + dec_pos, sizeof(dec_buf) - dec_pos, "DEC "); for (byte i = 0; i < 10; i++) { - if (frame[i] < 10) - Serial.print(" "); - else if (frame[i] < 100) - Serial.print(" "); - Serial.print(frame[i]); - Serial.print(" "); + enc_pos += snprintf(enc_buf + enc_pos, sizeof(enc_buf) - enc_pos, "%3d ", frame[i]); + dec_pos += snprintf(dec_buf + dec_pos, sizeof(dec_buf) - dec_pos, "%3d ", decoded[i]); } - Serial.println(); - Serial.print("DEC "); - for (byte i = 0; i < 10; i++) { - if (decoded[i] < 10) - Serial.print(" "); - else if (decoded[i] < 100) - Serial.print(" "); - Serial.print(decoded[i]); - Serial.print(" "); - } - Serial.println(); + ESP_LOGD(TAG, "%s", enc_buf); + ESP_LOGD(TAG, "%s", dec_buf); } } void somfy_frame_t::decodeFrame(somfy_rx_t *rx) { @@ -435,21 +422,11 @@ void somfy_frame_t::encodeFrame(byte *frame) { } } void somfy_frame_t::print() { - Serial.println("----------- Receiving -------------"); - Serial.print("RSSI:"); - Serial.print(this->rssi); - Serial.print(" LQI:"); - Serial.println(this->lqi); - Serial.print("CMD:"); - Serial.print(translateSomfyCommand(this->cmd)); - Serial.print(" ADDR:"); - Serial.print(this->remoteAddress); - Serial.print(" RCODE:"); - Serial.println(this->rollingCode); - Serial.print("KEY:"); - Serial.print(this->encKey, HEX); - Serial.print(" CS:"); - Serial.println(this->checksum); + ESP_LOGD(TAG, "----------- Receiving -------------"); + ESP_LOGD(TAG, "RSSI:%d LQI:%d", this->rssi, this->lqi); + ESP_LOGD(TAG, "CMD:%s ADDR:%d RCODE:%d", + translateSomfyCommand(this->cmd).c_str(), this->remoteAddress, this->rollingCode); + ESP_LOGD(TAG, "KEY:%02X CS:%d", this->encKey, this->checksum); } bool somfy_frame_t::isSynonym(somfy_frame_t &frame) { return this->remoteAddress == frame.remoteAddress && this->cmd != frame.cmd && this->rollingCode == frame.rollingCode; } bool somfy_frame_t::isRepeat(somfy_frame_t &frame) { return this->remoteAddress == frame.remoteAddress && this->cmd == frame.cmd && this->rollingCode == frame.rollingCode; } @@ -513,7 +490,7 @@ void SomfyShadeController::updateGroupFlags() { } #ifdef USE_NVS bool SomfyShadeController::loadLegacy() { - Serial.println("Loading Legacy shades using NVS"); + ESP_LOGI(TAG, "Loading Legacy shades using NVS"); pref.begin("Shades", true); pref.getBytes("shadeIds", this->m_shadeIds, sizeof(this->m_shadeIds)); pref.end(); @@ -549,7 +526,6 @@ bool SomfyShadeController::loadLegacy() { DEBUG_SOMFY.print(this->m_shadeIds[i]); if(i < SOMFY_MAX_SHADES - 1) DEBUG_SOMFY.print(","); } - Serial.println(); #endif #ifdef USE_NVS if(!this->useNVS()) { @@ -565,12 +541,12 @@ bool SomfyShadeController::loadLegacy() { bool SomfyShadeController::begin() { // Load up all the configuration data. //ShadeConfigFile::getAppVersion(this->appVersion); - Serial.printf("App Version:%u.%u.%u\n", settings.appVersion.major, settings.appVersion.minor, settings.appVersion.build); + ESP_LOGI(TAG, "App Version:%u.%u.%u", settings.appVersion.major, settings.appVersion.minor, settings.appVersion.build); #ifdef USE_NVS if(!this->useNVS()) { // At 1.4 we started using the configuration file. If the file doesn't exist then booh. // We need to remove all the extraeneous data from NVS for the shades. From here on out we // will rely on the shade configuration. - Serial.println("No longer using NVS"); + ESP_LOGI(TAG, "No longer using NVS"); if(ShadeConfigFile::exists()) { ShadeConfigFile::load(this); } @@ -595,11 +571,11 @@ bool SomfyShadeController::begin() { } #endif if(ShadeConfigFile::exists()) { - Serial.println("shades.cfg exists so we are using that"); + ESP_LOGI(TAG, "shades.cfg exists so we are using that"); ShadeConfigFile::load(this); } else { - Serial.println("Starting clean"); + ESP_LOGI(TAG, "Starting clean"); #ifdef USE_NVS this->loadLegacy(); #endif @@ -774,8 +750,7 @@ void SomfyShade::commitShadePosition() { char shadeKey[15]; if(somfy.useNVS()) { snprintf(shadeKey, sizeof(shadeKey), "SomfyShade%u", this->shadeId); - Serial.print("Writing current shade position: "); - Serial.println(this->currentPos, 4); + ESP_LOGD(TAG, "Writing current shade position: %.4f", this->currentPos); pref.begin(shadeKey); pref.putFloat("currentPos", this->currentPos); pref.end(); @@ -788,9 +763,7 @@ void SomfyShade::commitMyPosition() { if(somfy.useNVS()) { char shadeKey[15]; snprintf(shadeKey, sizeof(shadeKey), "SomfyShade%u", this->shadeId); - Serial.print("Writing my shade position:"); - Serial.print(this->myPos); - Serial.println("%"); + ESP_LOGD(TAG, "Writing my shade position:%.2f%%", this->myPos); pref.begin(shadeKey); pref.putUShort("myPos", this->myPos); pref.end(); @@ -803,8 +776,7 @@ void SomfyShade::commitTiltPosition() { if(somfy.useNVS()) { char shadeKey[15]; snprintf(shadeKey, sizeof(shadeKey), "SomfyShade%u", this->shadeId); - Serial.print("Writing current shade tilt position: "); - Serial.println(this->currentTiltPos, 4); + ESP_LOGD(TAG, "Writing current shade tilt position: %.4f", this->currentTiltPos); pref.begin(shadeKey); pref.putFloat("currentTiltPos", this->currentTiltPos); pref.end(); @@ -956,19 +928,19 @@ void SomfyShade::setGPIOs() { case -1: digitalWrite(this->gpioDown, p_off); digitalWrite(this->gpioUp, p_on); - if(dir != this->gpioDir) Serial.printf("UP: true, DOWN: false\n"); + if(dir != this->gpioDir) ESP_LOGD(TAG, "UP: true, DOWN: false"); this->gpioDir = dir; break; case 1: digitalWrite(this->gpioUp, p_off); digitalWrite(this->gpioDown, p_on); - if(dir != this->gpioDir) Serial.printf("UP: false, DOWN: true\n"); + if(dir != this->gpioDir) ESP_LOGD(TAG, "UP: false, DOWN: true"); this->gpioDir = dir; break; default: digitalWrite(this->gpioUp, p_off); digitalWrite(this->gpioDown, p_off); - if(dir != this->gpioDir) Serial.printf("UP: false, DOWN: false\n"); + if(dir != this->gpioDir) ESP_LOGD(TAG, "UP: false, DOWN: false"); this->gpioDir = dir; break; } @@ -998,7 +970,7 @@ void SomfyShade::triggerGPIOs(somfy_frame_t &frame) { digitalWrite(this->gpioDown, p_off); digitalWrite(this->gpioMy, p_on); dir = 0; - if(dir != this->gpioDir) Serial.printf("UP: false, DOWN: false, MY: true\n"); + if(dir != this->gpioDir) ESP_LOGD(TAG, "UP: false, DOWN: false, MY: true"); } break; case somfy_commands::Up: @@ -1007,7 +979,7 @@ void SomfyShade::triggerGPIOs(somfy_frame_t &frame) { digitalWrite(this->gpioDown, p_off); digitalWrite(this->gpioUp, p_on); dir = -1; - Serial.printf("UP: true, DOWN: false, MY: false\n"); + ESP_LOGD(TAG, "UP: true, DOWN: false, MY: false"); } break; case somfy_commands::Toggle: @@ -1018,14 +990,14 @@ void SomfyShade::triggerGPIOs(somfy_frame_t &frame) { } digitalWrite(this->gpioDown, p_on); dir = 1; - Serial.printf("UP: false, DOWN: true, MY: false\n"); + ESP_LOGD(TAG, "UP: false, DOWN: true, MY: false"); break; case somfy_commands::MyUp: if(this->shadeType != shade_types::drycontact && !this->isToggle() && this->shadeType != shade_types::drycontact2) { digitalWrite(this->gpioDown, p_off); digitalWrite(this->gpioMy, p_on); digitalWrite(this->gpioUp, p_on); - Serial.printf("UP: true, DOWN: false, MY: true\n"); + ESP_LOGD(TAG, "UP: true, DOWN: false, MY: true"); } break; case somfy_commands::MyDown: @@ -1033,7 +1005,7 @@ void SomfyShade::triggerGPIOs(somfy_frame_t &frame) { digitalWrite(this->gpioUp, p_off); digitalWrite(this->gpioMy, p_on); digitalWrite(this->gpioDown, p_on); - Serial.printf("UP: false, DOWN: true, MY: true\n"); + ESP_LOGD(TAG, "UP: false, DOWN: true, MY: true"); } break; case somfy_commands::MyUpDown: @@ -1041,7 +1013,7 @@ void SomfyShade::triggerGPIOs(somfy_frame_t &frame) { digitalWrite(this->gpioUp, p_on); digitalWrite(this->gpioMy, p_on); digitalWrite(this->gpioDown, p_on); - Serial.printf("UP: true, DOWN: true, MY: true\n"); + ESP_LOGD(TAG, "UP: true, DOWN: true, MY: true"); } break; default: @@ -1089,7 +1061,7 @@ void SomfyShade::checkMovement() { this->p_target(this->myPos >= 0 ? this->myPos : 100.0f); //this->target = this->myPos >= 0 ? this->myPos : 100.0f; this->sunDone = true; - Serial.printf("[%u] Sun -> done\r\n", this->shadeId); + ESP_LOGD(TAG, "[%u] Sun -> done", this->shadeId); } if (!this->noWindDone && this->noWindStart @@ -1098,7 +1070,7 @@ void SomfyShade::checkMovement() { this->p_target(this->myPos >= 0 ? this->myPos : 100.0f); //this->target = this->myPos >= 0 ? this->myPos : 100.0f; this->noWindDone = true; - Serial.printf("[%u] No Wind -> done\r\n", this->shadeId); + ESP_LOGD(TAG, "[%u] No Wind -> done", this->shadeId); } } if (!isSunny @@ -1109,7 +1081,7 @@ void SomfyShade::checkMovement() { if(this->tiltType == tilt_types::tiltonly) this->p_tiltTarget(0.0f); this->p_target(0.0f); this->noSunDone = true; - Serial.printf("[%u] No Sun -> done\r\n", this->shadeId); + ESP_LOGD(TAG, "[%u] No Sun -> done", this->shadeId); } } @@ -1121,7 +1093,7 @@ void SomfyShade::checkMovement() { if(this->tiltType == tilt_types::tiltonly) this->p_tiltTarget(0.0f); this->p_target(0.0f); this->windDone = true; - Serial.printf("[%u] Wind -> done\r\n", this->shadeId); + ESP_LOGD(TAG, "[%u] Wind -> done", this->shadeId); } if(!tilt_first && this->direction > 0) { @@ -1167,7 +1139,7 @@ void SomfyShade::checkMovement() { // not moving otherwise the my function will kick in. if(this->settingPos) { if(!isAtTarget()) { - Serial.printf("We are not at our tilt target: %.2f\n", this->tiltTarget); + ESP_LOGD(TAG, "We are not at our tilt target: %.2f", this->tiltTarget); if(this->target != 100.0) SomfyRemote::sendCommand(somfy_commands::My, this->repeats); delay(100); // We now need to move the tilt to the position we requested. @@ -1219,7 +1191,7 @@ void SomfyShade::checkMovement() { // not moving otherwise the my function will kick in. if(this->settingPos) { if(!isAtTarget()) { - Serial.printf("We are not at our tilt target: %.2f\n", this->tiltTarget); + ESP_LOGD(TAG, "We are not at our tilt target: %.2f", this->tiltTarget); if(this->target != 0.0) SomfyRemote::sendCommand(somfy_commands::My, this->repeats); delay(100); // We now need to move the tilt to the position we requested. @@ -1330,7 +1302,7 @@ void SomfyShade::checkMovement() { } this->p_tiltDirection(0); this->settingTiltPos = false; - Serial.println("Stopping at tilt position"); + ESP_LOGI(TAG, "Stopping at tilt position"); if(this->isAtTarget()) this->commitShadePosition(); } } @@ -1402,16 +1374,9 @@ void SomfyShade::load() { this->tiltTarget = floor(this->currentTiltPos); pref.getBytes("linkedAddr", linkedAddresses, sizeof(linkedAddresses)); pref.end(); - Serial.print("shadeId:"); - Serial.print(this->getShadeId()); - Serial.print(" name:"); - Serial.print(this->name); - Serial.print(" address:"); - Serial.print(this->getRemoteAddress()); - Serial.print(" position:"); - Serial.print(this->currentPos); - Serial.print(" myPos:"); - Serial.println(this->myPos); + ESP_LOGI(TAG, "shadeId:%d name:%s address:%d position:%.2f myPos:%.2f", + this->getShadeId(), this->name, this->getRemoteAddress(), + this->currentPos, this->myPos); pref.begin("ShadeCodes"); this->lastRollingCode = pref.getUShort(this->m_remotePrefId, 0); for(uint8_t j = 0; j < SOMFY_MAX_LINKED_REMOTES; j++) { @@ -1470,7 +1435,7 @@ void SomfyShade::publishState() { void SomfyShade::publishDisco() { if(!mqtt.connected() || !settings.MQTT.pubDisco) return; char topic[128] = ""; - DynamicJsonDocument doc(2048); + JsonDocument doc; JsonObject obj = doc.to(); snprintf(topic, sizeof(topic), "%s/shades/%d", settings.MQTT.rootTopic, this->shadeId); obj["~"] = topic; @@ -2095,12 +2060,8 @@ void SomfyShade::processWaitingFrame() { this->p_tiltTarget(dir > 0 ? 100.0f : 0.0f); this->setTiltMovement(dir); this->lastFrame.processed = true; - Serial.print(this->name); - Serial.print(" Processing tilt "); - Serial.print(translateSomfyCommand(this->lastFrame.cmd)); - Serial.print(" after "); - Serial.print(this->lastFrame.repeats); - Serial.println(" repeats"); + ESP_LOGD(TAG, "%s Processing tilt %s after %d repeats", + this->name, translateSomfyCommand(this->lastFrame.cmd).c_str(), this->lastFrame.repeats); this->emitCommand(cmd, "remote", this->lastFrame.remoteAddress); } else { @@ -2121,12 +2082,8 @@ void SomfyShade::processWaitingFrame() { this->p_target(dir > 0 ? 100.0f : 0.0f); this->setMovement(dir); this->lastFrame.processed = true; - Serial.print(this->name); - Serial.print(" Processing "); - Serial.print(translateSomfyCommand(this->lastFrame.cmd)); - Serial.print(" after "); - Serial.print(this->lastFrame.repeats); - Serial.println(" repeats"); + ESP_LOGD(TAG, "%s Processing %s after %d repeats", + this->name, translateSomfyCommand(this->lastFrame.cmd).c_str(), this->lastFrame.repeats); this->emitCommand(cmd, "remote", this->lastFrame.remoteAddress); } else { @@ -2174,10 +2131,7 @@ void SomfyShade::processWaitingFrame() { } if(this->lastFrame.repeats > SETMY_REPEATS + 2) this->lastFrame.processed = true; if(this->lastFrame.processed) { - Serial.print(this->name); - Serial.print(" Processing MY after "); - Serial.print(this->lastFrame.repeats); - Serial.println(" repeats"); + ESP_LOGD(TAG, "%s Processing MY after %d repeats", this->name, this->lastFrame.repeats); } break; default: @@ -2264,25 +2218,25 @@ void SomfyShade::processFrame(somfy_frame_t &frame, bool internal) { { this->sunStart = curTime; this->sunDone = false; - Serial.printf("[%u] Sun -> start\r\n", this->shadeId); + ESP_LOGD(TAG, "[%u] Sun -> start", this->shadeId); } else if (!isSunny && wasSunny) { this->noSunStart = curTime; this->noSunDone = false; - Serial.printf("[%u] No Sun -> start\r\n", this->shadeId); + ESP_LOGD(TAG, "[%u] No Sun -> start", this->shadeId); } if (isWindy && !wasWindy) { this->windStart = curTime; this->windDone = false; - Serial.printf("[%u] Wind -> start\r\n", this->shadeId); + ESP_LOGD(TAG, "[%u] Wind -> start", this->shadeId); } else if (!isWindy && wasWindy) { this->noWindStart = curTime; this->noWindDone = false; - Serial.printf("[%u] No Wind -> start\r\n", this->shadeId); + ESP_LOGD(TAG, "[%u] No Wind -> start", this->shadeId); } this->emitState(); somfy.updateGroupFlags(); @@ -2425,7 +2379,7 @@ void SomfyShade::processFrame(somfy_frame_t &frame, bool internal) { } else { if(this->lastFrame.processed) return; - Serial.println("Moving to My target"); + ESP_LOGI(TAG, "Moving to My target"); this->lastFrame.processed = true; if(this->myTiltPos >= 0.0f && this->myTiltPos <= 100.0f) this->p_tiltTarget(this->myTiltPos); if(this->myPos >= 0.0f && this->myPos <= 100.0f && this->tiltType != tilt_types::tiltonly) this->p_target(this->myPos); @@ -2610,7 +2564,7 @@ void SomfyShade::processInternalCommand(somfy_commands cmd, uint8_t repeat) { break; case somfy_commands::My: if(this->isIdle()) { - Serial.printf("Shade #%d is idle\n", this->getShadeId()); + ESP_LOGD(TAG, "Shade #%d is idle", this->getShadeId()); if(this->simMy()) { this->moveToMyPosition(); } @@ -2705,7 +2659,7 @@ void SomfyShade::processInternalCommand(somfy_commands cmd, uint8_t repeat) { this->emitState(); } else { - Serial.printf("Shade does not have sensor %d\n", this->flags); + ESP_LOGW(TAG, "Shade does not have sensor %d", this->flags); } break; case somfy_commands::SunFlag: @@ -2725,7 +2679,7 @@ void SomfyShade::processInternalCommand(somfy_commands cmd, uint8_t repeat) { this->emitState(); } else - Serial.printf("Shade does not have sensor %d\n", this->flags); + ESP_LOGW(TAG, "Shade does not have sensor %d", this->flags); break; default: dir = 0; @@ -2864,7 +2818,7 @@ void SomfyShade::setMyPosition(int8_t pos, int8_t tilt) { } void SomfyShade::moveToMyPosition() { if(!this->isIdle()) return; - Serial.println("Moving to My Position"); + ESP_LOGI(TAG, "Moving to My Position"); if(this->tiltType == tilt_types::tiltonly) { this->p_currentPos(100.0f); this->p_myPos(-1.0f); @@ -2881,7 +2835,7 @@ void SomfyShade::moveToMyPosition() { if(this->myTiltPos >= 0.0f && this->myTiltPos <= 100.0f) this->p_tiltTarget(this->myTiltPos); this->settingPos = false; if(this->simMy()) { - Serial.print("Moving to simulated favorite\n"); + ESP_LOGI(TAG, "Moving to simulated favorite"); this->moveToTarget(this->myPos, this->myTiltPos); } else @@ -2889,7 +2843,7 @@ void SomfyShade::moveToMyPosition() { } void SomfyShade::sendCommand(somfy_commands cmd) { this->sendCommand(cmd, this->repeats); } void SomfyShade::sendCommand(somfy_commands cmd, uint8_t repeat, uint8_t stepSize) { - Serial.print("Send command start\n"); + ESP_LOGD(TAG, "Send command start"); // This sendCommand function will always be called externally. sendCommand at the remote level // is expected to be called internally when the motor needs commanded. if(this->bitLength == 0) this->bitLength = somfy.transceiver.config.type; @@ -2897,7 +2851,7 @@ void SomfyShade::sendCommand(somfy_commands cmd, uint8_t repeat, uint8_t stepSiz // The real motor stops on its own when it receives the same direction again. if((cmd == somfy_commands::Up && this->direction == -1) || (cmd == somfy_commands::Down && this->direction == 1)) { - Serial.println("Same command as dir"); + ESP_LOGD(TAG, "Same command as dir"); SomfyRemote::sendCommand(cmd, repeat); this->p_target(this->currentPos); this->p_tiltTarget(this->currentTiltPos); @@ -2944,12 +2898,12 @@ void SomfyShade::sendCommand(somfy_commands cmd, uint8_t repeat, uint8_t stepSiz if(this->isToggle() || this->shadeType == shade_types::drycontact) SomfyRemote::sendCommand(cmd, repeat); else if(this->shadeType == shade_types::drycontact2){ - Serial.print("Send command start 1\n"); + ESP_LOGD(TAG, "Send command start 1"); return; } else if(this->isIdle()) { this->moveToMyPosition(); - Serial.print("Send command end 2\n"); + ESP_LOGD(TAG, "Send command end 2"); return; } else { @@ -2968,7 +2922,7 @@ void SomfyShade::sendCommand(somfy_commands cmd, uint8_t repeat, uint8_t stepSiz else { SomfyRemote::sendCommand(cmd, repeat, stepSize); } - Serial.print("Send command end\n"); + ESP_LOGD(TAG, "Send command end"); } void SomfyGroup::sendCommand(somfy_commands cmd) { this->sendCommand(cmd, this->repeats); } void SomfyGroup::sendCommand(somfy_commands cmd, uint8_t repeat, uint8_t stepSize) { @@ -3028,12 +2982,8 @@ void SomfyShade::moveToTiltTarget(float target) { // Only send a command if the lift is not moving. if(this->currentPos == this->target || this->tiltType == tilt_types::tiltmotor) { if(cmd != somfy_commands::My) { - Serial.print("Moving Tilt to "); - Serial.print(target); - Serial.print("% from "); - Serial.print(this->currentTiltPos); - Serial.print("% using "); - Serial.println(translateSomfyCommand(cmd)); + ESP_LOGI(TAG, "Moving Tilt to %.2f%% from %.2f%% using %s", + target, this->currentTiltPos, translateSomfyCommand(cmd).c_str()); SomfyRemote::sendCommand(cmd, this->tiltType == tilt_types::tiltmotor ? TILT_REPEATS : this->repeats); } // If the blind is currently moving then the command to stop it @@ -3071,18 +3021,13 @@ void SomfyShade::moveToTarget(float pos, float tilt) { cmd = somfy_commands::Down; } if(cmd != somfy_commands::My) { - Serial.print("Moving to "); - Serial.print(pos); - Serial.print("% from "); - Serial.print(this->currentPos); if(tilt >= 0) { - Serial.print(" tilt "); - Serial.print(tilt); - Serial.print("% from "); - Serial.print(this->currentTiltPos); + ESP_LOGI(TAG, "Moving to %.2f%% from %.2f%% tilt %.2f%% from %.2f%% using %s", + pos, this->currentPos, tilt, this->currentTiltPos, translateSomfyCommand(cmd).c_str()); + } else { + ESP_LOGI(TAG, "Moving to %.2f%% from %.2f%% using %s", + pos, this->currentPos, translateSomfyCommand(cmd).c_str()); } - Serial.print("% using "); - Serial.println(translateSomfyCommand(cmd)); SomfyRemote::sendCommand(cmd, this->tiltType == tilt_types::euromode ? TILT_REPEATS : this->repeats); this->settingPos = true; this->p_target(pos); @@ -3521,8 +3466,7 @@ uint8_t SomfyShadeController::getNextShadeId() { } } if(!id_exists) { - Serial.print("Got next Shade Id:"); - Serial.print(i); + ESP_LOGD(TAG, "Got next Shade Id:%d", i); return i; } } @@ -3559,8 +3503,7 @@ uint8_t SomfyShadeController::getNextGroupId() { } } if(!id_exists) { - Serial.print("Got next Group Id:"); - Serial.print(i); + ESP_LOGD(TAG, "Got next Group Id:%d", i); return i; } } @@ -3579,8 +3522,7 @@ uint8_t SomfyShadeController::getNextRoomId() { } } if(!id_exists) { - Serial.print("Got next room Id:"); - Serial.print(i); + ESP_LOGD(TAG, "Got next room Id:%d", i); return i; } } @@ -3659,7 +3601,7 @@ SomfyShade *SomfyShadeController::addShade() { if(shade) { shade->setShadeId(shadeId); shade->sortOrder = this->getMaxShadeOrder() + 1; - Serial.printf("Sort order set to %d\n", shade->sortOrder); + ESP_LOGD(TAG, "Sort order set to %d", shade->sortOrder); this->isDirty = true; #ifdef USE_NVS if(this->useNVS()) { @@ -3688,25 +3630,30 @@ SomfyShade *SomfyShadeController::addShade() { pref.begin("Shades"); pref.remove("shadeIds"); int x = pref.putBytes("shadeIds", this->m_shadeIds, sizeof(this->m_shadeIds)); - Serial.printf("WROTE %d bytes to shadeIds\n", x); + ESP_LOGD(TAG, "WROTE %d bytes to shadeIds", x); pref.end(); - for(uint8_t i = 0; i < sizeof(this->m_shadeIds); i++) { - if(i != 0) Serial.print(","); - else Serial.print("Shade Ids: "); - Serial.print(this->m_shadeIds[i]); + { + char shade_ids_buf[256]; + int spos = snprintf(shade_ids_buf, sizeof(shade_ids_buf), "Shade Ids: "); + for(uint8_t i = 0; i < sizeof(this->m_shadeIds); i++) { + if(i != 0) spos += snprintf(shade_ids_buf + spos, sizeof(shade_ids_buf) - spos, ","); + spos += snprintf(shade_ids_buf + spos, sizeof(shade_ids_buf) - spos, "%d", this->m_shadeIds[i]); + } + ESP_LOGD(TAG, "%s", shade_ids_buf); } - Serial.println(); pref.begin("Shades"); pref.getBytes("shadeIds", this->m_shadeIds, sizeof(this->m_shadeIds)); - Serial.print("LENGTH:"); - Serial.println(pref.getBytesLength("shadeIds")); + ESP_LOGD(TAG, "LENGTH:%d", pref.getBytesLength("shadeIds")); pref.end(); - for(uint8_t i = 0; i < sizeof(this->m_shadeIds); i++) { - if(i != 0) Serial.print(","); - else Serial.print("Shade Ids: "); - Serial.print(this->m_shadeIds[i]); + { + char shade_ids_buf[256]; + int spos = snprintf(shade_ids_buf, sizeof(shade_ids_buf), "Shade Ids: "); + for(uint8_t i = 0; i < sizeof(this->m_shadeIds); i++) { + if(i != 0) spos += snprintf(shade_ids_buf + spos, sizeof(shade_ids_buf) - spos, ","); + spos += snprintf(shade_ids_buf + spos, sizeof(shade_ids_buf) - spos, "%d", this->m_shadeIds[i]); + } + ESP_LOGD(TAG, "%s", shade_ids_buf); } - Serial.println(); } #endif } @@ -3818,14 +3765,9 @@ void SomfyRemote::sendSensorCommand(int8_t isWindy, int8_t isSunny, uint8_t repe this->lastFrame.encKey = 160; // Sensor commands are always encryption code 160. this->lastFrame.cmd = somfy_commands::Sensor; this->lastFrame.processed = false; - Serial.print("CMD:"); - Serial.print(translateSomfyCommand(this->lastFrame.cmd)); - Serial.print(" ADDR:"); - Serial.print(this->lastFrame.remoteAddress); - Serial.print(" RCODE:"); - Serial.print(this->lastFrame.rollingCode); - Serial.print(" REPEAT:"); - Serial.println(repeat); + ESP_LOGD(TAG, "CMD:%s ADDR:%d RCODE:%d REPEAT:%d", + translateSomfyCommand(this->lastFrame.cmd).c_str(), + this->lastFrame.remoteAddress, this->lastFrame.rollingCode, repeat); somfy.sendFrame(this->lastFrame, repeat); somfy.processFrame(this->lastFrame, true); } @@ -3842,46 +3784,33 @@ void SomfyRemote::sendCommand(somfy_commands cmd, uint8_t repeat, uint8_t stepSi this->lastFrame.encKey = 0xA0 | static_cast(this->lastFrame.rollingCode & 0x000F); this->lastFrame.proto = this->proto; if(this->lastFrame.bitLength == 0) this->lastFrame.bitLength = bit_length; - if(this->lastFrame.rollingCode == 0) Serial.println("ERROR: Setting rcode to 0"); + if(this->lastFrame.rollingCode == 0) ESP_LOGE(TAG, "Setting rcode to 0"); this->p_lastRollingCode(this->lastFrame.rollingCode); // We have to set the processed to clear this if we are sending // another command. this->lastFrame.processed = false; if(this->proto == radio_proto::GP_Relay) { - Serial.print("CMD:"); - Serial.print(translateSomfyCommand(this->lastFrame.cmd)); - Serial.print(" ADDR:"); - Serial.print(this->lastFrame.remoteAddress); - Serial.print(" RCODE:"); - Serial.print(this->lastFrame.rollingCode); - Serial.println(" SETTING GPIO"); + ESP_LOGD(TAG, "CMD:%s ADDR:%d RCODE:%d SETTING GPIO", + translateSomfyCommand(this->lastFrame.cmd).c_str(), + this->lastFrame.remoteAddress, this->lastFrame.rollingCode); } else if(this->proto == radio_proto::GP_Remote) { - Serial.print("CMD:"); - Serial.print(translateSomfyCommand(this->lastFrame.cmd)); - Serial.print(" ADDR:"); - Serial.print(this->lastFrame.remoteAddress); - Serial.print(" RCODE:"); - Serial.print(this->lastFrame.rollingCode); - Serial.println(" TRIGGER GPIO"); + ESP_LOGD(TAG, "CMD:%s ADDR:%d RCODE:%d TRIGGER GPIO", + translateSomfyCommand(this->lastFrame.cmd).c_str(), + this->lastFrame.remoteAddress, this->lastFrame.rollingCode); this->triggerGPIOs(this->lastFrame); } else { - Serial.print("CMD:"); - Serial.print(translateSomfyCommand(this->lastFrame.cmd)); - Serial.print(" ADDR:"); - Serial.print(this->lastFrame.remoteAddress); - Serial.print(" RCODE:"); - Serial.print(this->lastFrame.rollingCode); - Serial.print(" REPEAT:"); - Serial.println(repeat); + ESP_LOGD(TAG, "CMD:%s ADDR:%d RCODE:%d REPEAT:%d", + translateSomfyCommand(this->lastFrame.cmd).c_str(), + this->lastFrame.remoteAddress, this->lastFrame.rollingCode, repeat); somfy.sendFrame(this->lastFrame, repeat); } somfy.processFrame(this->lastFrame, true); } bool SomfyRemote::isLastCommand(somfy_commands cmd) { if(this->lastFrame.cmd != cmd || this->lastFrame.rollingCode != this->lastRollingCode) { - Serial.printf("Not the last command %d: %d - %d\n", static_cast(this->lastFrame.cmd), this->lastFrame.rollingCode, this->lastRollingCode); + ESP_LOGD(TAG, "Not the last command %d: %d - %d", static_cast(this->lastFrame.cmd), this->lastFrame.rollingCode, this->lastRollingCode); return false; } return true; @@ -4006,7 +3935,7 @@ uint16_t SomfyRemote::setRollingCode(uint16_t code) { pref.putUShort(this->m_remotePrefId, code); pref.end(); this->lastRollingCode = code; - Serial.printf("Setting Last Rolling code %d\n", this->lastRollingCode); + ESP_LOGD(TAG, "Setting Last Rolling code %d", this->lastRollingCode); } return code; } @@ -4151,7 +4080,7 @@ void somfy_tx_queue_t::push(uint8_t hwsync, uint8_t *payload, uint8_t bit_length this->delay_time = millis() + TX_QUEUE_DELAY; // We do not want to process this frame until a full frame beat has passed. } void somfy_rx_queue_t::init() { - Serial.println("Initializing RX Queue"); + ESP_LOGD(TAG, "Initializing RX Queue"); for (uint8_t i = 0; i < MAX_RX_BUFFER; i++) this->items[i].clear(); memset(&this->index[0], 0xFF, MAX_RX_BUFFER); @@ -4395,7 +4324,7 @@ void Transceiver::beginFrequencyScan() { markFreq = currFreq = 433.0f; markRSSI = -100; ELECHOUSE_cc1101.setMHZ(currFreq); - Serial.printf("Begin frequency scan on Pin #%d\n", this->config.RXPin); + ESP_LOGD(TAG, "Begin frequency scan on Pin #%d", this->config.RXPin); attachInterrupt(interruptPin, handleReceive, CHANGE); this->emitFrequencyScan(); } @@ -4538,7 +4467,7 @@ void Transceiver::enableReceive(void) { ELECHOUSE_cc1101.SetRx(); //attachInterrupt(interruptPin, handleReceive, FALLING); attachInterrupt(interruptPin, handleReceive, CHANGE); - Serial.printf("Enabled receive on Pin #%d Timing: %ld\n", this->config.RXPin, millis() - timing); + ESP_LOGD(TAG, "Enabled receive on Pin #%d Timing: %ld", this->config.RXPin, millis() - timing); } } void Transceiver::disableReceive(void) { @@ -4623,7 +4552,7 @@ void transceiver_config_t::fromJSON(JsonObject& obj) { if (obj.containsKey("appendStatus")) this->appendStatus = obj["appendStatus"]; if (obj.containsKey("printBuffer")) this->printBuffer = obj["printBuffer"]; */ - Serial.printf("SCK:%u MISO:%u MOSI:%u CSN:%u RX:%u TX:%u\n", this->SCKPin, this->MISOPin, this->MOSIPin, this->CSNPin, this->RXPin, this->TXPin); + ESP_LOGD(TAG, "SCK:%u MISO:%u MOSI:%u CSN:%u RX:%u TX:%u", this->SCKPin, this->MISOPin, this->MOSIPin, this->CSNPin, this->RXPin, this->TXPin); } /* void transceiver_config_t::toJSON(JsonObject& obj) { @@ -4714,12 +4643,11 @@ void transceiver_config_t::save() { */ pref.end(); - Serial.print("Save Radio Settings "); - Serial.printf("SCK:%u MISO:%u MOSI:%u CSN:%u RX:%u TX:%u\n", this->SCKPin, this->MISOPin, this->MOSIPin, this->CSNPin, this->RXPin, this->TXPin); + ESP_LOGI(TAG, "Save Radio Settings SCK:%u MISO:%u MOSI:%u CSN:%u RX:%u TX:%u", this->SCKPin, this->MISOPin, this->MOSIPin, this->CSNPin, this->RXPin, this->TXPin); } void transceiver_config_t::removeNVSKey(const char *key) { if(pref.isKey(key)) { - Serial.printf("Removing NVS Key: CC1101.%s\n", key); + ESP_LOGD(TAG, "Removing NVS Key: CC1101.%s", key); pref.remove(key); } } @@ -4728,7 +4656,7 @@ void transceiver_config_t::load() { esp_chip_info(&ci); switch(ci.model) { case esp_chip_model_t::CHIP_ESP32S3: - Serial.println("Setting S3 Transceiver Defaults..."); + ESP_LOGD(TAG, "Setting S3 Transceiver Defaults..."); this->TXPin = 15; this->RXPin = 14; this->MOSIPin = 11; @@ -4812,8 +4740,7 @@ void transceiver_config_t::apply() { this->radioInit = false; pref.end(); if(!radioInit) return; - Serial.print("Applying radio settings "); - Serial.printf("Setting Data Pins RX:%u TX:%u\n", this->RXPin, this->TXPin); + ESP_LOGD(TAG, "Applying radio settings - Setting Data Pins RX:%u TX:%u", this->RXPin, this->TXPin); //if(this->TXPin != this->RXPin) // pinMode(this->TXPin, OUTPUT); //pinMode(this->RXPin, INPUT); @@ -4822,9 +4749,9 @@ void transceiver_config_t::apply() { ELECHOUSE_cc1101.setGDO0(this->TXPin); // This pin may be shared. else ELECHOUSE_cc1101.setGDO(this->TXPin, this->RXPin); // GDO0, GDO2 - Serial.printf("Setting SPI Pins SCK:%u MISO:%u MOSI:%u CSN:%u\n", this->SCKPin, this->MISOPin, this->MOSIPin, this->CSNPin); + ESP_LOGD(TAG, "Setting SPI Pins SCK:%u MISO:%u MOSI:%u CSN:%u", this->SCKPin, this->MISOPin, this->MOSIPin, this->CSNPin); ELECHOUSE_cc1101.setSpiPin(this->SCKPin, this->MISOPin, this->MOSIPin, this->CSNPin); - Serial.println("Radio Pins Configured!"); + ESP_LOGD(TAG, "Radio Pins Configured!"); ELECHOUSE_cc1101.Init(); ELECHOUSE_cc1101.setCCMode(0); // set config for internal transmission mode. ELECHOUSE_cc1101.setMHZ(this->frequency); // Here you can set your basic frequency. The lib calculates the frequency automatically (default = 433.92).The cc1101 can: 300-348 MHZ, 387-464MHZ and 779-928MHZ. Read More info from datasheet. @@ -4860,11 +4787,11 @@ void transceiver_config_t::apply() { if (!ELECHOUSE_cc1101.getCC1101()) { - Serial.println("Error setting up the radio"); + ESP_LOGE(TAG, "Error setting up the radio"); this->radioInit = false; } else { - Serial.println("Successfully set up the radio"); + ESP_LOGI(TAG, "Successfully set up the radio"); somfy.transceiver.enableReceive(); this->radioInit = true; } @@ -4919,7 +4846,7 @@ void Transceiver::loop() { for(uint8_t i = 0; i < SOMFY_MAX_REPEATERS; i++) { if(somfy.repeaters[i] == frame.remoteAddress) { tx_queue.push(&rx); - Serial.println("Queued repeater frame..."); + ESP_LOGD(TAG, "Queued repeater frame..."); break; } } @@ -4933,12 +4860,15 @@ void Transceiver::loop() { somfy_tx_t tx; tx_queue.pop(&tx); - Serial.printf("Sending frame %d - %d-BIT [", tx.hwsync, tx.bit_length); - for(uint8_t j = 0; j < 10; j++) { - Serial.print(tx.payload[j]); - if(j < 9) Serial.print(", "); + { + char frame_buf[128]; + int fpos = snprintf(frame_buf, sizeof(frame_buf), "Sending frame %d - %d-BIT [", tx.hwsync, tx.bit_length); + for(uint8_t j = 0; j < 10; j++) { + fpos += snprintf(frame_buf + fpos, sizeof(frame_buf) - fpos, "%d%s", tx.payload[j], j < 9 ? ", " : ""); + } + snprintf(frame_buf + fpos, sizeof(frame_buf) - fpos, "]"); + ESP_LOGD(TAG, "%s", frame_buf); } - Serial.println("]"); this->sendFrame(tx.payload, tx.hwsync, tx.bit_length); tx_queue.delay_time = millis() + TX_QUEUE_DELAY; diff --git a/src/SomfyController.ino b/src/SomfyController.ino index af80702..cdff1b0 100644 --- a/src/SomfyController.ino +++ b/src/SomfyController.ino @@ -1,4 +1,3 @@ -#define LOG_LOCAL_LEVEL ESP_LOG_INFO #include "esp_log.h" #include #include @@ -13,6 +12,8 @@ #include "GitOTA.h" #include "esp_core_dump.h" +static const char *TAG = "Main"; + ConfigSettings settings; Web webServer; SocketEmitter sockEmit; @@ -25,19 +26,19 @@ GitUpdater git; uint32_t oldheap = 0; void listDir(const char *dirname, uint8_t levels) { - Serial.printf("Listing: %s\n", dirname); + ESP_LOGI(TAG, "Listing: %s", dirname); File root = LittleFS.open(dirname); if (!root || !root.isDirectory()) { - Serial.println("Failed to open directory"); + ESP_LOGE(TAG, "Failed to open directory"); return; } File file = root.openNextFile(); while (file) { if (file.isDirectory()) { - Serial.printf(" DIR : %s\n", file.name()); + ESP_LOGI(TAG, " DIR : %s", file.name()); if (levels) listDir(file.path(), levels - 1); } else { - Serial.printf(" FILE: %-30s %d bytes\n", file.name(), file.size()); + ESP_LOGI(TAG, " FILE: %-30s %d bytes", file.name(), file.size()); } file = root.openNextFile(); } @@ -45,39 +46,37 @@ void listDir(const char *dirname, uint8_t levels) { void setup() { Serial.begin(115200); - Serial.println(); - Serial.println("Startup/Boot...."); + ESP_LOGI(TAG, "Startup/Boot...."); esp_core_dump_summary_t summary; if (esp_core_dump_get_summary(&summary) == ESP_OK) { - Serial.println("*** Previous crash coredump found ***"); - Serial.printf(" Task: %s\n", summary.exc_task); - Serial.printf(" PC: 0x%08x\n", summary.exc_pc); - Serial.printf(" Cause: %d\n", summary.ex_info.exc_cause); - Serial.printf(" Backtrace:"); + ESP_LOGW(TAG, "*** Previous crash coredump found ***"); + ESP_LOGW(TAG, " Task: %s", summary.exc_task); + ESP_LOGW(TAG, " PC: 0x%08x", summary.exc_pc); + ESP_LOGW(TAG, " Cause: %d", summary.ex_info.exc_cause); + char bt_buf[256] = {0}; + int pos = 0; for (int i = 0; i < summary.exc_bt_info.depth; i++) { - Serial.printf(" 0x%08x", summary.exc_bt_info.bt[i]); + pos += snprintf(bt_buf + pos, sizeof(bt_buf) - pos, " 0x%08x", summary.exc_bt_info.bt[i]); } - Serial.println(); + ESP_LOGW(TAG, " Backtrace:%s", bt_buf); } - Serial.println("Mounting File System..."); + ESP_LOGI(TAG, "Mounting File System..."); if (LittleFS.begin()) { - Serial.printf("\nTotal: %d bytes\n", LittleFS.totalBytes()); - Serial.printf("Used: %d bytes\n", LittleFS.usedBytes()); - Serial.printf("Free: %d bytes\n", LittleFS.totalBytes() - LittleFS.usedBytes()); - Serial.println(); + ESP_LOGI(TAG, "Total: %d bytes", LittleFS.totalBytes()); + ESP_LOGI(TAG, "Used: %d bytes", LittleFS.usedBytes()); + ESP_LOGI(TAG, "Free: %d bytes", LittleFS.totalBytes() - LittleFS.usedBytes()); listDir("/", 3); } else { - Serial.println("LittleFS mount failed!"); + ESP_LOGE(TAG, "LittleFS mount failed!"); } - if(LittleFS.begin()) Serial.println("File system mounted successfully"); - else Serial.println("Error mounting file system"); + if(LittleFS.begin()) ESP_LOGI(TAG, "File system mounted successfully"); + else ESP_LOGE(TAG, "Error mounting file system"); settings.begin(); if(WiFi.status() == WL_CONNECTED) WiFi.disconnect(true); delay(10); - Serial.println(); webServer.startup(); webServer.begin(); delay(1000); @@ -93,9 +92,7 @@ void loop() { // put your main code here, to run repeatedly: //uint32_t heap = ESP.getFreeHeap(); if(rebootDelay.reboot && millis() > rebootDelay.rebootTime) { - Serial.print("Rebooting after "); - Serial.print(rebootDelay.rebootTime); - Serial.println("ms"); + ESP_LOGI(TAG, "Rebooting after %lums", rebootDelay.rebootTime); net.end(); ESP.restart(); return; @@ -103,11 +100,11 @@ void loop() { uint32_t timing = millis(); net.loop(); - if(millis() - timing > 100) Serial.printf("Timing Net: %ldms\n", millis() - timing); + if(millis() - timing > 100) ESP_LOGD(TAG, "Timing Net: %ldms", millis() - timing); timing = millis(); esp_task_wdt_reset(); somfy.loop(); - if(millis() - timing > 100) Serial.printf("Timing Somfy: %ldms\n", millis() - timing); + if(millis() - timing > 100) ESP_LOGD(TAG, "Timing Somfy: %ldms", millis() - timing); timing = millis(); esp_task_wdt_reset(); if(net.connected() || net.softAPOpened) { @@ -117,11 +114,11 @@ void loop() { } webServer.loop(); esp_task_wdt_reset(); - if(millis() - timing > 100) Serial.printf("Timing WebServer: %ldms\n", millis() - timing); + if(millis() - timing > 100) ESP_LOGD(TAG, "Timing WebServer: %ldms", millis() - timing); esp_task_wdt_reset(); timing = millis(); sockEmit.loop(); - if(millis() - timing > 100) Serial.printf("Timing Socket: %ldms\n", millis() - timing); + if(millis() - timing > 100) ESP_LOGD(TAG, "Timing Socket: %ldms", millis() - timing); esp_task_wdt_reset(); timing = millis(); } diff --git a/src/WResp.cpp b/src/WResp.cpp index f64c0fa..c00c1c5 100644 --- a/src/WResp.cpp +++ b/src/WResp.cpp @@ -1,4 +1,7 @@ #include "WResp.h" +#include "esp_log.h" + +static const char *TAG = "WResp"; void JsonSockEvent::beginEvent(AsyncWebSocket *server, const char *evt, char *buff, size_t buffSize) { this->server = server; this->buff = buff; @@ -24,8 +27,7 @@ void JsonSockEvent::_safecat(const char *val, bool escape) { size_t len = (escape ? this->calcEscapedLength(val) : strlen(val)) + strlen(this->buff); if(escape) len += 2; if(len >= this->buffSize) { - Serial.printf("Socket exceeded buffer size %d - %d\n", this->buffSize, len); - Serial.println(this->buff); + ESP_LOGE(TAG, "Socket exceeded buffer size %d - %d: %s", this->buffSize, len, this->buff); return; } if(escape) strcat(this->buff, "\""); diff --git a/src/Web.cpp b/src/Web.cpp index 07994f7..344e39a 100644 --- a/src/Web.cpp +++ b/src/Web.cpp @@ -2,6 +2,7 @@ #include #include #include +#include "esp_log.h" #include "mbedtls/md.h" #include "ConfigSettings.h" #include "ConfigFile.h" @@ -40,10 +41,12 @@ static const char _encoding_text[] = "text/plain"; static const char _encoding_html[] = "text/html"; static const char _encoding_json[] = "application/json"; +static const char *TAG = "Web"; + AsyncWebServer asyncServer(80); AsyncWebServer asyncApiServer(8081); void Web::startup() { - Serial.println("Launching web server..."); + ESP_LOGI(TAG, "Launching web server..."); asyncServer.on("/loginContext", HTTP_GET, [](AsyncWebServerRequest *request) { AsyncJsonResponse *response = new AsyncJsonResponse(); @@ -58,17 +61,17 @@ void Web::startup() { request->send(response); }); asyncApiServer.begin(); - Serial.println("Async API server started on port 8081"); + ESP_LOGI(TAG, "Async API server started on port 8081"); } void Web::loop() { delay(1); } bool Web::isAuthenticated(AsyncWebServerRequest *request, bool cfg) { - Serial.println("Checking async authentication"); + ESP_LOGD(TAG, "Checking async authentication"); if(settings.Security.type == security_types::None) return true; else if(!cfg && (settings.Security.permissions & static_cast(security_permissions::ConfigOnly)) == 0x01) return true; else if(request->hasHeader("apikey")) { - Serial.println("Checking API Key..."); + ESP_LOGD(TAG, "Checking API Key..."); char token[65]; memset(token, 0x00, sizeof(token)); this->createAPIToken(request->client()->remoteIP(), token); @@ -79,7 +82,7 @@ bool Web::isAuthenticated(AsyncWebServerRequest *request, bool cfg) { // Key is valid } else { - Serial.println("Not authenticated..."); + ESP_LOGE(TAG, "Not authenticated..."); request->send(401, _encoding_text, "Unauthorized API Key"); return false; } @@ -99,14 +102,13 @@ bool Web::createAPIToken(const char *payload, char *token) { mbedtls_md_hmac_starts(&ctx, (const unsigned char *)settings.serverId, strlen(settings.serverId)); mbedtls_md_hmac_update(&ctx, (const unsigned char *)payload, strlen(payload)); mbedtls_md_hmac_finish(&ctx, hmacResult); - Serial.print("Hash: "); token[0] = '\0'; for(int i = 0; i < sizeof(hmacResult); i++){ char str[3]; sprintf(str, "%02x", (int)hmacResult[i]); strcat(token, str); } - Serial.println(token); + ESP_LOGD(TAG, "Hash: %s", token); return true; } bool Web::createAPIToken(const IPAddress ipAddress, char *token) { @@ -325,7 +327,7 @@ static void serializeGitRelease(GitRelease *rel, JsonFormatter &json) { // -- Async handler implementations -- void Web::handleDiscovery(AsyncWebServerRequest *request) { if(request->method() == HTTP_POST || request->method() == HTTP_GET) { - Serial.println("Async Discovery Requested"); + ESP_LOGD(TAG, "Async Discovery Requested"); char connType[10] = "Unknown"; if(net.connType == conn_types_t::ethernet) strcpy(connType, "Ethernet"); else if(net.connType == conn_types_t::wifi) strcpy(connType, "Wifi"); @@ -794,7 +796,7 @@ void Web::handleDownloadFirmware(AsyncWebServerRequest *request) { GitRepo repo; GitRelease *rel = nullptr; int8_t err = repo.getReleases(); - Serial.println("Async downloadFirmware called..."); + ESP_LOGI(TAG, "Async downloadFirmware called..."); if(err == 0) { if(asyncHasParam(request, "ver")) { String ver = asyncParam(request, "ver"); @@ -826,7 +828,7 @@ void Web::handleBackup(AsyncWebServerRequest *request) { if(!this->isAuthenticated(request)) return; bool attach = false; if(asyncHasParam(request, "attach")) attach = toBoolean(asyncParam(request, "attach").c_str(), false); - Serial.println("Async saving current shade information"); + ESP_LOGI(TAG, "Async saving current shade information"); somfy.writeBackup(); if(somfy.backupData.length() == 0) { request->send(500, _encoding_text, "backup failed"); @@ -854,7 +856,7 @@ void Web::handleReboot(AsyncWebServerRequest *request) { if(request->method() == HTTP_OPTIONS) { request->send(200); return; } if(!this->isAuthenticated(request)) return; if(request->method() == HTTP_POST || request->method() == HTTP_PUT) { - Serial.println("Async Rebooting ESP..."); + ESP_LOGI(TAG, "Async Rebooting ESP..."); rebootDelay.reboot = true; rebootDelay.rebootTime = millis() + 500; request->send(200, _encoding_json, "{\"status\":\"OK\",\"desc\":\"Successfully started reboot\"}"); @@ -868,7 +870,7 @@ void Web::handleNotFound(AsyncWebServerRequest *request) { } void Web::begin() { - Serial.println("Creating Web MicroServices..."); + ESP_LOGI(TAG, "Creating Web MicroServices..."); // Async API Server (port 8081) DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*"); DefaultHeaders::Instance().addHeader("Access-Control-Allow-Methods", "PUT,POST,GET,OPTIONS"); @@ -1014,8 +1016,8 @@ void Web::begin() { restore_options_t opts; if(asyncHasParam(request, "data")) { String dataStr = asyncParam(request, "data"); - Serial.println(dataStr); - StaticJsonDocument<256> doc; + ESP_LOGD(TAG, "%s", dataStr.c_str()); + JsonDocument doc; DeserializationError err = deserializeJson(doc, dataStr); if(err) { request->send(500, "application/json", "{\"status\":\"ERROR\",\"desc\":\"JSON parse error\"}"); @@ -1027,11 +1029,11 @@ void Web::begin() { } } else { - Serial.println("No restore options sent. Using defaults..."); + ESP_LOGD(TAG, "No restore options sent. Using defaults..."); opts.shades = true; } ShadeConfigFile::restore(&somfy, "/shades.tmp", opts); - Serial.println("Rebooting ESP for restored settings..."); + ESP_LOGI(TAG, "Rebooting ESP for restored settings..."); rebootDelay.reboot = true; rebootDelay.rebootTime = millis() + 1000; } @@ -1040,7 +1042,7 @@ void Web::begin() { esp_task_wdt_reset(); if(index == 0) { webServer.uploadSuccess = false; - Serial.printf("Restore: %s\n", filename.c_str()); + ESP_LOGD(TAG, "Restore: %s", filename.c_str()); File fup = LittleFS.open("/shades.tmp", "w"); fup.close(); } @@ -1103,7 +1105,7 @@ void Web::begin() { asyncServer.addHandler(new AsyncCallbackJsonWebHandler("/addRoom", [](AsyncWebServerRequest *request, JsonVariant &json) { if(json.isNull()) { request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"No room object supplied.\"}")); return; } - Serial.println("Adding a room"); + ESP_LOGD(TAG, "Adding a room"); JsonObject obj = json.as(); if(somfy.roomCount() > SOMFY_MAX_ROOMS) { request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"Maximum number of rooms exceeded.\"}")); @@ -1126,7 +1128,7 @@ void Web::begin() { asyncServer.addHandler(new AsyncCallbackJsonWebHandler("/addShade", [](AsyncWebServerRequest *request, JsonVariant &json) { if(json.isNull()) { request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"No shade object supplied.\"}")); return; } - Serial.println("Adding a shade"); + ESP_LOGD(TAG, "Adding a shade"); JsonObject obj = json.as(); if(somfy.shadeCount() > SOMFY_MAX_SHADES) { request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"Maximum number of shades exceeded.\"}")); @@ -1149,7 +1151,7 @@ void Web::begin() { asyncServer.addHandler(new AsyncCallbackJsonWebHandler("/addGroup", [](AsyncWebServerRequest *request, JsonVariant &json) { if(json.isNull()) { request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"No group object supplied.\"}")); return; } - Serial.println("Adding a group"); + ESP_LOGD(TAG, "Adding a group"); JsonObject obj = json.as(); if(somfy.groupCount() > SOMFY_MAX_GROUPS) { request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"Maximum number of groups exceeded.\"}")); @@ -1210,7 +1212,7 @@ void Web::begin() { asyncServer.addHandler(new AsyncCallbackJsonWebHandler("/saveRoom", [](AsyncWebServerRequest *request, JsonVariant &json) { if(json.isNull()) { request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"No room object supplied.\"}")); return; } - Serial.println("Updating a room"); + ESP_LOGD(TAG, "Updating a room"); JsonObject obj = json.as(); if(obj.containsKey("roomId")) { SomfyRoom* room = somfy.getRoomById(obj["roomId"]); @@ -1232,7 +1234,7 @@ void Web::begin() { asyncServer.addHandler(new AsyncCallbackJsonWebHandler("/saveShade", [](AsyncWebServerRequest *request, JsonVariant &json) { if(json.isNull()) { request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"No shade object supplied.\"}")); return; } - Serial.println("Updating a shade"); + ESP_LOGD(TAG, "Updating a shade"); JsonObject obj = json.as(); if(obj.containsKey("shadeId")) { SomfyShade* shade = somfy.getShadeById(obj["shadeId"]); @@ -1260,7 +1262,7 @@ void Web::begin() { asyncServer.addHandler(new AsyncCallbackJsonWebHandler("/saveGroup", [](AsyncWebServerRequest *request, JsonVariant &json) { if(json.isNull()) { request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"No group object supplied.\"}")); return; } - Serial.println("Updating a group"); + ESP_LOGD(TAG, "Updating a group"); JsonObject obj = json.as(); if(obj.containsKey("groupId")) { SomfyGroup* group = somfy.getGroupById(obj["groupId"]); @@ -1493,7 +1495,7 @@ void Web::begin() { [](AsyncWebServerRequest *request, JsonVariant &json) { uint32_t address = 0; if(!json.isNull()) { - Serial.println("Linking a repeater"); + ESP_LOGD(TAG, "Linking a repeater"); JsonObject obj = json.as(); if(obj.containsKey("address")) address = obj["address"]; else if(obj.containsKey("remoteAddress")) address = obj["remoteAddress"]; @@ -1534,7 +1536,7 @@ void Web::begin() { [](AsyncWebServerRequest *request, JsonVariant &json) { uint32_t address = 0; if(!json.isNull()) { - Serial.println("Unlinking a repeater"); + ESP_LOGD(TAG, "Unlinking a repeater"); JsonObject obj = json.as(); if(obj.containsKey("address")) address = obj["address"]; else if(obj.containsKey("remoteAddress")) address = obj["remoteAddress"]; @@ -1600,7 +1602,7 @@ void Web::begin() { asyncServer.addHandler(new AsyncCallbackJsonWebHandler("/linkRemote", [](AsyncWebServerRequest *request, JsonVariant &json) { if(json.isNull()) { request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"No remote object supplied.\"}")); return; } - Serial.println("Linking a remote"); + ESP_LOGD(TAG, "Linking a remote"); JsonObject obj = json.as(); if(obj.containsKey("shadeId")) { SomfyShade* shade = somfy.getShadeById(obj["shadeId"]); @@ -1628,7 +1630,7 @@ void Web::begin() { asyncServer.addHandler(new AsyncCallbackJsonWebHandler("/linkToGroup", [](AsyncWebServerRequest *request, JsonVariant &json) { if(json.isNull()) { request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"No linking object supplied.\"}")); return; } - Serial.println("Linking a shade to a group"); + ESP_LOGD(TAG, "Linking a shade to a group"); JsonObject obj = json.as(); uint8_t shadeId = obj.containsKey("shadeId") ? obj["shadeId"] : 0; uint8_t groupId = obj.containsKey("groupId") ? obj["groupId"] : 0; @@ -1663,7 +1665,7 @@ void Web::begin() { asyncServer.addHandler(new AsyncCallbackJsonWebHandler("/unlinkFromGroup", [](AsyncWebServerRequest *request, JsonVariant &json) { if(json.isNull()) { request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"No unlinking object supplied.\"}")); return; } - Serial.println("Unlinking a shade from a group"); + ESP_LOGD(TAG, "Unlinking a shade from a group"); JsonObject obj = json.as(); uint8_t shadeId = obj.containsKey("shadeId") ? obj["shadeId"] : 0; uint8_t groupId = obj.containsKey("groupId") ? obj["groupId"] : 0; @@ -1699,7 +1701,7 @@ void Web::begin() { [](AsyncWebServerRequest *request, JsonVariant &json) { uint8_t roomId = 0; if(!json.isNull()) { - Serial.println("Deleting a Room"); + ESP_LOGD(TAG, "Deleting a Room"); JsonObject obj = json.as(); if(obj.containsKey("roomId")) roomId = obj["roomId"]; else { request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"No room id was supplied.\"}")); return; } @@ -1730,7 +1732,7 @@ void Web::begin() { [](AsyncWebServerRequest *request, JsonVariant &json) { uint8_t shadeId = 255; if(!json.isNull()) { - Serial.println("Deleting a shade"); + ESP_LOGD(TAG, "Deleting a shade"); JsonObject obj = json.as(); if(obj.containsKey("shadeId")) shadeId = obj["shadeId"]; else { request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"No shade id was supplied.\"}")); return; } @@ -1767,7 +1769,7 @@ void Web::begin() { [](AsyncWebServerRequest *request, JsonVariant &json) { uint8_t groupId = 255; if(!json.isNull()) { - Serial.println("Deleting a group"); + ESP_LOGD(TAG, "Deleting a group"); JsonObject obj = json.as(); if(obj.containsKey("groupId")) groupId = obj["groupId"]; else { request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"No group id was supplied.\"}")); return; } @@ -1806,9 +1808,9 @@ void Web::begin() { [](AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) { if(index == 0) { webServer.uploadSuccess = false; - Serial.printf("Update: %s\n", filename.c_str()); + ESP_LOGI(TAG, "Update: %s", filename.c_str()); if(!Update.begin(UPDATE_SIZE_UNKNOWN)) { - Update.printError(Serial); + ESP_LOGE(TAG, "Update begin failed"); } else { somfy.transceiver.end(); @@ -1817,18 +1819,17 @@ void Web::begin() { } if(len > 0) { if(Update.write(data, len) != len) { - Update.printError(Serial); - Serial.printf("Upload of %s aborted invalid size %d\n", filename.c_str(), len); + ESP_LOGE(TAG, "Upload of %s aborted invalid size %d", filename.c_str(), len); Update.abort(); } } if(final) { if(Update.end(true)) { - Serial.printf("Update Success: %u\nRebooting...\n", index + len); + ESP_LOGI(TAG, "Update Success: %u Rebooting...", index + len); webServer.uploadSuccess = true; } else { - Update.printError(Serial); + ESP_LOGE(TAG, "Update end failed"); } } esp_task_wdt_reset(); @@ -1845,7 +1846,7 @@ void Web::begin() { }, [](AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) { if(index == 0) { - Serial.printf("Update: shades.cfg\n"); + ESP_LOGI(TAG, "Update: shades.cfg"); File fup = LittleFS.open("/shades.tmp", "w"); fup.close(); } @@ -1872,9 +1873,9 @@ void Web::begin() { [](AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) { if(index == 0) { webServer.uploadSuccess = false; - Serial.printf("Update: %s\n", filename.c_str()); + ESP_LOGI(TAG, "Update: %s", filename.c_str()); if(!Update.begin(UPDATE_SIZE_UNKNOWN, U_SPIFFS)) { - Update.printError(Serial); + ESP_LOGE(TAG, "Update begin failed"); } else { somfy.transceiver.end(); @@ -1883,20 +1884,19 @@ void Web::begin() { } if(len > 0) { if(Update.write(data, len) != len) { - Update.printError(Serial); - Serial.printf("Upload of %s aborted invalid size %d\n", filename.c_str(), len); + ESP_LOGE(TAG, "Upload of %s aborted invalid size %d", filename.c_str(), len); Update.abort(); } } if(final) { if(Update.end(true)) { webServer.uploadSuccess = true; - Serial.printf("Update Success: %u\nRebooting...\n", index + len); + ESP_LOGI(TAG, "Update Success: %u Rebooting...", index + len); somfy.commit(); } else { somfy.commit(); - Update.printError(Serial); + ESP_LOGE(TAG, "Update end failed"); } } esp_task_wdt_reset(); @@ -1908,9 +1908,7 @@ void Web::begin() { if(net.softAPOpened) WiFi.disconnect(false); int n = WiFi.scanNetworks(false, true); esp_task_wdt_add(NULL); - Serial.print("Scanned "); - Serial.print(n); - Serial.println(" networks"); + ESP_LOGI(TAG, "Scanned %d networks", n); AsyncJsonResp resp; resp.beginResponse(request, g_async_content, sizeof(g_async_content)); resp.beginObject(); @@ -1949,7 +1947,7 @@ void Web::begin() { settings.Security.save(); char token[65]; webServer.createAPIToken(request->client()->remoteIP(), token); - DynamicJsonDocument sdoc(1024); + JsonDocument sdoc; JsonObject sobj = sdoc.to(); settings.Security.toJSON(sobj); sobj["apiKey"] = token; @@ -1959,7 +1957,7 @@ void Web::begin() { // getSecurity asyncServer.on("/getSecurity", HTTP_GET, [](AsyncWebServerRequest *request) { - DynamicJsonDocument doc(512); + JsonDocument doc; JsonObject obj = doc.to(); settings.Security.toJSON(obj); serializeJson(doc, g_async_content, sizeof(g_async_content)); @@ -2091,7 +2089,7 @@ void Web::begin() { settings.Ethernet.save(); } if(reboot) { - Serial.println("Rebooting ESP for new Network settings..."); + ESP_LOGI(TAG, "Rebooting ESP for new Network settings..."); rebootDelay.reboot = true; rebootDelay.rebootTime = millis() + 1000; } @@ -2105,7 +2103,7 @@ void Web::begin() { request->send(500, "application/json", "{\"status\":\"ERROR\",\"desc\":\"JSON parse error\"}"); return; } - Serial.println("Setting IP..."); + ESP_LOGD(TAG, "Setting IP..."); JsonObject obj = json.as(); settings.IP.fromJSON(obj); settings.IP.save(); @@ -2120,7 +2118,7 @@ void Web::begin() { return; } JsonObject obj = json.as(); - Serial.println("Settings WIFI connection..."); + ESP_LOGD(TAG, "Settings WIFI connection..."); String ssid = ""; String passphrase = ""; if(obj.containsKey("ssid")) ssid = obj["ssid"].as(); @@ -2138,7 +2136,7 @@ void Web::begin() { settings.WIFI.print(); request->send(201, _encoding_json, "{\"status\":\"OK\",\"desc\":\"Successfully set server connection\"}"); if(reboot) { - Serial.println("Rebooting ESP for new WiFi settings..."); + ESP_LOGI(TAG, "Rebooting ESP for new WiFi settings..."); rebootDelay.reboot = true; rebootDelay.rebootTime = millis() + 1000; } @@ -2164,7 +2162,7 @@ void Web::begin() { // networksettings asyncServer.on("/networksettings", HTTP_GET, [](AsyncWebServerRequest *request) { - DynamicJsonDocument doc(2048); + JsonDocument doc; JsonObject obj = doc.to(); settings.toJSON(obj); obj["fwVersion"] = settings.fwVersion.name; @@ -2186,11 +2184,11 @@ void Web::begin() { return; } JsonObject obj = json.as(); - Serial.print("Saving MQTT "); + ESP_LOGD(TAG, "Saving MQTT"); mqtt.disconnect(); settings.MQTT.fromJSON(obj); settings.MQTT.save(); - DynamicJsonDocument sdoc(1024); + JsonDocument sdoc; JsonObject sobj = sdoc.to(); settings.MQTT.toJSON(sobj); serializeJson(sdoc, g_async_content, sizeof(g_async_content)); @@ -2199,7 +2197,7 @@ void Web::begin() { // mqttsettings asyncServer.on("/mqttsettings", HTTP_GET, [](AsyncWebServerRequest *request) { - DynamicJsonDocument doc(1024); + JsonDocument doc; JsonObject obj = doc.to(); settings.MQTT.toJSON(obj); serializeJson(doc, g_async_content, sizeof(g_async_content)); From 84e713d1b2d802720daab4f86f54a82812c55444 Mon Sep 17 00:00:00 2001 From: cjkas Date: Tue, 24 Mar 2026 22:08:26 +0100 Subject: [PATCH 3/3] fix release build --- .github/workflows/release.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 96b5d08..f97bede 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -36,8 +36,8 @@ jobs: with: python-version: "3.12" - - name: Install PlatformIO - run: pip install platformio + - name: Install PlatformIO and esptool + run: pip install platformio esptool - name: Build firmware run: pio run -e ${{ matrix.env }}