some changes

This commit is contained in:
Dmitry Borisenko
2020-05-26 17:42:50 +02:00
parent bf75e9f4b7
commit ec76321206
17 changed files with 237 additions and 356 deletions

30
Cmd.ino
View File

@@ -133,7 +133,7 @@ void buttonSet() {
String button_number = sCmd.next();
String button_state = sCmd.next();
String button_param = jsonRead(optionJson, "button_param" + button_number);
String button_param = jsonReadStr(optionJson, "button_param" + button_number);
if (button_param != "na" || button_param != "scenario" || button_param.indexOf("line") != -1) {
digitalWrite(button_param.toInt(), button_state.toInt());
@@ -167,7 +167,7 @@ void buttonSet() {
void buttonChange() {
String button_number = sCmd.next();
String current_state = jsonRead(configJson, "button" + button_number);
String current_state = jsonReadStr(configJson, "button" + button_number);
if (current_state == "1") {
current_state = "0";
} else if (current_state == "0") {
@@ -220,7 +220,7 @@ void pwmSet() {
String pwm_state = sCmd.next();
int pwm_state_int = pwm_state.toInt();
int pin = jsonReadtoInt(optionJson, "pwm_pin" + pwm_number);
int pin = jsonReadInt(optionJson, "pwm_pin" + pwm_number);
analogWrite(pin, pwm_state_int);
eventGen ("pwm", pwm_number);
@@ -367,18 +367,18 @@ void stepperSet() {
String steps = sCmd.next();
jsonWriteStr(optionJson, "steps" + stepper_number, steps);
String stepper_speed = sCmd.next();
String pin_step = selectToMarker (jsonRead(optionJson, "stepper" + stepper_number), " ");
String pin_dir = deleteBeforeDelimiter (jsonRead(optionJson, "stepper" + stepper_number), " ");
String pin_step = selectToMarker (jsonReadStr(optionJson, "stepper" + stepper_number), " ");
String pin_dir = deleteBeforeDelimiter (jsonReadStr(optionJson, "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(jsonReadtoInt(optionJson, "steps1") * 2);
int steps_int = abs(jsonReadInt(optionJson, "steps1") * 2);
static int count;
count++;
String pin_step = selectToMarker (jsonRead(optionJson, "stepper1"), " ");
String pin_step = selectToMarker (jsonReadStr(optionJson, "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(jsonReadtoInt(optionJson, "steps2") * 2);
int steps_int = abs(jsonReadInt(optionJson, "steps2") * 2);
static int count;
count++;
String pin_step = selectToMarker (jsonRead(optionJson, "stepper2"), " ");
String pin_step = selectToMarker (jsonReadStr(optionJson, "stepper2"), " ");
digitalWrite(pin_step.toInt(), !digitalRead(pin_step.toInt()));
yield();
if (count > steps_int) {
@@ -465,13 +465,13 @@ void servoSet() {
String servo_state = sCmd.next();
int servo_state_int = servo_state.toInt();
int pin = jsonReadtoInt(optionJson, "servo_pin" + servo_number);
int pin = jsonReadInt(optionJson, "servo_pin" + servo_number);
servo_state_int = map(servo_state_int,
jsonReadtoInt(optionJson, "s_min_val" + servo_number),
jsonReadtoInt(optionJson, "s_max_val" + servo_number),
jsonReadtoInt(optionJson, "s_min_deg" + servo_number),
jsonReadtoInt(optionJson, "s_max_deg" + servo_number));
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));
if (servo_number == "1") {
#ifdef ESP8266
@@ -523,7 +523,7 @@ void mqttOrderSend() {
String id = sCmd.next();
String order = sCmd.next();
String all_line = jsonRead(configSetup, "mqttPrefix") + "/" + id + "/order";
String all_line = jsonReadStr(configSetup, "mqttPrefix") + "/" + id + "/order";
//Serial.print(all_line);
//Serial.print("->");
//Serial.println(order);

6
FS.ino
View File

@@ -9,8 +9,8 @@ void File_system_init() {
configSetup.replace(" ", "");
configSetup.replace("\r\n", "");
Serial.println(configSetup);
jsonWriteStr(configJson, "name", jsonRead(configSetup, "name"));
jsonWriteStr(configJson, "lang", jsonRead(configSetup, "lang"));
jsonWriteStr(configJson, "name", jsonReadStr(configSetup, "name"));
jsonWriteStr(configJson, "lang", jsonReadStr(configSetup, "lang"));
#ifdef ESP32
@@ -27,7 +27,7 @@ void File_system_init() {
jsonWriteStr(configSetup, "firmware_version", firmware_version);
prex = jsonRead(configSetup, "mqttPrefix") + "/" + chipID;
prex = jsonReadStr(configSetup, "mqttPrefix") + "/" + chipID;
Serial.println(chipID);
}

View File

@@ -86,7 +86,7 @@ void Device_init() {
//-------------------------------сценарии-----------------------------------------------------
void Scenario_init() {
if (jsonRead(configSetup, "scenario") == "1") {
if (jsonReadStr(configSetup, "scenario") == "1") {
scenario = readFile("firmware.s.txt", 2048);
}
}
@@ -238,7 +238,7 @@ void statistics() {
#endif
urls += "&";
//-----------------------------------------------------------------
urls += "ver: " + firmware_version; // + " " + DATE_COMPILING + " " + TIME_COMPILING;
urls += "ver: " + firmware_version;
//-----------------------------------------------------------------
String stat = getURL(urls);
//Serial.println(stat);

View File

@@ -16,35 +16,35 @@ void logging() {
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", jsonReadtoInt(optionJson, tmp_buf_1 + "_c"), jsonRead(configJson, tmp_buf_1));
deleteOldDate("log." + tmp_buf_1 + ".txt", jsonReadInt(optionJson, tmp_buf_1 + "_c"), jsonReadStr(configJson, 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", jsonReadtoInt(optionJson, tmp_buf_2 + "_c"), jsonRead(configJson, tmp_buf_2));
deleteOldDate("log." + tmp_buf_2 + ".txt", jsonReadInt(optionJson, tmp_buf_2 + "_c"), jsonReadStr(configJson, 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", jsonReadtoInt(optionJson, tmp_buf_3 + "_c"), jsonRead(configJson, tmp_buf_3));
deleteOldDate("log." + tmp_buf_3 + ".txt", jsonReadInt(optionJson, tmp_buf_3 + "_c"), jsonReadStr(configJson, 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", jsonReadtoInt(optionJson, tmp_buf_4 + "_c"), jsonRead(configJson, tmp_buf_4));
deleteOldDate("log." + tmp_buf_4 + ".txt", jsonReadInt(optionJson, tmp_buf_4 + "_c"), jsonReadStr(configJson, 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", jsonReadtoInt(optionJson, tmp_buf_5 + "_c"), jsonRead(configJson, tmp_buf_5));
deleteOldDate("log." + tmp_buf_5 + ".txt", jsonReadInt(optionJson, tmp_buf_5 + "_c"), jsonReadStr(configJson, tmp_buf_5));
Serial.println("[i] LOGGING for sensor '" + tmp_buf_5 + "' done");
}, nullptr, false);
}

View File

@@ -1,7 +1,7 @@
void handleScenario() {
if (jsonRead(configSetup, "scenario") == "1") {
if ((jsonRead(optionJson, "scenario_status") != "")) {
if (jsonReadStr(configSetup, "scenario") == "1") {
if ((jsonReadStr(optionJson, "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 = jsonRead(optionJson, "scenario_status"); //читаем весь файл событий
String order = jsonReadStr(optionJson, "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 = jsonRead(configJson, value);
value = jsonReadStr(configJson, value);
}
if (value.indexOf("time") != -1) {
// value = add_set(value);
value = jsonRead(configJson, value);
value = jsonReadStr(configJson, value);
}
boolean flag = false; //если одно из значений совпало то только тогда начинаем выполнять комнады
if (sign == "=") {
if (jsonRead(configJson, param_name) == value) flag = true;
if (jsonReadStr(configJson, param_name) == value) flag = true;
}
if (sign == "!=") {
if (jsonRead(configJson, param_name) != value) flag = true;
if (jsonReadStr(configJson, param_name) != value) flag = true;
}
if (sign == "<") {
if (jsonRead(configJson, param_name).toInt() < value.toInt()) flag = true;
if (jsonReadStr(configJson, param_name).toInt() < value.toInt()) flag = true;
}
if (sign == ">") {
if (jsonRead(configJson, param_name).toInt() > value.toInt()) flag = true;
if (jsonReadStr(configJson, param_name).toInt() > value.toInt()) flag = true;
}
if (sign == ">=") {
if (jsonRead(configJson, param_name).toInt() >= value.toInt()) flag = true;
if (jsonReadStr(configJson, param_name).toInt() >= value.toInt()) flag = true;
}
if (sign == "<=") {
if (jsonRead(configJson, param_name).toInt() <= value.toInt()) flag = true;
if (jsonReadStr(configJson, param_name).toInt() <= value.toInt()) flag = true;
}
if (flag) {
@@ -63,7 +63,7 @@ void handleScenario() {
str = deleteBeforeDelimiter(str, "end\n"); //удаляем первый сценарий
//-----------------------------------------------------------------------------------------------------------------------
}
String tmp2 = jsonRead(optionJson, "scenario_status"); //читаем файл событий
String tmp2 = jsonReadStr(optionJson, "scenario_status"); //читаем файл событий
tmp2 = deleteBeforeDelimiter(tmp2, ","); //удаляем выполненное событие
jsonWriteStr(optionJson, "scenario_status", tmp2); //записываем обновленный файл событий
i = 0;
@@ -73,8 +73,8 @@ void handleScenario() {
void eventGen (String event_name, String number) { //событие выглядит как имя плюс set плюс номер: button+Set+1
if (jsonRead(configSetup, "scenario") == "1") {
String tmp = jsonRead(optionJson, "scenario_status") ; //генерирование события
if (jsonReadStr(configSetup, "scenario") == "1") {
String tmp = jsonReadStr(optionJson, "scenario_status") ; //генерирование события
//Serial.println(event_name);
jsonWriteStr(optionJson, "scenario_status", tmp + event_name + number + ",");
}

View File

@@ -72,8 +72,8 @@ void level_reading() {
int distance_cm;
int level;
static int counter;
int trig = jsonReadtoInt(optionJson, "trig");
int echo = jsonReadtoInt(optionJson, "echo");
int trig = jsonReadInt(optionJson, "trig");
int echo = jsonReadInt(optionJson, "echo");
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
@@ -86,8 +86,8 @@ void level_reading() {
if (counter > tank_level_times_to_send) {
counter = 0;
level = map(distance_cm,
jsonReadtoInt(optionJson, "e_lev"),
jsonReadtoInt(optionJson, "f_lev"), 0, 100);
jsonReadInt(optionJson, "e_lev"),
jsonReadInt(optionJson, "f_lev"), 0, 100);
jsonWriteInt(configJson, level_value_name, level);
eventGen (level_value_name, "");
sendSTATUS(level_value_name, String(level));
@@ -134,10 +134,10 @@ void analog_reading1() {
int analog_in = analogRead(A0);
#endif
int analog = map(analog_in,
jsonReadtoInt(optionJson, value_name + "_st") ,
jsonReadtoInt(optionJson, value_name + "_end"),
jsonReadtoInt(optionJson, value_name + "_st_out"),
jsonReadtoInt(optionJson, value_name + "_end_out"));
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);
eventGen (value_name, "");
sendSTATUS(value_name, String(analog));
@@ -153,10 +153,10 @@ void analog_reading2() {
int analog_in = analogRead(A0);
#endif
int analog = map(analog_in,
jsonReadtoInt(optionJson, value_name + "_st") ,
jsonReadtoInt(optionJson, value_name + "_end"),
jsonReadtoInt(optionJson, value_name + "_st_out"),
jsonReadtoInt(optionJson, value_name + "_end_out"));
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);
eventGen (value_name, "");
sendSTATUS(value_name, String(analog));
@@ -285,7 +285,7 @@ void dhtP_reading() {
if (dht.getStatus() != 0) {
sendSTATUS("dhtPerception", String(dht.getStatusString()));
} else {
value = dht.computePerception(jsonRead(configJson, dhtT_value_name).toFloat(), jsonRead(configJson, dhtH_value_name).toFloat(), false);
value = dht.computePerception(jsonReadStr(configJson, dhtT_value_name).toFloat(), jsonReadStr(configJson, dhtH_value_name).toFloat(), false);
String final_line = perception(value);
jsonWriteStr(configJson, "dhtPerception", final_line);
eventGen ("dhtPerception", "");
@@ -322,7 +322,7 @@ void dhtC_reading() {
if (dht.getStatus() != 0) {
sendSTATUS("dhtComfort", String(dht.getStatusString()));
} else {
value = dht.getComfortRatio(cf, jsonRead(configJson, dhtT_value_name).toFloat(), jsonRead(configJson, dhtH_value_name).toFloat(), false);
value = dht.getComfortRatio(cf, jsonReadStr(configJson, dhtT_value_name).toFloat(), jsonReadStr(configJson, dhtH_value_name).toFloat(), false);
String final_line = get_comfort_status(cf);
jsonWriteStr(configJson, "dhtComfort", final_line);
eventGen ("dhtComfort", "");
@@ -383,7 +383,7 @@ void dhtD_reading() {
if (dht.getStatus() != 0) {
sendSTATUS("dhtDewpoint", String(dht.getStatusString()));
} else {
value = dht.computeDewPoint(jsonRead(configJson, dhtT_value_name).toFloat(), jsonRead(configJson, dhtH_value_name).toFloat(), false);
value = dht.computeDewPoint(jsonReadStr(configJson, dhtT_value_name).toFloat(), jsonReadStr(configJson, dhtH_value_name).toFloat(), false);
jsonWriteInt(configJson, "dhtDewpoint", value);
eventGen ("dhtDewpoint", "");
sendSTATUS("dhtDewpoint", String(value));

View File

@@ -25,7 +25,7 @@ void time_check() {
void reconfigTime() {
if (WiFi.status() == WL_CONNECTED) {
String ntp = jsonRead(configSetup, "ntp");
String ntp = jsonReadStr(configSetup, "ntp");
configTime(0, 0, ntp.c_str());
int i = 0;
Serial.println("[i] Awaiting for time ");
@@ -69,7 +69,7 @@ String GetTimeUnix() {
// Получение текущего времени
String GetTime() {
time_t now = time(nullptr); // получаем время с помощью библиотеки time.h
int zone = 3600 * jsonRead(configSetup, "timezone").toInt();
int zone = 3600 * jsonReadStr(configSetup, "timezone").toInt();
now = now + zone;
String Time = ""; // Строка для результатов времени
Time += ctime(&now); // Преобразуем время в строку формата Thu Jan 19 00:55:35 2017
@@ -80,7 +80,7 @@ String GetTime() {
String GetTimeWOsec() {
time_t now = time(nullptr); // получаем время с помощью библиотеки time.h
int zone = 3600 * jsonRead(configSetup, "timezone").toInt();
int zone = 3600 * jsonReadStr(configSetup, "timezone").toInt();
now = now + zone;
String Time = ""; // Строка для результатов времени
Time += ctime(&now); // Преобразуем время в строку формата Thu Jan 19 00:55:35 2017
@@ -92,7 +92,7 @@ String GetTimeWOsec() {
// Получение даты
String GetDate() {
time_t now = time(nullptr); // получаем время с помощью библиотеки time.h
int zone = 3600 * jsonRead(configSetup, "timezone").toInt();
int zone = 3600 * jsonReadStr(configSetup, "timezone").toInt();
now = now + zone;
String Data = ""; // Строка для результатов времени
Data += ctime(&now); // Преобразуем время в строку формата Thu Jan 19 00:55:35 2017

View File

@@ -4,7 +4,7 @@ void Timer_countdown_init() {
ts.add(TIMER_COUNTDOWN, 1000, [&](void*) {
String old_line = jsonRead(optionJson, "timers");
String old_line = jsonReadStr(optionJson, "timers");
if (old_line != "") {
//Serial.println(old_line);
int i = 0;
@@ -35,7 +35,7 @@ void timerStart() {
String type = sCmd.next();
if (period_of_time.indexOf("digit") != -1) {
//period_of_time = add_set(period_of_time);
period_of_time = jsonRead(configJson, period_of_time);
period_of_time = jsonReadStr(configJson, period_of_time);
}
if (type == "sec") period_of_time = period_of_time;
if (type == "min") period_of_time = String(period_of_time.toInt() * 60);
@@ -44,7 +44,7 @@ void timerStart() {
jsonWriteStr(configJson, "timer" + number, "1");
}
void addTimer(String number, String time) {
String tmp = jsonRead(optionJson, "timers"); //1:60,2:120,
String tmp = jsonReadStr(optionJson, "timers"); //1:60,2:120,
String new_timer = number + ":" + time;
int psn1 = tmp.indexOf(number + ":"); //0 ищем позицию таймера который надо заменить
if (psn1 != -1) { //если он есть
@@ -66,7 +66,7 @@ void timerStop() {
}
void delTimer (String number) {
String tmp = jsonRead(optionJson, "timers"); //1:60,2:120,
String tmp = jsonReadStr(optionJson, "timers"); //1:60,2:120,
int psn1 = tmp.indexOf(number + ":"); //0 ищем позицию таймера который надо удалить
if (psn1 != -1) { //если он есть
int psn2 = tmp.indexOf(",", psn1); //4 от этой позиции находим позицию запятой
@@ -77,7 +77,7 @@ void delTimer (String number) {
}
int readTimer(int number) {
String tmp = jsonRead(optionJson, "timers"); //1:60,2:120,
String tmp = jsonReadStr(optionJson, "timers"); //1:60,2:120,
int psn1 = tmp.indexOf(String(number) + ":"); //0 ищем позицию таймера который надо прочитать
String timer;
if (psn1 != -1) { //если он есть

View File

@@ -1,22 +1,19 @@
void Web_server_init() {
//========================================OTA============================================
/*********************************************************************************
***************************************OTA****************************************
*********************************************************************************/
#ifdef OTA_enable
//Send OTA events to the browser
ArduinoOTA.onStart([]() {
events.send("Update Start", "ota");
});
ArduinoOTA.onEnd([]() {
events.send("Update End", "ota");
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
char p[32];
sprintf(p, "Progress: %u%%\n", (progress / (total / 100)));
events.send(p, "ota");
});
ArduinoOTA.onError([](ota_error_t error) {
if (error == OTA_AUTH_ERROR) events.send("Auth Failed", "ota");
else if (error == OTA_BEGIN_ERROR) events.send("Begin Failed", "ota");
@@ -25,17 +22,18 @@ void Web_server_init() {
else if (error == OTA_END_ERROR) events.send("End Failed", "ota");
});
ArduinoOTA.setHostname(hostName);
ArduinoOTA.begin();
#endif
//========================================MDNS============================================
/*********************************************************************************
**************************************MDNS****************************************
*********************************************************************************/
#ifdef MDNS_enable
MDNS.addService("http", "tcp", 80);
#endif
//SPIFFS.begin();
//========================================WS============================================
/*********************************************************************************
**************************************WS******************************************
*********************************************************************************/
#ifdef WS_enable
ws.onEvent(onWsEvent);
server.addHandler(&ws);
@@ -46,26 +44,25 @@ void Web_server_init() {
server.addHandler(&events);
#endif
//======================================================================================
/*********************************************************************************
**************************************WEB****************************************
*********************************************************************************/
#ifdef ESP32
server.addHandler(new SPIFFSEditor(SPIFFS, jsonRead(configSetup, "web_login").c_str(), jsonRead(configSetup, "web_pass").c_str()));
server.addHandler(new SPIFFSEditor(SPIFFS, jsonReadStr(configSetup, "web_login").c_str(), jsonReadStr(configSetup, "web_pass").c_str()));
#elif defined(ESP8266)
server.addHandler(new SPIFFSEditor(jsonRead(configSetup, "web_login").c_str(), jsonRead(configSetup, "web_pass").c_str()));
server.addHandler(new SPIFFSEditor(jsonReadStr(configSetup, "web_login").c_str(), jsonReadStr(configSetup, "web_pass").c_str()));
#endif
server.on("/heap", HTTP_GET, [](AsyncWebServerRequest * request) {
/* server.on("/heap", HTTP_GET, [](AsyncWebServerRequest * request) {
request->send(200, "text/plain", String(ESP.getFreeHeap()));
});
});*/
server.serveStatic("/css/", SPIFFS, "/css/").setCacheControl("max-age=31536000");
server.serveStatic("/js/", SPIFFS, "/js/").setCacheControl("max-age=31536000");
server.serveStatic("/", SPIFFS, "/favicon.ico").setCacheControl("max-age=31536000");
server.serveStatic("/favicon.ico", SPIFFS, "/favicon.ico").setCacheControl("max-age=31536000");
server.serveStatic("/", SPIFFS, "/").setDefaultFile("index.htm")
.setAuthentication(jsonRead(configSetup, "web_login").c_str(), jsonRead(configSetup, "web_pass").c_str());
.setAuthentication(jsonReadStr(configSetup, "web_login").c_str(), jsonReadStr(configSetup, "web_pass").c_str());
server.onNotFound([](AsyncWebServerRequest * request) {
Serial.printf("NOT_FOUND: ");
@@ -114,6 +111,7 @@ void Web_server_init() {
request->send(404);
});
server.onFileUpload([](AsyncWebServerRequest * request, const String & filename, size_t index, uint8_t *data, size_t len, bool final) {
if (!index)
Serial.printf("UploadStart: %s\n", filename.c_str());
@@ -122,6 +120,7 @@ void Web_server_init() {
Serial.printf("UploadEnd: %s (%u)\n", filename.c_str(), index + len);
});
server.onRequestBody([](AsyncWebServerRequest * request, uint8_t *data, size_t len, size_t index, size_t total) {
if (!index)
Serial.printf("BodyStart: %u\n", total);
@@ -132,8 +131,6 @@ void Web_server_init() {
server.begin();
//=============================Устанавливаем реакции на запросы к серверу============================
// --------------------Выдаем данные configJson //config.live.json - динамические данные
server.on("/config.live.json", HTTP_GET, [](AsyncWebServerRequest * request) {
request->send(200, "application/json", configJson);
@@ -148,14 +145,17 @@ void Web_server_init() {
});
// ------------------Выполнение команды из запроса
server.on("/cmd", HTTP_GET, [](AsyncWebServerRequest * request) { //http://192.168.88.45/cmd?command=rel%201%201
//http://192.168.88.45/cmd?command=rel%201%201
server.on("/cmd", HTTP_GET, [](AsyncWebServerRequest * request) {
String com = request->getParam("command")->value();
Serial.println(com);
order_loop += com + ",";
request->send(200, "text/text", "OK"); // отправляем ответ о выполнении
});
}
//========================================WS=========================================================================================
/*********************************************************************************************************************************
*********************************************************WS**********************************************************************
********************************************************************************************************************************/
#ifdef WS_enable
void onWsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len) {
if (type == WS_EVT_CONNECT) {

View File

@@ -52,8 +52,8 @@ void ROUTER_Connecting() {
WiFi.mode(WIFI_STA);
byte tries = 20;
String _ssid = jsonRead(configSetup, "ssid");
String _password = jsonRead(configSetup, "password");
String _ssid = jsonReadStr(configSetup, "ssid");
String _password = jsonReadStr(configSetup, "password");
//WiFi.persistent(false);
if (_ssid == "" && _password == "") {
@@ -108,8 +108,8 @@ bool StartAPMode() {
WiFi.mode(WIFI_AP);
String _ssidAP = jsonRead(configSetup, "ssidAP");
String _passwordAP = jsonRead(configSetup, "passwordAP");
String _ssidAP = jsonReadStr(configSetup, "ssidAP");
String _passwordAP = jsonReadStr(configSetup, "passwordAP");
WiFi.softAP(_ssidAP.c_str(), _passwordAP.c_str());
IPAddress myIP = WiFi.softAPIP();
led_blink("on");
@@ -117,10 +117,10 @@ bool StartAPMode() {
Serial.println(myIP);
jsonWriteStr(configJson, "ip", myIP.toString());
if (jsonReadtoInt(optionJson, "pass_status") != 1) {
if (jsonReadInt(optionJson, "pass_status") != 1) {
ts.add(ROUTER_SEARCHING, 10 * 1000, [&](void*) {
Serial.println("->try find router");
if (RouterFind(jsonRead(configSetup, "ssid"))) {
if (RouterFind(jsonReadStr(configSetup, "ssid"))) {
ts.remove(ROUTER_SEARCHING);
WiFi.scanDelete();
ROUTER_Connecting();
@@ -186,7 +186,7 @@ boolean RouterFind(String ssid) {
data["pass"] = (WiFi.encryptionType(i) == ENC_TYPE_NONE) ? "" : "*";
int8_t dbm = WiFi.RSSI(i);
data["dbm"] = dbm;
if (ssidMy == jsonRead(configSetup, "ssid")) {
if (ssidMy == jsonReadStr(configSetup, "ssid")) {
jsonWriteStr(configJson, "dbm", dbm);
}
}

View File

@@ -1,72 +0,0 @@
/*
const char* local_root_ca1 = \
"-----BEGIN CERTIFICATE-----\n" \
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D5Leo31Rpg0Gcg19hCC0Wvgmje3WYkN5Ap\n" \
"lBlGGSW4gNfL1IYoakRwJiNiqZ+Gb7+6kHDSVneFeO/qJakXzlByjAA6quPbYzSf\n" \
"+AZxAeKCINT+b72x\n" \
"-----END CERTIFICATE-----\n";
*/

223
main.ino
View File

@@ -1,17 +1,49 @@
//============================================================================================================
//=============================================JSON===========================================================
// ------------- Чтение значения json
String jsonRead(String &json, String name) {
// ------------- Чтение значения json ------------------------------------------------------------------------
String jsonReadStr(String &json, String name) {
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(json);
return root[name].as<String>();
}
// ------------- Чтение значения json
int jsonReadtoInt(String &json, String name) {
// ------------- Чтение значения json ------------------------------------------------------------------------
int jsonReadInt(String &json, String name) {
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(json);
return root[name];
}
// ------------- Запись значения json String -----------------------------------------------------------------
String jsonWriteStr(String &json, String name, String volume) {
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(json);
root[name] = volume;
json = "";
root.printTo(json);
return json;
}
// ------------- Запись значения json int ---------------------------------------------------------------------
String jsonWriteInt(String &json, String name, int volume) {
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(json);
root[name] = volume;
json = "";
root.printTo(json);
return json;
}
// ------------- Запись значения json float -------------------------------------------------------------------
String jsonWriteFloat(String &json, String name, float volume) {
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(json);
root[name] = volume;
json = "";
root.printTo(json);
return json;
}
/*
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(json);
@@ -27,60 +59,43 @@ int jsonReadtoInt(String &json, String name) {
serializeJson(jsonBuffer,json);
return json;
*/
// ------------- Запись значения json String
String jsonWriteStr(String &json, String name, String volume) {
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(json);
root[name] = volume;
json = "";
root.printTo(json);
return json;
}
// ------------- Запись значения json int
String jsonWriteInt(String &json, String name, int volume) {
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(json);
root[name] = volume;
json = "";
root.printTo(json);
return json;
}
// ------------- Запись значения json float
String jsonWriteFloat(String &json, String name, float volume) {
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(json);
root[name] = volume;
json = "";
root.printTo(json);
return json;
}
/*
String jsonWriteArray(String &json, String value1, String value2, String value3) {
const int capacity = JSON_ARRAY_SIZE(1) + 3 * JSON_OBJECT_SIZE(3);
StaticJsonBuffer<capacity> jb;
JsonArray& arr = jb.createArray();
JsonObject& obj1 = jb.createObject();
obj1[value1] = 1;
obj1[value2] = 2;
obj1[value3] = 3;
arr.add(obj1);
arr.printTo(json);
return json;
}
*/
//============================================================================================================
//=============================================BIT AND BYTE===================================================
uint8_t hexStringToUint8(String hex) {
uint8_t tmp = strtol(hex.c_str(), NULL, 0);
if (tmp >= 0x00 && tmp <= 0xFF) {
return tmp;
}
}
uint16_t hexStringToUint16(String hex) {
uint16_t tmp = strtol(hex.c_str(), NULL, 0);
if (tmp >= 0x0000 && tmp <= 0xFFFF) {
return tmp;
}
}
//==============================================================================================================
//=============================================CONFIG===========================================================
void saveConfig () {
writeFile("config.json", configSetup);
}
//=============================================ТЕКСТ============================================================
//==============================================================================================================
//=============================================STRING===========================================================
// --------Выделяем строку от конца строки до маркера-----------------------------------------------------------
String selectToMarkerLast (String str, String found) {
int p = str.lastIndexOf(found);
@@ -114,11 +129,12 @@ String deleteToMarkerLast (String str, String found) {
int p = str.lastIndexOf(found);
return str.substring(0, p);
}
// -------------------Выделяем строку от конца строки до маркера + ----------------------------------------------
String selectToMarkerPlus (String str, String found, int plus) {
int p = str.indexOf(found);
return str.substring(0, p + plus);
}
//--------------------Выделяем строку от маркера до маркера
//--------------------Выделяем строку от маркера до маркера -----------------------------------------------------
String selectFromMarkerToMarker(String str, String found, int number) {
if (str.indexOf(found) == -1) return "not found"; // если строки поиск нет сразу выход
str += found; // добавим для корректного поиска
@@ -130,7 +146,7 @@ String selectFromMarkerToMarker(String str, String found, int number) {
} while (str.length() != 0); // повторим пока строка не пустая
return "not found"; // Достигли пустой строки и ничего не нашли
}
//--------------------Посчитать
//--------------------Посчитать -----------------------------------------------------------------------------------
int count(String str, String found) {
if (str.indexOf(found) == -1) return 0; // если строки поиск нет сразу выход
str += found; // добавим для корректного поиска
@@ -142,6 +158,7 @@ int count(String str, String found) {
return i; // Достигли пустой строки и ничего не нашли
}
//--------------------проверка на цифры ---------------------------------------------------------------------------
boolean isDigitStr (String str) {
if (str.length() == 1) {
return Digit (str);
@@ -153,7 +170,6 @@ boolean isDigitStr (String str) {
return true;
}
}
boolean Digit (String str) {
if (str == "0" || str == "1" || str == "2" || str == "3" || str == "4" || str == "5" || str == "6" || str == "7" || str == "8" || str == "9") {
return true;
@@ -161,6 +177,7 @@ boolean Digit (String str) {
return false;
}
}
//==================================================================================================================
//============================================URL===================================================================
// ----------------------Запрос на удаленный URL
String getURL(String urls) {
@@ -177,11 +194,10 @@ String getURL(String urls) {
http.end();
return answer;
}
//===================================================================================================================
//===========================================FILES===================================================================
String safeDataToFile(String data, String Folder)
{
// ------------- Добавление файла -----------------------------------------------------------------------------------
String safeDataToFile(String data, String Folder) {
//String fileName = GetDate();
String fileName;
fileName.toLowerCase();
@@ -189,13 +205,11 @@ String safeDataToFile(String data, String Folder)
fileName.replace(" ", ".");
fileName.replace("..", ".");
fileName = Folder + "/" + fileName + ".txt";
// addFile(fileName, GetTime() + "/" + data);
Serial.println(fileName);
jsonWriteStr(configJson, "test", fileName);
}
// ------------- Чтение файла в строку
// ------------- Чтение файла в строку -------------------------------------------------------------------------------
String readFile(String fileName, size_t len ) {
File configFile = SPIFFS.open("/" + fileName, "r");
if (!configFile) {
@@ -210,7 +224,7 @@ String readFile(String fileName, size_t len ) {
configFile.close();
return temp;
}
// ------------- Размер файла ----------------------------------------------------------------------------------------
String sizeFile(String fileName) {
File configFile = SPIFFS.open("/" + fileName, "r");
if (!configFile) {
@@ -220,8 +234,7 @@ String sizeFile(String fileName) {
configFile.close();
return String(size);
}
// ------------- Запись строки в файл
// ------------- Запись строки в файл ---------------------------------------------------------------------------------
String writeFile(String fileName, String strings ) {
File configFile = SPIFFS.open("/" + fileName, "w");
if (!configFile) {
@@ -232,8 +245,7 @@ String writeFile(String fileName, String strings ) {
configFile.close();
return "Write sucsses";
}
// ------------- Добовление строки в файл
// ------------- Добовление строки в файл ------------------------------------------------------------------------------
String addFile(String fileName, String strings ) {
File configFile = SPIFFS.open("/" + fileName, "a");
if (!configFile) {
@@ -243,8 +255,7 @@ String addFile(String fileName, String strings ) {
configFile.close();
return "Write sucsses";
}
// ------------- Чтение строки из файла
// ------------- Чтение строки из файла ---------------------------------------------------------------------------------
//возвращает стоку из файла в которой есть искомое слово found
String readFileString(String fileName, String found) {
File configFile = SPIFFS.open("/" + fileName, "r");
@@ -256,63 +267,11 @@ String readFileString(String fileName, String found) {
}
configFile.close();
}
// Запись данных в файл с частотой 1 секунда и более. Максимальное количество данных в суточном файле 1440 значений
void safeDataToFile(int inter, String par, uint16_t data) {
yield();
// Формируем зоголовок (префикс) Интервал, Параметр, размер_параметра
uint16_t dataSize = sizeof(data);
String prifexFile;
prifexFile += inter;
prifexFile += "," + par;
prifexFile += ",";
prifexFile += dataSize;
prifexFile += ":";
uint16_t prifexLen = prifexFile.length(); //Размер префикса
// Сделаем имя файла
String fileName = GetDate();
fileName = deleteBeforeDelimiter(fileName, " "); // удалим день недели
fileName.replace(" ", ".");
fileName.replace("..", "."); // Заменяем пробелы точками
fileName = par + "/" + fileName + ".txt"; // Имя файла параметр в виде директории и дата
fileName.toLowerCase(); //fileName = "san aug 31 2018"; Имя файла строчными буквами
Serial.println(fileName);
File configFile = SPIFFS.open("/" + fileName, "a"); // Открываем файл на добавление
size_t size = configFile.size();
yield();
if (size == 0) {
configFile.print(prifexFile);
}
size = configFile.size();
// Получим время и определим позицию в файле
String time = GetTime();
//time = "00:15:00";
int timeM = timeToMin(time); // Здесь количество минут с начала суток
timeM = timeM / inter;
int poz = timeM * dataSize + prifexLen + 1; // позиция в которую нужно записать.
int endF = (size - prifexLen) * dataSize + prifexLen + 1; // позиция конца файла
if (poz >= endF) { // если файл имел пропуски в записи данных
int i = (poz - endF) / dataSize;
for (int j = 0; j < i; j++) { // Заполним недостающие данные
for (int d = 0; d < dataSize; d++) {
yield();
configFile.write(0); // нулями
}
}
}
yield();
configFile.write(data >> 8); // добавим текущие
configFile.write(data); // данные
configFile.close();
}
//=======================================УПРАВЛЕНИЕ ВИДЖЕТАМИ MQTT======================================================================
//=========================================================================================================================
//=======================================УПРАВЛЕНИЕ ВИДЖЕТАМИ MQTT=========================================================
void sendCONFIG(String topik, String widgetConfig, String key, String date) {
yield();
topik = jsonRead(configSetup, "mqttPrefix") + "/" + chipID + "/" + topik + "/status";
topik = jsonReadStr(configSetup, "mqttPrefix") + "/" + chipID + "/" + topik + "/status";
String outer = "{\"widgetConfig\":";
String inner = "{\"";
inner = inner + key;
@@ -325,24 +284,11 @@ void sendCONFIG(String topik, String widgetConfig, String key, String date) {
//client_mqtt.publish(MQTT::Publish(topik, t).set_qos(1));
yield();
}
uint8_t hexStringToUint8(String hex) {
uint8_t tmp = strtol(hex.c_str(), NULL, 0);
if (tmp >= 0x00 && tmp <= 0xFF) {
return tmp;
}
}
uint16_t hexStringToUint16(String hex) {
uint16_t tmp = strtol(hex.c_str(), NULL, 0);
if (tmp >= 0x0000 && tmp <= 0xFFFF) {
return tmp;
}
}
//=============================================================================================================
//=========================================================================================================================
//=========================================МИГАНИЕ СВЕТОДИОДОМ=============================================================
void led_blink(String satus) {
#ifdef blink_pin
#ifdef ESP8266
#ifdef blink_pin
pinMode(blink_pin, OUTPUT);
if (satus == "off") {
noTone(blink_pin);
@@ -354,10 +300,11 @@ void led_blink(String satus) {
}
if (satus == "slow") tone(blink_pin, 1);
if (satus == "fast") tone(blink_pin, 20);
#endif
#endif
#endif
}
//=========================================================================================================================
//=========================================ОСТАВШАЯСЯ ОПЕРАТИВНАЯ ПАМЯТЬ===================================================
void getMemoryLoad(String text) {
#ifdef ESP8266
int all_memory = 52864;
@@ -378,15 +325,17 @@ void getMemoryLoad(String text) {
//esp32 full memory = 362868 k bytes
//esp8266 full memory = 52864 k bytes
//===================================================================
/*
void web_print (String text) {
if (WiFi.status() == WL_CONNECTED) {
jsonWriteStr(json, "test1", jsonRead(json, "test2"));
jsonWriteStr(json, "test2", jsonRead(json, "test3"));
jsonWriteStr(json, "test3", jsonRead(json, "test4"));
jsonWriteStr(json, "test4", jsonRead(json, "test5"));
jsonWriteStr(json, "test5", jsonRead(json, "test6"));
jsonWriteStr(json, "test1", jsonReadStr(json, "test2"));
jsonWriteStr(json, "test2", jsonReadStr(json, "test3"));
jsonWriteStr(json, "test3", jsonReadStr(json, "test4"));
jsonWriteStr(json, "test4", jsonReadStr(json, "test5"));
jsonWriteStr(json, "test5", jsonReadStr(json, "test6"));
jsonWriteStr(json, "test6", GetTime() + " " + text);

View File

@@ -75,21 +75,21 @@ void handleMQTT() {
}
//===============================================ПОДКЛЮЧЕНИЕ========================================================
boolean MQTT_Connecting() {
String mqtt_server = jsonRead(configSetup, "mqttServer");
String mqtt_server = jsonReadStr(configSetup, "mqttServer");
if ((mqtt_server != "")) {
Serial.println("[E] Lost MQTT connection, start reconnecting");
led_blink("fast");
client_mqtt.setServer(mqtt_server.c_str(), jsonReadtoInt(configSetup, "mqttPort"));
client_mqtt.setServer(mqtt_server.c_str(), jsonReadInt(configSetup, "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(), jsonRead(configSetup, "mqttUser").c_str(), jsonRead(configSetup, "mqttPass").c_str())) {
if (client_mqtt.connect(chipID.c_str(), jsonReadStr(configSetup, "mqttUser").c_str(), jsonReadStr(configSetup, "mqttPass").c_str())) {
Serial.println("[VV] MQTT connected");
led_blink("off");
client_mqtt.setCallback(callback);
client_mqtt.subscribe(jsonRead(configSetup, "mqttPrefix").c_str()); // Для приема получения HELLOW и подтверждения связи
client_mqtt.subscribe((jsonRead(configSetup, "mqttPrefix") + "/" + chipID + "/+/control").c_str()); // Подписываемся на топики control
client_mqtt.subscribe((jsonRead(configSetup, "mqttPrefix") + "/" + chipID + "/order").c_str()); // Подписываемся на топики order
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
Serial.println("[V] Callback set, subscribe done");
return true;
} else {
@@ -157,34 +157,34 @@ void outcoming_date() {
//======================================CONFIG==================================================
boolean sendMQTT(String end_of_topik, String data) {
String topik = jsonRead(configSetup, "mqttPrefix") + "/" + chipID + "/" + end_of_topik;
String topik = jsonReadStr(configSetup, "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 = jsonRead(configSetup, "mqttPrefix") + "/" + chipID + "/" + topik + "/" + "status";
topik = jsonReadStr(configSetup, "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 = jsonRead(configSetup, "mqttPrefix") + "/" + chipID + "/" + topik + "/" + "status";
topik = jsonReadStr(configSetup, "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 = jsonRead(configSetup, "mqttPrefix") + "/" + chipID + "/" + topik + "/" + "status";
topik = jsonReadStr(configSetup, "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 = jsonRead(configSetup, "mqttPrefix") + "/" + id + "/" + topik + "/control";
String all_line = jsonReadStr(configSetup, "mqttPrefix") + "/" + id + "/" + topik + "/control";
int send_status = client_mqtt.publish (all_line.c_str(), state.c_str(), false);
}
@@ -284,7 +284,7 @@ String stateMQTT() {
/*void scenario_devices_topiks_subscribe() {
//SCENARIO ANALOG > 5 800324-1458415 rel1 0
if (jsonRead(configSetup, "scenario") == "1") {
if (jsonReadStr(configSetup, "scenario") == "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 +293,7 @@ String stateMQTT() {
String line_ = selectToMarker (all_text, "\n");
String id = selectFromMarkerToMarker(line_, " ", 4);
if (id != "not found") {
client_mqtt.subscribe((jsonRead(configSetup, "mqttPrefix") + "/" + id + "/+/status").c_str(), 0);
client_mqtt.subscribe((jsonReadStr(configSetup, "mqttPrefix") + "/" + id + "/+/status").c_str(), 0);
Serial.println("subscribed to device, id: " + id);
}
all_text = deleteBeforeDelimiter(all_text, "\n");
@@ -303,7 +303,7 @@ String stateMQTT() {
*/
/*void scenario_devices_test_msg_send() {
if (jsonRead(configSetup, "scenario") == "1") {
if (jsonReadStr(configSetup, "scenario") == "1") {
String all_text = scenario + "\r\n";
all_text.replace("\r\n", "\n");
@@ -313,7 +313,7 @@ String stateMQTT() {
String id = selectFromMarkerToMarker(line_, " ", 4);
if (id != "not found") {
//Serial.println();
Serial.println(client_mqtt.publish ((jsonRead(configSetup, "mqttPrefix") + "/" + id).c_str(), "CHECK", true));
Serial.println(client_mqtt.publish ((jsonReadStr(configSetup, "mqttPrefix") + "/" + id).c_str(), "CHECK", true));
}
all_text = deleteBeforeDelimiter(all_text, "\n");

View File

@@ -22,7 +22,7 @@ void pushControl() {
static String body_old;
const char* logServer = "api.pushingbox.com";
String deviceId = jsonRead(configSetup, "pushingbox_id");
String deviceId = jsonReadStr(configSetup, "pushingbox_id");
Serial.println("- starting client");

38
set.h
View File

@@ -1,38 +1,38 @@
//===============FIRMWARE SETTINGS=====================================
String firmware_version = "2.3.3";
/*******************************************************************
**********************FIRMWARE SETTINGS****************************
******************************************************************/
String firmware_version = "2.3.4";
boolean mb_4_of_memory = true;
//#define OTA_enable
//#define MDNS_enable
//#define WS_enable
//#define layout_in_ram
//===================================================================
//====================udp============================================
#define UDP_enable
//====================sensors========================================
/*==========================SENSORS===============================*/
#define level_enable
#define analog_enable
#define dallas_enable
#define dht_enable //подъедает оперативку сука
#define bmp_enable
#define bme_enable
//====================logging=========================================
/*=========================LOGGING================================*/
#define logging_enable
//=====================gears==========================================
/*==========================GEARS=================================*/
#define stepper_enable
#define servo_enable
//=====================other==========================================
/*=========================OTHER==================================*/
#define serial_enable
#define push_enable
//====================================================================
//====================================================================
/*================================================================*/
#define wifi_mqtt_reconnecting 20000
#define blink_pin 2
#define tank_level_times_to_send 10 //после скольки выстрелов делать отправку данных
#define statistics_update 1000 * 60 * 60 * 2
//======================================================================
//===============библиотеки и объекты для ESP8266========================
/*================================================================*/
//===============библиотеки и объекты для ESP8266=======================
#ifdef ESP8266
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
@@ -50,6 +50,8 @@ Servo myServo2;
#endif
#endif
//===============библиотеки и объекты для ESP32===========================
#ifdef ESP32
#include <WiFi.h>
@@ -69,6 +71,8 @@ Servo myServo2;
#endif
#endif
//===============общие библиотеки и объекты===============================
#include <Arduino.h>
#include "time.h"
@@ -95,8 +99,6 @@ AsyncEventSource events("/events");
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 };
TickerScheduler ts(TEST + 1);
//LEVEL, ANALOG1, ANALOG2, DALLAS, DHTT, DHTH, DHTC, DHTP, DHTD, BMP280T, BMP280P,
#include <PubSubClient.h>
WiFiClient espClient;
PubSubClient client_mqtt(espClient);
@@ -135,7 +137,7 @@ Adafruit_Sensor *bmp_temp = bmp.getTemperatureSensor();
Adafruit_Sensor *bmp_pressure = bmp.getPressureSensor();
#endif
#ifdef bmp_enable
#ifdef bme_enable
#include <Adafruit_BME280.h>
Adafruit_BME280 bme; // use I2C interface
Adafruit_Sensor *bme_temp = bme.getTemperatureSensor();
@@ -145,6 +147,8 @@ Adafruit_Sensor *bme_humidity = bme.getHumiditySensor();
//#include <SoftwareSerial.h>
//SoftwareSerial mySerial(14, 12);
//===============FIRMWARE VARS========================
boolean just_load = true;
const char* hostName = "IoT Manager";

BIN
sync.ffs_db Normal file

Binary file not shown.

30
udp.ino
View File

@@ -48,10 +48,10 @@ void UDP_init() {
udp_period = random(50000, 60000);
ts.add(UDP, udp_period, [&](void*) {
if (jsonRead(configSetup, "udponoff") == "1") {
if (jsonReadStr(configSetup, "udponoff") == "1") {
if (WiFi.status() == WL_CONNECTED) {
if (!udp_busy) {
String line_to_send = "iotm;" + chipID + ";" + jsonRead(configSetup, "name");
String line_to_send = "iotm;" + chipID + ";" + jsonReadStr(configSetup, "name");
#ifdef ESP8266
Udp.beginPacketMulticast(udp_multicastIP, udp_port, WiFi.localIP());
Udp.write(line_to_send.c_str());
@@ -69,7 +69,7 @@ void UDP_init() {
void handleUdp() {
#ifdef ESP8266
if (jsonRead(configSetup, "udponoff") == "1") {
if (jsonReadStr(configSetup, "udponoff") == "1") {
if (WiFi.status() == WL_CONNECTED) {
int packetSize = Udp.parsePacket();
if (packetSize) {
@@ -100,7 +100,7 @@ void handleUdp_esp32() {
udp.onPacket([](AsyncUDPPacket packet) {
received_udp_line = (char*)packet.data();
received_ip = packet.remoteIP().toString();
if (jsonRead(configSetup, "udponoff") == "1") {
if (jsonReadStr(configSetup, "udponoff") == "1") {
if (received_udp_line.indexOf("iotm;") >= 0) {
udp_data_parse = true;
@@ -122,11 +122,11 @@ void do_udp_data_parse() {
Serial.print(" ");
Serial.println(received_udp_line);
if (received_udp_line.indexOf("mqttServer") >= 0) {
jsonWriteStr(configSetup, "mqttServer", jsonRead(received_udp_line, "mqttServer"));
jsonWriteInt(configSetup, "mqttPort", jsonReadtoInt(received_udp_line, "mqttPort"));
jsonWriteStr(configSetup, "mqttPrefix", jsonRead(received_udp_line, "mqttPrefix"));
jsonWriteStr(configSetup, "mqttUser", jsonRead(received_udp_line, "mqttUser"));
jsonWriteStr(configSetup, "mqttPass", jsonRead(received_udp_line, "mqttPass"));
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"));
saveConfig();
Serial.println("[V] new mqtt setting received from udp and saved");
mqtt_connection = true;
@@ -145,15 +145,15 @@ void add_dev_in_list(String fileName, String id, String dev_name, String ip) {
}
void send_mqtt_to_udp() {
if (jsonRead(configSetup, "udponoff") == "1") {
if (jsonReadStr(configSetup, "udponoff") == "1") {
if (WiFi.status() == WL_CONNECTED) {
udp_busy = true;
String mqtt_data = "{}";
jsonWriteStr(mqtt_data, "mqttServer", jsonRead(configSetup, "mqttServer"));
jsonWriteInt(mqtt_data, "mqttPort", jsonReadtoInt(configSetup, "mqttPort"));
jsonWriteStr(mqtt_data, "mqttPrefix", jsonRead(configSetup, "mqttPrefix"));
jsonWriteStr(mqtt_data, "mqttUser", jsonRead(configSetup, "mqttUser"));
jsonWriteStr(mqtt_data, "mqttPass", jsonRead(configSetup, "mqttPass"));
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"));
Serial.println(mqtt_data);
#ifdef ESP8266
Udp.beginPacketMulticast(udp_multicastIP, udp_port, WiFi.localIP());