diff --git a/Cmd.ino b/Cmd.ino index 6e1b58a1..41d8af9e 100644 --- a/Cmd.ino +++ b/Cmd.ino @@ -99,16 +99,16 @@ void button() { String start_state = sCmd.next(); String page_number = sCmd.next(); - jsonWriteStr(optionJson, "button_param" + button_number, button_param); - jsonWriteStr(configJson, "button" + button_number, start_state); + jsonWriteStr(configOptionJson, "button_param" + button_number, button_param); + jsonWriteStr(configLiveJson, "button" + button_number, start_state); if (isDigitStr (button_param)) { pinMode(button_param.toInt(), OUTPUT); digitalWrite(button_param.toInt(), start_state.toInt()); } - if (button_param == "scenario") { - jsonWriteStr(configSetup, "scenario", start_state); + if (button_param == "scen") { + jsonWriteStr(configSetupJson, "scen", start_state); Scenario_init(); saveConfig(); } @@ -133,14 +133,14 @@ void buttonSet() { String button_number = sCmd.next(); String button_state = sCmd.next(); - String button_param = jsonReadStr(optionJson, "button_param" + button_number); + String button_param = jsonReadStr(configOptionJson, "button_param" + button_number); - if (button_param != "na" || button_param != "scenario" || button_param.indexOf("line") != -1) { + if (button_param != "na" || button_param != "scen" || button_param.indexOf("line") != -1) { digitalWrite(button_param.toInt(), button_state.toInt()); } - if (button_param == "scenario") { - jsonWriteStr(configSetup, "scenario", button_state); + if (button_param == "scen") { + jsonWriteStr(configSetupJson, "scen", button_state); Scenario_init(); saveConfig(); } @@ -161,20 +161,20 @@ void buttonSet() { eventGen ("button", button_number); - jsonWriteStr(configJson, "button" + button_number, button_state); + jsonWriteStr(configLiveJson, "button" + button_number, button_state); sendSTATUS("button" + button_number, button_state); } void buttonChange() { String button_number = sCmd.next(); - String current_state = jsonReadStr(configJson, "button" + button_number); + String current_state = jsonReadStr(configLiveJson, "button" + button_number); if (current_state == "1") { current_state = "0"; } else if (current_state == "0") { current_state = "1"; } order_loop += "buttonSet " + button_number + " " + current_state + ","; - jsonWriteStr(configJson, "button" + button_number, current_state); + jsonWriteStr(configLiveJson, "button" + button_number, current_state); sendSTATUS("button" + button_number, current_state); } @@ -205,11 +205,11 @@ void pwm() { uint8_t pwm_pin_int = pwm_pin.toInt(); - jsonWriteStr(optionJson, "pwm_pin" + pwm_number, pwm_pin); + jsonWriteStr(configOptionJson, "pwm_pin" + pwm_number, pwm_pin); pinMode(pwm_pin_int, INPUT); analogWrite(pwm_pin_int, start_state.toInt()); //analogWriteFreq(32000); - jsonWriteStr(configJson, "pwm" + pwm_number, start_state); + jsonWriteStr(configLiveJson, "pwm" + pwm_number, start_state); createWidget (widget_name, page_name, page_number, "widgets/widget.range.json", "pwm" + pwm_number); } @@ -220,12 +220,12 @@ void pwmSet() { String pwm_state = sCmd.next(); int pwm_state_int = pwm_state.toInt(); - int pin = jsonReadInt(optionJson, "pwm_pin" + pwm_number); + int pin = jsonReadInt(configOptionJson, "pwm_pin" + pwm_number); analogWrite(pin, pwm_state_int); eventGen ("pwm", pwm_number); - jsonWriteStr(configJson, "pwm" + pwm_number, pwm_state); + jsonWriteStr(configLiveJson, "pwm" + pwm_number, pwm_state); sendSTATUS("pwm" + pwm_number, pwm_state); } //================================================================================================================== @@ -251,13 +251,13 @@ void handleButton() { eventGen ("switch", String(switch_number)); - jsonWriteStr(configJson, "switch" + String(switch_number), "1"); + jsonWriteStr(configLiveJson, "switch" + String(switch_number), "1"); } if (buttons[switch_number].rose()) { eventGen ("switch", String(switch_number)); - jsonWriteStr(configJson, "switch" + String(switch_number), "0"); + jsonWriteStr(configLiveJson, "switch" + String(switch_number), "0"); } } switch_number++; @@ -275,13 +275,13 @@ void inputDigit() { page_name.replace("#", " "); String start_state = sCmd.next(); String page_number = sCmd.next(); - jsonWriteStr(configJson, "digit" + number, start_state); + jsonWriteStr(configLiveJson, "digit" + number, start_state); createWidget (widget_name, page_name, page_number, "widgets/widget.inputNum.json", "digit" + number); } void digitSet() { String number = sCmd.next(); String value = sCmd.next(); - jsonWriteStr(configJson, "digit" + number, value); + jsonWriteStr(configLiveJson, "digit" + number, value); sendSTATUS("digit" + number, value); } //===================================================================================================================================== @@ -295,13 +295,13 @@ void inputTime() { page_name.replace("#", " "); String start_state = sCmd.next(); String page_number = sCmd.next(); - jsonWriteStr(configJson, "time" + number, start_state); + jsonWriteStr(configLiveJson, "time" + number, start_state); createWidget (widget_name, page_name, page_number, "widgets/widget.inputTime.json", "time" + number); } void timeSet() { String number = sCmd.next(); String value = sCmd.next(); - jsonWriteStr(configJson, "time" + number, value); + jsonWriteStr(configLiveJson, "time" + number, value); sendSTATUS("time" + number, value); } @@ -309,9 +309,9 @@ void handle_time_init() { ts.add(TIME, 1000, [&](void*) { String tmp = GetTime(); - jsonWriteStr(configJson, "time", tmp); + jsonWriteStr(configLiveJson, "time", tmp); tmp.replace(":", "-"); - jsonWriteStr(configJson, "timenow", tmp); + jsonWriteStr(configLiveJson, "timenow", tmp); eventGen ("timenow", ""); }, nullptr, true); @@ -344,7 +344,7 @@ void textSet() { text = text + " " + GetDataDigital() + " " + time; } - jsonWriteStr(configJson, "text" + number, text); + jsonWriteStr(configLiveJson, "text" + number, text); sendSTATUS("text" + number, text); } //===================================================================================================================================== @@ -356,7 +356,7 @@ void stepper() { String pin_step = sCmd.next(); String pin_dir = sCmd.next(); - jsonWriteStr(optionJson, "stepper" + stepper_number, pin_step + " " + pin_dir); + jsonWriteStr(configOptionJson, "stepper" + stepper_number, pin_step + " " + pin_dir); pinMode(pin_step.toInt(), OUTPUT); pinMode(pin_dir.toInt(), OUTPUT); } @@ -365,20 +365,20 @@ void stepper() { void stepperSet() { String stepper_number = sCmd.next(); String steps = sCmd.next(); - jsonWriteStr(optionJson, "steps" + stepper_number, steps); + jsonWriteStr(configOptionJson, "steps" + stepper_number, steps); String stepper_speed = sCmd.next(); - String pin_step = selectToMarker (jsonReadStr(optionJson, "stepper" + stepper_number), " "); - String pin_dir = deleteBeforeDelimiter (jsonReadStr(optionJson, "stepper" + stepper_number), " "); + String pin_step = selectToMarker (jsonReadStr(configOptionJson, "stepper" + stepper_number), " "); + String pin_dir = deleteBeforeDelimiter (jsonReadStr(configOptionJson, "stepper" + stepper_number), " "); Serial.println(pin_step); Serial.println(pin_dir); if (steps.toInt() > 0) digitalWrite(pin_dir.toInt(), HIGH); if (steps.toInt() < 0) digitalWrite(pin_dir.toInt(), LOW); if (stepper_number == "1") { ts.add(STEPPER1, stepper_speed.toInt(), [&](void*) { - int steps_int = abs(jsonReadInt(optionJson, "steps1") * 2); + int steps_int = abs(jsonReadInt(configOptionJson, "steps1") * 2); static int count; count++; - String pin_step = selectToMarker (jsonReadStr(optionJson, "stepper1"), " "); + String pin_step = selectToMarker (jsonReadStr(configOptionJson, "stepper1"), " "); digitalWrite(pin_step.toInt(), !digitalRead(pin_step.toInt())); yield(); if (count > steps_int) { @@ -390,10 +390,10 @@ void stepperSet() { } if (stepper_number == "2") { ts.add(STEPPER2, stepper_speed.toInt(), [&](void*) { - int steps_int = abs(jsonReadInt(optionJson, "steps2") * 2); + int steps_int = abs(jsonReadInt(configOptionJson, "steps2") * 2); static int count; count++; - String pin_step = selectToMarker (jsonReadStr(optionJson, "stepper2"), " "); + String pin_step = selectToMarker (jsonReadStr(configOptionJson, "stepper2"), " "); digitalWrite(pin_step.toInt(), !digitalRead(pin_step.toInt())); yield(); if (count > steps_int) { @@ -425,7 +425,7 @@ void servo_() { String page_number = sCmd.next(); - jsonWriteStr(optionJson, "servo_pin" + servo_number, servo_pin); + 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()); if (servo_number == "1") { @@ -450,12 +450,12 @@ void servo_() { #endif } - jsonWriteStr(optionJson, "s_min_val" + servo_number, min_value); - jsonWriteStr(optionJson, "s_max_val" + servo_number, max_value); - jsonWriteStr(optionJson, "s_min_deg" + servo_number, min_deg); - jsonWriteStr(optionJson, "s_max_deg" + servo_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); - jsonWriteStr(configJson, "servo" + servo_number, start_state); + jsonWriteStr(configLiveJson, "servo" + servo_number, start_state); createWidgetParam (widget_name, page_name, page_number, "widgets/widget.range.json", "servo" + servo_number, "min", min_value, "max", max_value, "k", "1"); } @@ -465,13 +465,13 @@ void servoSet() { String servo_state = sCmd.next(); int servo_state_int = servo_state.toInt(); - int pin = jsonReadInt(optionJson, "servo_pin" + servo_number); + int pin = jsonReadInt(configOptionJson, "servo_pin" + servo_number); servo_state_int = map(servo_state_int, - jsonReadInt(optionJson, "s_min_val" + servo_number), - jsonReadInt(optionJson, "s_max_val" + servo_number), - jsonReadInt(optionJson, "s_min_deg" + servo_number), - jsonReadInt(optionJson, "s_max_deg" + servo_number)); + 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 @@ -495,7 +495,7 @@ void servoSet() { eventGen ("servo", servo_number); - jsonWriteStr(configJson, "servo" + servo_number, servo_state); + jsonWriteStr(configLiveJson, "servo" + servo_number, servo_state); sendSTATUS("servo" + servo_number, servo_state); } #endif @@ -523,7 +523,7 @@ void mqttOrderSend() { String id = sCmd.next(); String order = sCmd.next(); - String all_line = jsonReadStr(configSetup, "mqttPrefix") + "/" + id + "/order"; + String all_line = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + id + "/order"; //Serial.print(all_line); //Serial.print("->"); //Serial.println(order); @@ -547,7 +547,7 @@ void firmware() { String widget_name = sCmd.next(); String page_name = sCmd.next(); String page_number = sCmd.next(); - jsonWriteStr(configJson, "firm1", firmware_version); + jsonWriteStr(configLiveJson, "firm1", firmware_version); choose_widget_and_create(widget_name, page_name, page_number, "any-data", "firm1"); } diff --git a/FS.ino b/FS.ino index 5b4b5ee6..54b4ec54 100644 --- a/FS.ino +++ b/FS.ino @@ -5,29 +5,29 @@ void File_system_init() { Serial.println("--------------started----------------"); //-------------------------------------------------------------- SPIFFS.begin(); - configSetup = readFile("config.json", 4096); - configSetup.replace(" ", ""); - configSetup.replace("\r\n", ""); - Serial.println(configSetup); - jsonWriteStr(configJson, "name", jsonReadStr(configSetup, "name")); - jsonWriteStr(configJson, "lang", jsonReadStr(configSetup, "lang")); + configSetupJson = readFile("config.json", 4096); + configSetupJson.replace(" ", ""); + configSetupJson.replace("\r\n", ""); + Serial.println(configSetupJson); + //jsonWriteStr(configLiveJson, "name", jsonReadStr(configSetupJson, "name")); + //jsonWriteStr(configLiveJson, "lang", jsonReadStr(configSetupJson, "lang")); #ifdef ESP32 uint32_t chipID_u = ESP.getEfuseMac(); chipID = String(chipID_u); - jsonWriteStr(configSetup, "chipID", chipID); + jsonWriteStr(configSetupJson, "chipID", chipID); #endif #ifdef ESP8266 chipID = String( ESP.getChipId() ) + "-" + String(ESP.getFlashChipId()); - jsonWriteStr(configSetup, "chipID", chipID); + jsonWriteStr(configSetupJson, "chipID", chipID); Serial.setDebugOutput(0); #endif - jsonWriteStr(configSetup, "firmware_version", firmware_version); + jsonWriteStr(configSetupJson, "firmware_version", firmware_version); - prex = jsonReadStr(configSetup, "mqttPrefix") + "/" + chipID; + prex = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipID; Serial.println(chipID); } diff --git a/Init.ino b/Init.ino index 49922054..c5dd153d 100644 --- a/Init.ino +++ b/Init.ino @@ -1,43 +1,4 @@ void All_init() { - - server.on("/init", HTTP_GET, [](AsyncWebServerRequest * request) { - String value; - if (request->hasArg("arg")) { - value = request->getParam("arg")->value(); - } - if (value == "0") { //выкл сценариев - jsonWriteStr(configSetup, "scenario", value); - saveConfig(); - Scenario_init(); - request->send(200, "text/text", "OK"); - } - if (value == "1") { //вкл сценариев - jsonWriteStr(configSetup, "scenario", value); - saveConfig(); - Scenario_init(); - request->send(200, "text/text", "OK"); - } - if (value == "2") { //инициализация - Device_init(); - request->send(200, "text/text", "OK"); - } - if (value == "3") { -#ifdef logging_enable - clean_log_date(); -#endif - request->send(200, "text/text", "OK"); - } - if (value == "4") { - Scenario_init(); - request->send(200, "text/text", "OK"); - } - if (value == "5") { - i2c_scanning = true; - request->redirect("/?utilities"); - } - }); - - prsets_init(); Device_init(); Scenario_init(); Timer_countdown_init(); @@ -86,135 +47,27 @@ void Device_init() { //-------------------------------сценарии----------------------------------------------------- void Scenario_init() { - if (jsonReadStr(configSetup, "scenario") == "1") { + if (jsonReadStr(configSetupJson, "scen") == "1") { scenario = readFile("firmware.s.txt", 2048); } } -void prsets_init() { - server.on("/preset", HTTP_GET, [](AsyncWebServerRequest * request) { - String value; - if (request->hasArg("arg")) { - value = request->getParam("arg")->value(); - } - if (value == "1") { - writeFile("firmware.c.txt", readFile("configs/relay.c.txt", 2048)); - writeFile("firmware.s.txt", readFile("configs/relay.s.txt", 2048)); - } - if (value == "2") { - writeFile("firmware.c.txt", readFile("configs/relay_t.c.txt", 2048)); - writeFile("firmware.s.txt", readFile("configs/relay_t.s.txt", 2048)); - } - if (value == "3") { - writeFile("firmware.c.txt", readFile("configs/relay_c.c.txt", 2048)); - writeFile("firmware.s.txt", readFile("configs/relay_c.s.txt", 2048)); - } - if (value == "4") { - writeFile("firmware.c.txt", readFile("configs/relay_s.c.txt", 2048)); - writeFile("firmware.s.txt", readFile("configs/relay_s.s.txt", 2048)); - } - if (value == "5") { - writeFile("firmware.c.txt", readFile("configs/relay_sw.c.txt", 2048)); - writeFile("firmware.s.txt", readFile("configs/relay_sw.s.txt", 2048)); - } - if (value == "6") { - writeFile("firmware.c.txt", readFile("configs/relay_br.c.txt", 2048)); - writeFile("firmware.s.txt", readFile("configs/relay_br.s.txt", 2048)); - } - if (value == "7") { - writeFile("firmware.c.txt", readFile("configs/relay_sr.c.txt", 2048)); - writeFile("firmware.s.txt", readFile("configs/relay_sr.s.txt", 2048)); - } - if (value == "8") { - writeFile("firmware.c.txt", readFile("configs/pwm.c.txt", 2048)); - writeFile("firmware.s.txt", readFile("configs/pwm.s.txt", 2048)); - } - if (value == "9") { - writeFile("firmware.c.txt", readFile("configs/dht11.c.txt", 2048)); - writeFile("firmware.s.txt", readFile("configs/dht11.s.txt", 2048)); - } - if (value == "10") { - writeFile("firmware.c.txt", readFile("configs/dht22.c.txt", 2048)); - writeFile("firmware.s.txt", readFile("configs/dht22.s.txt", 2048)); - } - if (value == "11") { - writeFile("firmware.c.txt", readFile("configs/analog.c.txt", 2048)); - writeFile("firmware.s.txt", readFile("configs/analog.s.txt", 2048)); - } - if (value == "12") { - writeFile("firmware.c.txt", readFile("configs/dallas.c.txt", 2048)); - writeFile("firmware.s.txt", readFile("configs/dallas.s.txt", 2048)); - } - if (value == "13") { - writeFile("firmware.c.txt", readFile("configs/termostat.c.txt", 2048)); - writeFile("firmware.s.txt", readFile("configs/termostat.s.txt", 2048)); - } - if (value == "14") { - writeFile("firmware.c.txt", readFile("configs/level.c.txt", 2048)); - writeFile("firmware.s.txt", readFile("configs/level.s.txt", 2048)); - } - if (value == "15") { - writeFile("firmware.c.txt", readFile("configs/moution_r.c.txt", 2048)); - writeFile("firmware.s.txt", readFile("configs/moution_r.s.txt", 2048)); - } - if (value == "16") { - writeFile("firmware.c.txt", readFile("configs/moution_s.c.txt", 2048)); - writeFile("firmware.s.txt", readFile("configs/moution_s.s.txt", 2048)); - } - if (value == "17") { - writeFile("firmware.c.txt", readFile("configs/stepper.c.txt", 2048)); - writeFile("firmware.s.txt", readFile("configs/stepper.s.txt", 2048)); - } - if (value == "18") { - writeFile("firmware.c.txt", readFile("configs/servo.c.txt", 2048)); - writeFile("firmware.s.txt", readFile("configs/servo.s.txt", 2048)); - } - if (value == "19") { - writeFile("firmware.c.txt", readFile("configs/firmware.c.txt", 2048)); - writeFile("firmware.s.txt", readFile("configs/firmware.s.txt", 2048)); - } - Device_init(); - Scenario_init(); - request->redirect("/?configuration"); - }); -} - -void up_time() { - uint32_t ss = millis() / 1000; - uint32_t mm = ss / 60; - uint32_t hh = mm / 60; - uint32_t dd = hh / 24; - - String out = ""; - - if (ss != 0) { - out = "[i] uptime = " + String(ss) + " sec"; - jsonWriteStr(configJson, "uptime", String(ss) + " sec"); - } - if (mm != 0) { - out = "[i] uptime = " + String(mm) + " min"; - jsonWriteStr(configJson, "uptime", String(mm) + " min"); - } - if (hh != 0) { - out = "[i] uptime = " + String(hh) + " hours"; - jsonWriteStr(configJson, "uptime", String(hh) + " hours"); - } - if (dd != 0) { - out = "[i] uptime = " + String(dd) + " days"; - jsonWriteStr(configJson, "uptime", String(dd) + " days"); - } - Serial.println(out + ", mqtt_lost_error: " + String(mqtt_lost_error) + ", wifi_lost_error: " + String(wifi_lost_error)); -} - -void statistics_init() { +void uptime_init() { + ts.add(UPTIME, 5000, [&](void*) { + handle_uptime(); + }, nullptr, true); ts.add(STATISTICS, statistics_update, [&](void*) { - - statistics(); - + handle_statistics(); }, nullptr, true); } -void statistics() { +void handle_uptime() { + if (myUpTime.check()) { + jsonWriteStr(configSetupJson, "uptime", uptime_as_string()); + } +} + +void handle_statistics() { if (WiFi.status() == WL_CONNECTED) { String urls = "http://backup.privet.lv/visitors/?"; //----------------------------------------------------------------- diff --git a/Logging.ino b/Logging.ino index 8f25bad1..0becb878 100644 --- a/Logging.ino +++ b/Logging.ino @@ -11,40 +11,40 @@ void logging() { String page_number = sCmd.next(); logging_value_names_list += value_name + ","; enter_to_logging_counter++; //считаем количество входов в эту функцию - jsonWriteStr(optionJson, value_name + "_c", maxCount); //создаем в файловой системе переменную количества точек на графике с отметкой _c что значит count + jsonWriteStr(configOptionJson, value_name + "_c", maxCount); //создаем в файловой системе переменную количества точек на графике с отметкой _c что значит count createChart (widget_name, page_name, page_number, "widgets/widget.chart.json", value_name + "_ch", maxCount); //создаем график в приложении с топиком _ch /prefix/3234045-1589487/value_name_ch if (enter_to_logging_counter == LOG1) { ts.add(LOG1, period_min.toInt() * 1000 * 60, [&](void*) { String tmp_buf_1 = selectFromMarkerToMarker(logging_value_names_list, ",", 0); - deleteOldDate("log." + tmp_buf_1 + ".txt", jsonReadInt(optionJson, tmp_buf_1 + "_c"), jsonReadStr(configJson, tmp_buf_1)); + deleteOldDate("log." + tmp_buf_1 + ".txt", jsonReadInt(configOptionJson, tmp_buf_1 + "_c"), jsonReadStr(configLiveJson, tmp_buf_1)); Serial.println("[i] LOGGING for sensor '" + tmp_buf_1 + "' done"); }, nullptr, false); } if (enter_to_logging_counter == LOG2) { ts.add(LOG2, period_min.toInt() * 1000 * 60, [&](void*) { String tmp_buf_2 = selectFromMarkerToMarker(logging_value_names_list, ",", 1); - deleteOldDate("log." + tmp_buf_2 + ".txt", jsonReadInt(optionJson, tmp_buf_2 + "_c"), jsonReadStr(configJson, tmp_buf_2)); + deleteOldDate("log." + tmp_buf_2 + ".txt", jsonReadInt(configOptionJson, tmp_buf_2 + "_c"), jsonReadStr(configLiveJson, tmp_buf_2)); Serial.println("[i] LOGGING for sensor '" + tmp_buf_2 + "' done"); }, nullptr, false); } if (enter_to_logging_counter == LOG3) { ts.add(LOG3, period_min.toInt() * 1000 * 60, [&](void*) { String tmp_buf_3 = selectFromMarkerToMarker(logging_value_names_list, ",", 2); - deleteOldDate("log." + tmp_buf_3 + ".txt", jsonReadInt(optionJson, tmp_buf_3 + "_c"), jsonReadStr(configJson, tmp_buf_3)); + deleteOldDate("log." + tmp_buf_3 + ".txt", jsonReadInt(configOptionJson, tmp_buf_3 + "_c"), jsonReadStr(configLiveJson, tmp_buf_3)); Serial.println("[i] LOGGING for sensor '" + tmp_buf_3 + "' done"); }, nullptr, false); } if (enter_to_logging_counter == LOG4) { ts.add(LOG4, period_min.toInt() * 1000 * 60, [&](void*) { String tmp_buf_4 = selectFromMarkerToMarker(logging_value_names_list, ",", 3); - deleteOldDate("log." + tmp_buf_4 + ".txt", jsonReadInt(optionJson, tmp_buf_4 + "_c"), jsonReadStr(configJson, tmp_buf_4)); + deleteOldDate("log." + tmp_buf_4 + ".txt", jsonReadInt(configOptionJson, tmp_buf_4 + "_c"), jsonReadStr(configLiveJson, tmp_buf_4)); Serial.println("[i] LOGGING for sensor '" + tmp_buf_4 + "' done"); }, nullptr, false); } if (enter_to_logging_counter == LOG5) { ts.add(LOG5, period_min.toInt() * 1000 * 60, [&](void*) { String tmp_buf_5 = selectFromMarkerToMarker(logging_value_names_list, ",", 4); - deleteOldDate("log." + tmp_buf_5 + ".txt", jsonReadInt(optionJson, tmp_buf_5 + "_c"), jsonReadStr(configJson, tmp_buf_5)); + deleteOldDate("log." + tmp_buf_5 + ".txt", jsonReadInt(configOptionJson, tmp_buf_5 + "_c"), jsonReadStr(configLiveJson, tmp_buf_5)); Serial.println("[i] LOGGING for sensor '" + tmp_buf_5 + "' done"); }, nullptr, false); } diff --git a/Scenario.ino b/Scenario.ino index 52828b79..96411b48 100644 --- a/Scenario.ino +++ b/Scenario.ino @@ -1,7 +1,7 @@ void handleScenario() { - if (jsonReadStr(configSetup, "scenario") == "1") { - if ((jsonReadStr(optionJson, "scenario_status") != "")) { + if (jsonReadStr(configSetupJson, "scen") == "1") { + if ((jsonReadStr(configOptionJson, "scenario_status") != "")) { int i = 0; String str = scenario; //читаем переменную с сценариями (то что из файла на странице) str += "\n"; @@ -17,7 +17,7 @@ void handleScenario() { //Serial.println(i); String condition = selectToMarker (tmp, "\n"); //выделяем первую строку самого сценария button1 = 1 (условие) String param_name = selectFromMarkerToMarker(condition, " " , 0); - String order = jsonReadStr(optionJson, "scenario_status"); //читаем весь файл событий + String order = jsonReadStr(configOptionJson, "scenario_status"); //читаем весь файл событий String param = selectToMarker (order, ","); //читаем первое событие из файла событий if (param_name == param) { //если поступившее событие равно событию заданному buttonSet1 в файле начинаем его обработку @@ -25,30 +25,30 @@ void handleScenario() { String value = selectFromMarkerToMarker(condition, " " , 2); //читаем значение (1) if (value.indexOf("digit") != -1) { // value = add_set(value); - value = jsonReadStr(configJson, value); + value = jsonReadStr(configLiveJson, value); } if (value.indexOf("time") != -1) { // value = add_set(value); - value = jsonReadStr(configJson, value); + value = jsonReadStr(configLiveJson, value); } boolean flag = false; //если одно из значений совпало то только тогда начинаем выполнять комнады if (sign == "=") { - if (jsonReadStr(configJson, param_name) == value) flag = true; + if (jsonReadStr(configLiveJson, param_name) == value) flag = true; } if (sign == "!=") { - if (jsonReadStr(configJson, param_name) != value) flag = true; + if (jsonReadStr(configLiveJson, param_name) != value) flag = true; } if (sign == "<") { - if (jsonReadStr(configJson, param_name).toInt() < value.toInt()) flag = true; + if (jsonReadStr(configLiveJson, param_name).toInt() < value.toInt()) flag = true; } if (sign == ">") { - if (jsonReadStr(configJson, param_name).toInt() > value.toInt()) flag = true; + if (jsonReadStr(configLiveJson, param_name).toInt() > value.toInt()) flag = true; } if (sign == ">=") { - if (jsonReadStr(configJson, param_name).toInt() >= value.toInt()) flag = true; + if (jsonReadStr(configLiveJson, param_name).toInt() >= value.toInt()) flag = true; } if (sign == "<=") { - if (jsonReadStr(configJson, param_name).toInt() <= value.toInt()) flag = true; + if (jsonReadStr(configLiveJson, param_name).toInt() <= value.toInt()) flag = true; } if (flag) { @@ -63,9 +63,9 @@ void handleScenario() { str = deleteBeforeDelimiter(str, "end\n"); //удаляем первый сценарий //----------------------------------------------------------------------------------------------------------------------- } - String tmp2 = jsonReadStr(optionJson, "scenario_status"); //читаем файл событий + String tmp2 = jsonReadStr(configOptionJson, "scenario_status"); //читаем файл событий tmp2 = deleteBeforeDelimiter(tmp2, ","); //удаляем выполненное событие - jsonWriteStr(optionJson, "scenario_status", tmp2); //записываем обновленный файл событий + jsonWriteStr(configOptionJson, "scenario_status", tmp2); //записываем обновленный файл событий i = 0; } } @@ -73,10 +73,10 @@ void handleScenario() { void eventGen (String event_name, String number) { //событие выглядит как имя плюс set плюс номер: button+Set+1 - if (jsonReadStr(configSetup, "scenario") == "1") { - String tmp = jsonReadStr(optionJson, "scenario_status") ; //генерирование события + if (jsonReadStr(configSetupJson, "scen") == "1") { + String tmp = jsonReadStr(configOptionJson, "scenario_status") ; //генерирование события //Serial.println(event_name); - jsonWriteStr(optionJson, "scenario_status", tmp + event_name + number + ","); + jsonWriteStr(configOptionJson, "scenario_status", tmp + event_name + number + ","); } } diff --git a/Sensors.ino b/Sensors.ino index 6f234457..81f58aad 100644 --- a/Sensors.ino +++ b/Sensors.ino @@ -57,10 +57,10 @@ void level() { String full_level = sCmd.next(); String page_number = sCmd.next(); level_value_name = value_name; - jsonWriteStr(optionJson, "e_lev", empty_level); - jsonWriteStr(optionJson, "f_lev", full_level); - jsonWriteStr(optionJson, "trig", trig); - jsonWriteStr(optionJson, "echo", echo); + jsonWriteStr(configOptionJson, "e_lev", empty_level); + jsonWriteStr(configOptionJson, "f_lev", full_level); + jsonWriteStr(configOptionJson, "trig", trig); + jsonWriteStr(configOptionJson, "echo", echo); pinMode(trig.toInt(), OUTPUT); pinMode(echo.toInt(), INPUT); choose_widget_and_create(widget_name, page_name, page_number, type, value_name); @@ -72,8 +72,8 @@ void level_reading() { int distance_cm; int level; static int counter; - int trig = jsonReadInt(optionJson, "trig"); - int echo = jsonReadInt(optionJson, "echo"); + int trig = jsonReadInt(configOptionJson, "trig"); + int echo = jsonReadInt(configOptionJson, "echo"); digitalWrite(trig, LOW); delayMicroseconds(2); digitalWrite(trig, HIGH); @@ -86,9 +86,9 @@ void level_reading() { if (counter > tank_level_times_to_send) { counter = 0; level = map(distance_cm, - jsonReadInt(optionJson, "e_lev"), - jsonReadInt(optionJson, "f_lev"), 0, 100); - jsonWriteInt(configJson, level_value_name, level); + jsonReadInt(configOptionJson, "e_lev"), + jsonReadInt(configOptionJson, "f_lev"), 0, 100); + jsonWriteInt(configLiveJson, level_value_name, level); eventGen (level_value_name, ""); sendSTATUS(level_value_name, String(level)); Serial.println("[i] sensor '" + level_value_name + "' data: " + String(level)); @@ -112,10 +112,10 @@ void analog() { String page_number = sCmd.next(); analog_value_names_list += value_name + ","; enter_to_analog_counter++; - jsonWriteStr(optionJson, value_name + "_st", analog_start); - jsonWriteStr(optionJson, value_name + "_end", analog_end); - jsonWriteStr(optionJson, value_name + "_st_out", analog_start_out); - jsonWriteStr(optionJson, value_name + "_end_out", analog_end_out); + jsonWriteStr(configOptionJson, value_name + "_st", analog_start); + jsonWriteStr(configOptionJson, value_name + "_end", analog_end); + jsonWriteStr(configOptionJson, value_name + "_st_out", analog_start_out); + jsonWriteStr(configOptionJson, value_name + "_end_out", analog_end_out); choose_widget_and_create(widget_name, page_name, page_number, type, value_name); if (enter_to_analog_counter == 1) { sensors_reading_map[1] = 1; @@ -134,11 +134,11 @@ void analog_reading1() { int analog_in = analogRead(A0); #endif int analog = map(analog_in, - jsonReadInt(optionJson, value_name + "_st") , - jsonReadInt(optionJson, value_name + "_end"), - jsonReadInt(optionJson, value_name + "_st_out"), - jsonReadInt(optionJson, value_name + "_end_out")); - jsonWriteInt(configJson, value_name, analog); + jsonReadInt(configOptionJson, value_name + "_st") , + jsonReadInt(configOptionJson, value_name + "_end"), + jsonReadInt(configOptionJson, value_name + "_st_out"), + jsonReadInt(configOptionJson, value_name + "_end_out")); + jsonWriteInt(configLiveJson, value_name, analog); eventGen (value_name, ""); sendSTATUS(value_name, String(analog)); Serial.println("[i] sensor '" + value_name + "' data: " + String(analog)); @@ -153,11 +153,11 @@ void analog_reading2() { int analog_in = analogRead(A0); #endif int analog = map(analog_in, - jsonReadInt(optionJson, value_name + "_st") , - jsonReadInt(optionJson, value_name + "_end"), - jsonReadInt(optionJson, value_name + "_st_out"), - jsonReadInt(optionJson, value_name + "_end_out")); - jsonWriteInt(configJson, value_name, analog); + jsonReadInt(configOptionJson, value_name + "_st") , + jsonReadInt(configOptionJson, value_name + "_end"), + jsonReadInt(configOptionJson, value_name + "_st_out"), + jsonReadInt(configOptionJson, value_name + "_end_out")); + jsonWriteInt(configLiveJson, value_name, analog); eventGen (value_name, ""); sendSTATUS(value_name, String(analog)); Serial.println("[i] sensor '" + value_name + "' data: " + String(analog)); @@ -186,7 +186,7 @@ void dallas_reading() { float temp = 0; sensors.requestTemperatures(); temp = sensors.getTempCByIndex(0); - jsonWriteStr(configJson, "dallas", String(temp)); + jsonWriteStr(configLiveJson, "dallas", String(temp)); eventGen ("dallas", ""); sendSTATUS("dallas", String(temp)); Serial.println("[i] sensor 'dallas' send date " + String(temp)); @@ -226,7 +226,7 @@ void dhtT_reading() { value = dht.getTemperature(); if (String(value) != "nan") { eventGen (dhtT_value_name, ""); - jsonWriteStr(configJson, dhtT_value_name, String(value)); + jsonWriteStr(configLiveJson, dhtT_value_name, String(value)); sendSTATUS(dhtT_value_name, String(value)); Serial.println("[i] sensor '" + dhtT_value_name + "' data: " + String(value)); } @@ -264,7 +264,7 @@ void dhtH_reading() { value = dht.getHumidity(); if (String(value) != "nan") { eventGen (dhtH_value_name, ""); - jsonWriteStr(configJson, dhtH_value_name, String(value)); + jsonWriteStr(configLiveJson, dhtH_value_name, String(value)); sendSTATUS(dhtH_value_name, String(value)); Serial.println("[i] sensor '" + dhtH_value_name + "' data: " + String(value)); } @@ -285,9 +285,9 @@ void dhtP_reading() { if (dht.getStatus() != 0) { sendSTATUS("dhtPerception", String(dht.getStatusString())); } else { - value = dht.computePerception(jsonReadStr(configJson, dhtT_value_name).toFloat(), jsonReadStr(configJson, dhtH_value_name).toFloat(), false); + value = dht.computePerception(jsonReadStr(configLiveJson, dhtT_value_name).toFloat(), jsonReadStr(configLiveJson, dhtH_value_name).toFloat(), false); String final_line = perception(value); - jsonWriteStr(configJson, "dhtPerception", final_line); + jsonWriteStr(configLiveJson, "dhtPerception", final_line); eventGen ("dhtPerception", ""); sendSTATUS("dhtPerception", final_line); if (client_mqtt.connected()) { @@ -322,9 +322,9 @@ void dhtC_reading() { if (dht.getStatus() != 0) { sendSTATUS("dhtComfort", String(dht.getStatusString())); } else { - value = dht.getComfortRatio(cf, jsonReadStr(configJson, dhtT_value_name).toFloat(), jsonReadStr(configJson, dhtH_value_name).toFloat(), false); + value = dht.getComfortRatio(cf, jsonReadStr(configLiveJson, dhtT_value_name).toFloat(), jsonReadStr(configLiveJson, dhtH_value_name).toFloat(), false); String final_line = get_comfort_status(cf); - jsonWriteStr(configJson, "dhtComfort", final_line); + jsonWriteStr(configLiveJson, "dhtComfort", final_line); eventGen ("dhtComfort", ""); sendSTATUS("dhtComfort", final_line); Serial.println("[i] sensor 'dhtComfort' send date " + final_line); @@ -383,8 +383,8 @@ void dhtD_reading() { if (dht.getStatus() != 0) { sendSTATUS("dhtDewpoint", String(dht.getStatusString())); } else { - value = dht.computeDewPoint(jsonReadStr(configJson, dhtT_value_name).toFloat(), jsonReadStr(configJson, dhtH_value_name).toFloat(), false); - jsonWriteInt(configJson, "dhtDewpoint", value); + value = dht.computeDewPoint(jsonReadStr(configLiveJson, dhtT_value_name).toFloat(), jsonReadStr(configLiveJson, dhtH_value_name).toFloat(), false); + jsonWriteInt(configLiveJson, "dhtDewpoint", value); eventGen ("dhtDewpoint", ""); sendSTATUS("dhtDewpoint", String(value)); Serial.println("[i] sensor 'dhtDewpoint' data: " + String(value)); @@ -420,7 +420,7 @@ void bmp280T_rading() { sensors_event_t temp_event, pressure_event; bmp_temp->getEvent(&temp_event); value = temp_event.temperature; - jsonWriteStr(configJson, bmp280T_value_name, String(value)); + jsonWriteStr(configLiveJson, bmp280T_value_name, String(value)); eventGen(bmp280T_value_name, ""); sendSTATUS(bmp280T_value_name, String(value)); Serial.println("[i] sensor '" + bmp280T_value_name + "' data: " + String(value)); @@ -452,7 +452,7 @@ void bmp280P_reading() { bmp_pressure->getEvent(&pressure_event); value = pressure_event.pressure; value = value / 1.333224; - jsonWriteStr(configJson, bmp280P_value_name, String(value)); + jsonWriteStr(configLiveJson, bmp280P_value_name, String(value)); eventGen(bmp280P_value_name, ""); sendSTATUS(bmp280P_value_name, String(value)); Serial.println("[i] sensor '" + bmp280P_value_name + "' data: " + String(value)); @@ -478,7 +478,7 @@ void bme280T() { void bme280T_reading() { float value = 0; value = bme.readTemperature(); - jsonWriteStr(configJson, bme280T_value_name, String(value)); + jsonWriteStr(configLiveJson, bme280T_value_name, String(value)); eventGen(bme280T_value_name, ""); sendSTATUS(bme280T_value_name, String(value)); Serial.println("[i] sensor '" + bme280T_value_name + "' data: " + String(value)); @@ -502,7 +502,7 @@ void bme280P_reading() { float value = 0; value = bme.readPressure(); value = value / 1.333224; - jsonWriteStr(configJson, bme280P_value_name, String(value)); + jsonWriteStr(configLiveJson, bme280P_value_name, String(value)); eventGen(bme280P_value_name, ""); sendSTATUS(bme280P_value_name, String(value)); Serial.println("[i] sensor '" + bme280P_value_name + "' data: " + String(value)); @@ -525,7 +525,7 @@ void bme280H() { void bme280H_reading() { float value = 0; value = bme.readHumidity(); - jsonWriteStr(configJson, bme280H_value_name, String(value)); + jsonWriteStr(configLiveJson, bme280H_value_name, String(value)); eventGen(bme280H_value_name, ""); sendSTATUS(bme280H_value_name, String(value)); Serial.println("[i] sensor '" + bme280H_value_name + "' data: " + String(value)); @@ -548,7 +548,7 @@ void bme280A() { void bme280A_reading() { float value = 0; value = bme.readAltitude(1013.25); - jsonWriteStr(configJson, bme280A_value_name, String(value)); + jsonWriteStr(configLiveJson, bme280A_value_name, String(value)); eventGen(bme280A_value_name, ""); sendSTATUS(bme280A_value_name, String(value)); Serial.println("[i] sensor '" + bme280A_value_name + "' data: " + String(value)); diff --git a/Time.ino b/Time.ino index 365d40e4..6eb6d43e 100644 --- a/Time.ino +++ b/Time.ino @@ -1,16 +1,4 @@ void Time_Init() { - server.on("/time", HTTP_GET, [](AsyncWebServerRequest * request) { - if (request->hasArg("timezone")) { - jsonWriteStr(configSetup, "timezone", request->getParam("timezone")->value()); - } - if (request->hasArg("ntp")) { - jsonWriteStr(configSetup, "ntp", request->getParam("ntp")->value()); - } - saveConfig(); - reconfigTime(); - request->send(200, "text/text", "OK"); // отправляем ответ о выполнении - }); - ts.add(TIME_SYNC, 30000, [&](void*) { time_check(); }, nullptr, true); @@ -24,11 +12,11 @@ void time_check() { } void reconfigTime() { - if (WiFi.status() == WL_CONNECTED) { - String ntp = jsonReadStr(configSetup, "ntp"); - configTime(0, 0, ntp.c_str()); + if (WiFi.status() == WL_CONNECTED) { + String ntp = jsonReadStr(configSetupJson, "ntp"); + configTime(0, 0, ntp.c_str()); int i = 0; - Serial.println("[i] Awaiting for time "); + Serial.println("[i] Awaiting for time "); #ifdef ESP32 struct tm timeinfo; while (!getLocalTime(&timeinfo) && i <= 4) { @@ -41,7 +29,7 @@ void reconfigTime() { //while (!time(nullptr) && i < 4) { // Serial.print("."); // i++; - delay(2000); + delay(2000); //} #endif if (GetTimeUnix() != "failed") { @@ -69,7 +57,7 @@ String GetTimeUnix() { // Получение текущего времени String GetTime() { time_t now = time(nullptr); // получаем время с помощью библиотеки time.h - int zone = 3600 * jsonReadStr(configSetup, "timezone").toInt(); + int zone = 3600 * jsonReadStr(configSetupJson, "timezone").toInt(); now = now + zone; String Time = ""; // Строка для результатов времени Time += ctime(&now); // Преобразуем время в строку формата Thu Jan 19 00:55:35 2017 @@ -80,7 +68,7 @@ String GetTime() { String GetTimeWOsec() { time_t now = time(nullptr); // получаем время с помощью библиотеки time.h - int zone = 3600 * jsonReadStr(configSetup, "timezone").toInt(); + int zone = 3600 * jsonReadStr(configSetupJson, "timezone").toInt(); now = now + zone; String Time = ""; // Строка для результатов времени Time += ctime(&now); // Преобразуем время в строку формата Thu Jan 19 00:55:35 2017 @@ -92,7 +80,7 @@ String GetTimeWOsec() { // Получение даты String GetDate() { time_t now = time(nullptr); // получаем время с помощью библиотеки time.h - int zone = 3600 * jsonReadStr(configSetup, "timezone").toInt(); + int zone = 3600 * jsonReadStr(configSetupJson, "timezone").toInt(); now = now + zone; String Data = ""; // Строка для результатов времени Data += ctime(&now); // Преобразуем время в строку формата Thu Jan 19 00:55:35 2017 diff --git a/Timers.ino b/Timers.ino index 941f0c0d..a744a310 100644 --- a/Timers.ino +++ b/Timers.ino @@ -4,7 +4,7 @@ void Timer_countdown_init() { ts.add(TIMER_COUNTDOWN, 1000, [&](void*) { - String old_line = jsonReadStr(optionJson, "timers"); + String old_line = jsonReadStr(configOptionJson, "timers"); if (old_line != "") { //Serial.println(old_line); int i = 0; @@ -17,7 +17,7 @@ void Timer_countdown_init() { int time = readTimer(number); if (time == 0) { delTimer (String (number)); - jsonWriteStr(configJson, "timer" + String(number), "0"); + jsonWriteStr(configLiveJson, "timer" + String(number), "0"); eventGen ("timer", String(number)); } else { time--; @@ -35,16 +35,16 @@ void timerStart() { String type = sCmd.next(); if (period_of_time.indexOf("digit") != -1) { //period_of_time = add_set(period_of_time); - period_of_time = jsonReadStr(configJson, period_of_time); + period_of_time = jsonReadStr(configLiveJson, period_of_time); } if (type == "sec") period_of_time = period_of_time; if (type == "min") period_of_time = String(period_of_time.toInt() * 60); if (type == "hours") period_of_time = String(period_of_time.toInt() * 60 * 60); addTimer(number, period_of_time); - jsonWriteStr(configJson, "timer" + number, "1"); + jsonWriteStr(configLiveJson, "timer" + number, "1"); } void addTimer(String number, String time) { - String tmp = jsonReadStr(optionJson, "timers"); //1:60,2:120, + String tmp = jsonReadStr(configOptionJson, "timers"); //1:60,2:120, String new_timer = number + ":" + time; int psn1 = tmp.indexOf(number + ":"); //0 ищем позицию таймера который надо заменить if (psn1 != -1) { //если он есть @@ -56,7 +56,7 @@ void addTimer(String number, String time) { } else { //если его нет tmp += new_timer + ","; } - jsonWriteStr(optionJson, "timers", tmp); + jsonWriteStr(configOptionJson, "timers", tmp); //Serial.println("ura"); } @@ -66,18 +66,18 @@ void timerStop() { } void delTimer (String number) { - String tmp = jsonReadStr(optionJson, "timers"); //1:60,2:120, + String tmp = jsonReadStr(configOptionJson, "timers"); //1:60,2:120, int psn1 = tmp.indexOf(number + ":"); //0 ищем позицию таймера который надо удалить if (psn1 != -1) { //если он есть int psn2 = tmp.indexOf(",", psn1); //4 от этой позиции находим позицию запятой String timer = tmp.substring(psn1, psn2) + ","; //1:60, выделяем таймер который надо удалить tmp.replace(timer, ""); //удаляем таймер - jsonWriteStr(optionJson, "timers", tmp); + jsonWriteStr(configOptionJson, "timers", tmp); } } int readTimer(int number) { - String tmp = jsonReadStr(optionJson, "timers"); //1:60,2:120, + String tmp = jsonReadStr(configOptionJson, "timers"); //1:60,2:120, int psn1 = tmp.indexOf(String(number) + ":"); //0 ищем позицию таймера который надо прочитать String timer; if (psn1 != -1) { //если он есть diff --git a/Upgrade.ino b/Upgrade.ino index f576bfe6..b5290308 100644 --- a/Upgrade.ino +++ b/Upgrade.ino @@ -1,55 +1,13 @@ void initUpgrade() { - #ifdef ESP8266 if (WiFi.status() == WL_CONNECTED) last_version = getURL("http://91.204.228.124:1100/update/esp8266/version.txt"); #endif #ifdef ESP32 if (WiFi.status() == WL_CONNECTED) last_version = getURL("http://91.204.228.124:1100/update/esp32/version.txt"); #endif - jsonWriteStr(configSetup, "last_version", last_version); + jsonWriteStr(configSetupJson, "last_version", last_version); Serial.print("[i] Last firmware version: "); Serial.println(last_version); - - server.on("/check", HTTP_GET, [](AsyncWebServerRequest * request) { - upgrade_url = true; - Serial.print("[i] Last firmware version: "); - Serial.println(last_version); - String tmp = "{}"; - if (WiFi.status() == WL_CONNECTED) { - if (mb_4_of_memory) { - if (last_version != "") { - if (last_version != "error") { - if (last_version == firmware_version) { - jsonWriteStr(tmp, "title", "Последняя версия прошивки уже установлена."); - jsonWriteStr(tmp, "class", "pop-up"); - } else { - jsonWriteStr(tmp, "title", "Имеется новая версия прошивкиИдет обновление прошивки, после обновления страница перезагрузится автоматически...')\">Установить"); - jsonWriteStr(tmp, "class", "pop-up"); - } - } else { - jsonWriteStr(tmp, "title", "Ошибка... Cервер не найден. Попробуйте позже..."); - jsonWriteStr(tmp, "class", "pop-up"); - } - } else { - jsonWriteStr(tmp, "title", "Нажмите на кнопку \"обновить прошивку\" повторно..."); - jsonWriteStr(tmp, "class", "pop-up"); - } - } else { - jsonWriteStr(tmp, "title", "Обновление по воздуху не поддерживается, модуль имеет меньше 4 мб памяти..."); - jsonWriteStr(tmp, "class", "pop-up"); - } - } else { - jsonWriteStr(tmp, "title", "Устройство не подключен к роутеру..."); - jsonWriteStr(tmp, "class", "pop-up"); - } - request->send(200, "text/text", tmp); - }); - - server.on("/upgrade", HTTP_GET, [](AsyncWebServerRequest * request) { - upgrade = true; - String tmp = "{}"; - request->send(200, "text/text", "ok"); - }); } void do_upgrade_url() { @@ -57,12 +15,11 @@ void do_upgrade_url() { upgrade_url = false; #ifdef ESP32 last_version = getURL("http://91.204.228.124:1100/update/esp32/version.txt"); - jsonWriteStr(configSetup, "last_version", last_version); #endif #ifdef ESP8266 last_version = getURL("http://91.204.228.124:1100/update/esp8266/version.txt"); - jsonWriteStr(configSetup, "last_version", last_version); #endif + jsonWriteStr(configSetupJson, "last_version", last_version); } } @@ -73,7 +30,7 @@ void upgrade_firmware() { String configSetup_for_update; scenario_for_update = readFile("firmware.s.txt", 4000); config_for_update = readFile("firmware.c.txt", 4000); - configSetup_for_update = configSetup; + configSetup_for_update = configSetupJson; Serial.println("Start upgrade SPIFFS, please wait..."); @@ -108,7 +65,7 @@ void upgrade_firmware() { #endif if (ret == HTTP_UPDATE_OK) { - + Serial.println("BUILD upgrade done!"); Serial.println("Restart ESP...."); ESP.restart(); diff --git a/Web.ino b/Web.ino new file mode 100644 index 00000000..00022fb4 --- /dev/null +++ b/Web.ino @@ -0,0 +1,352 @@ +void web_init() { + server.on("/set", HTTP_GET, [](AsyncWebServerRequest * request) { + String value; + //============================device settings===================================== + if (request->hasArg("preset")) { + //-------------------------------------------------------------------------------- + String value; + value = request->getParam("preset")->value(); + if (value == "1") { + writeFile("firmware.c.txt", readFile("configs/1-relay.c.txt", 2048)); + writeFile("firmware.s.txt", readFile("configs/1-relay.s.txt", 2048)); + } + if (value == "2") { + writeFile("firmware.c.txt", readFile("configs/2-relay.c.txt", 2048)); + writeFile("firmware.s.txt", readFile("configs/2-relay.s.txt", 2048)); + } + if (value == "3") { + writeFile("firmware.c.txt", readFile("configs/3-relay.c.txt", 2048)); + writeFile("firmware.s.txt", readFile("configs/3-relay.s.txt", 2048)); + } + if (value == "4") { + writeFile("firmware.c.txt", readFile("configs/4-relay.c.txt", 2048)); + writeFile("firmware.s.txt", readFile("configs/4-relay.s.txt", 2048)); + } + if (value == "5") { + writeFile("firmware.c.txt", readFile("configs/5-relay.c.txt", 2048)); + writeFile("firmware.s.txt", readFile("configs/5-relay.s.txt", 2048)); + } + if (value == "6") { + writeFile("firmware.c.txt", readFile("configs/6-relay.c.txt", 2048)); + writeFile("firmware.s.txt", readFile("configs/6-relay.s.txt", 2048)); + } + if (value == "7") { + writeFile("firmware.c.txt", readFile("configs/7-relay.c.txt", 2048)); + writeFile("firmware.s.txt", readFile("configs/7-relay.s.txt", 2048)); + } + if (value == "8") { + writeFile("firmware.c.txt", readFile("configs/8-pwm.c.txt", 2048)); + writeFile("firmware.s.txt", readFile("configs/8-pwm.s.txt", 2048)); + } + if (value == "9") { + writeFile("firmware.c.txt", readFile("configs/9-dht11.c.txt", 2048)); + writeFile("firmware.s.txt", readFile("configs/9-dht11.s.txt", 2048)); + } + if (value == "10") { + writeFile("firmware.c.txt", readFile("configs/10-dht22.c.txt", 2048)); + writeFile("firmware.s.txt", readFile("configs/10-dht22.s.txt", 2048)); + } + if (value == "11") { + writeFile("firmware.c.txt", readFile("configs/11-analog.c.txt", 2048)); + writeFile("firmware.s.txt", readFile("configs/11-analog.s.txt", 2048)); + } + if (value == "12") { + writeFile("firmware.c.txt", readFile("configs/12-bmp280.c.txt", 2048)); + writeFile("firmware.s.txt", readFile("configs/12-bmp280.s.txt", 2048)); + } + if (value == "13") { + writeFile("firmware.c.txt", readFile("configs/13-bme280.c.txt", 2048)); + writeFile("firmware.s.txt", readFile("configs/13-bme280.s.txt", 2048)); + } + if (value == "14") { + writeFile("firmware.c.txt", readFile("configs/14-dallas.c.txt", 2048)); + writeFile("firmware.s.txt", readFile("configs/14-dallas.s.txt", 2048)); + } + if (value == "15") { + writeFile("firmware.c.txt", readFile("configs/15-termostat.c.txt", 2048)); + writeFile("firmware.s.txt", readFile("configs/15-termostat.s.txt", 2048)); + } + if (value == "16") { + writeFile("firmware.c.txt", readFile("configs/16-level.c.txt", 2048)); + writeFile("firmware.s.txt", readFile("configs/16-level.s.txt", 2048)); + } + if (value == "17") { + writeFile("firmware.c.txt", readFile("configs/17-moution.c.txt", 2048)); + writeFile("firmware.s.txt", readFile("configs/17-moution.s.txt", 2048)); + } + if (value == "18") { + writeFile("firmware.c.txt", readFile("configs/18-moution.c.txt", 2048)); + writeFile("firmware.s.txt", readFile("configs/18-moution.s.txt", 2048)); + } + if (value == "19") { + writeFile("firmware.c.txt", readFile("configs/19-stepper.c.txt", 2048)); + writeFile("firmware.s.txt", readFile("configs/19-stepper.s.txt", 2048)); + } + if (value == "20") { + writeFile("firmware.c.txt", readFile("configs/20-servo.c.txt", 2048)); + writeFile("firmware.s.txt", readFile("configs/20-servo.s.txt", 2048)); + } + if (value == "21") { + writeFile("firmware.c.txt", readFile("configs/firmware.c.txt", 2048)); + writeFile("firmware.s.txt", readFile("configs/firmware.s.txt", 2048)); + } + Device_init(); + Scenario_init(); + request->redirect("/?set.device"); + } + //-------------------------------------------------------------------------------- + if (request->hasArg("devinit")) { + Device_init(); + request->send(200, "text/text", "OK"); + } + //-------------------------------------------------------------------------------- + if (request->hasArg("scen")) { + value = request->getParam("scen")->value(); + if (value == "0") { + jsonWriteStr(configSetupJson, "scen", value); + saveConfig(); + Scenario_init(); + } + if (value == "1") { + jsonWriteStr(configSetupJson, "scen", value); + saveConfig(); + Scenario_init(); + } + request->send(200, "text/text", "OK"); + } + //-------------------------------------------------------------------------------- + if (request->hasArg("sceninit")) { + Scenario_init(); + request->send(200, "text/text", "OK"); + } + //-------------------------------------------------------------------------------- +#ifdef logging_enable + if (request->hasArg("cleanlog")) { + clean_log_date(); + request->send(200, "text/text", "OK"); + } +#endif + //==============================udp settings============================================= + if (request->hasArg("udponoff")) { + value = request->getParam("udponoff")->value(); + if (value == "0") { + jsonWriteStr(configSetupJson, "udponoff", value); + saveConfig(); + Scenario_init(); + } + if (value == "1") { + jsonWriteStr(configSetupJson, "udponoff", value); + saveConfig(); + Scenario_init(); + } + request->send(200, "text/text", "OK"); + } + //-------------------------------------------------------------------------------- + if (request->hasArg("updatelist")) { + SPIFFS.remove("/dev.csv"); + addFile("dev.csv", "device id;device name;ip address"); + request->redirect("/?set.udp"); + } + //-------------------------------------------------------------------------------- + if (request->hasArg("updatepage")) { + request->redirect("/?set.udp"); + } + //-------------------------------------------------------------------------------- + if (request->hasArg("devname")) { + jsonWriteStr(configSetupJson, "name", request->getParam("devname")->value()); + saveConfig(); + request->send(200, "text/text", "OK"); + } + //==============================wifi settings============================================= + if (request->hasArg("routerssid")) { + jsonWriteStr(configSetupJson, "routerssid", request->getParam("routerssid")->value()); + saveConfig(); + request->send(200, "text/text", "OK"); + } + if (request->hasArg("routerpass")) { + jsonWriteStr(configSetupJson, "routerpass", request->getParam("routerpass")->value()); + saveConfig(); + request->send(200, "text/text", "OK"); + } + //-------------------------------------------------------------------------------- + if (request->hasArg("apssid")) { + jsonWriteStr(configSetupJson, "apssid", request->getParam("apssid")->value()); + saveConfig(); + request->send(200, "text/text", "OK"); + } + if (request->hasArg("appass")) { + jsonWriteStr(configSetupJson, "appass", request->getParam("appass")->value()); + saveConfig(); + request->send(200, "text/text", "OK"); + } + //-------------------------------------------------------------------------------- + if (request->hasArg("weblogin")) { + jsonWriteStr(configSetupJson, "weblogin", request->getParam("weblogin")->value()); + saveConfig(); + request->send(200, "text/text", "OK"); + } + if (request->hasArg("webpass")) { + jsonWriteStr(configSetupJson, "webpass", request->getParam("webpass")->value()); + saveConfig(); + request->send(200, "text/text", "OK"); + } + //-------------------------------------------------------------------------------- + if (request->hasArg("timezone")) { + jsonWriteStr(configSetupJson, "timezone", request->getParam("timezone")->value()); + saveConfig(); + reconfigTime(); + request->send(200, "text/text", "OK"); + } + if (request->hasArg("ntp")) { + jsonWriteStr(configSetupJson, "ntp", request->getParam("ntp")->value()); + saveConfig(); + reconfigTime(); + request->send(200, "text/text", "OK"); + } + //-------------------------------------------------------------------------------- + if (request->hasArg("device")) { + if (request->getParam("device")->value() == "ok") ESP.restart(); + request->send(200, "text/text", "OK"); + } + //-------------------------------------------------------------------------------- + if (request->hasArg("blink")) { + 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"); + } + //==============================mqtt settings============================================= + if (request->hasArg("mqttServer")) { + jsonWriteStr(configSetupJson, "mqttServer", request->getParam("mqttServer")->value()); + saveConfig(); + mqtt_connection = true; + request->send(200, "text/text", "ok"); + } + if (request->hasArg("mqttPort")) { + int port = (request->getParam("mqttPort")->value()).toInt(); + jsonWriteInt(configSetupJson, "mqttPort", port); + saveConfig(); + mqtt_connection = true; + request->send(200, "text/text", "ok"); + } + if (request->hasArg("mqttPrefix")) { + jsonWriteStr(configSetupJson, "mqttPrefix", request->getParam("mqttPrefix")->value()); + saveConfig(); + mqtt_connection = true; + request->send(200, "text/text", "ok"); + } + if (request->hasArg("mqttUser")) { + jsonWriteStr(configSetupJson, "mqttUser", request->getParam("mqttUser")->value()); + saveConfig(); + mqtt_connection = true; + request->send(200, "text/text", "ok"); + } + if (request->hasArg("mqttPass")) { + jsonWriteStr(configSetupJson, "mqttPass", request->getParam("mqttPass")->value()); + saveConfig(); + mqtt_connection = true; + request->send(200, "text/text", "ok"); + } + //-------------------------------------------------------------------------------- + if (request->hasArg("mqttsend")) { + mqtt_send_settings_to_udp = true; + request->send(200, "text/text", "ok"); + } + //-------------------------------------------------------------------------------- + if (request->hasArg("mqttcheck")) { + String tmp = "{}"; + jsonWriteStr(tmp, "title", "" + stateMQTT()); + jsonWriteStr(tmp, "class", "pop-up"); + request->send(200, "text/text", tmp); + } + //==============================push settings============================================= +#ifdef push_enable + if (request->hasArg("pushingboxid")) { + jsonWriteStr(configSetupJson, "pushingboxid", request->getParam("pushingboxid")->value()); + saveConfig(); + request->send(200, "text/text", "ok"); + } +#endif + //==============================utilities settings============================================= + if (request->hasArg("itoc")) { + i2c_scanning = true; + request->redirect("/?set.utilities"); + } + }); + //==============================upgrade settings============================================= + server.on("/check", HTTP_GET, [](AsyncWebServerRequest * request) { + upgrade_url = true; + Serial.print("[i] Last firmware version: "); + Serial.println(last_version); + String tmp = "{}"; + int case_of_update; + + if (WiFi.status() != WL_CONNECTED) last_version = "nowifi"; + if (!mb_4_of_memory) last_version = "less"; + + if (last_version == firmware_version) case_of_update = 1; + if (last_version != firmware_version) case_of_update = 2; + if (last_version == "error") case_of_update = 3; + if (last_version == "") case_of_update = 4; + if (last_version == "less") case_of_update = 5; + if (last_version == "nowifi") case_of_update = 6; + if (last_version == "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; + } + } + request->send(200, "text/text", tmp); + }); + + server.on("/upgrade", HTTP_GET, [](AsyncWebServerRequest * request) { + upgrade = true; + String tmp = "{}"; + request->send(200, "text/text", "ok"); + }); +} diff --git a/Web_server.ino b/Web_server.ino index f4e01087..b9d77cf6 100644 --- a/Web_server.ino +++ b/Web_server.ino @@ -48,9 +48,9 @@ void Web_server_init() { **************************************WEB**************************************** *********************************************************************************/ #ifdef ESP32 - server.addHandler(new SPIFFSEditor(SPIFFS, jsonReadStr(configSetup, "web_login").c_str(), jsonReadStr(configSetup, "web_pass").c_str())); + server.addHandler(new SPIFFSEditor(SPIFFS, jsonReadStr(configSetupJson, "web_login").c_str(), jsonReadStr(configSetupJson, "web_pass").c_str())); #elif defined(ESP8266) - server.addHandler(new SPIFFSEditor(jsonReadStr(configSetup, "web_login").c_str(), jsonReadStr(configSetup, "web_pass").c_str())); + server.addHandler(new SPIFFSEditor(jsonReadStr(configSetupJson, "web_login").c_str(), jsonReadStr(configSetupJson, "web_pass").c_str())); #endif /* server.on("/heap", HTTP_GET, [](AsyncWebServerRequest * request) { @@ -60,9 +60,10 @@ void Web_server_init() { server.serveStatic("/css/", SPIFFS, "/css/").setCacheControl("max-age=31536000"); server.serveStatic("/js/", SPIFFS, "/js/").setCacheControl("max-age=31536000"); server.serveStatic("/favicon.ico", SPIFFS, "/favicon.ico").setCacheControl("max-age=31536000"); + server.serveStatic("/icon.jpeg", SPIFFS, "/icon.jpeg").setCacheControl("max-age=31536000"); server.serveStatic("/", SPIFFS, "/").setDefaultFile("index.htm") - .setAuthentication(jsonReadStr(configSetup, "web_login").c_str(), jsonReadStr(configSetup, "web_pass").c_str()); + .setAuthentication(jsonReadStr(configSetupJson, "web_login").c_str(), jsonReadStr(configSetupJson, "web_pass").c_str()); server.onNotFound([](AsyncWebServerRequest * request) { Serial.printf("NOT_FOUND: "); @@ -133,15 +134,15 @@ void Web_server_init() { // --------------------Выдаем данные configJson //config.live.json - динамические данные server.on("/config.live.json", HTTP_GET, [](AsyncWebServerRequest * request) { - request->send(200, "application/json", configJson); + request->send(200, "application/json", configLiveJson); }); // --------------------Выдаем данные optionJson //config.option.json - данные не являющиеся событиями server.on("/config.option.json", HTTP_GET, [](AsyncWebServerRequest * request) { - request->send(200, "application/json", optionJson); + request->send(200, "application/json", configOptionJson); }); // -------------------Выдаем данные configSetup //config.setup.json - для хранения постоянных данных server.on("/config.setup.json", HTTP_GET, [](AsyncWebServerRequest * request) { - request->send(200, "application/json", configSetup); + request->send(200, "application/json", configSetupJson); }); // ------------------Выполнение команды из запроса diff --git a/WiFi.ino b/WiFi.ino index 501e5a8f..87eb411c 100644 --- a/WiFi.ino +++ b/WiFi.ino @@ -1,59 +1,12 @@ -void WIFI_init() { - - // --------------------Получаем ssid password со страницы - server.on("/ssid", HTTP_GET, [](AsyncWebServerRequest * request) { - if (request->hasArg("ssid")) { - jsonWriteStr(configSetup, "ssid", request->getParam("ssid")->value()); - } - if (request->hasArg("password")) { - jsonWriteStr(configSetup, "password", request->getParam("password")->value()); - } - saveConfig(); // Функция сохранения данных во Flash - request->send(200, "text/text", "OK"); // отправляем ответ о выполнении - }); - // --------------------Получаем ssidAP passwordAP со страницы - server.on("/ssidap", HTTP_GET, [](AsyncWebServerRequest * request) { - if (request->hasArg("ssidAP")) { - jsonWriteStr(configSetup, "ssidAP", request->getParam("ssidAP")->value()); - } - if (request->hasArg("passwordAP")) { - jsonWriteStr(configSetup, "passwordAP", request->getParam("passwordAP")->value()); - } - saveConfig(); // Функция сохранения данных во Flash - request->send(200, "text/text", "OK"); // отправляем ответ о выполнении - }); - - // --------------------Получаем логин и пароль для web со страницы - server.on("/web", HTTP_GET, [](AsyncWebServerRequest * request) { - if (request->hasArg("web_login")) { - jsonWriteStr(configSetup, "web_login", request->getParam("web_login")->value()); - } - if (request->hasArg("web_pass")) { - jsonWriteStr(configSetup, "web_pass", request->getParam("web_pass")->value()); - } - saveConfig(); // Функция сохранения данных во Flash - //Web_server_init(); - request->send(200, "text/text", "OK"); // отправляем ответ о выполнении - }); - - server.on("/restart", HTTP_GET, [](AsyncWebServerRequest * request) { - if (request->hasArg("device")) { - if (request->getParam("device")->value() == "ok") ESP.restart(); - } - request->send(200, "text/text", "OK"); // отправляем ответ о выполнении - }); - ROUTER_Connecting(); -} - void ROUTER_Connecting() { - - led_blink("slow"); + led_blink("slow"); + WiFi.mode(WIFI_STA); byte tries = 20; - String _ssid = jsonReadStr(configSetup, "ssid"); - String _password = jsonReadStr(configSetup, "password"); + String _ssid = jsonReadStr(configSetupJson, "routerssid"); + String _password = jsonReadStr(configSetupJson, "routerpass"); //WiFi.persistent(false); if (_ssid == "" && _password == "") { @@ -66,12 +19,11 @@ void ROUTER_Connecting() { } // Делаем проверку подключения до тех пор пока счетчик tries // не станет равен нулю или не получим подключение - while (--tries && WiFi.status() != WL_CONNECTED) - { + while (--tries && WiFi.status() != WL_CONNECTED) { if (WiFi.status() == WL_CONNECT_FAILED) { Serial.println("[E] password is not correct"); tries = 1; - jsonWriteInt(optionJson, "pass_status", 1); + jsonWriteInt(configOptionJson, "pass_status", 1); } Serial.print("."); delay(1000); @@ -93,12 +45,10 @@ void ROUTER_Connecting() { Serial.print("[V] IP address: http://"); Serial.print(WiFi.localIP()); Serial.println(""); - jsonWriteStr(configJson, "ip", WiFi.localIP().toString()); - + jsonWriteStr(configSetupJson, "ip", WiFi.localIP().toString()); led_blink("off"); - //add_dev_in_list("dev.txt", chipID, WiFi.localIP().toString()); - + MQTT_init(); } } @@ -108,26 +58,25 @@ bool StartAPMode() { WiFi.mode(WIFI_AP); - String _ssidAP = jsonReadStr(configSetup, "ssidAP"); - String _passwordAP = jsonReadStr(configSetup, "passwordAP"); + String _ssidAP = jsonReadStr(configSetupJson, "apssid"); + String _passwordAP = jsonReadStr(configSetupJson, "appass"); WiFi.softAP(_ssidAP.c_str(), _passwordAP.c_str()); IPAddress myIP = WiFi.softAPIP(); led_blink("on"); Serial.print("AP IP address: "); Serial.println(myIP); - jsonWriteStr(configJson, "ip", myIP.toString()); + jsonWriteStr(configSetupJson, "ip", myIP.toString()); - if (jsonReadInt(optionJson, "pass_status") != 1) { + //if (jsonReadInt(configOptionJson, "pass_status") != 1) { ts.add(ROUTER_SEARCHING, 10 * 1000, [&](void*) { Serial.println("->try find router"); - if (RouterFind(jsonReadStr(configSetup, "ssid"))) { + if (RouterFind(jsonReadStr(configSetupJson, "routerssid"))) { ts.remove(ROUTER_SEARCHING); WiFi.scanDelete(); ROUTER_Connecting(); - MQTT_init(); } }, nullptr, true); - } + //} return true; } @@ -182,12 +131,12 @@ boolean RouterFind(String ssid) { for (uint8_t i = 0; i < n; i++) { JsonObject& data = networks.createNestedObject(); String ssidMy = WiFi.SSID(i); - data["ssid"] = ssidMy; + data["routerssid"] = ssidMy; data["pass"] = (WiFi.encryptionType(i) == ENC_TYPE_NONE) ? "" : "*"; int8_t dbm = WiFi.RSSI(i); data["dbm"] = dbm; - if (ssidMy == jsonReadStr(configSetup, "ssid")) { - jsonWriteStr(configJson, "dbm", dbm); + if (ssidMy == jsonReadStr(configSetupJson, "routerssid")) { + jsonWriteStr(configLiveJson, "dbm", dbm); } } String root; @@ -199,14 +148,14 @@ boolean RouterFind(String ssid) { { "type":"wifi", "title":"{{LangWiFi1}}", - "name":"ssid", + "name":"routerssid", "state":"{{ssid}}", "pattern":".{1,}" }, { - "type":"password", + "type":"routerpass", "title":"{{LangPass}}", - "name":"ssidPass", + "name":"routerpass", "state":"{{ssidPass}}", "pattern":".{8,}" }, diff --git a/bus.ino b/bus.ino index 17486aab..447c5c78 100644 --- a/bus.ino +++ b/bus.ino @@ -5,10 +5,10 @@ void do_i2c_scanning() { if (tmp == "error") { tmp = i2c_scan(); Serial.println(tmp); - jsonWriteStr(configJson, "i2c", tmp); + jsonWriteStr(configLiveJson, "i2c", tmp); } else { Serial.println(tmp); - jsonWriteStr(configJson, "i2c", tmp); + jsonWriteStr(configLiveJson, "i2c", tmp); } } } diff --git a/data/config.json b/data/config.json index 180bdcd3..589bab8c 100644 --- a/data/config.json +++ b/data/config.json @@ -1,10 +1,10 @@ { "name": "IoTmanager", "chipID": "", - "ssidAP": "WiFi2", - "passwordAP": "", - "ssid": "rise", - "password": "hostel3333", + "apssid": "IoTmanager", + "appass": "", + "routerssid": "rise", + "routerpass": "hostel3333", "timezone": 2, "ntp": "pool.ntp.org", "mqttServer": "91.204.228.124", @@ -12,9 +12,10 @@ "mqttPrefix": "/rise", "mqttUser": "test", "mqttPass": "test", - "scenario": "1", - "pushingbox_id": "v7C133E426B0C69E", - "web_login": "admin", - "web_pass": "admin", - "udponoff": "1" + "scen": "1", + "pushingboxid": "v7C133E426B0C69E", + "weblogin": "admin", + "webpass": "admin", + "udponoff": "1", + "blink":"1" } \ No newline at end of file diff --git a/data/configs/relay.c.txt b/data/configs/1-relay.c.txt similarity index 100% rename from data/configs/relay.c.txt rename to data/configs/1-relay.c.txt diff --git a/data/configs/analog.s.txt b/data/configs/1-relay.s.txt similarity index 100% rename from data/configs/analog.s.txt rename to data/configs/1-relay.s.txt diff --git a/data/configs/dht22.c.txt b/data/configs/10-dht22.c.txt similarity index 100% rename from data/configs/dht22.c.txt rename to data/configs/10-dht22.c.txt diff --git a/data/configs/dallas.s.txt b/data/configs/10-dht22.s.txt similarity index 100% rename from data/configs/dallas.s.txt rename to data/configs/10-dht22.s.txt diff --git a/data/configs/analog.c.txt b/data/configs/11-analog.c.txt similarity index 100% rename from data/configs/analog.c.txt rename to data/configs/11-analog.c.txt diff --git a/data/configs/dht11.s.txt b/data/configs/11-analog.s.txt similarity index 100% rename from data/configs/dht11.s.txt rename to data/configs/11-analog.s.txt diff --git a/data/configs/12-bmp280.c.txt b/data/configs/12-bmp280.c.txt new file mode 100644 index 00000000..16956455 --- /dev/null +++ b/data/configs/12-bmp280.c.txt @@ -0,0 +1,6 @@ +bmp280T temp1 0x76 Температура#bmp280 Датчики any-data 1 +bmp280P press1 0x76 Давление#bmp280 Датчики any-data 2 +logging temp1 1 100 Температура Датчики 3 +logging press1 1 100 Давление Датчики 4 + +//Чтение и логгирование датчика bmp280. Датчик подключается к шине i2c (esp8266 - gpio 5, 4) \ No newline at end of file diff --git a/data/configs/dht22.s.txt b/data/configs/12-bmp280.s.txt similarity index 100% rename from data/configs/dht22.s.txt rename to data/configs/12-bmp280.s.txt diff --git a/data/configs/13-bme280.c.txt b/data/configs/13-bme280.c.txt new file mode 100644 index 00000000..e8414f61 --- /dev/null +++ b/data/configs/13-bme280.c.txt @@ -0,0 +1,9 @@ +bme280T temp1 0x76 Температура#bmp280 Датчики any-data 1 +bme280P pres1 0x76 Давление#bmp280 Датчики any-data 2 +bme280H hum1 0x76 Влажность#bmp280 Датчики any-data 3 +bme280A altit1 0x76 Высота#bmp280 Датчики any-data 4 +logging temp1 1 100 Температура Датчики 5 +logging press1 1 100 Давление Датчики 6 +logging hum1 1 100 Влажность Датчики 7 + +//Чтение и логгирование датчика bme280. Датчик подключается к шине i2c (esp8266 - gpio 5, 4) \ No newline at end of file diff --git a/data/configs/pwm.s.txt b/data/configs/13-bme280.s.txt similarity index 100% rename from data/configs/pwm.s.txt rename to data/configs/13-bme280.s.txt diff --git a/data/configs/dallas.c.txt b/data/configs/14-dallas.c.txt similarity index 100% rename from data/configs/dallas.c.txt rename to data/configs/14-dallas.c.txt diff --git a/data/configs/relay.s.txt b/data/configs/14-dallas.s.txt similarity index 100% rename from data/configs/relay.s.txt rename to data/configs/14-dallas.s.txt diff --git a/data/configs/termostat.c.txt b/data/configs/15-termostat.c.txt similarity index 100% rename from data/configs/termostat.c.txt rename to data/configs/15-termostat.c.txt diff --git a/data/configs/termostat.s.txt b/data/configs/15-termostat.s.txt similarity index 100% rename from data/configs/termostat.s.txt rename to data/configs/15-termostat.s.txt diff --git a/data/configs/level.c.txt b/data/configs/16-level.c.txt similarity index 100% rename from data/configs/level.c.txt rename to data/configs/16-level.c.txt diff --git a/data/configs/level.s.txt b/data/configs/16-level.s.txt similarity index 100% rename from data/configs/level.s.txt rename to data/configs/16-level.s.txt diff --git a/data/configs/moution_r.c.txt b/data/configs/17-moution.c.txt similarity index 100% rename from data/configs/moution_r.c.txt rename to data/configs/17-moution.c.txt diff --git a/data/configs/moution_r.s.txt b/data/configs/17-moution.s.txt similarity index 100% rename from data/configs/moution_r.s.txt rename to data/configs/17-moution.s.txt diff --git a/data/configs/moution_s.c.txt b/data/configs/18-moution.c.txt similarity index 100% rename from data/configs/moution_s.c.txt rename to data/configs/18-moution.c.txt diff --git a/data/configs/moution_s.s.txt b/data/configs/18-moution.s.txt similarity index 100% rename from data/configs/moution_s.s.txt rename to data/configs/18-moution.s.txt diff --git a/data/configs/stepper.c.txt b/data/configs/19-stepper.c.txt similarity index 100% rename from data/configs/stepper.c.txt rename to data/configs/19-stepper.c.txt diff --git a/data/configs/stepper.s.txt b/data/configs/19-stepper.s.txt similarity index 100% rename from data/configs/stepper.s.txt rename to data/configs/19-stepper.s.txt diff --git a/data/configs/relay_t.c.txt b/data/configs/2-relay.c.txt similarity index 100% rename from data/configs/relay_t.c.txt rename to data/configs/2-relay.c.txt diff --git a/data/configs/relay_t.s.txt b/data/configs/2-relay.s.txt similarity index 100% rename from data/configs/relay_t.s.txt rename to data/configs/2-relay.s.txt diff --git a/data/configs/servo.c.txt b/data/configs/20-servo.c.txt similarity index 100% rename from data/configs/servo.c.txt rename to data/configs/20-servo.c.txt diff --git a/data/configs/servo.s.txt b/data/configs/20-servo.s.txt similarity index 100% rename from data/configs/servo.s.txt rename to data/configs/20-servo.s.txt diff --git a/data/configs/relay_c.c.txt b/data/configs/3-relay.c.txt similarity index 100% rename from data/configs/relay_c.c.txt rename to data/configs/3-relay.c.txt diff --git a/data/configs/relay_c.s.txt b/data/configs/3-relay.s.txt similarity index 100% rename from data/configs/relay_c.s.txt rename to data/configs/3-relay.s.txt diff --git a/data/configs/relay_s.c.txt b/data/configs/4-relay.c.txt similarity index 100% rename from data/configs/relay_s.c.txt rename to data/configs/4-relay.c.txt diff --git a/data/configs/relay_s.s.txt b/data/configs/4-relay.s.txt similarity index 100% rename from data/configs/relay_s.s.txt rename to data/configs/4-relay.s.txt diff --git a/data/configs/relay_sw.c.txt b/data/configs/5-relay.c.txt similarity index 100% rename from data/configs/relay_sw.c.txt rename to data/configs/5-relay.c.txt diff --git a/data/configs/relay_sw.s.txt b/data/configs/5-relay.s.txt similarity index 100% rename from data/configs/relay_sw.s.txt rename to data/configs/5-relay.s.txt diff --git a/data/configs/relay_br.c.txt b/data/configs/6-relay.c.txt similarity index 100% rename from data/configs/relay_br.c.txt rename to data/configs/6-relay.c.txt diff --git a/data/configs/relay_br.s.txt b/data/configs/6-relay.s.txt similarity index 100% rename from data/configs/relay_br.s.txt rename to data/configs/6-relay.s.txt diff --git a/data/configs/relay_sr.c.txt b/data/configs/7-relay.c.txt similarity index 100% rename from data/configs/relay_sr.c.txt rename to data/configs/7-relay.c.txt diff --git a/data/configs/relay_sr.s.txt b/data/configs/7-relay.s.txt similarity index 100% rename from data/configs/relay_sr.s.txt rename to data/configs/7-relay.s.txt diff --git a/data/configs/pwm.c.txt b/data/configs/8-pwm.c.txt similarity index 100% rename from data/configs/pwm.c.txt rename to data/configs/8-pwm.c.txt diff --git a/data/configs/8-pwm.s.txt b/data/configs/8-pwm.s.txt new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/data/configs/8-pwm.s.txt @@ -0,0 +1 @@ + diff --git a/data/configs/dht11.c.txt b/data/configs/9-dht11.c.txt similarity index 100% rename from data/configs/dht11.c.txt rename to data/configs/9-dht11.c.txt diff --git a/data/configs/9-dht11.s.txt b/data/configs/9-dht11.s.txt new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/data/configs/9-dht11.s.txt @@ -0,0 +1 @@ + diff --git a/data/configs/relay_rm.c.txt b/data/configs/relay_rm.c.txt deleted file mode 100644 index 92abc26d..00000000 --- a/data/configs/relay_rm.c.txt +++ /dev/null @@ -1,3 +0,0 @@ -switch 1 0 10 - -//физическая кнопка номер 1 подключенная к пину 0, задержка от дребезга 10 мс \ No newline at end of file diff --git a/data/configs/relay_rm.s.txt b/data/configs/relay_rm.s.txt deleted file mode 100644 index 827e1495..00000000 --- a/data/configs/relay_rm.s.txt +++ /dev/null @@ -1,3 +0,0 @@ -switch1 = 1 -mqtt 3233662-1589489 buttonChange_1 -end \ No newline at end of file diff --git a/data/configuration.json b/data/configuration.json deleted file mode 100644 index fb4381dd..00000000 --- a/data/configuration.json +++ /dev/null @@ -1,118 +0,0 @@ -{ - "configs": [ - "/config.live.json", - "/config.setup.json", - "/config.option.json" - ], - "class": "col-sm-offset-1 col-sm-10", - "content": [ - { - "type": "h5", - "title": "{{name}}", - "class": "alert-warning" - }, - { - "type": "h4", - "title": "Device ID: {{chipID}}" - }, - { - "type": "h4", - "title": "IP address: {{ip}}" - }, - { - "type": "h4", - "title": "Uptime: {{uptime}}" - }, - { - "type": "h4", - "title": "Time: {{time}}" - }, - { - "type": "hr" - }, - { - "type": "dropdown", - "name": "help-url", - "class": "btn btn-warning btn-lg", - "style": "display:inline", - "title": { - "#": "Выбирите то, во что Вы хотите превратить это устройство ", - "/preset?arg=1": "1.Вкл. выкл. локального реле", - "/preset?arg=2": "2.Вкл. выкл. локального реле в определенное время", - "/preset?arg=3": "3.Вкл. выкл. локального реле на определенный период времени", - "/preset?arg=4": "4.Вкл. выкл. нескольких локальных реле кнопкой в приложении", - "/preset?arg=5": "5.Вкл. выкл. локального реле физической кнопкой и кнопкой в приложении параллельно (для выключателя света)", - "/preset?arg=6": "6.Вкл. выкл. нескольких удаленных реле кнопкой в приложении (нужно указать Device ID)", - "/preset?arg=7": "7.Вкл. выкл. нескольких удаленных реле физической кнопкой (нужно указать Device ID)", - "/preset?arg=8": "8.Широтно импульсная модуляция", - "/preset?arg=9": "9.Сенсор DHT11 и логгирование", - "/preset?arg=10": "10.Сенсор DHT22, DHT33, DHT44, AM2302, RHT03 и логгирование", - "/preset?arg=11": "11.Аналоговый сенсор и логгирование", - "/preset?arg=12": "12.Сенсор DS18B20 и логгирование", - "/preset?arg=13": "13.Термостат на DS18B20 с переключением в ручной режим и логгированием", - "/preset?arg=14": "14.Контроль уровня в баке на сенсорах: JSN-SR04T, HC-SR04, HY-SRF05 и логгирование (управление насосом)", - "/preset?arg=15": "15.Датчик движения включающий свет", - "/preset?arg=16": "16.Охранный датчик движения", - "/preset?arg=17": "17.Система управления шаговыми двигателями на основе драйвера A4988 (открытие закрытие штор)", - "/preset?arg=18": "18.Система управления сервоприводами", - "/preset?arg=19": "Настройки по умолчанию" - } - }, - { - "type": "h2", - "title": "Конфигурация устройства" - }, - { - "type": "file", - "state": "firmware.c.txt", - "style": "width:100%;height:400px", - "title": "Сохранить", - "action": "/init?arg=2", - "class": "btn btn-block btn-success" - }, - { - "type": "link", - "title": "Подробная инструкция", - "action": "https://github.com/DmitryBorisenko33/esp32-esp8266_iot-manager_modules_firmware/wiki/Instruction", - "class": "btn btn-block btn-primary" - }, - { - "type": "h2", - "title": "Сценарии" - }, - { - "type": "checkbox", - "name": "scenario", - "title": "Включить сценарии", - "action": "/init?arg=[[scenario]]", - "state": "{{scenario}}" - }, - { - "type": "h6", - "title": "" - }, - { - "type": "file", - "state": "firmware.s.txt", - "style": "width:100%;height:400px", - "title": "Сохранить", - "action": "/init?arg=4", - "class": "btn btn-block btn-success" - }, - { - "type": "hr" - }, - { - "type": "link", - "title": "Очистить логи сенсоров", - "action": "/init?arg=3", - "class": "btn btn-block btn-success" - }, - { - "type": "link", - "title": "Главная", - "action": "/", - "class": "btn btn-block btn-danger btn-sm" - } - ] -} \ No newline at end of file diff --git a/data/css/build.css.gz b/data/css/build.css.gz index fc58d776..4bf6e060 100644 Binary files a/data/css/build.css.gz and b/data/css/build.css.gz differ diff --git a/data/dev.json b/data/dev.json deleted file mode 100644 index 9b474644..00000000 --- a/data/dev.json +++ /dev/null @@ -1,92 +0,0 @@ -{ - "configs": [ - "/config.live.json", - "/config.setup.json" - ], - "title": "Главная", - "class": "col-sm-offset-1 col-sm-10 col-md-offset-2 col-md-8 col-lg-offset-3 col-lg-6", - "content": [ - { - "type": "h5", - "title": "{{name}}", - "class": "alert-warning" - }, - { - "type": "h3", - "title": "Список других устройств в сети:" - }, - { - "type": "hr" - }, - { - "type": "csv", - "title": [ - "html", - "html", - "html" - ], - "state": "dev.csv", - "style": "width:100%;", - "class": "nan" - }, - { - "type": "hr" - }, - { - "type": "link", - "title": "Переформировать список устройств", - "action": "udp?arg=3", - "class": "btn btn-block btn-success" - }, - { - "type": "link", - "title": "Обновить страницу", - "action": "udp?arg=4", - "class": "btn btn-block btn-success" - }, - { - "type": "hr" - }, - { - "type": "text", - "class": "alert alert-warning", - "title": "После нажатия на кнопку 'Переформировать список устройств' ждите примерно минуту, а затем обновите страницу и список появится вновь" - }, - { - "type": "h3", - "title": "Имя этого устройства:" - }, - { - "type": "input", - "title": "Имя устройства", - "name": "dev_name", - "state": "{{name}}", - "pattern": "[A-Za-z0-9]{6,12}" - }, - { - "type": "button", - "title": "Сохранить", - "action": "name?arg=[[dev_name]]", - "class": "btn btn-block btn-success" - }, - { - "type": "hr" - }, - { - "type": "checkbox", - "name": "udponoff", - "title": "Включить обмен данными между устройствами", - "action": "/udp?arg=[[udponoff]]", - "state": "{{udponoff}}" - }, - { - "type": "hr" - }, - { - "type": "link", - "title": "Главная", - "action": "/", - "class": "btn btn-block btn-danger" - } - ] -} \ No newline at end of file diff --git a/data/icon.jpeg b/data/icon.jpeg new file mode 100644 index 00000000..abdd18c0 Binary files /dev/null and b/data/icon.jpeg differ diff --git a/data/index.htm.gz b/data/index.htm.gz index 0e9eb070..139f0040 100644 Binary files a/data/index.htm.gz and b/data/index.htm.gz differ diff --git a/data/index.json b/data/index.json index 26adcc1a..1b6413ad 100644 --- a/data/index.json +++ b/data/index.json @@ -1,7 +1,8 @@ { "configs": [ "/config.live.json", - "/config.setup.json" + "/config.setup.json", + "/lang/lang.ru.json" ], "title": "Главная", "class": "col-sm-offset-1 col-sm-10 col-md-offset-2 col-md-8 col-lg-offset-3 col-lg-6", @@ -9,104 +10,60 @@ { "type": "h5", "title": "{{name}}", - "class": "alert-warning" + "class": "alert-default" }, { - "type": "h4", - "title": "Device ID: {{chipID}}" - }, - { - "type": "h4", - "title": "IP address: {{ip}}" - }, - { - "type": "h4", - "title": "Uptime: {{uptime}}" - }, - { - "type": "h4", - "title": "Time: {{time}}" - }, - { - "type": "h4", - "title": "Build version: {{firmware_version}}" - }, - { - "type": "h4", - "title": "SPIFFS version: 2.3.3" - }, - { - "type": "hr" - }, + "type": "text", + "class": "alert alert-light", + "title": "
IoT Manager
" + }, { "type": "link", "title": "Конфигурация устройства", - "action": "/?configuration", - "class": "btn btn-block btn-primary" - }, - { - "type": "hr" + "action": "/?set.device", + "class": "btn btn-block btn-default" }, { "type": "link", "title": "Список других устройств в сети", - "action": "/?dev", - "class": "btn btn-block btn-success" + "action": "/?set.udp", + "class": "btn btn-block btn-default" }, { "type": "link", "title": "Конфигурация WIFI", - "action": "/?setup", - "class": "btn btn-block btn-success" + "action": "/?set.wifi", + "class": "btn btn-block btn-default" }, { "type": "link", "title": "Конфигурация MQTT", - "action": "/?mqtt", - "class": "btn btn-block btn-success" + "action": "/?set.mqtt", + "class": "btn btn-block btn-default" }, { "type": "link", "title": "Конфигурация push", - "action": "/?pushingbox", - "class": "btn btn-block btn-success" + "action": "/?set.push", + "class": "btn btn-block btn-default" }, { "type": "link", "title": "Утилиты", - "action": "/?utilities", - "class": "btn btn-block btn-success" - }, - { - "type": "h3", - "name": "my-block", - "style": "position:fixed;top:50%;left:50%;width:400px;margin-left:-200px;text-align:center;", - "class": "hidden" - }, - { - "type": "hr" - }, - { - "type": "button", - "title": "Обновить прошивку", - "action": "/check", - "response": "[[my-block]]", - "class": "btn btn-block btn-danger" - }, - { - "type": "hr" + "action": "/?set.utilities", + "class": "btn btn-block btn-default" }, { "type": "link", "title": "Скачать приложение IoT Manager для android", "action": "https://play.google.com/store/apps/details?id=ru.esp8266.iotmanager", - "class": "btn btn-block btn-warning" + "class": "btn btn-block btn-default" }, { "type": "link", "title": "Скачать приложение IoT Manager для iphone", "action": "https://apps.apple.com/ru/app/iot-manager/id1155934877", - "class": "btn btn-block btn-warning" + "class": "btn btn-block btn-default" } ] } diff --git a/data/js/build.chart.js.gz b/data/js/build.chart.js.gz index bb94fbc9..ac021668 100644 Binary files a/data/js/build.chart.js.gz and b/data/js/build.chart.js.gz differ diff --git a/data/js/function.js.gz b/data/js/function.js.gz index 7e661ff6..443fbca2 100644 Binary files a/data/js/function.js.gz and b/data/js/function.js.gz differ diff --git a/data/lang/lang.ru.json b/data/lang/lang.ru.json new file mode 100644 index 00000000..2c089bcb --- /dev/null +++ b/data/lang/lang.ru.json @@ -0,0 +1,39 @@ +{ + "SetDevConf": "Конфигурация устройства", + "SetDevPreset": "Выберите из списка подходящий пресет кофигурации", + + "ButSave":"Сохранить", + "ButMainPage":"Главная", + + + "SetUDPList": "Список других устройств в сети:", + "SetUDPWarn1": "После нажатия на кнопку переформировать список устройств ждите примерно минуту, а затем обновите страницу и список появится вновь", + + "SetUDPUpdateList":"Переформировать список устройств", + "SetUDPUpdatePage":"Обновить страницу", + "SetUDPNameOfDev":"Имя этого устройства:", + "SetUDPDateExchange":"Включить обмен данными между устройствами", + "SetUDPWarn2":"Если обмен данными включен, то устройства будут обмениваться широковещательными пакетами udp для формирования списка устройств и для осуществления посылки настроек mqtt. Данный обмен создает дополнительную нагрузку на wifi сеть.", + + "SetWiFiNameOfDev":"Имя устройства:", + "SetWiFiRouterConnect":"Подключение к WiFi роутеру:", + "SetWiFiAccessPoint":"Точка доступа:", + "SetWiFiWeb":"Логин и пароль web interface:", + "SetWiFiTimeZone":"Временная зона:", + "SetWiFiNTP":"Сервер NTP:", + "SetWiFiWarn1":"Имя устройства должно состоять из английских букв и иметь длинну от 6 до 12 символов", + "SetWiFiWarn2":"После того как вы введете логин пароль от вашего wifi роутера необходимо нажать кнопку сохранить, а затем обязательно нажать кнопку перезагрузить устройство внизу этой страницы", + "SetWiFiWarn3":"Устройство постоянно сканирует сеть на наличие wifi. Если роутер отключен, то устройство автоматически перейдет в режим точки доступа. Когда wifi появится устройство автоматически подключится к роутеру снова, и выключит точку доступа", + "SetWiFiWarn4":"После изменения поля NTP сервер необходимо перезагрузить устройство", + "SetWiFiWarn5":"Светодиод статуса подключения показывает четыре состояния подключения:
1. мигает редко - идет подключение к wifi
2. мигает часто - идет подключение к серверу mqtt
3. горит постоянно - модуль в режиме точки доступа,
4. не горит - модуль подключен к wifi и к mqtt.
Светодиод подключен к gpio2. Если галочка стоит - то использовать этот пин нельзя", + + "SetMQTTServerName":"Имя сервера:", + "SetMQTTPort":"Номер порта:", + "SetMQTTPrefix":"Префикс:", + "SetMQTTUserName":"Имя пользователя:", + "SetMQTTPassword":"Пароль:", + + "SetMQTTSendSettings":"Отправить настройки MQTT с этого устройства на все остальные", + "SetMQTTWarn1":"Обратите внимание что поле префикс может состоять только из одного слова и одного разделителя: /prefix, вариант вида: /prefix1/prefix2 работать не будет. После изменения поля prefix необходимо перезагрузить устройство", + "SetMQTTWarn2":"Прежде чем нажимать на кнопку Отправить настройки MQTT сохрание их, если Вы их меняли. Настройки получат и перезапишут все устройства в локальной сети" +} \ No newline at end of file diff --git a/data/mqtt.json b/data/mqtt.json deleted file mode 100644 index 0bd4acc5..00000000 --- a/data/mqtt.json +++ /dev/null @@ -1,111 +0,0 @@ -{ - "configs": [ - "/config.setup.json" - ], - "class": "col-sm-offset-1 col-sm-10 col-md-offset-2 col-md-8 col-lg-offset-3 col-lg-6", - "content": [ - { - "type": "h5", - "title": "{{name}}", - "class": "alert-warning" - }, - { - "type": "text", - "class": "alert alert-warning", - "title": "Обратите внимание что поле prefix может состоять только из одного слова и одного разделителя: /prefix, вариант вида: /prefix1/prefix2 работать не будет. После изменения поля prefix необходимо перезагрузить устройство" - }, - { - "type": "h4", - "title": "Server name:" - }, - { - "type": "input", - "title": "", - "name": "1", - "state": "{{mqttServer}}" - }, - { - "type": "h4", - "title": "Port:" - }, - { - "type": "input", - "title": "", - "name": "2", - "state": "{{mqttPort}}" - }, - { - "type": "h4", - "title": "Prefix:" - }, - { - "type": "input", - "title": "", - "name": "3", - "state": "{{mqttPrefix}}" - }, - { - "type": "h4", - "title": "User name:" - }, - { - "type": "input", - "title": "", - "name": "4", - "state": "{{mqttUser}}" - }, - { - "type": "h4", - "title": "Password:" - }, - { - "type": "input", - "title": "", - "name": "5", - "state": "{{mqttPass}}" - }, - { - "type": "h3", - "name": "my-block", - "style": "position:fixed;top:30%;left:50%;width:400px;margin-left:-200px;text-align:center;", - "class": "hidden" - }, - { - "type": "text", - "class": "alert alert-warning", - "title": "Прежде чем нажимать на кнопку 'Отправить настройки MQTT' сохрание их, если Вы их меняли. Настройки получат и перезапишут все устройства в локальной сети" - }, - { - "type": "button", - "title": "Сохранить", - "action": "mqttSave?mqttServer=[[1]]&mqttPort=[[2]]&mqttPrefix=[[3]]&mqttUser=[[4]]&mqttPass=[[5]]", - "class": "btn btn-block btn-success" - }, - { - "type": "button", - "title": "Отправить настройки MQTT с этого устройства на все остальные", - "action": "udp?arg=2", - "class": "btn btn-block btn-success" - }, - - { - "type": "button", - "title": "Проверить соединение с MQTT", - "action": "mqttCheck", - "response": "[[my-block]]", - "class": "btn btn-block btn-success" - }, - { - "type": "link", - "title": "Перезагрузить устройство", - "action": "javascript:if(confirm(renameBlock(jsonResponse,'Перезагрузить?'))){send_request(this,'/restart?device=ok');}", - "class": "btn btn-block btn-success" - }, - { - "type": "link", - "title": "Главная", - "action": "/", - "class": "btn btn-block btn-danger btn-sm" - } - ] -} \ No newline at end of file diff --git a/data/pushingbox.json b/data/pushingbox.json deleted file mode 100644 index eac5a080..00000000 --- a/data/pushingbox.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "configs": [ -"/config.setup.json" - ], - "class":"col-sm-offset-1 col-sm-10 col-md-offset-2 col-md-8 col-lg-offset-3 col-lg-6", - "content": [ - { - "type": "h5", - "title": "{{name}}", - "class":"alert-warning" - }, - { - "type": "h4", - "title": "Device id:" - }, -{ - "type": "input", - "title": "", - "name":"1", - "state": "{{pushingbox_id}}" - }, - -{ - "type": "button", - "title":"Сохранить", - "action": "pushingboxDate?pushingbox_id=[[1]]", - "class": "btn btn-block btn-success", - "style": "width:100%;display:inline" - }, -{ - "type": "hr" - }, - { - "type": "link", - "title": "Перезагрузить устройство", - "action": "javascript:if(confirm(renameBlock(jsonResponse,'Перезагрузить?'))){send_request(this,'/restart?device=ok');}", - "class": "btn btn-block btn-warning" - }, - { - "type": "link", - "title": "Главная", - "action": "/", - "class": "btn btn-block btn-danger btn-sm" - } - ] -} diff --git a/data/set.device.json b/data/set.device.json new file mode 100644 index 00000000..11df7191 --- /dev/null +++ b/data/set.device.json @@ -0,0 +1,143 @@ +{ + "configs": [ + "/config.setup.json", + "/config.option.json", + "/config.live.json", + "/lang/lang.ru.json" + ], + "class": "col-sm-offset-1 col-sm-10", + "content": [ + { + "type": "h5", + "title": "{{name}}", + "class": "alert-default" + }, + { + "type": "link", + "title": "{{ButMainPage}}", + "action": "/", + "class": "btn btn-block btn-default" + }, + { + "type": "hr" + }, + { + "type": "h4", + "title": "Device ID: {{chipID}}" + }, + { + "type": "h4", + "title": "IP address: {{ip}}" + }, + { + "type": "h4", + "title": "Time: {{time}}" + }, + { + "type": "h4", + "title": "Uptime: {{uptime}}" + }, + { + "type": "h4", + "title": "Build version: {{firmware_version}}" + }, + { + "type": "h4", + "title": "SPIFFS version: 2.3.3" + }, + { + "type": "hr" + }, + { + "type": "dropdown", + "name": "help-url", + "class": "btn btn-default", + "style": "display:inline", + "title": { + "#": "{{SetDevPreset}}", + "/set?preset=1": "1.Вкл. выкл. локального реле", + "/set?preset=2": "2.Вкл. выкл. локального реле в определенное время", + "/set?preset=3": "3.Вкл. выкл. локального реле на определенный период времени", + "/set?preset=4": "4.Вкл. выкл. нескольких локальных реле кнопкой в приложении", + "/set?preset=5": "5.Вкл. выкл. локального реле физической кнопкой и кнопкой в приложении параллельно (для выключателя света)", + "/set?preset=6": "6.Вкл. выкл. нескольких удаленных реле кнопкой в приложении (нужно указать Device ID)", + "/set?preset=7": "7.Вкл. выкл. нескольких удаленных реле физической кнопкой (нужно указать Device ID)", + "/set?preset=8": "8.Широтно импульсная модуляция", + "/set?preset=9": "9.Сенсор DHT11 (темп, влажность) и логгирование", + "/set?preset=10": "10.Сенсор DHT22, DHT33, DHT44, AM2302, RHT03 (темп, влажность) и логгирование", + "/set?preset=11": "11.Аналоговый сенсор и логгирование", + "/set?preset=12": "12.Cенсор bmp280 (темп, давление) и логгирование", + "/set?preset=13": "13.Cенсор bme280 (темп, давление, влажность, высота) и логгирование", + "/set?preset=14": "12.Сенсор DS18B20 (темп) и логгирование", + "/set?preset=15": "13.Термостат на DS18B20 с переключением в ручной режим и логгированием", + "/set?preset=16": "14.Котроль уровня в баке (датчик расстояния) на сенсорах: JSN-SR04T, HC-SR04, HY-SRF05 и логгирование", + "/set?preset=17": "15.Датчик движения включающий свет", + "/set?preset=18": "16.Охранный датчик движения", + "/set?preset=19": "17.Система управления шаговыми двигателями на основе драйвера A4988 (открытие закрытие штор)", + "/set?preset=20": "18.Система управления сервоприводами", + "/set?preset=21": "Настройки по умолчанию" + } + }, + { + "type": "h2", + "title": "{{SetDevConf}}" + }, + { + "type": "file", + "state": "firmware.c.txt", + "style": "width:100%;height:350px", + "title": "Сохранить", + "action": "/set?devinit", + "class": "btn btn-block btn-default" + }, + { + "type": "h2", + "title": "Сценарии" + }, + { + "type": "checkbox", + "name": "scen", + "title": "Включить сценарии", + "action": "/set?scen=[[scen]]", + "state": "{{scen}}" + }, + { + "type": "file", + "state": "firmware.s.txt", + "style": "width:100%;height:350px", + "title": "Сохранить", + "action": "/set?sceninit", + "class": "btn btn-block btn-default" + }, + + { + "type": "link", + "title": "Инструкция к системе автоматизации", + "action": "https://github.com/DmitryBorisenko33/esp32-esp8266_iot-manager_modules_firmware/wiki/Instruction", + "class": "btn btn-block btn-default" + }, + { + "type": "link", + "title": "Очистить логи сенсоров", + "action": "/set?cleanlog", + "class": "btn btn-block btn-default" + }, + { + "type": "hr" + }, + { + "type": "h3", + "name": "my-block", + "style": "position:fixed;top:50%;left:50%;width:400px;margin-left:-200px;text-align:center;", + "class": "hidden" + }, + + { + "type": "button", + "title": "Обновить прошивку устройства", + "action": "/check", + "response": "[[my-block]]", + "class": "btn btn-block btn-default" + } + ] +} \ No newline at end of file diff --git a/data/set.mqtt.json b/data/set.mqtt.json new file mode 100644 index 00000000..a088c2dc --- /dev/null +++ b/data/set.mqtt.json @@ -0,0 +1,133 @@ +{ + "configs": [ + "/config.setup.json", + "/lang/lang.ru.json" + ], + "class": "col-sm-offset-1 col-sm-10 col-md-offset-2 col-md-8 col-lg-offset-3 col-lg-6", + "content": [ + { + "type": "h5", + "title": "{{name}}", + "class": "alert-default" + + }, + { + "type": "link", + "title": "{{ButMainPage}}", + "action": "/", + "class": "btn btn-block btn-default" + }, + { + "type": "hr" + }, + + { + "type": "h4", + "title": "{{SetMQTTServerName}}", + "style": "width:60%;float:left;" + }, + { + "type": "input", + "title": "", + "name": "mqttServer-arg", + "state": "{{mqttServer}}", + "style": "width:40%;float:right" + }, + { + "type": "h4", + "title": "{{SetMQTTPort}}", + "style": "width:60%;float:left;" + }, + { + "type": "input", + "title": "", + "name": "mqttPort-arg", + "state": "{{mqttPort}}", + "style": "width:40%;float:right" + }, + { + "type": "h4", + "title": "{{SetMQTTPrefix}}", + "style": "width:60%;float:left;" + }, + { + "type": "input", + "title": "", + "name": "mqttPrefix-arg", + "state": "{{mqttPrefix}}", + "style": "width:40%;float:right" + }, + { + "type": "h4", + "title": "{{SetMQTTUserName}}", + "style": "width:60%;float:left;" + }, + { + "type": "input", + "title": "", + "name": "mqttUser-arg", + "state": "{{mqttUser}}", + "style": "width:40%;float:right" + }, + { + "type": "h4", + "title": "{{SetMQTTPassword}}", + "style": "width:60%;float:left;" + }, + { + "type": "input", + "title": "", + "name": "mqttPass-arg", + "state": "{{mqttPass}}", + "style": "width:40%;float:right" + }, + { + "type": "h3", + "name": "my-block", + "style": "position:fixed;top:30%;left:50%;width:400px;margin-left:-200px;text-align:center;", + "class": "hidden" + }, + + { + "type": "button", + "title": "{{ButSave}}", + "style": "width:100%;float:left;", + "action": "set?mqttServer=[[mqttServer-arg]]&mqttPort=[[mqttPort-arg]]&mqttPrefix=[[mqttPrefix-arg]]&mqttUser=[[mqttUser-arg]]&mqttPass=[[mqttPass-arg]]", + "class": "btn btn-block btn-default" + }, + { + "type": "button", + "style": "width:100%;float:left;", + "title": "{{SetMQTTSendSettings}}", + "action": "set?mqttsend", + "class": "btn btn-block btn-default" + }, + + { + "type": "button", + "style": "width:100%;float:left;", + "title": "Проверить соединение с MQTT", + "action": "set?mqttcheck", + "response": "[[my-block]]", + "class": "btn btn-block btn-default" + }, + { + "type": "text", + "style": "width:100%;float:left;", + "title": "

{{SetMQTTWarn1}}

" + + }, + { + "type": "text", + "style": "width:100%;float:left;", + "title": "

{{SetMQTTWarn2}}

" + }, + { + "type": "link", + "style": "width:100%;float:left;", + "title": "Перезагрузить устройство", + "action": "javascript:if(confirm(renameBlock(jsonResponse,'Перезагрузить?'))){send_request(this,'/restart?device=ok');}", + "class": "btn btn-block btn-danger" + } + ] +} \ No newline at end of file diff --git a/data/set.push.json b/data/set.push.json new file mode 100644 index 00000000..555797e4 --- /dev/null +++ b/data/set.push.json @@ -0,0 +1,51 @@ +{ + "configs": [ + "/config.setup.json", + "/lang/lang.ru.json" + ], + "class": "col-sm-offset-1 col-sm-10 col-md-offset-2 col-md-8 col-lg-offset-3 col-lg-6", + "content": [ + { + "type": "h5", + "title": "{{name}}", + "class": "alert-default" + }, + { + "type": "link", + "title": "{{ButMainPage}}", + "action": "/", + "class": "btn btn-block btn-default" + }, + { + "type": "hr" + }, + { + "type": "h4", + "style": "width:60%;float:left;", + "title": "Device id:" + }, + { + "type": "input", + "title": "", + "name": "push-arg", + "style": "width:40%;float:right", + "state": "{{pushingboxid}}" + }, + { + "type": "button", + "title": "{{ButSave}}", + "action": "set?pushingboxid=[[push-arg]]", + "class": "btn btn-block btn-default", + "style": "width:100%;display:inline" + }, + { + "type": "hr" + }, + { + "type": "link", + "title": "Перезагрузить устройство", + "action": "javascript:if(confirm(renameBlock(jsonResponse,'Перезагрузить?'))){send_request(this,'/restart?device=ok');}", + "class": "btn btn-block btn-danger" + } + ] +} \ No newline at end of file diff --git a/data/set.udp.json b/data/set.udp.json new file mode 100644 index 00000000..6bea3042 --- /dev/null +++ b/data/set.udp.json @@ -0,0 +1,96 @@ +{ + "configs": [ + "/config.setup.json", + "/lang/lang.ru.json" + ], + "title": "Главная", + "class": "col-sm-offset-1 col-sm-10 col-md-offset-2 col-md-8 col-lg-offset-3 col-lg-6", + "content": [ + { + "type": "h5", + "title": "{{name}}", + "class": "alert-default" + }, + { + "type": "link", + "title": "{{ButMainPage}}", + "action": "/", + "class": "btn btn-block btn-default" + }, + { + "type": "hr" + }, + { + "type": "h3", + "title": "{{SetUDPList}}" + }, + { + "type": "hr" + }, + { + "type": "csv", + "title": [ + "html", + "html", + "html" + ], + "state": "dev.csv", + "style": "width:100%;", + "class": "nan" + }, + { + "type": "hr" + }, + { + "type": "link", + "title": "{{SetUDPUpdateList}}", + "action": "/set?updatelist", + "class": "btn btn-block btn-default" + }, + { + "type": "link", + "title": "{{SetUDPUpdatePage}}", + "action": "/set?updatepage", + "class": "btn btn-block btn-default" + }, + { + "type": "hr" + }, + { + "type": "text", + "title": "

{{SetUDPWarn1}}

", + "style": "width:100%;float:left;" + }, + { + "type": "h3", + "title": "{{SetUDPNameOfDev}}" + }, + { + "type": "input", + "title": "{{SetUDPNameOfDev}}", + "name": "devname-arg", + "state": "{{name}}", + "pattern": "[A-Za-z0-9]{6,12}" + }, + { + "type": "button", + "title": "{{ButSave}}", + "action": "/set?devname=[[devname-arg]]", + "class": "btn btn-block btn-default" + }, + { + "type": "hr" + }, + { + "type": "checkbox", + "name": "udponoff", + "title": "{{SetUDPDateExchange}}", + "action": "/set?udponoff=[[udponoff]]", + "state": "{{udponoff}}" + }, + { + "type": "text", + "title": "

{{SetUDPWarn2}}

" + } + ] +} \ No newline at end of file diff --git a/data/utilities.json b/data/set.utilities.json similarity index 70% rename from data/utilities.json rename to data/set.utilities.json index ee82a0c0..92769f85 100644 --- a/data/utilities.json +++ b/data/set.utilities.json @@ -1,7 +1,8 @@ { "configs": [ "/config.live.json", - "/config.setup.json" + "/config.setup.json", + "/lang/lang.ru.json" ], "title": "Главная", "class": "col-sm-offset-1 col-sm-10 col-md-offset-2 col-md-8 col-lg-offset-3 col-lg-6", @@ -9,7 +10,13 @@ { "type": "h5", "title": "{{name}}", - "class": "alert-warning" + "class": "alert-default" + }, + { + "type": "link", + "title": "{{ButMainPage}}", + "action": "/", + "class": "btn btn-block btn-default" }, { "type": "hr" @@ -25,17 +32,8 @@ { "type": "link", "title": "Сканировать", - "action": "/init?arg=5", - "class": "btn btn-block btn-success" - }, - { - "type": "hr" - }, - { - "type": "link", - "title": "Главная", - "action": "/", - "class": "btn btn-block btn-danger" + "action": "/set?itoc", + "class": "btn btn-block btn-default" } ] } \ No newline at end of file diff --git a/data/set.wifi.json b/data/set.wifi.json new file mode 100644 index 00000000..d68edc7f --- /dev/null +++ b/data/set.wifi.json @@ -0,0 +1,185 @@ +{ + "configs": [ + "/config.setup.json", + "/lang/lang.ru.json" + ], + "title": "Конфигурация", + "class": "col-sm-offset-1 col-sm-10 col-md-offset-2 col-md-8 col-lg-offset-3 col-lg-6", + "content": [ + { + "type": "h5", + "title": "{{name}}", + "class": "alert-default" + }, + { + "type": "link", + "title": "{{ButMainPage}}", + "action": "/", + "class": "btn btn-block btn-default" + }, + { + "type": "hr" + }, + { + "type": "h3", + "title": "{{SetWiFiNameOfDev}}" + }, + { + "type": "input", + "title": "{{SetWiFiNameOfDev}}", + "name": "devname-arg", + "state": "{{name}}", + "pattern": "[A-Za-z0-9]{6,12}" + }, + { + "type": "button", + "title": "{{ButSave}}", + "action": "set?devname=[[devname-arg]]", + "class": "btn btn-block btn-default" + }, + { + "type": "text", + "title": "

{{SetWiFiWarn1}}

" + }, + { + "type": "hr" + }, + { + "type": "h3", + "title": "{{SetWiFiRouterConnect}}" + }, + { + "type": "input", + "title": "", + "name": "routerssid-arg", + "state": "{{routerssid}}" + }, + { + "type": "password", + "title": "", + "name": "routerpass-arg", + "state": "{{routerpass}}" + }, + { + "type": "button", + "title": "{{ButSave}}", + "class": "btn btn-block btn-default", + "action": "set?routerssid=[[routerssid-arg]]&routerpass=[[routerpass-arg]]" + }, + { + "type": "text", + "title": "

{{SetWiFiWarn2}}

" + }, + { + "type": "hr" + }, + { + "type": "checkbox", + "name": "blink", + "title": "Включить светодиод статуса подключения", + "action": "/set?blink=[[blink]]", + "state": "{{blink}}" + }, + { + "type": "text", + "title": "

{{SetWiFiWarn5}}

" + }, + { + "type": "hr" + }, + { + "type": "h3", + "title": "{{SetWiFiAccessPoint}}" + }, + { + "type": "input", + "title": "", + "name": "apssid-arg", + "state": "{{apssid}}", + "pattern": ".{1,20}" + }, + { + "type": "password", + "title": "", + "name": "appass-arg", + "state": "{{appass}}", + "pattern": ".{8,20}" + }, + { + "type": "button", + "title": "{{ButSave}}", + "action": "set?apssid=[[apssid-arg]]&appass=[[appass-arg]]", + "class": "btn btn-block btn-default" + }, + { + "type": "text", + "title": "

{{SetWiFiWarn3}}

" + }, + { + "type": "hr" + }, + { + "type": "h3", + "title": "{{SetWiFiWeb}}" + }, + { + "type": "input", + "title": "Логин", + "name": "weblogin-arg", + "state": "{{weblogin}}", + "pattern": ".{1,20}" + }, + { + "type": "password", + "title": "Пароль", + "name": "webpass-arg", + "state": "{{webpass}}", + "pattern": ".{1,20}" + }, + { + "type": "button", + "title": "{{ButSave}}", + "action": "set?weblogin=[[weblogin-arg]]&webpass=[[webpass-arg]]", + "class": "btn btn-block btn-default" + }, + { + "type": "hr" + }, + { + "type": "h3", + "title": "{{SetWiFiTimeZone}}" + }, + { + "type": "input", + "title": "", + "name": "timezone-arg", + "state": "{{timezone}}", + "pattern": ".{1,20}" + }, + { + "type": "input", + "title": "", + "name": "ntp-arg", + "state": "{{ntp}}" + }, + { + "type": "button", + "title": "{{ButSave}}", + "action": "set?timezone=[[timezone-arg]]&ntp=[[ntp-arg]]", + "class": "btn btn-block btn-default" + }, + { + "type": "text", + "title": "

{{SetWiFiWarn4}}

" + }, + { + "type": "hr" + }, + { + "type": "link", + "title": "Перезагрузить устройство", + "action": "javascript:if(confirm(renameBlock(jsonResponse,'Перезагрузить?'))){send_request(this,'/set?device=ok');}", + "class": "btn btn-block btn-danger" + } + ] +} \ No newline at end of file diff --git a/data/setup.json b/data/setup.json deleted file mode 100644 index 18ebf108..00000000 --- a/data/setup.json +++ /dev/null @@ -1,162 +0,0 @@ -{ - "configs": [ - "/config.setup.json" - ], - "title": "Конфигурация", - "class": "col-sm-offset-1 col-sm-10 col-md-offset-2 col-md-8 col-lg-offset-3 col-lg-6", - "content": [ - { - "type": "h5", - "title": "{{name}}", - "class": "alert-warning" - }, - { - "type": "link", - "title": "Главная", - "action": "/", - "class": "btn btn-block btn-danger" - }, - { - "type": "hr" - }, - { - "type": "h2", - "title": "Имя устройства" - }, - { - "type": "input", - "title": "Имя устройства", - "name": "dev_name", - "state": "{{name}}", - "pattern": "[A-Za-z0-9]{6,12}" - }, - { - "type": "button", - "title": "Сохранить", - "action": "name?arg=[[dev_name]]", - "class": "btn btn-block btn-success" - }, - { - "type": "hr" - }, - { - "type": "h2", - "title": "Подключение к Wi-Fi роутеру" - }, - { - "type": "input", - "title": "Сеть", - "name": "ssid", - "state": "{{ssid}}" - }, - { - "type": "password", - "title": "Введите пароль", - "name": "ssidPass", - "state": "{{password}}" - }, - { - "type": "button", - "title": "Сохранить", - "class": "btn btn-block btn-success", - "action": "ssid?ssid=[[ssid]]&password=[[ssidPass]]" - }, - { - "type": "hr" - }, - { - "type": "h2", - "title": "Точка доступа" - }, - { - "type": "input", - "title": "Имя WI-FI сети", - "name": "ssidap", - "state": "{{ssidAP}}", - "pattern": ".{1,20}" - }, - { - "type": "password", - "title": "Пароль", - "name": "ssidApPass", - "state": "{{passwordAP}}", - "pattern": ".{8,20}" - }, - { - "type": "button", - "title": "Сохранить", - "action": "ssidap?ssidAP=[[ssidap]]&passwordAP=[[ssidApPass]]", - "class": "btn btn-block btn-success" - }, - { - "type": "hr" - }, - { - "type": "h2", - "title": "Логин и пароль web interface" - }, - { - "type": "input", - "title": "Логин", - "name": "web-login", - "state": "{{web_login}}", - "pattern": ".{1,20}" - }, - { - "type": "password", - "title": "Пароль", - "name": "web-pass", - "state": "{{web_pass}}", - "pattern": ".{1,20}" - }, - { - "type": "button", - "title": "Сохранить", - "action": "web?web_login=[[web-login]]&web_pass=[[web-pass]]", - "class": "btn btn-block btn-success" - }, - { - "type": "hr" - }, - { - "type": "h2", - "title": "Временная зона" - }, - { - "type": "input", - "title": "Временная зона", - "name": "1", - "state": "{{timezone}}", - "pattern": ".{1,20}" - }, - { - "type": "input", - "title": "Название ntp сервера", - "name": "2", - "state": "{{ntp}}" - }, - { - "type": "button", - "title": "Сохранить", - "action": "time?timezone=[[1]]&ntp=[[2]]", - "class": "btn btn-block btn-success" - }, - { - "type": "hr" - }, - { - "type": "text", - "class": "alert alert-warning", - "title": "После изменения поля 'NTP сервер' необходимо перезагрузить устройство" - }, - { - "type": "hr" - }, - { - "type": "link", - "title": "Перезагрузить устройство", - "action": "javascript:if(confirm(renameBlock(jsonResponse,'Перезагрузить?'))){send_request(this,'/restart?device=ok');}", - "class": "btn btn-block btn-warning" - } - ] -} \ No newline at end of file diff --git a/esp32-esp8266_iot-manager_modules_firmware.ino b/esp32-esp8266_iot-manager_modules_firmware.ino index 2d4b9031..1feaecd0 100644 --- a/esp32-esp8266_iot-manager_modules_firmware.ino +++ b/esp32-esp8266_iot-manager_modules_firmware.ino @@ -14,10 +14,10 @@ void setup() { All_init(); Serial.println("[V] All_init"); //-------------------------------------------------------------- - WIFI_init(); - Serial.println("[V] WIFI_init"); + ROUTER_Connecting(); + Serial.println("[V] ROUTER_Connecting"); //-------------------------------------------------------------- - statistics_init(); + uptime_init(); Serial.println("[V] statistics_init"); //-------------------------------------------------------------- initUpgrade(); @@ -26,17 +26,12 @@ void setup() { Web_server_init(); Serial.println("[V] Web_server_init"); //-------------------------------------------------------------- - MQTT_init(); - Serial.println("[V] MQTT_init"); + web_init(); + Serial.println("[V] web_init"); //-------------------------------------------------------------- Time_Init(); Serial.println("[V] Time_Init"); //-------------------------------------------------------------- -#ifdef push_enable - Push_init(); - Serial.println("[V] Push_init"); -#endif - //-------------------------------------------------------------- #ifdef UDP_enable UDP_init(); Serial.println("[V] UDP_init"); diff --git a/main.ino b/main.ino index 01d90421..0e28ffc1 100644 --- a/main.ino +++ b/main.ino @@ -89,10 +89,89 @@ uint16_t hexStringToUint16(String hex) { return tmp; } } + +String u16toStr(uint16_t u16Input) +{ + char tmp[16]; + sprintf(tmp, "0x%.4X", u16Input); + return tmp; +} + +String u8toStr(uint8_t u8Input) +{ + char tmp[8]; + sprintf(tmp, "0x%.2X", u8Input); + return tmp; +} + +String u64toStr(uint64_t input) +{ + String result = "";// + uint8_t base = 16; //hex 10 dec + + do { + char c = input % base; input /= base; + if (c < 10) { + c += '0'; + } else { + c += 'A' - 10; + } + result = c + result; + } while (input); + switch (result.length()) { + case 1: { + result = "000000000000000" + result; + } break; + case 2: { + result = "00000000000000" + result; + } break; + case 3: { + result = "0000000000000" + result; + } break; + case 4: { + result = "000000000000" + result; + } break; + case 5: { + result = "00000000000" + result; + } break; + case 6: { + result = "0000000000" + result; + } break; + case 7: { + result = "000000000" + result; + } break; + case 8: { + result = "00000000" + result; + } break; + case 9: { + result = "0000000" + result; + } break; + case 10: { + result = "000000" + result; + } break; + case 11: { + result = "00000" + result; + } break; + case 12: { + result = "0000" + result; + } break; + case 13: { + result = "000" + result; + } break; + case 14: { + result = "00" + result; + } break; + case 15: { + result = "0" + result; + } break; + } + return result; +} + //============================================================================================================== //=============================================CONFIG=========================================================== void saveConfig () { - writeFile("config.json", configSetup); + writeFile("config.json", configSetupJson); } //============================================================================================================== //=============================================STRING=========================================================== @@ -207,7 +286,7 @@ String safeDataToFile(String data, String Folder) { fileName = Folder + "/" + fileName + ".txt"; // addFile(fileName, GetTime() + "/" + data); Serial.println(fileName); - jsonWriteStr(configJson, "test", fileName); + jsonWriteStr(configLiveJson, "test", fileName); } // ------------- Чтение файла в строку ------------------------------------------------------------------------------- String readFile(String fileName, size_t len ) { @@ -271,7 +350,7 @@ String readFileString(String fileName, String found) { //=======================================УПРАВЛЕНИЕ ВИДЖЕТАМИ MQTT========================================================= void sendCONFIG(String topik, String widgetConfig, String key, String date) { yield(); - topik = jsonReadStr(configSetup, "mqttPrefix") + "/" + chipID + "/" + topik + "/status"; + topik = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipID + "/" + topik + "/status"; String outer = "{\"widgetConfig\":"; String inner = "{\""; inner = inner + key; @@ -289,17 +368,19 @@ void sendCONFIG(String topik, String widgetConfig, String key, String date) { void led_blink(String satus) { #ifdef ESP8266 #ifdef blink_pin - pinMode(blink_pin, OUTPUT); - if (satus == "off") { - noTone(blink_pin); - digitalWrite(blink_pin, HIGH); + if (jsonReadStr(configSetupJson, "blink") == "1") { + pinMode(blink_pin, OUTPUT); + if (satus == "off") { + noTone(blink_pin); + digitalWrite(blink_pin, HIGH); + } + if (satus == "on") { + noTone(blink_pin); + digitalWrite(blink_pin, LOW); + } + if (satus == "slow") tone(blink_pin, 1); + if (satus == "fast") tone(blink_pin, 20); } - if (satus == "on") { - noTone(blink_pin); - digitalWrite(blink_pin, LOW); - } - if (satus == "slow") tone(blink_pin, 1); - if (satus == "fast") tone(blink_pin, 20); #endif #endif } diff --git a/mqtt.ino b/mqtt.ino index 4a877914..8980c741 100644 --- a/mqtt.ino +++ b/mqtt.ino @@ -1,8 +1,6 @@ //===============================================ИНИЦИАЛИЗАЦИЯ================================================ void MQTT_init() { - ts.add(WIFI_MQTT_CONNECTION_CHECK, wifi_mqtt_reconnecting, [&](void*) { - up_time(); if (WiFi.status() == WL_CONNECTED) { Serial.println("[VV] WiFi-ok"); if (client_mqtt.connected()) { @@ -19,43 +17,8 @@ void MQTT_init() { StartAPMode(); } }, nullptr, true); - - - server.on("/mqttSave", HTTP_GET, [](AsyncWebServerRequest * request) { - if (request->hasArg("mqttServer")) { - jsonWriteStr(configSetup, "mqttServer", request->getParam("mqttServer")->value()); - } - if (request->hasArg("mqttPort")) { - int port = (request->getParam("mqttPort")->value()).toInt(); - jsonWriteInt(configSetup, "mqttPort", port); - } - if (request->hasArg("mqttPrefix")) { - jsonWriteStr(configSetup, "mqttPrefix", request->getParam("mqttPrefix")->value()); - } - if (request->hasArg("mqttUser")) { - jsonWriteStr(configSetup, "mqttUser", request->getParam("mqttUser")->value()); - } - if (request->hasArg("mqttPass")) { - jsonWriteStr(configSetup, "mqttPass", request->getParam("mqttPass")->value()); - } - saveConfig(); - mqtt_connection = true; - - request->send(200, "text/text", "ok"); - }); - - server.on("/mqttCheck", HTTP_GET, [](AsyncWebServerRequest * request) { - String tmp = "{}"; - jsonWriteStr(tmp, "title", "" + stateMQTT()); - jsonWriteStr(tmp, "class", "pop-up"); - request->send(200, "text/text", tmp); - }); - - } - - void do_mqtt_connection() { if (mqtt_connection) { mqtt_connection = false; @@ -75,21 +38,21 @@ void handleMQTT() { } //===============================================ПОДКЛЮЧЕНИЕ======================================================== boolean MQTT_Connecting() { - String mqtt_server = jsonReadStr(configSetup, "mqttServer"); + String mqtt_server = jsonReadStr(configSetupJson, "mqttServer"); if ((mqtt_server != "")) { Serial.println("[E] Lost MQTT connection, start reconnecting"); led_blink("fast"); - client_mqtt.setServer(mqtt_server.c_str(), jsonReadInt(configSetup, "mqttPort")); + client_mqtt.setServer(mqtt_server.c_str(), jsonReadInt(configSetupJson, "mqttPort")); if (WiFi.status() == WL_CONNECTED) { if (!client_mqtt.connected()) { Serial.println("[V] Connecting to MQTT server commenced"); - if (client_mqtt.connect(chipID.c_str(), jsonReadStr(configSetup, "mqttUser").c_str(), jsonReadStr(configSetup, "mqttPass").c_str())) { + if (client_mqtt.connect(chipID.c_str(), jsonReadStr(configSetupJson, "mqttUser").c_str(), jsonReadStr(configSetupJson, "mqttPass").c_str())) { Serial.println("[VV] MQTT connected"); led_blink("off"); client_mqtt.setCallback(callback); - client_mqtt.subscribe(jsonReadStr(configSetup, "mqttPrefix").c_str()); // Для приема получения HELLOW и подтверждения связи - client_mqtt.subscribe((jsonReadStr(configSetup, "mqttPrefix") + "/" + chipID + "/+/control").c_str()); // Подписываемся на топики control - client_mqtt.subscribe((jsonReadStr(configSetup, "mqttPrefix") + "/" + chipID + "/order").c_str()); // Подписываемся на топики order + client_mqtt.subscribe(jsonReadStr(configSetupJson, "mqttPrefix").c_str()); // Для приема получения HELLOW и подтверждения связи + client_mqtt.subscribe((jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipID + "/+/control").c_str()); // Подписываемся на топики control + client_mqtt.subscribe((jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipID + "/order").c_str()); // Подписываемся на топики order Serial.println("[V] Callback set, subscribe done"); return true; } else { @@ -157,34 +120,34 @@ void outcoming_date() { //======================================CONFIG================================================== boolean sendMQTT(String end_of_topik, String data) { - String topik = jsonReadStr(configSetup, "mqttPrefix") + "/" + chipID + "/" + end_of_topik; + String topik = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipID + "/" + end_of_topik; boolean send_status = client_mqtt.beginPublish(topik.c_str(), data.length(), false); client_mqtt.print(data); client_mqtt.endPublish(); return send_status; } boolean sendCHART(String topik, String data) { - topik = jsonReadStr(configSetup, "mqttPrefix") + "/" + chipID + "/" + topik + "/" + "status"; + topik = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipID + "/" + topik + "/" + "status"; boolean send_status = client_mqtt.beginPublish(topik.c_str(), data.length(), false); client_mqtt.print(data); client_mqtt.endPublish(); return send_status; } boolean sendCHART_test(String topik, String data) { - topik = jsonReadStr(configSetup, "mqttPrefix") + "/" + chipID + "/" + topik + "/" + "status"; + topik = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipID + "/" + topik + "/" + "status"; boolean send_status = client_mqtt.publish (topik.c_str(), data.c_str(), false); return send_status; } //======================================STATUS================================================== void sendSTATUS(String topik, String state) { - topik = jsonReadStr(configSetup, "mqttPrefix") + "/" + chipID + "/" + topik + "/" + "status"; + topik = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipID + "/" + topik + "/" + "status"; String json_ = "{}"; jsonWriteStr(json_, "status", state); int send_status = client_mqtt.publish (topik.c_str(), json_.c_str(), false); } //======================================CONTROL================================================== void sendCONTROL(String id, String topik, String state) { - String all_line = jsonReadStr(configSetup, "mqttPrefix") + "/" + id + "/" + topik + "/control"; + String all_line = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + id + "/" + topik + "/control"; int send_status = client_mqtt.publish (all_line.c_str(), state.c_str(), false); } @@ -231,7 +194,7 @@ void sendAllWigets() { //=====================================================ОТПРАВЛЯЕМ ДАННЫЕ В ВИДЖЕТЫ ПРИ ОБНОВЛЕНИИ СТРАНИЦЫ======================================================== void sendAllData() { //берет строку json и ключи превращает в топики а значения колючей в них посылает - String current_config = configJson; //{"name":"MODULES","lang":"","ip":"192.168.43.60","DS":"34.00","rel1":"1","rel2":"1"} + String current_config = configLiveJson; //{"name":"MODULES","lang":"","ip":"192.168.43.60","DS":"34.00","rel1":"1","rel2":"1"} getMemoryLoad("[i] after send all date"); current_config.replace("{", ""); current_config.replace("}", ""); //"name":"MODULES","lang":"","ip":"192.168.43.60","DS":"34.00","rel1":"1","rel2":"1" @@ -284,7 +247,7 @@ String stateMQTT() { /*void scenario_devices_topiks_subscribe() { //SCENARIO ANALOG > 5 800324-1458415 rel1 0 - if (jsonReadStr(configSetup, "scenario") == "1") { + if (jsonReadStr(configSetupJson, "scen") == "1") { //String all_text = readFile("firmware.s.txt", 1024) + "\r\n"; String all_text = scenario + "\r\n"; all_text.replace("\r\n", "\n"); @@ -293,7 +256,7 @@ String stateMQTT() { String line_ = selectToMarker (all_text, "\n"); String id = selectFromMarkerToMarker(line_, " ", 4); if (id != "not found") { - client_mqtt.subscribe((jsonReadStr(configSetup, "mqttPrefix") + "/" + id + "/+/status").c_str(), 0); + client_mqtt.subscribe((jsonReadStr(configSetupJson, "mqttPrefix") + "/" + id + "/+/status").c_str(), 0); Serial.println("subscribed to device, id: " + id); } all_text = deleteBeforeDelimiter(all_text, "\n"); @@ -303,7 +266,7 @@ String stateMQTT() { */ /*void scenario_devices_test_msg_send() { - if (jsonReadStr(configSetup, "scenario") == "1") { + if (jsonReadStr(configSetupJson, "scen") == "1") { String all_text = scenario + "\r\n"; all_text.replace("\r\n", "\n"); @@ -313,7 +276,7 @@ String stateMQTT() { String id = selectFromMarkerToMarker(line_, " ", 4); if (id != "not found") { //Serial.println(); - Serial.println(client_mqtt.publish ((jsonReadStr(configSetup, "mqttPrefix") + "/" + id).c_str(), "CHECK", true)); + Serial.println(client_mqtt.publish ((jsonReadStr(configSetupJson, "mqttPrefix") + "/" + id).c_str(), "CHECK", true)); } all_text = deleteBeforeDelimiter(all_text, "\n"); diff --git a/push_pushingbox.ino b/push_pushingbox.ino index 6d5ddcb3..9cb062c4 100644 --- a/push_pushingbox.ino +++ b/push_pushingbox.ino @@ -1,17 +1,4 @@ #ifdef push_enable -void Push_init() { - server.on("/pushingboxDate", HTTP_GET, [](AsyncWebServerRequest * request) { - - if (request->hasArg("pushingbox_id")) { - jsonWriteStr(configSetup, "pushingbox_id", request->getParam("pushingbox_id")->value()); - } - - saveConfig(); - - request->send(200, "text/text", "ok"); // отправляем ответ о выполнении - }); -} - void pushControl() { String title = sCmd.next(); @@ -22,7 +9,7 @@ void pushControl() { static String body_old; const char* logServer = "api.pushingbox.com"; - String deviceId = jsonReadStr(configSetup, "pushingbox_id"); + String deviceId = jsonReadStr(configSetupJson, "pushingboxid"); Serial.println("- starting client"); diff --git a/set.h b/set.h index c1de1f87..b42456d1 100644 --- a/set.h +++ b/set.h @@ -1,20 +1,20 @@ /******************************************************************* **********************FIRMWARE SETTINGS**************************** ******************************************************************/ -String firmware_version = "2.3.3"; -boolean mb_4_of_memory = true; +String firmware_version = "2.3.4"; +boolean mb_4_of_memory = false; //#define OTA_enable //#define MDNS_enable //#define WS_enable //#define layout_in_ram #define UDP_enable /*==========================SENSORS===============================*/ -//#define level_enable -//#define analog_enable -//#define dallas_enable -//#define dht_enable //подъедает оперативку сука -//#define bmp_enable -//#define bme_enable +#define level_enable +#define analog_enable +#define dallas_enable +#define dht_enable //подъедает оперативку сука +#define bmp_enable +#define bme_enable /*=========================LOGGING================================*/ #define logging_enable /*==========================GEARS=================================*/ @@ -96,9 +96,12 @@ AsyncEventSource events("/events"); #include #include -enum {ROUTER_SEARCHING, WIFI_MQTT_CONNECTION_CHECK, SENSORS, STEPPER1, STEPPER2, LOG1, LOG2, LOG3, LOG4, LOG5, TIMER_COUNTDOWN, TIME, TIME_SYNC, STATISTICS, UDP, UDP_DB, TEST }; +enum {ROUTER_SEARCHING, WIFI_MQTT_CONNECTION_CHECK, SENSORS, STEPPER1, STEPPER2, LOG1, LOG2, LOG3, LOG4, LOG5, TIMER_COUNTDOWN, TIME, TIME_SYNC, STATISTICS, UPTIME, UDP, UDP_DB, TEST }; TickerScheduler ts(TEST + 1); +#include +uptime_interval myUpTime(10); + #include WiFiClient espClient; PubSubClient client_mqtt(espClient); @@ -123,7 +126,7 @@ OneWire *oneWire; DallasTemperature sensors; #endif -#ifdef dht_enable +#ifdef dht_enable #include DHTesp dht; #endif @@ -153,9 +156,9 @@ Adafruit_Sensor *bme_humidity = bme.getHumiditySensor(); boolean just_load = true; const char* hostName = "IoT Manager"; //JSON -String configSetup = "{}"; -String configJson = "{}"; -String optionJson = "{}"; +String configSetupJson = "{}"; //все настройки +String configLiveJson = "{}"; //все данные с датчиков (связан с mqtt) +String configOptionJson = "{}"; //для трансфера //MQTT String chipID = ""; String prex; diff --git a/sync.ffs_db b/sync.ffs_db index d62dff32..9249e09a 100644 Binary files a/sync.ffs_db and b/sync.ffs_db differ diff --git a/udp.ino b/udp.ino index 7b5d6928..88d36725 100644 --- a/udp.ino +++ b/udp.ino @@ -1,40 +1,6 @@ #ifdef UDP_enable void UDP_init() { - server.on("/udp", HTTP_GET, [](AsyncWebServerRequest * request) { - String value; - if (request->hasArg("arg")) { - value = request->getParam("arg")->value(); - } - if (value == "0") { - jsonWriteStr(configSetup, "udponoff", value); - request->send(200, "text/text", "ok"); - } - if (value == "1") { - jsonWriteStr(configSetup, "udponoff", value); - request->send(200, "text/text", "ok"); - } - if (value == "2") { - mqtt_send_settings_to_udp = true; - request->send(200, "text/text", "ok"); - } - if (value == "3") { - SPIFFS.remove("/dev.csv"); - addFile("dev.csv", "device id;device name;ip address"); - request->redirect("/?dev"); - } - if (value == "4") { - request->redirect("/?dev"); - } - }); - server.on("/name", HTTP_GET, [](AsyncWebServerRequest * request) { - if (request->hasArg("arg")) { - jsonWriteStr(configSetup, "name", request->getParam("arg")->value()); - jsonWriteStr(configJson, "name", request->getParam("arg")->value()); - saveConfig(); - } - request->send(200, "text/text", "OK"); - }); - + SPIFFS.remove("/dev.csv"); addFile("dev.csv", "device id;device name;ip address"); @@ -48,10 +14,10 @@ void UDP_init() { udp_period = random(50000, 60000); ts.add(UDP, udp_period, [&](void*) { - if (jsonReadStr(configSetup, "udponoff") == "1") { + if (jsonReadStr(configSetupJson, "udponoff") == "1") { if (WiFi.status() == WL_CONNECTED) { if (!udp_busy) { - String line_to_send = "iotm;" + chipID + ";" + jsonReadStr(configSetup, "name"); + String line_to_send = "iotm;" + chipID + ";" + jsonReadStr(configSetupJson, "name"); #ifdef ESP8266 Udp.beginPacketMulticast(udp_multicastIP, udp_port, WiFi.localIP()); Udp.write(line_to_send.c_str()); @@ -69,7 +35,7 @@ void UDP_init() { void handleUdp() { #ifdef ESP8266 - if (jsonReadStr(configSetup, "udponoff") == "1") { + if (jsonReadStr(configSetupJson, "udponoff") == "1") { if (WiFi.status() == WL_CONNECTED) { int packetSize = Udp.parsePacket(); if (packetSize) { @@ -100,7 +66,7 @@ void handleUdp_esp32() { udp.onPacket([](AsyncUDPPacket packet) { received_udp_line = (char*)packet.data(); received_ip = packet.remoteIP().toString(); - if (jsonReadStr(configSetup, "udponoff") == "1") { + if (jsonReadStr(configSetupJson, "udponoff") == "1") { if (received_udp_line.indexOf("iotm;") >= 0) { udp_data_parse = true; @@ -122,11 +88,11 @@ void do_udp_data_parse() { Serial.print(" "); Serial.println(received_udp_line); if (received_udp_line.indexOf("mqttServer") >= 0) { - jsonWriteStr(configSetup, "mqttServer", jsonReadStr(received_udp_line, "mqttServer")); - jsonWriteInt(configSetup, "mqttPort", jsonReadInt(received_udp_line, "mqttPort")); - jsonWriteStr(configSetup, "mqttPrefix", jsonReadStr(received_udp_line, "mqttPrefix")); - jsonWriteStr(configSetup, "mqttUser", jsonReadStr(received_udp_line, "mqttUser")); - jsonWriteStr(configSetup, "mqttPass", jsonReadStr(received_udp_line, "mqttPass")); + 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"); mqtt_connection = true; @@ -145,15 +111,15 @@ void add_dev_in_list(String fileName, String id, String dev_name, String ip) { } void send_mqtt_to_udp() { - if (jsonReadStr(configSetup, "udponoff") == "1") { + if (jsonReadStr(configSetupJson, "udponoff") == "1") { if (WiFi.status() == WL_CONNECTED) { udp_busy = true; String mqtt_data = "{}"; - jsonWriteStr(mqtt_data, "mqttServer", jsonReadStr(configSetup, "mqttServer")); - jsonWriteInt(mqtt_data, "mqttPort", jsonReadInt(configSetup, "mqttPort")); - jsonWriteStr(mqtt_data, "mqttPrefix", jsonReadStr(configSetup, "mqttPrefix")); - jsonWriteStr(mqtt_data, "mqttUser", jsonReadStr(configSetup, "mqttUser")); - jsonWriteStr(mqtt_data, "mqttPass", jsonReadStr(configSetup, "mqttPass")); + 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); #ifdef ESP8266 Udp.beginPacketMulticast(udp_multicastIP, udp_port, WiFi.localIP());