diff --git a/data/conf/c014.txt b/data/conf/c014.txt index 92c9346c..c850b3e2 100644 --- a/data/conf/c014.txt +++ b/data/conf/c014.txt @@ -1,5 +1,7 @@ -dallas temp1 2 123456 Водонагреватель,#t°C Датчики anydata 1 -logging dallas 1 100 Температура Датчики 2 +dallas temp1 2 1 Температура Датчики anydata 1 +dallas temp2 2 2 Температура Датчики anydata 2 +logging temp1 1 100 Температура Датчики 3 +logging temp2 1 100 Температура Датчики 4 //2 - номер пина датчика //варианты отображения: anydata, progress-round, progress-line, fillgauge \ No newline at end of file diff --git a/data/config.json b/data/config.json index 3cae98c6..34c25c56 100644 --- a/data/config.json +++ b/data/config.json @@ -17,5 +17,6 @@ "weblogin": "admin", "webpass": "admin", "udponoff": "1", - "blink": "1" + "blink": "1", + "oneWirePin": "2" } \ No newline at end of file diff --git a/data/set.utilities.json b/data/set.utilities.json index 9f17cbe9..9314cd8b 100644 --- a/data/set.utilities.json +++ b/data/set.utilities.json @@ -23,7 +23,7 @@ }, { "type": "h3", - "title": "Сканирование адресов шины i2c" + "title": "Сканирование шины i2c" }, { "type": "h4", @@ -32,21 +32,7 @@ { "type": "link", "title": "Сканировать", - "action": "/set?itoc", - "class": "btn btn-block btn-default" - }, - { - "type": "h3", - "title": "Проверка ФС" - }, - { - "type": "h4", - "title": "{{fscheck}}" - }, - { - "type": "link", - "title": "Запустить", - "action": "/set?fscheck", + "action": "/set?i2c", "class": "btn btn-block btn-default" } ] diff --git a/data/sync.ffs_db b/data/sync.ffs_db deleted file mode 100644 index 9d3f2036..00000000 Binary files a/data/sync.ffs_db and /dev/null differ diff --git a/doc/pictures/pic1.png b/doc/pictures/pic1.png new file mode 100644 index 00000000..4cbed577 Binary files /dev/null and b/doc/pictures/pic1.png differ diff --git a/include/Bus/BusScanner.h b/include/Bus/BusScanner.h index e0618fdb..659aa501 100644 --- a/include/Bus/BusScanner.h +++ b/include/Bus/BusScanner.h @@ -2,72 +2,55 @@ #include -enum BusScanner_t { - BS_I2C, - BS_ONE_WIRE -}; - class BusScanner { public: - BusScanner(String& result, size_t tries) : _tries{tries}, _result{&result} {} - - void addResult(uint8_t addr, boolean last = true) { - _result->concat("0x"); - if (addr < 16) { - _result->concat("0"); - } - _result->concat(String(addr, HEX)); - _result->concat(!last ? ", " : ""); - }; + BusScanner(const char* tag, String& out, size_t tries) : _found{0}, + _tries{tries}, + _out{&out} { + _tag = new char(strlen(tag) + 1); + strcpy(_tag, tag); + } void scan() { - if (!syncScan() && _tries--) { - syncScan(); + init(); + bool res; + do { + res = syncScan(); + } while (!res && --_tries); + + if (!_found) { + addResult("не найдено"); } } - virtual boolean syncScan(); + + const char* tag() { + return _tag; + } + + protected: + virtual void init(){}; + + virtual boolean syncScan() = 0; + + protected: + void addResult(const String& str) { + _out->concat(str); + } + + void addResult(uint8_t addr, boolean last = true) { + _found++; + String str = "0x"; + if (addr < 16) { + str += "0"; + } + str += String(addr, HEX); + str += !last ? ", " : ", "; + addResult(str); + }; private: + char* _tag; + size_t _found; size_t _tries; - BusScanner_t _type; - String* _result; -}; - -class I2CScanner : public BusScanner { - public: - I2CScanner(String& result) : BusScanner(result, 2){}; - - virtual boolean syncScan() override; -}; - -class OneWireScanner : public BusScanner { - public: - OneWireScanner(String& result) : BusScanner(result, 1){}; - - virtual boolean syncScan() override; -}; - -class BusScannerFactory { - public: - static const char* label(BusScanner_t type) { - switch (type) { - case BS_I2C: - return "i2c"; - case BS_ONE_WIRE: - return "onewire"; - default: - return ""; - } - } - - static BusScanner* get(String& str, BusScanner_t type, size_t tries = 1) { - switch (type) { - case BS_I2C: - return new I2CScanner(str); - case BS_ONE_WIRE: - return new OneWireScanner(str); - default: - return nullptr; - } - } + String* _out; }; diff --git a/include/Bus/BusScannerFactory.h b/include/Bus/BusScannerFactory.h new file mode 100644 index 00000000..867cf860 --- /dev/null +++ b/include/Bus/BusScannerFactory.h @@ -0,0 +1,18 @@ +#pragma once + +#include "Bus/BusScanner.h" +#include "Bus/I2CScanner.h" +#include "Consts.h" +#include "Utils/JsonUtils.h" + +class BusScannerFactory { + public: + static BusScanner* get(String& config, BusScanner_t type, String& str) { + switch (type) { + case BS_I2C: + return new I2CScanner(str); + default: + return nullptr; + } + } +}; diff --git a/include/Bus/I2CScanner.h b/include/Bus/I2CScanner.h new file mode 100644 index 00000000..9678d089 --- /dev/null +++ b/include/Bus/I2CScanner.h @@ -0,0 +1,12 @@ +#pragma once + +#include "Bus/BusScanner.h" + +class I2CScanner : public BusScanner { + public: + I2CScanner(String& out); + + protected: + virtual void init() override; + virtual boolean syncScan() override; +}; \ No newline at end of file diff --git a/include/CaptiveRequestHandler.h b/include/CaptiveRequestHandler.h deleted file mode 100644 index 97c74370..00000000 --- a/include/CaptiveRequestHandler.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once - -#include - -class CaptiveRequestHandler : public AsyncWebHandler { - public: - CaptiveRequestHandler(const char *host); - - virtual ~CaptiveRequestHandler(); - - bool canHandle(AsyncWebServerRequest *request) override; - - void handleRequest(AsyncWebServerRequest *request) override; - - private: - bool isLocalIp(String name); - bool isLocalName(String name); - - private: - char _local_name[32]; - IPAddress _local_ip; -}; diff --git a/include/Clock.h b/include/Clock.h index d09d388d..743a61cc 100644 --- a/include/Clock.h +++ b/include/Clock.h @@ -3,8 +3,9 @@ #include "Utils/TimeUtils.h" #include "Utils/PrintMessage.h" -#include "TZ.h" +#ifdef ESP8266 #include "sntp.h" +#endif class Clock { const char* MODULE = "Clock"; @@ -76,19 +77,23 @@ class Clock { } _hasSynced = hasTimeSynced(); if (_hasSynced) { - pm.info("synced " + getDateDigitalFormated() + " " + getTime()); + pm.info("synced " + getDateDotFormated() + " " + getTime()); } else { pm.error("failed to obtain"); } } void setupSntp() { +#ifdef ESP2866 sntp_setservername(0, _ntp.c_str()); sntp_setservername(1, "ru.pool.ntp.org"); sntp_setservername(2, "pool.ntp.org"); sntp_stop(); sntp_set_timezone(0); // UTC time sntp_init(); +#else + configTime(0, 0, _ntp.c_str(), "ru.pool.ntp.org", "pool.ntp.org"); +#endif } bool hasTimeSynced() const { @@ -112,12 +117,21 @@ class Clock { /* * Локальное время "дд.ММ.гг" */ - const String getDateDigitalFormated() { + const String getDateDotFormated() { char buf[32]; sprintf(buf, "%02d.%02d.%02d", _time_local.day_of_month, _time_local.month, _time_local.year); return String(buf); } + /* + * Локальное дата время "дд.ММ.гг чч.мм.cc" + */ + const String getDateTimeDotFormated() { + char buf[32]; + sprintf(buf, "%02d.%02d.%02d %02d:%02d:%02d", _time_local.day_of_month, _time_local.month, _time_local.year, _time_local.hour, _time_local.minute, _time_local.second); + return String(buf); + } + /* * Локальное время "чч:мм:cc" */ diff --git a/include/CommonTypes.h b/include/CommonTypes.h deleted file mode 100644 index a5783b30..00000000 --- a/include/CommonTypes.h +++ /dev/null @@ -1,77 +0,0 @@ -#pragma once - -struct Time_t { - uint8_t second; - uint8_t minute; - uint8_t hour; - uint8_t day_of_week; // sunday is day 1 - uint8_t day_of_month; - uint8_t month; - uint16_t day_of_year; - uint16_t year; - unsigned long days; - unsigned long valid; -}; - -enum TimerTask_t { WIFI_SCAN, - WIFI_MQTT_CONNECTION_CHECK, - SENSORS, - STEPPER1, - STEPPER2, - LOG1, - LOG2, - LOG3, - LOG4, - LOG5, - TIMER_COUNTDOWN, - TIME, - TIME_SYNC, - STATISTICS, - UPTIME, - UDP, - UDP_DB, - TEST }; - -enum ErrorType_t { - ET_NONE, - ET_FUNCTION, - ET_MODULE, - ET_SYSTEM -}; - -enum ErrorLevel_t { - EL_NONE, - EL_INFO, - EL_WARNING, - EL_ERROR -}; - -enum LedStatus_t { - LED_OFF, - LED_ON, - LED_SLOW, - LED_FAST -}; - -enum ConfigType_t { - CT_CONFIG, - CT_SCENARIO -}; - -enum Item_t { - RELAY, - PWM, - DHT11, - DHT22, - ANALOG, - BMP280, - BME280, - DALLAS, - TERMOSTAT, - ULTRASONIC, - MOTION, - STEPPER, - SERVO, - FIRMWARE, - NUM_ITEMS -}; \ No newline at end of file diff --git a/include/Consts.h b/include/Consts.h index bd8f5d06..f5b2cb38 100644 --- a/include/Consts.h +++ b/include/Consts.h @@ -15,6 +15,10 @@ #define DEFAULT_PRESET 100 #define DEFAULT_SCENARIO 100 +#define TAG_ONE_WIRE "oneWire" +#define TAG_I2C "i2c" +#define TAG_ONE_WIRE_PIN "oneWirePin" + /* * Optional */ @@ -47,3 +51,66 @@ #define LOGGING_ENABLED #define SERIAL_ENABLED #define PUSH_ENABLED + +struct Time_t { + uint8_t second; + uint8_t minute; + uint8_t hour; + uint8_t day_of_week; + uint8_t day_of_month; + uint8_t month; + uint16_t day_of_year; + uint16_t year; + unsigned long days; + unsigned long valid; +}; + +enum TimerTask_t { WIFI_SCAN, + WIFI_MQTT_CONNECTION_CHECK, + SENSORS, + STEPPER1, + STEPPER2, + LOG1, + LOG2, + LOG3, + LOG4, + LOG5, + TIMER_COUNTDOWN, + TIME, + TIME_SYNC, + STATISTICS, + UPTIME, + UDP, + UDP_DB, + TEST }; + +enum ErrorType_t { + ET_NONE, + ET_FUNCTION, + ET_MODULE, + ET_SYSTEM +}; + +enum ErrorLevel_t { + EL_NONE, + EL_INFO, + EL_WARNING, + EL_ERROR +}; + +enum LedStatus_t { + LED_OFF, + LED_ON, + LED_SLOW, + LED_FAST +}; + +enum ConfigType_t { + CT_CONFIG, + CT_SCENARIO +}; + +enum BusScanner_t { + BS_I2C, + BS_ONE_WIRE +}; diff --git a/include/ESP8266.h b/include/ESP8266.h index 770692e6..6296fc81 100644 --- a/include/ESP8266.h +++ b/include/ESP8266.h @@ -1,19 +1,19 @@ #pragma once #ifdef ESP8266 - -#include -#include +#include #include -#include +#include "ESPAsyncTCP.h" +#include "ESPAsyncWebServer.h" #include #include #include #include +#include #ifdef MDNS_ENABLED #include #endif -extern WiFiUDP Udp; +extern WiFiUDP udp; #endif \ No newline at end of file diff --git a/include/Errors.h b/include/Errors.h index 047f0af2..cefac965 100644 --- a/include/Errors.h +++ b/include/Errors.h @@ -2,8 +2,6 @@ #include -#include "CommonTypes.h" - String getErrorLevelStr(ErrorLevel_t level); class Error : public Printable { diff --git a/include/Global.h b/include/Global.h index dceb7399..3ba69986 100644 --- a/include/Global.h +++ b/include/Global.h @@ -10,8 +10,6 @@ #include "ESP8266.h" // #include "Consts.h" -#include "CommonTypes.h" -#include "Bus/BusScanner.h" #include "Errors.h" #include "GyverFilters.h" #include "Upgrade.h" @@ -26,7 +24,7 @@ #include "Utils\WiFiUtils.h" //=========ПОДКЛЮЧЕНИЕ ОБЩИХ БИБЛИОТЕК=============== -#include + #include #include #include @@ -59,6 +57,8 @@ extern AsyncWebServer server; extern DallasTemperature sensors; +extern OneWire *oneWire; + extern boolean but[NUM_BUTTONS]; extern Bounce* buttons; @@ -82,6 +82,9 @@ extern String order_loop; extern String analog_value_names_list; extern int enter_to_analog_counter; +extern String dallas_value_name; +extern int enter_to_dallas_counter; + extern String levelPr_value_name; extern String ultrasonicCm_value_name; @@ -103,8 +106,8 @@ extern int scenario_line_status[40]; extern String lastVersion; -extern boolean upgrade_url; -extern boolean upgrade; +extern boolean checkUpdatesFlag; +extern boolean updateFlag; extern boolean mqttParamsChanged; extern boolean udp_data_parse; extern boolean mqtt_send_settings_to_udp; @@ -176,8 +179,10 @@ extern void choose_log_date_and_send(); // Main extern void setChipId(); extern void saveConfig(); +extern void setConfigParam(const char* param, const String& value); + extern String getURL(const String& urls); -extern void do_check_fs(); +extern void do_fscheck(); extern void do_scan_bus(); extern void servo_(); extern void clock_init(); @@ -248,7 +253,7 @@ extern void createChart(String widget_name, String page_name, String page_number extern void pushControl(); // UDP -extern void UDP_init(); +extern void udp_init(); extern void do_udp_data_parse(); extern void do_mqtt_send_settings_to_udp(); @@ -259,7 +264,7 @@ extern void loopButton(); extern void loopScenario(); extern void loopUdp(); -extern void flashUpgrade(); +extern void do_update(); // Init extern void uptime_init(); diff --git a/include/HttpServer.h b/include/HttpServer.h index d9dda20f..fa7a5187 100644 --- a/include/HttpServer.h +++ b/include/HttpServer.h @@ -6,4 +6,4 @@ namespace HttpServer { void init(); -} // namespace HttpServer \ No newline at end of file +} // namespace HttpServer diff --git a/include/Module/Runner.h b/include/Module/Runner.h index 2fcc2b6e..40f390ee 100644 --- a/include/Module/Runner.h +++ b/include/Module/Runner.h @@ -6,3 +6,11 @@ class Runner { public: virtual void run(const char*, Print*); }; + +class CmdRunner : public Runner { + public: + void run(const char* cmd, Print* out) override { + String cmdStr{cmd}; + stringExecute(cmdStr); + } +}; \ No newline at end of file diff --git a/include/Module/Terminal.h b/include/Module/Terminal.h index 3d3234d8..cbb8a6f8 100644 --- a/include/Module/Terminal.h +++ b/include/Module/Terminal.h @@ -1,6 +1,9 @@ #pragma once +#include + #include "Module/EditLine.h" +#include #define A_NORMAL 0x0000 // normal #define A_UNDERLINE 0x0001 // underline diff --git a/include/Servo/Servos.h b/include/Servo/Servos.h new file mode 100644 index 00000000..c4ac44dd --- /dev/null +++ b/include/Servo/Servos.h @@ -0,0 +1,25 @@ +#pragma once + +#include +#include + +struct Servo_t { + uint8_t num; + uint8_t pin; + Servo* obj; + Servo_t(uint8_t num, uint8_t pin) : num{num}, pin{pin}, obj{nullptr} {}; +}; + +class Servos { + public: + Servos(); + Servo* get(uint8_t num); + Servo* create(uint8_t num, uint8_t pin); + + size_t count(); + + private: + std::vector _items; +}; + +extern Servos myServo; \ No newline at end of file diff --git a/include/Upgrade.h b/include/Upgrade.h index b64e0eec..e031a765 100644 --- a/include/Upgrade.h +++ b/include/Upgrade.h @@ -2,4 +2,4 @@ void getLastVersion(); -void flashUpgrade(); \ No newline at end of file +void do_update(); \ No newline at end of file diff --git a/include/Utils/FileUtils.h b/include/Utils/FileUtils.h index f4840f9c..af4dadc9 100644 --- a/include/Utils/FileUtils.h +++ b/include/Utils/FileUtils.h @@ -2,6 +2,8 @@ #include +#include "Consts.h" + #include "FS.h" #ifdef ESP32 @@ -53,4 +55,8 @@ const String readFile(const String& filename, size_t max_size); */ const String getFileSize(const String& filename); -bool copyFile(const String& src, const String& dst, bool overwrite = true); \ No newline at end of file +bool copyFile(const String& src, const String& dst, bool overwrite = true); + +const String getFSSizeInfo(); + +const String getConfigFile(uint8_t preset, ConfigType_t type); diff --git a/include/Utils/JsonUtils.h b/include/Utils/JsonUtils.h index d5200cdb..f759361c 100644 --- a/include/Utils/JsonUtils.h +++ b/include/Utils/JsonUtils.h @@ -13,3 +13,5 @@ String jsonWriteStr(String& json, String name, String value); String jsonWriteInt(String& json, String name, int value); String jsonWriteFloat(String& json, String name, float value); + +String jsonWriteBool(String& json, String name, boolean value); \ No newline at end of file diff --git a/include/Utils/PresetUtils.h b/include/Utils/PresetUtils.h deleted file mode 100644 index 9366d515..00000000 --- a/include/Utils/PresetUtils.h +++ /dev/null @@ -1,10 +0,0 @@ -#pragma once - -#include - -#include "CommonTypes.h" - -const String getConfigFile(uint8_t preset, ConfigType_t type); - -const String getItemName(Item_t item); - diff --git a/include/Utils/PrintMessage.h b/include/Utils/PrintMessage.h index 04514ee5..d6425544 100644 --- a/include/Utils/PrintMessage.h +++ b/include/Utils/PrintMessage.h @@ -1,7 +1,6 @@ #pragma once #include "Arduino.h" -#include "CommonTypes.h" #include "Utils\StringUtils.h" #include "Utils\TimeUtils.h" #include "Errors.h" diff --git a/include/Utils/StringUtils.h b/include/Utils/StringUtils.h index 355cf262..1347b1ba 100644 --- a/include/Utils/StringUtils.h +++ b/include/Utils/StringUtils.h @@ -2,8 +2,6 @@ #include -#include "CommonTypes.h" - uint8_t hexStringToUint8(String hex); uint16_t hexStringToUint16(String hex); diff --git a/include/Utils/TimeUtils.h b/include/Utils/TimeUtils.h index b65e97f5..d20286cf 100644 --- a/include/Utils/TimeUtils.h +++ b/include/Utils/TimeUtils.h @@ -2,7 +2,7 @@ #include -#include "CommonTypes.h" +#include "Consts.h" #define ONE_MINUTE_s 60 #define ONE_HOUR_m 60 diff --git a/platformio.ini b/platformio.ini index ee5d86e3..4ee2b7d1 100644 --- a/platformio.ini +++ b/platformio.ini @@ -11,45 +11,69 @@ [platformio] default_envs = esp8266 -[env] -framework = arduino +[common_env_data] +lib_deps_external = + ArduinoJson@5.* + Bounce2 + PubSubClient + DHT sensor library for ESPx + Adafruit BMP280 Library + Adafruit BME280 Library + DallasTemperature +lib_deps_internal = + ESP Async WebServer + GyverFilters + OneWire [env:esp32] -platform = https://github.com/platformio/platform-espressif32.git -build_flags = ${env.build_flags} -D=${PIOENV} -extra_scripts = ./tools/littlefsbuilder.py +framework = arduino board = esp32dev -board_build.partitions = partitions_custom.csv +board_build.filesystem = littlefs +platform = https://github.com/platformio/platform-espressif32.git +lib_deps = + ${common_env_data.lib_deps_external} + ${common_env_data.lib_deps_internal} + AsyncTCP + ESP32Servo + LITTLEFS monitor_filters = esp32_exception_decoder monitor_speed = 115200 -lib_deps = - ModuleInterface@3.5.1 - ArduinoJson@5.* - ESP32Servo - Bounce2 - PubSubClient - ESP8266-StringCommand - DallasTemperature - DHT sensor library for ESPx - Adafruit BMP280 Library - Adafruit BME280 Library -[env:esp8266] +[env:esp8266_01_1m] +framework = arduino +board = esp01_1m +board_build.ldscript = eagle.flash.1m512.ld platform = https://github.com/platformio/platform-espressif8266.git -build_flags = ${env.build_flags} -D=${PIOENV} -##-DCORE_DEBUG_LEVEL=5 -board = nodemcuv2 +lib_deps = + ${common_env_data.lib_deps_external} + ${common_env_data.lib_deps_internal} + ESPAsyncTCP + ESPAsyncUDP + EspSoftwareSerial monitor_filters = esp8266_exception_decoder monitor_speed = 115200 -lib_deps = - ModuleInterface@3.5.1 - ArduinoJson@5.* - ESPAsyncTCP - Bounce2 - PubSubClient - ESP8266-StringCommand - DallasTemperature - DHT sensor library for ESPx - Adafruit BMP280 Library - Adafruit BME280 Library +board_build.filesystem = littlefs +[env:esp8266] +framework = arduino +board = nodemcuv2 +platform = https://github.com/platformio/platform-espressif8266.git +lib_deps = + ${common_env_data.lib_deps_external} + ${common_env_data.lib_deps_internal} + ESPAsyncTCP + ESPAsyncUDP + EspSoftwareSerial +monitor_filters = esp8266_exception_decoder +monitor_speed = 115200 +board_build.filesystem = littlefs +board_build.f_cpu = 160000000L + +; build_type = debug +; build_flags = +; -DDEBUG_ESP_CORE +; -DDEBUG_ESP_WIFI +; -DDEBUG_ESP_HTTP_UPDATE +; -DDEBUG_ESP_UPDATER +; -DDEBUG_ESP_OTA +; -DDEBUG_ESP_OOM diff --git a/src/Bus/i2c_bus.cpp b/src/Bus/I2CScanner.cpp similarity index 65% rename from src/Bus/i2c_bus.cpp rename to src/Bus/I2CScanner.cpp index 33e44a15..669b2903 100644 --- a/src/Bus/i2c_bus.cpp +++ b/src/Bus/I2CScanner.cpp @@ -1,18 +1,23 @@ -#include "Bus/BusScanner.h" +#include "Bus/I2CScanner.h" +#include "Utils/PrintMessage.h" #include -#include "Utils/PrintMessage.h" static const char* MODULE = "I2C"; -boolean I2CScanner::syncScan() { +I2CScanner::I2CScanner(String& out) : BusScanner(TAG_I2C, out, 2){}; + +void I2CScanner::init() { Wire.begin(); - pm.info("scanning i2c..."); +} + +boolean I2CScanner::syncScan() { + pm.info("scanning..."); size_t cnt = 0; for (uint8_t i = 8; i < 120; i++) { Wire.beginTransmission(i); if (Wire.endTransmission() == 0) { - pm.info("found device: " + i); + pm.info("found: " + i); addResult(i, i < 119); cnt++; } diff --git a/src/Bus/onewire_bus.cpp b/src/Bus/onewire_bus.cpp deleted file mode 100644 index a1ab283b..00000000 --- a/src/Bus/onewire_bus.cpp +++ /dev/null @@ -1,28 +0,0 @@ -#include "Bus/BusScanner.h" - -#include "Utils/PresetUtils.h" -#include "Utils/PrintMessage.h" - -#include - -const char* MODULE = "1Wire"; - -bool OneWireScanner::syncScan() { - // Connect your 1-wire device to pin 3 - OneWire ds(3); - uint8_t addr[8]; - - pm.info("scanning 1-Wire..."); - while (ds.search(addr)) { - for (uint8_t i = 0; i < 8; i++) { - pm.info("found device: " + i); - addResult(addr[i], i < 7); - } - } - if (OneWire::crc8(addr, 7) != addr[7]) { - pm.error("CRC!"); - return false; - } - ds.reset_search(); - return true; -} diff --git a/src/CaptiveRequestHandler.cpp b/src/CaptiveRequestHandler.cpp deleted file mode 100644 index 111021fb..00000000 --- a/src/CaptiveRequestHandler.cpp +++ /dev/null @@ -1,33 +0,0 @@ -#include "CaptiveRequestHandler.h" - -CaptiveRequestHandler::CaptiveRequestHandler(const char *host) { - strlcpy(_local_name, host, sizeof(_local_name)); - strcat(_local_name, ".local"); -} - -CaptiveRequestHandler::~CaptiveRequestHandler() { -} - -bool CaptiveRequestHandler::isLocalIp(String address) { - IPAddress ip; - return !ip.fromString(address) || (ip != _local_ip); -} - -bool CaptiveRequestHandler::isLocalName(String host_name) { - return host_name.equalsIgnoreCase(_local_name); -} - -bool CaptiveRequestHandler::canHandle(AsyncWebServerRequest *request) { - _local_ip = request->client()->localIP(); - - return !isLocalIp(request->getHeader("HOST")->value()) && !isLocalName(request->getHeader("HOST")->value()); -} - -void CaptiveRequestHandler::CaptiveRequestHandler::handleRequest(AsyncWebServerRequest *request) { - char buf[64]; - sprintf(buf, "http://%s%s", _local_name, request->url().c_str()); - auto response = request->beginResponse(302, "text/html"); - response->addHeader("Location", buf); - response->addHeader("Connection", "close"); - request->send(response); -}; diff --git a/src/Cmd.cpp b/src/Cmd.cpp index fbfe3638..49cac677 100644 --- a/src/Cmd.cpp +++ b/src/Cmd.cpp @@ -1,6 +1,7 @@ #include "Global.h" #include "Module/Terminal.h" +#include "Servo/Servos.h" static const char *MODULE = "Cmd"; @@ -9,9 +10,11 @@ Terminal *term = nullptr; boolean but[NUM_BUTTONS]; Bounce *buttons = new Bounce[NUM_BUTTONS]; -Servo myServo1; -Servo myServo2; +#ifdef ESP8266 SoftwareSerial *mySerial = nullptr; +#else +HardwareSerial *mySerial = nullptr; +#endif void getData(); @@ -105,6 +108,7 @@ void cmd_init() { //========================================================================================================== //==========================================Модуль кнопок=================================================== + void button() { pm.info("create 'button'"); String number = sCmd.next(); @@ -174,25 +178,23 @@ void buttonSet() { } eventGen("button", button_number); - jsonWriteStr(configLiveJson, "button" + button_number, button_state); - MqttClient::publishStatus("button" + button_number, button_state); } void buttonChange() { String button_number = sCmd.next(); - String current_state = jsonReadStr(configLiveJson, "button" + button_number); - - if (current_state == "1") { - current_state = "0"; - } else if (current_state == "0") { - current_state = "1"; + if (!isDigitStr(button_number)) { + pm.error("wrong button " + button_number); + return; } - order_loop += "buttonSet " + button_number + " " + current_state + ","; - jsonWriteStr(configLiveJson, "button" + button_number, current_state); + String name = "button" + button_number; + bool current_state = !jsonReadBool(configLiveJson, name); + String stateStr = current_state ? "1" : "0"; - MqttClient::publishStatus("button" + button_number, current_state); + jsonWriteStr(configLiveJson, name, stateStr); + addCommandLoop("buttonSet " + button_number + " " + stateStr); + MqttClient::publishStatus(name, stateStr); } void pinSet() { @@ -223,9 +225,8 @@ void pwm() { jsonWriteStr(configOptionJson, "pwm_pin" + pwm_number, pwm_pin); pinMode(pwm_pin_int, INPUT); analogWrite(pwm_pin_int, start_state.toInt()); - //analogWriteFreq(32000); - jsonWriteStr(configLiveJson, "pwm" + pwm_number, start_state); + jsonWriteStr(configLiveJson, "pwm" + pwm_number, start_state); createWidget(widget_name, page_name, page_number, "range", "pwm" + pwm_number); } @@ -246,13 +247,13 @@ void pwmSet() { //================================================================================================================== //==========================================Модуль физической кнопки================================================ void switch_() { - String switch_number = sCmd.next(); - String switch_pin = sCmd.next(); - String switch_delay = sCmd.next(); + int number = String(sCmd.next()).toInt(); + int pin = String(sCmd.next()).toInt(); + int delay = String(sCmd.next()).toInt(); - buttons[switch_number.toInt()].attach(switch_pin.toInt()); - buttons[switch_number.toInt()].interval(switch_delay.toInt()); - but[switch_number.toInt()] = true; + buttons[number].attach(pin); + buttons[number].interval(delay); + but[number] = true; } void loopSerial() { @@ -294,6 +295,7 @@ void inputDigit() { page_name.replace("#", " "); String start_state = sCmd.next(); String page_number = sCmd.next(); + jsonWriteStr(configLiveJson, "digit" + number, start_state); createWidget(widget_name, page_name, page_number, "inputNum", "digit" + number); } @@ -301,6 +303,7 @@ void inputDigit() { void digitSet() { String number = sCmd.next(); String value = sCmd.next(); + jsonWriteStr(configLiveJson, "digit" + number, value); MqttClient::publishStatus("digit" + number, value); } @@ -316,6 +319,7 @@ void inputTime() { page_name.replace("#", " "); String start_state = sCmd.next(); String page_number = sCmd.next(); + jsonWriteStr(configLiveJson, "time" + number, start_state); createWidget(widget_name, page_name, page_number, "inputTime", "time" + number); } @@ -323,6 +327,7 @@ void inputTime() { void timeSet() { String number = sCmd.next(); String value = sCmd.next(); + jsonWriteStr(configLiveJson, "time" + number, value); MqttClient::publishStatus("time" + number, value); } @@ -356,9 +361,7 @@ void textSet() { if (text.indexOf("-time") >= 0) { text.replace("-time", ""); text.replace("#", " "); - String time = timeNow->getTime(); - time.replace(":", "."); - text = text + " " + timeNow->getDateDigitalFormated() + " " + time; + text = text + " " + timeNow->getDateTimeDotFormated(); } jsonWriteStr(configLiveJson, "text" + number, text); @@ -431,94 +434,59 @@ void stepperSet() { #ifdef SERVO_ENABLED //servo 1 13 50 Мой#сервопривод Сервоприводы 0 100 0 180 2 void servo_() { - String servo_number = sCmd.next(); - String servo_pin = sCmd.next(); - String start_state = sCmd.next(); - int start_state_int = start_state.toInt(); - String widget_name = sCmd.next(); - String page_name = sCmd.next(); + String number = sCmd.next(); + uint8_t pin = String(sCmd.next()).toInt(); + int value = String(sCmd.next()).toInt(); - String min_value = sCmd.next(); - String max_value = sCmd.next(); + String widget = sCmd.next(); + String page = sCmd.next(); - String min_deg = sCmd.next(); - String max_deg = sCmd.next(); + int min_value = String(sCmd.next()).toInt(); + int max_value = String(sCmd.next()).toInt(); + int min_deg = String(sCmd.next()).toInt(); + int max_deg = String(sCmd.next()).toInt(); - String page_number = sCmd.next(); + String pageNumber = sCmd.next(); - jsonWriteStr(configOptionJson, "servo_pin" + servo_number, servo_pin); - start_state_int = map(start_state_int, min_value.toInt(), max_value.toInt(), min_deg.toInt(), max_deg.toInt()); + jsonWriteStr(configOptionJson, "servo_pin" + number, String(pin, DEC)); - if (servo_number == "1") { -#ifdef ESP8266 - myServo1.attach(servo_pin.toInt()); - myServo1.write(start_state_int); -#endif + value = map(value, min_value, max_value, min_deg, max_deg); + + Servo *servo = myServo.create(number.toInt(), pin); + servo->write(value); #ifdef ESP32 - myServo1.attach(servo_pin.toInt(), 500, 2400); - myServo1.write(start_state_int); + myServo1.attach(servo_pin.toInt(), 500, 2400); + myServo1.write(start_state_int); #endif - } - if (servo_number == "2") { -#ifdef ESP8266 - myServo2.attach(servo_pin.toInt()); - myServo2.write(start_state_int); -#endif -#ifdef ESP32 - myServo2.attach(servo_pin.toInt(), 500, 2400); - myServo2.write(start_state_int); -#endif - } + jsonWriteInt(configOptionJson, "s_min_val" + number, min_value); + jsonWriteInt(configOptionJson, "s_max_val" + number, max_value); + jsonWriteInt(configOptionJson, "s_min_deg" + number, min_deg); + jsonWriteInt(configOptionJson, "s_max_deg" + number, max_deg); - jsonWriteStr(configOptionJson, "s_min_val" + servo_number, min_value); - jsonWriteStr(configOptionJson, "s_max_val" + servo_number, max_value); - jsonWriteStr(configOptionJson, "s_min_deg" + servo_number, min_deg); - jsonWriteStr(configOptionJson, "s_max_deg" + servo_number, max_deg); + jsonWriteInt(configLiveJson, "servo" + number, value); - jsonWriteStr(configLiveJson, "servo" + servo_number, start_state); - - createWidgetParam(widget_name, page_name, page_number, "range", "servo" + servo_number, "min", min_value, "max", max_value, "k", "1"); + createWidgetParam(widget, page, pageNumber, "range", "servo" + number, "min", String(min_value), "max", String(max_value), "k", "1"); } void servoSet() { - String servo_number = sCmd.next(); - String servo_state = sCmd.next(); - int servo_state_int = servo_state.toInt(); + String number = sCmd.next(); + int value = String(sCmd.next()).toInt(); - //int pin = jsonReadInt(configOptionJson, "servo_pin" + servo_number); + value = map(value, + jsonReadInt(configOptionJson, "s_min_val" + number), + jsonReadInt(configOptionJson, "s_max_val" + number), + jsonReadInt(configOptionJson, "s_min_deg" + number), + jsonReadInt(configOptionJson, "s_max_deg" + number)); - servo_state_int = map(servo_state_int, - jsonReadInt(configOptionJson, "s_min_val" + servo_number), - jsonReadInt(configOptionJson, "s_max_val" + servo_number), - jsonReadInt(configOptionJson, "s_min_deg" + servo_number), - jsonReadInt(configOptionJson, "s_max_deg" + servo_number)); - - if (servo_number == "1") { -#ifdef ESP8266 - myServo1.write(servo_state_int); -#endif -#ifdef ESP32 - myServo1.write(servo_state_int); -#endif + Servo *servo = myServo.get(number.toInt()); + if (servo) { + servo->write(value); } - if (servo_number == "2") { -#ifdef ESP8266 - myServo2.write(servo_state_int); -#endif -#ifdef ESP32 - myServo2.write(servo_state_int); -#endif - } - - //Serial.println(servo_state_int); - - eventGen("servo", servo_number); - - jsonWriteStr(configLiveJson, "servo" + servo_number, servo_state); - - MqttClient::publishStatus("servo" + servo_number, servo_state); + eventGen("servo", number); + jsonWriteInt(configLiveJson, "servo" + number, value); + MqttClient::publishStatus("servo" + number, String(value, DEC)); } #endif @@ -532,8 +500,13 @@ void serialBegin() { delete mySerial; } +#ifdef ESP8266 mySerial = new SoftwareSerial(rxPin.toInt(), txPin.toInt()); mySerial->begin(s_speed.toInt()); +#else + mySerial = new HardwareSerial(2); + mySerial->begin(rxPin.toInt(), txPin.toInt()); +#endif term = new Terminal(mySerial); term->setEOL(LF); @@ -542,8 +515,6 @@ void serialBegin() { term->enableEcho(false); term->setOnReadLine([](const char *str) { String line = String(str); - pm.info("serial read: " + line); - //line.replace("#", " "); addCommandLoop(line); }); } @@ -583,7 +554,7 @@ void httpOrderSend() { } void firmwareUpdate() { - upgrade = true; + updateFlag = true; } void firmwareVersion() { @@ -592,7 +563,6 @@ void firmwareVersion() { String pageNumber = sCmd.next(); jsonWriteStr(configLiveJson, "firmver", FIRMWARE_VERSION); - createWidget(widget, page, pageNumber, "anydata", "firmver"); } @@ -605,20 +575,11 @@ void addCommandLoop(const String &cmdStr) { void fileExecute(const String &filename) { String cmdStr = readFile(filename, 2048); - cmdStr += "\r\n"; - cmdStr.replace("\r\n", "\n"); - cmdStr.replace("\r", "\n"); - - while (cmdStr.length() != 0) { - String buf = selectToMarker(cmdStr, "\n"); - sCmd.readStr(buf); - cmdStr = deleteBeforeDelimiter(cmdStr, "\n"); - } + stringExecute(cmdStr); } void stringExecute(String &cmdStr) { - cmdStr = cmdStr + "\r\n"; - + cmdStr += "\r\n"; cmdStr.replace("\r\n", "\n"); cmdStr.replace("\r", "\n"); @@ -632,8 +593,8 @@ void stringExecute(String &cmdStr) { void loopCmd() { if (order_loop.length()) { String tmp = selectToMarker(order_loop, ","); //выделяем первую команду rel 5 1, - sCmd.readStr(tmp); //выполняем - pm.info("do: " + order_loop); + pm.info("do: " + tmp); + sCmd.readStr(tmp); //выполняем order_loop = deleteBeforeDelimiter(order_loop, ","); //осекаем } } diff --git a/src/Global.cpp b/src/Global.cpp index 39599158..05b51345 100644 --- a/src/Global.cpp +++ b/src/Global.cpp @@ -17,6 +17,8 @@ StringCommand sCmd; AsyncWebServer server(80); +OneWire *oneWire; + DallasTemperature sensors; /* @@ -41,6 +43,9 @@ String order_loop = ""; String analog_value_names_list; int enter_to_analog_counter; +String dallas_value_name; +int enter_to_dallas_counter; + String levelPr_value_name; String ultrasonicCm_value_name; @@ -67,8 +72,8 @@ int scenario_line_status[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, String lastVersion = ""; // Async actions -boolean upgrade_url = false; -boolean upgrade = false; +boolean checkUpdatesFlag = false; +boolean updateFlag = false; boolean mqttParamsChanged = false; boolean udp_data_parse = false; diff --git a/src/HttpServer.cpp b/src/HttpServer.cpp index 3f9da6e4..78e898a4 100644 --- a/src/HttpServer.cpp +++ b/src/HttpServer.cpp @@ -15,8 +15,8 @@ void init() { String login = jsonReadStr(configSetupJson, "weblogin"); String pass = jsonReadStr(configSetupJson, "webpass"); #ifdef ESP32 - server.addHandler(new SPIFFSEditor(LittleFS, login, pass); -#elif defined(ESP8266) + server.addHandler(new SPIFFSEditor(LittleFS, login, pass)); +#else server.addHandler(new SPIFFSEditor(login, pass)); #endif @@ -51,7 +51,7 @@ void init() { server.on("/config.option.json", HTTP_GET, [](AsyncWebServerRequest *request) { request->send(200, "application/json", configOptionJson); }); - + // для хранения постоянных данных server.on("/config.setup.json", HTTP_GET, [](AsyncWebServerRequest *request) { request->send(200, "application/json", configSetupJson); @@ -59,13 +59,13 @@ void init() { server.on("/cmd", HTTP_GET, [](AsyncWebServerRequest *request) { String cmdStr = request->getParam("command")->value(); - pm.info("command: " + cmdStr); + pm.info("do: " + cmdStr); addCommandLoop(cmdStr); - request->send(200, "text/text", "OK"); + request->send(200, "text/html", "OK"); }); server.begin(); - + initOta(); initMDNS(); initWS(); @@ -190,7 +190,7 @@ void initWS() { ws.onEvent(onWsEvent); server.addHandler(&ws); events.onConnect([](AsyncEventSourceClient *client) { - //!!!client->send("hello!", NULL, millis(), 1000); + client->send("", NULL, millis(), 1000); }); server.addHandler(&events); #endif diff --git a/src/Init.cpp b/src/Init.cpp index 2573b68a..75d43ebb 100644 --- a/src/Init.cpp +++ b/src/Init.cpp @@ -30,6 +30,9 @@ void Device_init() { analog_value_names_list = ""; enter_to_analog_counter = 0; + dallas_value_name = ""; + enter_to_dallas_counter = 0; + levelPr_value_name = ""; ultrasonicCm_value_name = ""; diff --git a/src/Module/Telnet.cpp b/src/Module/Telnet.cpp index f4b92fc7..d8bec643 100644 --- a/src/Module/Telnet.cpp +++ b/src/Module/Telnet.cpp @@ -16,7 +16,7 @@ void Telnet::onEnd() { bool Telnet::onStart() { _server->begin(); _server->setNoDelay(true); - return _server->status() != CLOSED; + return true; } void Telnet::onStop() { diff --git a/src/Module/Terminal.cpp b/src/Module/Terminal.cpp index 4de12887..38c03b97 100644 --- a/src/Module/Terminal.cpp +++ b/src/Module/Terminal.cpp @@ -45,8 +45,8 @@ void Terminal::quit() {} void Terminal::loop() { if (_stream == nullptr || !_stream->available()) return; - sint8_t moveX = 0; - sint8_t moveY = 0; + byte moveX = 0; + byte moveY = 0; char c = _stream->read(); diff --git a/src/MqttClient.cpp b/src/MqttClient.cpp index 0f4fbd33..62a711e9 100644 --- a/src/MqttClient.cpp +++ b/src/MqttClient.cpp @@ -147,7 +147,7 @@ void handleSubscribedUpdates(char* topic, uint8_t* payload, size_t length) { order_loop += ","; } else if (topicStr.indexOf("update")) { if (payloadStr == "1") { - upgrade = true; + updateFlag = true; } } else if (topicStr.indexOf("devc")) { writeFile(String(DEVICE_CONFIG_FILE), payloadStr); @@ -279,7 +279,7 @@ const String getStateStr() { return F("connection failed"); break; case -1: - return F("client disconnected "); + return F("client disconnected"); break; case 0: return F("client connected"); diff --git a/src/Scenario.cpp b/src/Scenario.cpp index e7a78423..68269424 100644 --- a/src/Scenario.cpp +++ b/src/Scenario.cpp @@ -22,7 +22,6 @@ void loopScenario() { return; } i++; - if (scenario_line_status[i] == 1) { //выделяем первую строку самого сценария button1 = 1 (условие) String condition = selectToMarker(block, "\n"); @@ -30,9 +29,8 @@ void loopScenario() { String order = jsonReadStr(configOptionJson, "scenario_status"); //читаем весь файл событий String param = selectToMarker(order, ","); //читаем первое событие из файла событий if (param_name == param) { //если поступившее событие равно событию заданному buttonSet1 в файле начинаем его обработку - - String sign = selectFromMarkerToMarker(condition, " ", 1); //читаем знак (=) - String value = selectFromMarkerToMarker(condition, " ", 2); //читаем значение (1) + String sign = selectFromMarkerToMarker(condition, " ", 1); //читаем знак (=) + String value = selectFromMarkerToMarker(condition, " ", 2); //читаем значение (1) if (value.indexOf("digit") != -1) { // value = add_set(value); value = jsonReadStr(configLiveJson, value); @@ -41,31 +39,29 @@ void loopScenario() { // value = add_set(value); value = jsonReadStr(configLiveJson, value); } - boolean flag = false; //если одно из значений совпало то только тогда начинаем выполнять комнады + // если условие выполнилось, тогда начинаем выполнять комнады + boolean flag = false; + String param = jsonReadStr(configLiveJson, param_name); if (sign == "=") { - if (jsonReadStr(configLiveJson, param_name) == value) flag = true; - } - if (sign == "!=") { - if (jsonReadStr(configLiveJson, param_name) != value) flag = true; - } - if (sign == "<") { - if (jsonReadStr(configLiveJson, param_name).toInt() < value.toInt()) flag = true; - } - if (sign == ">") { - if (jsonReadStr(configLiveJson, param_name).toInt() > value.toInt()) flag = true; - } - if (sign == ">=") { - if (jsonReadStr(configLiveJson, param_name).toInt() >= value.toInt()) flag = true; - } - if (sign == "<=") { - if (jsonReadStr(configLiveJson, param_name).toInt() <= value.toInt()) flag = true; + flag = param == value; + } else if (sign == "!=") { + flag = param != value; + } else if (sign == "<") { + flag = param.toInt() < value.toInt(); + } else if (sign == ">") { + flag = param.toInt() > value.toInt(); + } else if (sign == ">=") { + flag = param.toInt() >= value.toInt(); + } else if (sign == "<=") { + flag = param.toInt() <= value.toInt(); } if (flag) { - block = deleteBeforeDelimiter(block, "\n"); //удаляем строку самого сценария оставляя только команды - stringExecute(block); //выполняем все команды - - pm.info(condition + "'"); + // удаляем строку самого сценария оставляя только команды + block = deleteBeforeDelimiter(block, "\n"); + pm.info("do: " + block); + // выполняем все команды + stringExecute(block); } } } diff --git a/src/Sensors.cpp b/src/Sensors.cpp index b5a3a242..a23b5d3e 100644 --- a/src/Sensors.cpp +++ b/src/Sensors.cpp @@ -1,6 +1,5 @@ #include "Global.h" -OneWire *oneWire; GMedian<10, int> medianFilter; DHTesp dht; @@ -232,32 +231,40 @@ void analog_reading2() { //========================================================================================================================================= //=========================================Модуль температурного сенсора ds18b20=========================================================== #ifdef DALLAS_ENABLED +//dallas temp1 2 1 Температура Датчики anydata 1 +//dallas temp2 2 2 Температура Датчики anydata 2 void dallas() { String value_name = sCmd.next(); String pin = sCmd.next(); String address = sCmd.next(); + jsonWriteStr(configOptionJson, value_name + "_ds", address); String widget_name = sCmd.next(); String page_name = sCmd.next(); String type = sCmd.next(); String page_number = sCmd.next(); - oneWire = new OneWire((uint8_t)pin.toInt()); - + oneWire = new OneWire((uint8_t) pin.toInt()); sensors.setOneWire(oneWire); sensors.begin(); sensors.setResolution(12); - - createWidgetByType(widget_name, page_name, page_number, type, "dallas"); + dallas_value_name += value_name + ";"; + createWidgetByType(widget_name, page_name, page_number, type, value_name); sensors_reading_map[3] = 1; } void dallas_reading() { float temp = 0; + byte num = sensors.getDS18Count(); + String dallas_value_name_tmp_buf = dallas_value_name; sensors.requestTemperatures(); - temp = sensors.getTempCByIndex(0); - jsonWriteStr(configLiveJson, "dallas", String(temp)); - eventGen("dallas", ""); - MqttClient::publishStatus("dallas", String(temp)); - Serial.println("[I] sensor 'dallas' send date " + String(temp)); + for (byte i = 0; i < num; i++) { + temp = sensors.getTempCByIndex(i); + String buf = selectToMarker(dallas_value_name_tmp_buf, ";"); + dallas_value_name_tmp_buf = deleteBeforeDelimiter(dallas_value_name_tmp_buf, ";"); + jsonWriteStr(configLiveJson, buf, String(temp)); + eventGen(buf, ""); + MqttClient::publishStatus(buf, String(temp)); + Serial.println("[I] sensor '" + buf + "' send date " + String(temp)); + } } #endif //========================================================================================================================================= diff --git a/src/Servo/Servs.cpp b/src/Servo/Servs.cpp new file mode 100644 index 00000000..96ebba91 --- /dev/null +++ b/src/Servo/Servs.cpp @@ -0,0 +1,40 @@ +#include "Servo/Servos.h" + +Servos myServo; + +Servos::Servos(){}; + +Servo *Servos::create(uint8_t num, uint8_t pin) { + // Ищем среди ранее созданных + for (size_t i = 0; i < _items.size(); i++) { + auto item = _items.at(i); + if (item.num == num) { + if (item.pin != pin) { + item.obj->attach(pin); + item.pin = pin; + }; + return item.obj; + } + } + // Добавляем новый + Servo_t newItem{num, pin}; + newItem.obj = new Servo(); + newItem.obj->attach(pin); + _items.push_back(newItem); + return newItem.obj; +} + +Servo *Servos::get(uint8_t num) { + // Ищем среди ранее созданных + for (size_t i = 0; i < _items.size(); i++) { + auto item = _items.at(i); + if (item.num == num) { + return item.obj; + } + } + return nullptr; +} + +size_t Servos::count() { + return _items.size(); +} diff --git a/src/Upgrade.cpp b/src/Upgrade.cpp index 802986d0..0ebfbc6c 100644 --- a/src/Upgrade.cpp +++ b/src/Upgrade.cpp @@ -1,30 +1,29 @@ #include "Upgrade.h" #include "Global.h" +#include "ESP8266.h" -static const char* MODULE = "Upgr"; +static const char* MODULE = "Update"; -static const char* filesystem_image_url PROGMEM = "http://91.204.228.124:1100/update/%s/fs.bin"; -static const char* available_url PROGMEM = "http://91.204.228.124:1100/update/%s/version.txt"; +static const char* check_update_url PROGMEM = "http://91.204.228.124:1100/update/%s/version.txt"; const String getAvailableUrl(const char* mcu) { char buf[128]; - sprintf_P(buf, available_url, mcu); + sprintf_P(buf, check_update_url, mcu); return buf; } void getLastVersion() { - if (upgrade_url) { - upgrade_url = false; + if (checkUpdatesFlag) { String url; -#ifdef ESP32 - url = getAvailableUrl("esp32"); -#endif #ifdef ESP8266 url = getAvailableUrl("esp8266"); +#else + url = getAvailableUrl("esp32"); #endif lastVersion = getURL(url); jsonWriteStr(configSetupJson, "last_version", lastVersion); + checkUpdatesFlag = false; } } @@ -38,76 +37,51 @@ void initUpdater() { } void upgrade_firmware() { - String scenario_for_update; - String config_for_update; - String configSetup_for_update; + String scanerioBackup, configBackup, setupBackup; - scenario_for_update = readFile(String(DEVICE_SCENARIO_FILE), 4000); - config_for_update = readFile(String(DEVICE_CONFIG_FILE), 4000); - configSetup_for_update = configSetupJson; + scanerioBackup = readFile(String(DEVICE_SCENARIO_FILE), 4096); + configBackup = readFile(String(DEVICE_CONFIG_FILE), 4096); + setupBackup = configSetupJson; - Serial.println("Start upgrade SPIFFS, please wait..."); - - WiFiClient client_for_upgrade; - -#ifdef ESP32 + pm.info("update data"); + WiFiClient wifiClient; +#ifdef ESP8266 + ESPhttpUpdate.rebootOnUpdate(false); + t_httpUpdate_return ret = ESPhttpUpdate.updateSpiffs(wifiClient, "http://91.204.228.124:1100/update/esp8266/esp32-esp8266_iot-manager_modules_firmware.spiffs.bin"); +#else httpUpdate.rebootOnUpdate(false); t_httpUpdate_return ret = httpUpdate.updateSpiffs(client_for_upgrade, "http://91.204.228.124:1100/update/esp32/esp32-esp8266_iot-manager_modules_firmware.spiffs.bin"); #endif -#ifdef ESP8266 - ESPhttpUpdate.rebootOnUpdate(false); - t_httpUpdate_return ret = ESPhttpUpdate.updateSpiffs(client_for_upgrade, "http://91.204.228.124:1100/update/esp8266/esp32-esp8266_iot-manager_modules_firmware.spiffs.bin"); -#endif - if (ret == HTTP_UPDATE_OK) { - writeFile(String(DEVICE_SCENARIO_FILE), scenario_for_update); - writeFile(String(DEVICE_CONFIG_FILE), config_for_update); - writeFile("config.json", configSetup_for_update); + writeFile(String(DEVICE_SCENARIO_FILE), scanerioBackup); + writeFile(String(DEVICE_CONFIG_FILE), configBackup); + writeFile("config.json", setupBackup); + saveConfig(); - Serial.println("Upgrade done!"); - Serial.println("Start upgrade BUILD, please wait..."); - -#ifdef ESP32 - //httpUpdate.rebootOnUpdate(true); - t_httpUpdate_return ret = httpUpdate.update(client_for_upgrade, "http://91.204.228.124:1100/update/esp32/esp32-esp8266_iot-manager_modules_firmware.ino.bin"); -#endif -#ifdef ESP8266 - //ESPhttpUpdate.rebootOnUpdate(true); - t_httpUpdate_return ret = ESPhttpUpdate.update(client_for_upgrade, "http://91.204.228.124:1100/update/esp8266/esp32-esp8266_iot-manager_modules_firmware.ino.bin"); -#endif - - if (ret == HTTP_UPDATE_OK) { - Serial.println("Upgrade done!"); - Serial.println("Restart..."); - ESP.restart(); - } else { - Serial.println("[E] on build"); - } + pm.info("done!"); } else { - Serial.println("[E] on upgrade"); + pm.error("on data"); + return; + } + + Serial.println("update firmware"); +#ifdef ESP8266 + ret = ESPhttpUpdate.update(wifiClient, "http://91.204.228.124:1100/update/esp8266/esp32-esp8266_iot-manager_modules_firmware.ino.bin"); +#else + ret = httpUpdate.update(client_for_upgrade, "http://91.204.228.124:1100/update/esp32/esp32-esp8266_iot-manager_modules_firmware.ino.bin"); +#endif + if (ret == HTTP_UPDATE_OK) { + pm.info("done! restart..."); + ESP.restart(); + } else { + pm.error("on firmware"); } } -void flashUpgrade() { - if (upgrade) { - upgrade = false; +void do_update() { + if (updateFlag) { + updateFlag = false; upgrade_firmware(); } -} - -/* - void upgrade_status(t_httpUpdate_return set) { - switch (set) { - case HTTP_UPDATE_FAILED: - Serial.printf("UPDATE_FAILED Error (%d): %s", httpUpdate.getLastError(), httpUpdate.getLastErrorString().c_str()); - break; - case HTTP_UPDATE_NO_UPDATES: - Serial.println("NO_UPDATES"); - break; - case HTTP_UPDATE_OK: - Serial.println("HTTP_UPDATE_OK"); - break; - } - } -*/ \ No newline at end of file +} \ No newline at end of file diff --git a/src/Utils/FileUtils.cpp b/src/Utils/FileUtils.cpp index 16975564..be3c4e5a 100644 --- a/src/Utils/FileUtils.cpp +++ b/src/Utils/FileUtils.cpp @@ -127,3 +127,24 @@ const String getFileSize(const String filename) { file.close(); return String(size); } + +const String getFSSizeInfo() { + String res; +#ifdef ESP8266 + FSInfo info; + if (LittleFS.info(info)) { + res = prettyBytes(info.usedBytes) + " of " + prettyBytes(info.totalBytes); + } else { + res = "error"; + } +#else + res = prettyBytes(LittleFS.usedBytes()) + " of " + prettyBytes(LittleFS.totalBytes()); +#endif + return res; +} + +const String getConfigFile(uint8_t preset, ConfigType_t type) { + char buf[64]; + sprintf(buf, "/conf/%s%03d.txt", (type == CT_CONFIG) ? "c" : "s", preset); + return String(buf); +} \ No newline at end of file diff --git a/src/Utils/JsonUtils.cpp b/src/Utils/JsonUtils.cpp index df6ff668..8bc3de8f 100644 --- a/src/Utils/JsonUtils.cpp +++ b/src/Utils/JsonUtils.cpp @@ -29,6 +29,10 @@ String jsonWriteStr(String& json, String name, String value) { return json; } +String jsonWriteBool(String& json, String name, boolean value) { + return jsonWriteStr(json, name, value ? "1" : "0"); +} + String jsonWriteInt(String& json, String name, int value) { DynamicJsonBuffer jsonBuffer; JsonObject& root = jsonBuffer.parseObject(json); diff --git a/src/Utils/PresetUtils.cpp b/src/Utils/PresetUtils.cpp deleted file mode 100644 index f82a7e40..00000000 --- a/src/Utils/PresetUtils.cpp +++ /dev/null @@ -1,9 +0,0 @@ -#include "Utils/PresetUtils.h" - -static const char* config_file_fmt PROGMEM = "/conf/%s%03d.txt"; - -const String getConfigFile(uint8_t preset, ConfigType_t type) { - char buf[64]; - sprintf_P(buf, config_file_fmt, (type == CT_CONFIG) ? "c" : "s", preset); - return String(buf); -} \ No newline at end of file diff --git a/src/Utils/StringUtils.cpp b/src/Utils/StringUtils.cpp index 8340a0b1..cd543761 100644 --- a/src/Utils/StringUtils.cpp +++ b/src/Utils/StringUtils.cpp @@ -1,5 +1,7 @@ #include "Utils\StringUtils.h" +#include "Consts.h" + String selectToMarkerLast(String str, String found) { int p = str.lastIndexOf(found); return str.substring(p + found.length()); diff --git a/src/Utils/SysUtils.cpp b/src/Utils/SysUtils.cpp index d46a343c..d4eb5039 100644 --- a/src/Utils/SysUtils.cpp +++ b/src/Utils/SysUtils.cpp @@ -22,9 +22,8 @@ const String getChipId() { #ifdef ESP8266 static uint32_t total_memory = 52864; -#endif -#ifdef ESP32 -static uint32_t total_memory = 362868; +#else +static uint32_t total_memory = ESP.getHeapSize(); #endif const String printMemoryStatus() { @@ -49,19 +48,10 @@ const String getHeapStats() { buf += '%'; return buf; } -#endif - -#ifdef ESP32 -String getHeapStats() { - uint32_t free; - uint16_t max; - uint8_t frag; - ESP.getHeapStats(&free, &max, &frag); +#else +const String getHeapStats() { String buf; - buf += prettyBytes(free); - buf += " "; - buf += frag; - buf += '%'; + buf = prettyBytes(ESP.getFreeHeap()); return buf; } #endif diff --git a/src/Utils/WiFiUtils.cpp b/src/Utils/WiFiUtils.cpp index e1727379..950ec1f2 100644 --- a/src/Utils/WiFiUtils.cpp +++ b/src/Utils/WiFiUtils.cpp @@ -20,11 +20,16 @@ void startSTAMode() { bool keepConnecting = true; uint8_t tries = 20; + sint8_t connRes; do { - sint8_t connRes = WiFi.waitForConnectResult(1000); +#ifdef ESP8266 + connRes = WiFi.waitForConnectResult(1000); +#else + byte connRes = WiFi.waitForConnectResult(); +#endif switch (connRes) { case WL_NO_SSID_AVAIL: { - pm.error("No ssid available"); + pm.error("no network"); keepConnecting = false; } break; case WL_CONNECTED: { @@ -34,7 +39,7 @@ void startSTAMode() { keepConnecting = false; } break; case WL_CONNECT_FAILED: { - pm.error("Check credentials"); + pm.error("check credentials"); jsonWriteInt(configOptionJson, "pass_status", 1); keepConnecting = false; } break; @@ -45,9 +50,9 @@ void startSTAMode() { if (isNetworkActive()) { MqttClient::init(); - setLedStatus(LED_OFF); } else { + pm.error("failed: " + String(connRes, DEC)); startAPMode(); }; } diff --git a/src/Web.cpp b/src/Web.cpp index 8f435189..ef5d8fbd 100644 --- a/src/Web.cpp +++ b/src/Web.cpp @@ -1,13 +1,7 @@ #include "Global.h" -#include "CaptiveRequestHandler.h" -#include "Utils/PresetUtils.h" - static const char* MODULE = "Web"; -static const uint8_t MIN_PRESET = 1; -static const uint8_t MAX_PRESET = 21; - bool parseRequestForPreset(AsyncWebServerRequest* request, uint8_t& preset) { if (request->hasArg("preset")) { preset = request->getParam("preset")->value().toInt(); @@ -17,8 +11,18 @@ bool parseRequestForPreset(AsyncWebServerRequest* request, uint8_t& preset) { } void web_init() { + // dnsServer.start(53, "*", WiFi.softAPIP()); // server.addHandler(new CaptiveRequestHandler(jsonReadStr(configSetupJson, "name").c_str())).setFilter(ON_AP_FILTER); + server.on("/restart", HTTP_GET, [](AsyncWebServerRequest* request) { + if (request->hasArg("device")) { + if (request->getParam("device")->value() == "ok") { + ESP.restart(); + } + request->send(200); + }; + }); + server.on("/set", HTTP_GET, [](AsyncWebServerRequest* request) { uint8_t preset; if (parseRequestForPreset(request, preset)) { @@ -35,49 +39,35 @@ void web_init() { //-------------------------------------------------------------------------------- if (request->hasArg("devinit")) { Device_init(); - request->send(200, "text/text", "OK"); + request->send(200); } //-------------------------------------------------------------------------------- if (request->hasArg("scen")) { - String value = request->getParam("scen")->value(); - if (value == "0") { - jsonWriteStr(configSetupJson, "scen", value); - saveConfig(); - loadScenario(); - } - if (value == "1") { - jsonWriteStr(configSetupJson, "scen", value); - saveConfig(); - loadScenario(); - } - request->send(200, "text/text", "OK"); + bool value = request->getParam("scen")->value().toInt(); + jsonWriteBool(configSetupJson, "scen", value); + saveConfig(); + loadScenario(); + request->send(200); } //-------------------------------------------------------------------------------- if (request->hasArg("sceninit")) { loadScenario(); - request->send(200, "text/text", "OK"); + request->send(200); } //-------------------------------------------------------------------------------- #ifdef LOGGING_ENABLED if (request->hasArg("cleanlog")) { clean_log_date(); - request->send(200, "text/text", "OK"); + request->send(200); } #endif //==============================udp settings============================================= if (request->hasArg("udponoff")) { - String value = request->getParam("udponoff")->value(); - if (value == "0") { - jsonWriteStr(configSetupJson, "udponoff", value); - saveConfig(); - loadScenario(); - } - if (value == "1") { - jsonWriteStr(configSetupJson, "udponoff", value); - saveConfig(); - loadScenario(); - } - request->send(200, "text/text", "OK"); + bool value = request->getParam("udponoff")->value().toInt(); + jsonWriteBool(configSetupJson, "udponoff", value); + saveConfig(); + loadScenario(); + request->send(200); } //-------------------------------------------------------------------------------- if (request->hasArg("updatelist")) { @@ -93,18 +83,18 @@ void web_init() { if (request->hasArg("devname")) { jsonWriteStr(configSetupJson, "name", request->getParam("devname")->value()); saveConfig(); - request->send(200, "text/text", "OK"); + request->send(200); } //==============================wifi settings============================================= if (request->hasArg("routerssid")) { jsonWriteStr(configSetupJson, "routerssid", request->getParam("routerssid")->value()); saveConfig(); - request->send(200, "text/text", "OK"); + request->send(200); } if (request->hasArg("routerpass")) { jsonWriteStr(configSetupJson, "routerpass", request->getParam("routerpass")->value()); saveConfig(); - request->send(200, "text/text", "OK"); + request->send(200); } //-------------------------------------------------------------------------------- if (request->hasArg("apssid")) { @@ -115,18 +105,18 @@ void web_init() { if (request->hasArg("appass")) { jsonWriteStr(configSetupJson, "appass", request->getParam("appass")->value()); saveConfig(); - request->send(200, "text/text", "OK"); + request->send(200); } //-------------------------------------------------------------------------------- if (request->hasArg("weblogin")) { jsonWriteStr(configSetupJson, "weblogin", request->getParam("weblogin")->value()); saveConfig(); - request->send(200, "text/text", "OK"); + request->send(200); } if (request->hasArg("webpass")) { jsonWriteStr(configSetupJson, "webpass", request->getParam("webpass")->value()); saveConfig(); - request->send(200, "text/text", "OK"); + request->send(200); } //-------------------------------------------------------------------------------- if (request->hasArg("timezone")) { @@ -134,79 +124,69 @@ void web_init() { jsonWriteStr(configSetupJson, "timezone", timezoneStr); saveConfig(); timeNow->setTimezone(timezoneStr.toInt()); - request->send(200, "text/text", "OK"); + request->send(200); } if (request->hasArg("ntp")) { String ntpStr = request->getParam("ntp")->value(); jsonWriteStr(configSetupJson, "ntp", ntpStr); saveConfig(); timeNow->setNtpPool(ntpStr); - request->send(200, "text/text", "OK"); - } - //-------------------------------------------------------------------------------- - if (request->hasArg("device")) { - if (request->getParam("device")->value() == "ok") ESP.restart(); - request->send(200, "text/text", "OK"); + request->send(200); } //-------------------------------------------------------------------------------- if (request->hasArg("blink")) { - String value = request->getParam("blink")->value(); - if (value == "0") { - jsonWriteStr(configSetupJson, "blink", value); - saveConfig(); - } - if (value == "1") { - jsonWriteStr(configSetupJson, "blink", value); - saveConfig(); - } - request->send(200, "text/text", "OK"); + bool value = request->getParam("blink")->value().toInt(); + jsonWriteBool(configSetupJson, "blink", value); + saveConfig(); + request->send(200); } //==============================mqtt settings============================================= if (request->hasArg("mqttServer")) { jsonWriteStr(configSetupJson, "mqttServer", request->getParam("mqttServer")->value()); saveConfig(); mqttParamsChanged = true; - request->send(200, "text/text", "ok"); + request->send(200); } if (request->hasArg("mqttPort")) { int port = (request->getParam("mqttPort")->value()).toInt(); jsonWriteInt(configSetupJson, "mqttPort", port); saveConfig(); mqttParamsChanged = true; - request->send(200, "text/text", "ok"); + request->send(200); } if (request->hasArg("mqttPrefix")) { jsonWriteStr(configSetupJson, "mqttPrefix", request->getParam("mqttPrefix")->value()); saveConfig(); mqttParamsChanged = true; - request->send(200, "text/text", "ok"); + request->send(200); } if (request->hasArg("mqttUser")) { jsonWriteStr(configSetupJson, "mqttUser", request->getParam("mqttUser")->value()); saveConfig(); mqttParamsChanged = true; - request->send(200, "text/text", "ok"); + request->send(200); } if (request->hasArg("mqttPass")) { jsonWriteStr(configSetupJson, "mqttPass", request->getParam("mqttPass")->value()); saveConfig(); mqttParamsChanged = true; - request->send(200, "text/text", "ok"); + request->send(200); } //-------------------------------------------------------------------------------- if (request->hasArg("mqttsend")) { mqtt_send_settings_to_udp = true; - request->send(200, "text/text", "ok"); + request->send(200); } + //-------------------------------------------------------------------------------- - if (request->hasArg("mqttcheck")) { - String buf = "{}"; - String payload = "" + MqttClient::getStateStr(); - jsonWriteStr(buf, "title", payload); - jsonWriteStr(buf, "class", "pop-up"); + String buf = "" + MqttClient::getStateStr(); - request->send(200, "text/text", buf); + String payload = "{}"; + jsonWriteStr(payload, "title", buf); + jsonWriteStr(payload, "class", "pop-up"); + + request->send(200, "text/html", payload); } //==============================push settings============================================= @@ -214,96 +194,68 @@ void web_init() { if (request->hasArg("pushingboxid")) { jsonWriteStr(configSetupJson, "pushingboxid", request->getParam("pushingboxid")->value()); saveConfig(); - request->send(200, "text/text", "ok"); + request->send(200); } #endif + //==============================utilities settings============================================= - if (request->hasArg("itoc")) { + if (request->hasArg(TAG_I2C)) { busScanFlag = true; busToScan = BS_I2C; request->redirect("/?set.utilities"); - } - - if (request->hasArg("onewire")) { + } else if (request->hasArg(TAG_ONE_WIRE)) { busScanFlag = true; busToScan = BS_ONE_WIRE; + if (request->hasParam(TAG_ONE_WIRE_PIN)) { + setConfigParam(TAG_ONE_WIRE_PIN, request->getParam(TAG_ONE_WIRE_PIN)->value()); + } request->redirect("/?set.utilities"); - } - - if (request->hasArg("fscheck")) { - fsCheckFlag = true; - request->redirect("/?set.utilities"); + } else if (request->hasArg(TAG_ONE_WIRE_PIN)) { + setConfigParam(TAG_ONE_WIRE_PIN, request->getParam(TAG_ONE_WIRE_PIN)->value()); + request->send(200); } }); - //==============================upgrade settings============================================= - server.on("/check", HTTP_GET, [](AsyncWebServerRequest* request) { - upgrade_url = true; - pm.info("firmware version: " + lastVersion); - String tmp = "{}"; - int case_of_update; - if (WiFi.status() != WL_CONNECTED) { - lastVersion = "nowifi"; - } + /* + * Check + */ + server.on("/check", HTTP_GET, [](AsyncWebServerRequest* request) { + checkUpdatesFlag = true; + pm.info("firmware version: " + lastVersion); if (!FLASH_4MB) { lastVersion = "less"; + } else if (isNetworkActive()) { + lastVersion = "nowifi"; } - if (lastVersion == FIRMWARE_VERSION) case_of_update = 1; - if (lastVersion != FIRMWARE_VERSION) case_of_update = 2; - if (lastVersion == "error") case_of_update = 3; - if (lastVersion == "") case_of_update = 4; - if (lastVersion == "less") case_of_update = 5; - if (lastVersion == "nowifi") case_of_update = 6; - if (lastVersion == "notsupported") case_of_update = 7; - - switch (case_of_update) { - case 1: { - jsonWriteStr(tmp, "title", "Последняя версия прошивки уже установлена."); - jsonWriteStr(tmp, "class", "pop-up"); - } break; - - case 2: { - jsonWriteStr(tmp, "title", "Имеется новая версия прошивкиИдет обновление прошивки, после обновления страница перезагрузится автоматически...')\">Установить"); - jsonWriteStr(tmp, "class", "pop-up"); - } break; - - case 3: { - jsonWriteStr(tmp, "title", "Ошибка... Cервер не найден. Попробуйте позже..."); - jsonWriteStr(tmp, "class", "pop-up"); - } break; - - case 4: { - jsonWriteStr(tmp, "title", "Нажмите на кнопку \"обновить прошивку\" повторно..."); - jsonWriteStr(tmp, "class", "pop-up"); - break; - } - - case 5: { - jsonWriteStr(tmp, "title", "Обновление по воздуху не поддерживается, модуль имеет меньше 4 мб памяти..."); - jsonWriteStr(tmp, "class", "pop-up"); - break; - } - - case 6: { - jsonWriteStr(tmp, "title", "Устройство не подключено к роутеру..."); - jsonWriteStr(tmp, "class", "pop-up"); - break; - } - - case 7: { - jsonWriteStr(tmp, "title", "Обновление на новую версию возможно только через usb..."); - jsonWriteStr(tmp, "class", "pop-up"); - break; - } + String msg = ""; + if (lastVersion == FIRMWARE_VERSION) { + msg = F("Актуальная версия прошивки уже установлена."); + } else if (lastVersion != FIRMWARE_VERSION) { + msg = F("Новая версия прошивкиИдет обновление прошивки, после обновления страница перезагрузится автоматически...')\">Установить"); + } else if (lastVersion == "error") { + msg = F("Cервер не найден. Попробуйте повторить позже..."); + } else if (lastVersion == "") { + msg = F("Нажмите на кнопку \"обновить прошивку\" повторно..."); + } else if (lastVersion == "less") { + msg = F("Обновление \"по воздуху\" не поддерживается!"); + } else if (lastVersion == "nowifi") { + msg = F("Устройство не подключено к роутеру!"); + } else if (lastVersion == "notsupported") { + msg = F("Обновление возможно только через usb!"); } - request->send(200, "text/text", tmp); + String tmp = "{}"; + jsonWriteStr(tmp, "title", "" + msg); + jsonWriteStr(tmp, "class", "pop-up"); + request->send(200, "text/html", tmp); }); + /* + * Upgrade + */ server.on("/upgrade", HTTP_GET, [](AsyncWebServerRequest* request) { - upgrade = true; - String tmp = "{}"; - request->send(200, "text/text", "ok"); + updateFlag = true; + request->send(200, "text/html"); }); } \ No newline at end of file diff --git a/src/Widgets.cpp b/src/Widgets.cpp index 3acad28c..9e200c3c 100644 --- a/src/Widgets.cpp +++ b/src/Widgets.cpp @@ -16,7 +16,6 @@ bool loadWidget(const String& filename, String& buf) { void createWidget(String widget, String page, String pageNumber, String filename, String topic) { String buf = "{}"; if (!loadWidget(filename, buf)) { - pm.error("failed " + widget); return; } widget.replace("#", " "); @@ -34,7 +33,9 @@ void createWidget(String widget, String page, String pageNumber, String filename #endif } -void createWidgetParam(String widget, String page, String pageNumber, String filename, String topic, String name1, String param1, String name2, String param2, String name3, String param3) { +//TODO Вот эта процедура, и несколько оберток +void createWidgetParam(String widget, String page, String pageNumber, String filename, String topic, + String name1, String param1, String name2, String param2, String name3, String param3) { String buf = ""; if (!loadWidget(filename, buf)) { return; @@ -59,7 +60,8 @@ void createWidgetParam(String widget, String page, String pageNumber, String fil #endif } -void createChart(String widget, String page, String pageNumber, String filename, String topic, String maxCount) { +void createChart(String widget, String page, String pageNumber, String filename, String topic, + String maxCount) { String buf = ""; if (!loadWidget(filename, buf)) { return; @@ -83,11 +85,9 @@ void createChart(String widget, String page, String pageNumber, String filename, } void createWidgetByType(String widget, String page, String pageNumber, String type, String topic) { - pm.info("create" + type); createWidget(widget, page, pageNumber, getWidgetFile(type), topic); } const String getWidgetFile(const String& name) { - pm.info("get " + name); return "/widgets/" + name + ".json"; } diff --git a/src/main.cpp b/src/main.cpp index 192912fe..7dcb3b06 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,7 +1,7 @@ #include "Global.h" #include "HttpServer.h" -#include "Bus/BusScanner.h" +#include "Bus/BusScannerFactory.h" #include "Utils/Timings.h" void not_async_actions(); @@ -62,7 +62,7 @@ void setup() { #ifdef UDP_ENABLED pm.info("Broadcast UDP"); - UDP_init(); + udp_init(); #endif ts.add( TEST, 1000 * 60, [&](void*) { @@ -114,7 +114,7 @@ void not_async_actions() { getLastVersion(); - flashUpgrade(); + do_update(); #ifdef UDP_ENABLED do_udp_data_parse(); @@ -122,8 +122,6 @@ void not_async_actions() { #endif do_scan_bus(); - - do_check_fs(); } String getURL(const String& urls) { @@ -140,42 +138,22 @@ String getURL(const String& urls) { return res; } -void safeDataToFile(String data, String Folder) { - String fileName; - fileName.toLowerCase(); - fileName = deleteBeforeDelimiter(fileName, " "); - fileName.replace(" ", "."); - fileName.replace("..", "."); - fileName = Folder + "/" + fileName + ".txt"; - - jsonWriteStr(configLiveJson, "test", fileName); -} - -void sendConfig(String topic, String widgetConfig, String key, String date) { - yield(); - topic = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipId + "/" + topic + "/status"; - String outer = "{\"widgetConfig\":"; - String inner = "{\""; - inner = inner + key; - inner = inner + "\":\""; - inner = inner + date; - inner = inner + "\""; - inner = inner + "}}"; - String t = outer + inner; - yield(); -} - void setChipId() { chipId = getChipId(); - Serial.println(chipId); + pm.info("id: " + chipId); } void saveConfig() { writeFile(String("config.json"), configSetupJson); } +void setConfigParam(const char* param, const String& value) { + pm.info("set " + String(param) + ": " + value); + jsonWriteStr(configSetupJson, param, value); + saveConfig(); +} + #ifdef ESP8266 -#ifdef LED_PIN void setLedStatus(LedStatus_t status) { pinMode(LED_PIN, OUTPUT); switch (status) { @@ -197,12 +175,25 @@ void setLedStatus(LedStatus_t status) { break; } } -#endif -#endif - -void do_fscheck(String& results) { - // TODO Проверка наличие важных файлов, возможно версии ФС +#else +void setLedStatus(LedStatus_t status) { + pinMode(LED_PIN, OUTPUT); + switch (status) { + case LED_OFF: + digitalWrite(LED_PIN, HIGH); + break; + case LED_ON: + digitalWrite(LED_PIN, LOW); + break; + case LED_SLOW: + break; + case LED_FAST: + break; + default: + break; + } } +#endif void clock_init() { timeNow = new Clock(); @@ -215,21 +206,13 @@ void clock_init() { }, nullptr, true); } + void do_scan_bus() { if (busScanFlag) { String res = ""; - BusScanner* scanner = BusScannerFactory::get(res, busToScan); + BusScanner* scanner = BusScannerFactory::get(configSetupJson, busToScan, res); scanner->scan(); - jsonWriteStr(configLiveJson, BusScannerFactory::label(busToScan), res); + jsonWriteStr(configLiveJson, String(scanner->tag()), res); busScanFlag = false; } } - -void do_check_fs() { - if (fsCheckFlag) { - String buf; - do_fscheck(buf); - jsonWriteStr(configLiveJson, "fscheck", buf); - fsCheckFlag = false; - } -} diff --git a/src/udp.cpp b/src/udp.cpp index 988a99d3..5b9dc977 100644 --- a/src/udp.cpp +++ b/src/udp.cpp @@ -1,30 +1,33 @@ #include "Global.h" +static const char* MODULE = "Udp"; + #ifdef ESP8266 IPAddress udp_multicastIP(255, 255, 255, 255); -ESP8266HTTPUpdateServer httpUpdater; -WiFiUDP Udp; +WiFiUDP udp; #endif #ifdef ESP32 IPAddress udp_multicastIP(239, 255, 255, 255); AsyncUDP udp; #endif -String received_ip; -String received_udp_line; +String remote_ip; +String received; int udp_period; boolean udp_busy = false; unsigned int udp_port = 4210; +//TODO Помомему тут ошибка в define'ах void handleUdp_esp32(); + void add_dev_in_list(String fileName, String id, String dev_name, String ip); #ifdef UDP_ENABLED -void UDP_init() { +void udp_init() { removeFile("dev.csv"); addFile("dev.csv", "device id;device name;ip address"); #ifdef ESP8266 - Udp.begin(udp_port); + udp.begin(udp_port); #endif handleUdp_esp32(); @@ -34,64 +37,68 @@ void UDP_init() { ts.add( UDP, udp_period, [&](void*) { - if (jsonReadStr(configSetupJson, "udponoff") == "1") { - if (WiFi.status() == WL_CONNECTED) { - if (!udp_busy) { - String line_to_send = "iotm;" + chipId + ";" + jsonReadStr(configSetupJson, "name"); + if (jsonReadBool(configSetupJson, "udponoff") && isNetworkActive() && !udp_busy) { + pm.info("send info"); + String payload = "iotm;"; + payload += chipId; + payload += ";"; + payload += jsonReadStr(configSetupJson, "name"); #ifdef ESP8266 - Udp.beginPacketMulticast(udp_multicastIP, udp_port, WiFi.localIP()); - Udp.write(line_to_send.c_str()); - Udp.endPacket(); + udp.beginPacketMulticast(udp_multicastIP, udp_port, WiFi.localIP()); + udp.write(payload.c_str()); + udp.endPacket(); #endif #ifdef ESP32 - udp.broadcast(line_to_send.c_str()); + udp.broadcast(line_to_send.c_str()); #endif - Serial.println("[UDP<=] dev info send"); - } - } } }, nullptr, false); } +bool isUdpEnabled() { + return jsonReadBool(configSetupJson, "udponoff") && isNetworkActive(); +} + void loopUdp() { #ifdef ESP8266 - if (jsonReadStr(configSetupJson, "udponoff") == "1") { - if (WiFi.status() == WL_CONNECTED) { - int packetSize = Udp.parsePacket(); - if (packetSize) { - char udp_incomingPacket[255]; - Serial.printf("[UDP=>] Received %d bytes from %s, port %d\n", packetSize, Udp.remoteIP().toString().c_str(), Udp.remotePort()); - received_ip = Udp.remoteIP().toString(); - int len = Udp.read(udp_incomingPacket, 255); - if (len > 0) { - udp_incomingPacket[len] = 0; - } - received_udp_line = String(udp_incomingPacket); + if (!isUdpEnabled()) { + return; + } - if (received_udp_line.indexOf("iotm;") >= 0) { - udp_data_parse = true; - } - if (received_udp_line.indexOf("mqttServer") >= 0) { - udp_data_parse = true; - } - } - } + int packetSize = udp.parsePacket(); + if (!packetSize) { + return; + } + + char udp_packet[255]; + remote_ip = udp.remoteIP().toString(); + + pm.info(prettyBytes(packetSize) + " from " + remote_ip + ":" + udp.remotePort()); + + int len = udp.read(udp_packet, 255); + if (len) { + udp_packet[len] = '\x00'; + } + received = String(udp_packet); + if (received.indexOf("iotm;") >= 0 || received.indexOf("mqttServer") >= 0) { + udp_data_parse = true; } #endif + ; } void handleUdp_esp32() { #ifdef ESP32 if (udp.listenMulticast(udp_multicastIP, udp_port)) { udp.onPacket([](AsyncUDPPacket packet) { - received_udp_line = (char*)packet.data(); - received_ip = packet.remoteIP().toString(); + received = (char*)packet.data(); + remote_ip = packet.remoteIP().toString(); if (jsonReadStr(configSetupJson, "udponoff") == "1") { - if (received_udp_line.indexOf("iotm;") >= 0) { + if (received.indexOf("iotm;") >= 0) { udp_data_parse = true; } - if (received_udp_line.indexOf("mqttServer") >= 0) { + if (received.indexOf("mqttServer") >= 0) { udp_data_parse = true; } } @@ -101,25 +108,23 @@ void handleUdp_esp32() { } void do_udp_data_parse() { - if (udp_data_parse) { - udp_data_parse = false; - Serial.print("[UDP=>] " + received_ip); - Serial.print(" "); - Serial.println(received_udp_line); - if (received_udp_line.indexOf("mqttServer") >= 0) { - jsonWriteStr(configSetupJson, "mqttServer", jsonReadStr(received_udp_line, "mqttServer")); - jsonWriteInt(configSetupJson, "mqttPort", jsonReadInt(received_udp_line, "mqttPort")); - jsonWriteStr(configSetupJson, "mqttPrefix", jsonReadStr(received_udp_line, "mqttPrefix")); - jsonWriteStr(configSetupJson, "mqttUser", jsonReadStr(received_udp_line, "mqttUser")); - jsonWriteStr(configSetupJson, "mqttPass", jsonReadStr(received_udp_line, "mqttPass")); - saveConfig(); - Serial.println("[V] new mqtt setting received from udp and saved"); - mqttParamsChanged = true; - } - if (received_udp_line.indexOf("iotm;") >= 0) { - add_dev_in_list("dev.csv", selectFromMarkerToMarker(received_udp_line, ";", 1), selectFromMarkerToMarker(received_udp_line, ";", 2), received_ip); - } + if (!udp_data_parse) { + return; } + if (received.indexOf("mqttServer") >= 0) { + pm.info("received setting"); + jsonWriteStr(configSetupJson, "mqttServer", jsonReadStr(received, "mqttServer")); + jsonWriteInt(configSetupJson, "mqttPort", jsonReadInt(received, "mqttPort")); + jsonWriteStr(configSetupJson, "mqttPrefix", jsonReadStr(received, "mqttPrefix")); + jsonWriteStr(configSetupJson, "mqttUser", jsonReadStr(received, "mqttUser")); + jsonWriteStr(configSetupJson, "mqttPass", jsonReadStr(received, "mqttPass")); + saveConfig(); + mqttParamsChanged = true; + } + if (received.indexOf("iotm;") >= 0) { + add_dev_in_list("dev.csv", selectFromMarkerToMarker(received, ";", 1), selectFromMarkerToMarker(received, ";", 2), received); + } + udp_data_parse = false; } void add_dev_in_list(String filename, String id, String dev_name, String ip) { @@ -130,28 +135,26 @@ void add_dev_in_list(String filename, String id, String dev_name, String ip) { } void send_mqtt_to_udp() { - if (jsonReadStr(configSetupJson, "udponoff") == "1") { - if (WiFi.status() == WL_CONNECTED) { - udp_busy = true; - String mqtt_data = "{}"; - jsonWriteStr(mqtt_data, "mqttServer", jsonReadStr(configSetupJson, "mqttServer")); - jsonWriteInt(mqtt_data, "mqttPort", jsonReadInt(configSetupJson, "mqttPort")); - jsonWriteStr(mqtt_data, "mqttPrefix", jsonReadStr(configSetupJson, "mqttPrefix")); - jsonWriteStr(mqtt_data, "mqttUser", jsonReadStr(configSetupJson, "mqttUser")); - jsonWriteStr(mqtt_data, "mqttPass", jsonReadStr(configSetupJson, "mqttPass")); - Serial.println(mqtt_data); + if (!isUdpEnabled()) { + return; + } + udp_busy = true; + String data = "{}"; + jsonWriteStr(data, "mqttServer", jsonReadStr(configSetupJson, "mqttServer")); + jsonWriteInt(data, "mqttPort", jsonReadInt(configSetupJson, "mqttPort")); + jsonWriteStr(data, "mqttPrefix", jsonReadStr(configSetupJson, "mqttPrefix")); + jsonWriteStr(data, "mqttUser", jsonReadStr(configSetupJson, "mqttUser")); + jsonWriteStr(data, "mqttPass", jsonReadStr(configSetupJson, "mqttPass")); #ifdef ESP8266 - Udp.beginPacketMulticast(udp_multicastIP, udp_port, WiFi.localIP()); - Udp.write(mqtt_data.c_str()); - Udp.endPacket(); + udp.beginPacketMulticast(udp_multicastIP, udp_port, WiFi.localIP()); + udp.write(data.c_str()); + udp.endPacket(); #endif #ifdef ESP32 - udp.broadcast(mqtt_data.c_str()); + udp.broadcast(mqtt_data.c_str()); #endif - Serial.println("[UDP<=] mqtt info send"); - udp_busy = false; - } - } + pm.info("sent info"); + udp_busy = false; } void do_mqtt_send_settings_to_udp() { diff --git a/test/README b/test/README deleted file mode 100644 index df5066e6..00000000 --- a/test/README +++ /dev/null @@ -1,11 +0,0 @@ - -This directory is intended for PIO Unit Testing and project tests. - -Unit Testing is a software testing method by which individual units of -source code, sets of one or more MCU program modules together with associated -control data, usage procedures, and operating procedures, are tested to -determine whether they are fit for use. Unit testing finds problems early -in the development cycle. - -More information about PIO Unit Testing: -- https://docs.platformio.org/page/plus/unit-testing.html