From 7c61ff2810df19e46429e8b945ad21518f964913 Mon Sep 17 00:00:00 2001 From: Yuri Trikoz Date: Thu, 25 Jun 2020 09:21:42 +0300 Subject: [PATCH] getData --- include/Clock.h | 98 +++++++++++++++++++++- include/Consts.h | 1 + include/Global.h | 9 +- include/Utils/JsonUtils.h | 2 + include/Utils/PrintMessage.h | 4 +- include/Utils/SysUtils.h | 4 +- include/Utils/TimeUtils.h | 6 -- platformio.ini | 4 +- src/Clock.cpp | 54 ------------ src/Cmd.cpp | 54 +++++++----- src/Global.cpp | 2 + src/Utils/JsonUtils.cpp | 6 ++ src/Utils/SysUtils.cpp | 13 ++- src/Utils/TimeUtils.cpp | 157 +++-------------------------------- src/Web.cpp | 10 ++- src/main.cpp | 10 ++- src/udp.cpp | 2 +- 17 files changed, 182 insertions(+), 254 deletions(-) delete mode 100644 src/Clock.cpp diff --git a/include/Clock.h b/include/Clock.h index 6c6efd84..94377691 100644 --- a/include/Clock.h +++ b/include/Clock.h @@ -1,7 +1,99 @@ #pragma once -#include "Global.h" +#include "Utils/TimeUtils.h" +#include "Utils/PrintMessage.h" -void startTimeSync(); +#include "time.h" -void reconfigTime(); \ No newline at end of file +class Clock { + const char* MODULE = "Clock"; + + public: + Clock() : _timezone{0}, _ntp{}, _hasSynced{false}, _configured{false} { + } + + bool hasSync() { + if (!_hasSynced) { + startSync(); + } + return _hasSynced; + } + + void + + setNtpPool(String ntp) { + _ntp = ntp; + } + + void setTimezone(int timezone) { + _timezone = timezone; + } + + time_t getSystemTime() { + timeval tv{0, 0}; + timezone tz = getTimeZone(getBiasInMinutes()); + time_t epoch = 0; + if (gettimeofday(&tv, &tz) != -1) + epoch = tv.tv_sec; + return epoch; + } + + void startSync() { + if (!_configured) { + pm.info("sync to: " + _ntp + " time zone: " + String(_timezone)); + setupSntp(); + _configured = true; + } + _hasSynced = hasTimeSynced(); + if (_hasSynced) { + pm.info("synced " + getDateDigitalFormated() + " " + getTime()); + } else { + pm.error("failed to obtain"); + } + } + + void setupSntp() { + int tzs = getBiasInSeconds(); + int tzh = tzs / 3600; + tzs -= tzh * 3600; + int tzm = tzs / 60; + tzs -= tzm * 60; + + char tzstr[64]; + snprintf(tzstr, sizeof tzstr, "ESPUSER<%+d:%02d:%02d>", tzh, tzm, tzs); + pm.info(String(tzstr)); + configTime(tzstr, _ntp.c_str()); + } + // #ifdef ESP32 + // uint8_t i = 0; + // struct tm timeinfo; + // while (!getLocalTime(&timeinfo) && i <= 4) { + // Serial.print("."); + // i++; + // delay(1000); + // } + // #endif + private: + bool hasTimeSynced() { + unsigned long now = time(nullptr); + return now > millis(); + } + + int getBiasInSeconds() { + return getBiasInMinutes() * 60; + } + + int getBiasInMinutes() { + return _timezone * 60; + } + + const timezone getTimeZone(int minutes) { + return timezone{minutes, 0}; + } + + private: + int _timezone; + String _ntp; + bool _hasSynced; + bool _configured; +}; \ No newline at end of file diff --git a/include/Consts.h b/include/Consts.h index 9fd36ace..7240c27c 100644 --- a/include/Consts.h +++ b/include/Consts.h @@ -9,6 +9,7 @@ #define MQTT_RECONNECT_INTERVAL 20000 // 1000 * 60 * 60 * 2 #define TELEMETRY_UPDATE_INTERVAL 0 + #define DEVICE_CONFIG_FILE "dev_conf.txt" #define DEVICE_SCENARIO_FILE "dev_scen.txt" #define DEFAULT_PRESET 100 diff --git a/include/Global.h b/include/Global.h index ace7f6ab..f236d5af 100644 --- a/include/Global.h +++ b/include/Global.h @@ -21,7 +21,6 @@ #include "Utils\JsonUtils.h" #include "Utils\StringUtils.h" #include "Utils\SysUtils.h" -#include "Utils\TimeUtils.h" #include "Utils\PrintMessage.h" #include "Utils\WiFiUtils.h" @@ -45,6 +44,8 @@ extern AsyncWebSocket ws; //extern AsyncEventSource events; #endif +extern Clock* rtc; + extern TickerScheduler ts; extern WiFiClient espClient; @@ -165,7 +166,6 @@ extern void choose_log_date_and_send(); // Main extern void setChipId(); -extern void printMemoryStatus(String text); extern void saveConfig(); extern String getURL(const String& urls); @@ -229,9 +229,10 @@ extern int readTimer(int number); extern void init_updater(); // widget -extern void createWidget(String widget_name, String page_name, String page_number, String file, String topic); + +extern void createWidgetByType(String widget_name, String page_name, String page_number, String file, String topic); extern void createWidgetParam(String widget_name, String page_name, String page_number, String file, String topic, String name1, String param1, String name2, String param2, String name3, String param3); -extern void createWidgetByType(String widget_name, String page_name, String page_number, String type, String topik); +extern void createWidget(String widget_name, String page_name, String page_number, String type, String topik); extern void createChart(String widget_name, String page_name, String page_number, String file, String topic, String maxCount); // PushingBox diff --git a/include/Utils/JsonUtils.h b/include/Utils/JsonUtils.h index 253bdc9b..762fc286 100644 --- a/include/Utils/JsonUtils.h +++ b/include/Utils/JsonUtils.h @@ -11,3 +11,5 @@ String jsonWriteStr(String& json, String name, String volume); String jsonWriteInt(String& json, String name, int volume); String jsonWriteFloat(String& json, String name, float volume); + +boolean jsonReadBool(String& json, String name); \ No newline at end of file diff --git a/include/Utils/PrintMessage.h b/include/Utils/PrintMessage.h index 1434907a..ec3ab5bb 100644 --- a/include/Utils/PrintMessage.h +++ b/include/Utils/PrintMessage.h @@ -14,11 +14,11 @@ class PrintMessage { _module = module; } - void error(const String str) { + void error(const String& str) { print(EL_ERROR, str); } - void info(const String str) { + void info(const String& str) { print(EL_INFO, str); } diff --git a/include/Utils/SysUtils.h b/include/Utils/SysUtils.h index a6bdbe27..12ceb5fe 100644 --- a/include/Utils/SysUtils.h +++ b/include/Utils/SysUtils.h @@ -4,6 +4,6 @@ const String getChipId(); -void printMemoryStatus(String text = ""); +const String printMemoryStatus(); -String getHeapStats(); +const String getHeapStats(); diff --git a/include/Utils/TimeUtils.h b/include/Utils/TimeUtils.h index 82337b34..658634d9 100644 --- a/include/Utils/TimeUtils.h +++ b/include/Utils/TimeUtils.h @@ -35,12 +35,6 @@ int timeToMin(String Time); const String prettyMillis(unsigned long time_ms = millis()); -int timeZoneInSeconds(const byte timeZone); - -bool hasTimeSynced(); - -int getBiasInSeconds(); - /* * Время (мс) прошедщее с @simce */ diff --git a/platformio.ini b/platformio.ini index 7815fdfc..ee5d86e3 100644 --- a/platformio.ini +++ b/platformio.ini @@ -36,7 +36,8 @@ lib_deps = [env:esp8266] platform = https://github.com/platformio/platform-espressif8266.git -build_flags = ${env.build_flags} -D=${PIOENV} +build_flags = ${env.build_flags} -D=${PIOENV} +##-DCORE_DEBUG_LEVEL=5 board = nodemcuv2 monitor_filters = esp8266_exception_decoder monitor_speed = 115200 @@ -51,3 +52,4 @@ lib_deps = DHT sensor library for ESPx Adafruit BMP280 Library Adafruit BME280 Library + diff --git a/src/Clock.cpp b/src/Clock.cpp deleted file mode 100644 index b2954b22..00000000 --- a/src/Clock.cpp +++ /dev/null @@ -1,54 +0,0 @@ -#include "Clock.h" - -#include "Utils/TimeUtils.h" - -static const char* MODULE = "Clock"; - -void startTimeSync() { - if (!hasTimeSynced()) { - pm.info("Start sync"); - reconfigTime(); - } -} - -void setupSntp() { - int tzs = getBiasInSeconds(); - int tzh = tzs / 3600; - tzs -= tzh * 3600; - int tzm = tzs / 60; - tzs -= tzm * 60; - - String ntp = jsonReadStr(configSetupJson, "ntp"); - pm.info("Setup ntp: " + ntp); - char tzstr[64]; - snprintf(tzstr, sizeof tzstr, "ESPUSER<%+d:%02d:%02d>", tzh, tzm, tzs); - return configTime(tzstr, ntp.c_str(), "pool.ntp.org", "time.nist.gov"); -} - -void reconfigTime() { -#ifdef ESP32 - uint8_t i = 0; - struct tm timeinfo; - while (!getLocalTime(&timeinfo) && i <= 4) { - Serial.print("."); - i++; - delay(1000); - } -#endif - -#ifdef ESP8266 - setupSntp(); - uint8_t i = 0; - while (!hasTimeSynced() && i < 4) { - Serial.print("."); - i++; - delay(30); - } -#endif - - if (getTimeUnix() != "failed") { - pm.info("Time synced " + getDateDigitalFormated() + " " + getTime()); - } else { - pm.error("Failed to obtain"); - } -} diff --git a/src/Cmd.cpp b/src/Cmd.cpp index c49a60d2..389a4529 100644 --- a/src/Cmd.cpp +++ b/src/Cmd.cpp @@ -13,6 +13,8 @@ Servo myServo1; Servo myServo2; SoftwareSerial *mySerial = nullptr; +void getData(); + void CMD_init() { sCmd.addCommand("button", button); sCmd.addCommand("buttonSet", buttonSet); @@ -97,36 +99,38 @@ void CMD_init() { sCmd.addCommand("firmwareUpdate", firmwareUpdate); sCmd.addCommand("firmwareVersion", firmwareVersion); + sCmd.addCommand("getData", getData); + handle_time_init(); } //========================================================================================================== //==========================================Модуль кнопок=================================================== void button() { - pm.info("create button"); - String button_number = sCmd.next(); - String button_param = sCmd.next(); + pm.info("create 'button'"); + String number = sCmd.next(); + String param = sCmd.next(); String widget = sCmd.next(); String page = sCmd.next(); - String start_state = sCmd.next(); + String state = sCmd.next(); String pageNumber = sCmd.next(); - jsonWriteStr(configOptionJson, "button_param" + button_number, button_param); - jsonWriteStr(configLiveJson, "button" + button_number, start_state); + jsonWriteStr(configOptionJson, "button_param" + number, param); + jsonWriteStr(configLiveJson, "button" + number, state); - if (isDigitStr(button_param)) { - pinMode(button_param.toInt(), OUTPUT); - digitalWrite(button_param.toInt(), start_state.toInt()); + if (isDigitStr(param)) { + pinMode(param.toInt(), OUTPUT); + digitalWrite(param.toInt(), state.toInt()); } - if (button_param == "scen") { - jsonWriteStr(configSetupJson, "scen", start_state); + if (param == "scen") { + jsonWriteStr(configSetupJson, "scen", state); loadScenario(); saveConfig(); } - if (button_param.indexOf("line") != -1) { - String str = button_param; + if (param.indexOf("line") != -1) { + String str = param; while (str.length()) { if (str == "") return; String tmp = selectToMarker(str, ","); //line1, @@ -134,11 +138,11 @@ void button() { number.replace(",", ""); Serial.println(number); int number_int = number.toInt(); - scenario_line_status[number_int] = start_state.toInt(); + scenario_line_status[number_int] = state.toInt(); str = deleteBeforeDelimiter(str, ","); } } - createWidget(widget, page, pageNumber, "toggle", "button" + button_number); + createWidget(widget, page, pageNumber, "toggle", "button" + number); } void buttonSet() { @@ -547,6 +551,14 @@ void serialBegin() { }); } +void getData() { + String param = sCmd.next(); + String res = param.length() ? jsonReadStr(configLiveJson, param) : configLiveJson; + if (term) { + term->println(res.c_str()); + } +} + void serialWrite() { String payload = sCmd.next(); if (term) { @@ -578,11 +590,13 @@ void firmwareUpdate() { } void firmwareVersion() { - String widget_name = sCmd.next(); - String page_name = sCmd.next(); - String page_number = sCmd.next(); + String widget = sCmd.next(); + String page = sCmd.next(); + String pageNumber = sCmd.next(); + jsonWriteStr(configLiveJson, "firmver", FIRMWARE_VERSION); - createWidgetByType(widget_name, page_name, page_number, "anydata", "firmver"); + + createWidget(widget, page, pageNumber, "anydata", "firmver"); } void addCommandLoop(const String &cmdStr) { @@ -596,7 +610,7 @@ void loopCmd() { if (order_loop.length()) { String tmp = selectToMarker(order_loop, ","); //выделяем первую команду rel 5 1, sCmd.readStr(tmp); //выполняем - Serial.println("[ORDER] => " + order_loop); + pm.info("do: " + order_loop); order_loop = deleteBeforeDelimiter(order_loop, ","); //осекаем } } diff --git a/src/Global.cpp b/src/Global.cpp index f1949f79..aec0b751 100644 --- a/src/Global.cpp +++ b/src/Global.cpp @@ -5,6 +5,8 @@ AsyncWebSocket ws; //AsyncEventSource events; #endif +Clock* rtc; + TickerScheduler ts(TEST + 1); WiFiClient espClient; diff --git a/src/Utils/JsonUtils.cpp b/src/Utils/JsonUtils.cpp index 3adeb6fd..d814c409 100644 --- a/src/Utils/JsonUtils.cpp +++ b/src/Utils/JsonUtils.cpp @@ -8,6 +8,12 @@ String jsonReadStr(String& json, String name) { return root[name].as(); } +boolean jsonReadBool(String& json, String name) { + DynamicJsonBuffer jsonBuffer; + JsonObject& root = jsonBuffer.parseObject(json); + return root[name].as(); +} + int jsonReadInt(String& json, String name) { DynamicJsonBuffer jsonBuffer; JsonObject& root = jsonBuffer.parseObject(json); diff --git a/src/Utils/SysUtils.cpp b/src/Utils/SysUtils.cpp index 51b32dc4..e67b9b02 100644 --- a/src/Utils/SysUtils.cpp +++ b/src/Utils/SysUtils.cpp @@ -23,25 +23,24 @@ static uint32_t total_memory = 52864; static uint32_t total_memory = 362868; #endif -void printMemoryStatus(String text) { +const String printMemoryStatus() { uint32_t free = ESP.getFreeHeap(); uint32_t used = total_memory - free; uint32_t memory_load = (used * 100) / total_memory; - if (text) { - Serial.print(text); - } - Serial.printf(" used: %d%% free: %s\n", memory_load, prettyBytes(free).c_str()); + char buf[64]; + sprintf(buf, "used: %d%% free: %s", memory_load, getHeapStats().c_str()); + return String(buf); } #ifdef ESP8266 -String getHeapStats() { +const String getHeapStats() { uint32_t free; uint16_t max; uint8_t frag; ESP.getHeapStats(&free, &max, &frag); String buf; buf += prettyBytes(free); - buf += " "; + buf += " frag: "; buf += frag; buf += '%'; return buf; diff --git a/src/Utils/TimeUtils.cpp b/src/Utils/TimeUtils.cpp index 1eb12867..59aa09cc 100644 --- a/src/Utils/TimeUtils.cpp +++ b/src/Utils/TimeUtils.cpp @@ -6,33 +6,17 @@ #define ONE_MINUTE_s 60 #define ONE_HOUR_s 60 * ONE_MINUTE_s -int getBiasInSeconds() { - return 3600 * jsonReadStr(configSetupJson, "timezone").toInt(); -} - -int getBiasInMinutes() { - return getBiasInSeconds() / 60; -} - -const timezone getTimeZone() { - return timezone{getBiasInMinutes(), 0}; -} - -time_t getSystemTime() { - timeval tv{0, 0}; - timezone tz = getTimeZone(); - time_t epoch = 0; - if (gettimeofday(&tv, &tz) != -1) - epoch = tv.tv_sec; - return epoch; -} - -bool hasTimeSynced() { - unsigned long now = time(nullptr); - return now > millis(); -} - +time_t t; +struct tm* tm; +static const char* wd[7] = {"Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat"}; String getTimeUnix() { + t = time(NULL); + tm = localtime(&t); + Serial.printf("%04d/%02d/%02d(%s) %02d:%02d:%02d\n", + tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, + wd[tm->tm_wday], + tm->tm_hour, tm->tm_min, tm->tm_sec); + delay(1000); time_t now = time(nullptr); if (now < 30000) { return "failed"; @@ -149,127 +133,6 @@ const String prettyMillis(unsigned long time_ms) { return String(buf); } -int timeZoneInSeconds(const byte timeZone) { - int res = 0; - switch (constrain(timeZone, 1, 38)) { - case 1: - res = -12 * ONE_HOUR_s; - break; - case 2: - res = -11 * ONE_HOUR_s; - break; - case 3: - res = -10 * ONE_HOUR_s; - break; - case 4: - res = -9 * ONE_HOUR_s - 30 * ONE_MINUTE_s; - break; - case 5: - res = -9 * ONE_HOUR_s; - break; - case 6: - res = -8 * ONE_HOUR_s; - break; - case 7: - res = -7 * ONE_HOUR_s; - break; - case 8: - res = -6 * ONE_HOUR_s; - break; - case 9: - res = -5 * ONE_HOUR_s; - break; - case 10: - res = -4 * ONE_HOUR_s; - break; - case 11: - res = -3 * ONE_HOUR_s - 30 * ONE_MINUTE_s; - break; - case 12: - res = -3 * ONE_HOUR_s; - break; - case 13: - res = -2 * ONE_HOUR_s; - break; - case 14: - res = -1 * ONE_HOUR_s; - break; - case 15: - res = 0; - break; - case 16: - res = 1 * ONE_HOUR_s; - break; - case 17: - res = 2 * ONE_HOUR_s; - break; - case 18: - res = 3 * ONE_HOUR_s; - break; - case 19: - res = 3 * ONE_HOUR_s + 30 * ONE_MINUTE_s; - break; - case 20: - res = 4 * ONE_HOUR_s; - break; - case 21: - res = 4 * ONE_HOUR_s + 30 * ONE_MINUTE_s; - break; - case 22: - res = 5 * ONE_HOUR_s; - break; - case 23: - res = 5 * ONE_HOUR_s + 30 * ONE_MINUTE_s; - break; - case 24: - res = 5 * ONE_HOUR_s + 45 * ONE_MINUTE_s; - break; - case 25: - res = 6 * ONE_HOUR_s; - break; - case 26: - res = 6 * ONE_HOUR_s + 30 * ONE_MINUTE_s; - break; - case 27: - res = 7 * ONE_HOUR_s; - break; - case 28: - res = 8 * ONE_HOUR_s; - break; - case 29: - res = 8 * ONE_HOUR_s + 45 * ONE_MINUTE_s; - break; - case 30: - res = 9 * ONE_HOUR_s; - break; - case 31: - res = 9 * ONE_HOUR_s + 30 * ONE_MINUTE_s; - break; - case 32: - res = 10 * ONE_HOUR_s; - break; - case 33: - res = 10 * ONE_HOUR_s + 30 * ONE_MINUTE_s; - break; - case 34: - res = 11 * ONE_HOUR_s; - break; - case 35: - res = 12 * ONE_HOUR_s; - break; - case 36: - res = 12 * ONE_HOUR_s + 45 * ONE_MINUTE_s; - break; - case 37: - res = 13 * ONE_HOUR_s; - break; - case 38: - res = 14 * ONE_HOUR_s; - break; - } - return res; -} - unsigned long millis_since(unsigned long sinse) { return millis_passed(sinse, millis()); } diff --git a/src/Web.cpp b/src/Web.cpp index 402e64ce..2cd0b397 100644 --- a/src/Web.cpp +++ b/src/Web.cpp @@ -130,15 +130,17 @@ void web_init() { } //-------------------------------------------------------------------------------- if (request->hasArg("timezone")) { - jsonWriteStr(configSetupJson, "timezone", request->getParam("timezone")->value()); + String timezoneStr = request->getParam("timezone")->value(); + jsonWriteStr(configSetupJson, "timezone", timezoneStr); saveConfig(); - reconfigTime(); + rtc->setTimezone(timezoneStr.toInt()); request->send(200, "text/text", "OK"); } if (request->hasArg("ntp")) { - jsonWriteStr(configSetupJson, "ntp", request->getParam("ntp")->value()); + String ntpStr = request->getParam("ntp")->value(); + jsonWriteStr(configSetupJson, "ntp", ntpStr); saveConfig(); - reconfigTime(); + rtc->setNtpPool(ntpStr); request->send(200, "text/text", "OK"); } //-------------------------------------------------------------------------------- diff --git a/src/main.cpp b/src/main.cpp index 616e6848..9edeb862 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -56,10 +56,14 @@ void setup() { pm.info("WebAdmin"); web_init(); - pm.info("TimeSync"); + pm.info("Clock"); + rtc = new Clock(); + rtc->setNtpPool(jsonReadStr(configSetupJson, "ntp")); + rtc->setTimezone(jsonReadStr(configSetupJson, "timezone").toInt()); + ts.add( TIME_SYNC, 30000, [&](void*) { - startTimeSync(); + rtc->hasSync(); }, nullptr, true); @@ -69,7 +73,7 @@ void setup() { #endif ts.add( TEST, 10000, [&](void*) { - printMemoryStatus(); + pm.info(printMemoryStatus()); }, nullptr, true); diff --git a/src/udp.cpp b/src/udp.cpp index f2a9be5a..988a99d3 100644 --- a/src/udp.cpp +++ b/src/udp.cpp @@ -20,7 +20,7 @@ void add_dev_in_list(String fileName, String id, String dev_name, String ip); #ifdef UDP_ENABLED void UDP_init() { - removeFile("/dev.csv"); + removeFile("dev.csv"); addFile("dev.csv", "device id;device name;ip address"); #ifdef ESP8266