add udp support and some new functions

This commit is contained in:
Dmitry Borisenko
2020-04-05 01:52:02 +02:00
parent 5250049e08
commit ba30af5182
23 changed files with 464 additions and 257 deletions

View File

@@ -1,24 +1,33 @@
void All_init() {
server.on("/all_modules_init", HTTP_GET, [](AsyncWebServerRequest * request) {
Device_init();
request->send(200, "text/text", "OK"); // отправляем ответ о выполнении
});
server.on("/scenario", HTTP_GET, [](AsyncWebServerRequest * request) {
if (request->hasArg("status")) {
jsonWriteStr(configSetup, "scenario", request->getParam("status")->value());
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();
}
if (value == "1") {
jsonWriteStr(configSetup, "scenario", value);
saveConfig();
Scenario_init();
}
if (value == "2") {
Device_init();
}
if (value == "3") {
clean_log_date();
}
if (value == "4") {
Scenario_init();
}
saveConfig();
Scenario_init();
request->send(200, "text/text", "OK"); // отправляем ответ о выполнении
});
server.on("/cleanlog", HTTP_GET, [](AsyncWebServerRequest * request) {
clean_log_date();
request->send(200, "text/text", "OK"); // отправляем ответ о выполнении
});
prsets_init();
Device_init();
Scenario_init();
Timer_countdown_init();
@@ -134,7 +143,7 @@ void prsets_init() {
}
Device_init();
Scenario_init();
request->redirect("/page.htm?configuration");
request->redirect("/?configuration");
});
}

View File

@@ -1,49 +0,0 @@
void SSDP_init() {
server.on("/ssdp", HTTP_GET, [](AsyncWebServerRequest * request) {
if (request->hasArg("ssdp")) {
jsonWriteStr(configSetup, "SSDP", request->getParam("ssdp")->value());
jsonWriteStr(configJson, "SSDP", request->getParam("ssdp")->value());
}
saveConfig();
request->send(200, "text/text", "OK");
});
}
/*
// --------------------Получаем ssdp со страницы
server.on("/ssdp", HTTP_GET, [](AsyncWebServerRequest * request) {
if (request->hasArg("ssdp")) {
jsonWriteStr(configSetup, "SSDP", request->getParam("ssdp")->value());
jsonWriteStr(configJson, "SSDP", request->getParam("ssdp")->value());
SSDP.setName(jsonRead(configSetup, "SSDP"));
}
saveConfig();
request->send(200, "text/text", "OK");
});
// SSDP дескриптор
server.on("/description.xml", [](AsyncWebServerRequest * request) {
//SSDP.schema(http.client());
request->send(200, "text/text", "OK");
});
if (WiFi.status() == WL_CONNECTED) {
//Если версия 2.0.0 закаментируйте следующую строчку
SSDP.setDeviceType("upnp:rootdevice");
SSDP.setSchemaURL("description.xml");
SSDP.setHTTPPort(80);
SSDP.setName(jsonRead(configSetup, "SSDP"));
SSDP.setSerialNumber(chipID);
SSDP.setURL("/");
SSDP.setModelName("tech");
SSDP.setModelNumber(chipID + "/" + jsonRead(configSetup, "SSDP"));
SSDP.setModelURL("https://github.com/DmitryBorisenko33/esp32-esp8266_iot-manager_modules_firmware");
SSDP.setManufacturer("Borisenko Dmitry");
SSDP.setManufacturerURL("https://www.instagram.com/rriissee3");
SSDP.begin();
}
}
*/

View File

@@ -10,29 +10,20 @@ void initUpgrade() {
Serial.print("[i] Last firmware version: ");
Serial.println(last_version);
server.on("/upgrade", HTTP_GET, [](AsyncWebServerRequest * request) {
start_check_version = true;
server.on("/check", HTTP_GET, [](AsyncWebServerRequest * request) {
upgrade_url = true;
Serial.print("[i] Last firmware version: ");
Serial.println(last_version);
#ifdef ESP8266
int ChipRealSize = ESP.getFlashChipRealSize() / 1048576;
#endif
#ifdef ESP32
int ChipRealSize = 4;
#endif
String tmp = "{}";
if (WiFi.status() == WL_CONNECTED) {
if (ChipRealSize >= 4) {
if (mb_4_of_memory) {
if (last_version != "") {
if (last_version != "error") {
if (last_version == firmware_version) {
jsonWriteStr(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>Последняя версия прошивки уже установлена.");
jsonWriteStr(tmp, "class", "pop-up");
} else {
upgrade_flag = true;
jsonWriteStr(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>Идет обновление прошивки... После завершения устройство перезагрузится. Подождите одну минуту!!!");
} else {
jsonWriteStr(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>Имеется новая версия прошивки<a href=\"#\" class=\"btn btn-block btn-danger\" onclick=\"send_request(this, '/upgrade');setTimeout(function(){ location.href='/'; }, 30000);html('my-block','<span class=loader></span>Идет обновление прошивки, после обновления страница перезагрузится автоматически...')\">Установить</a>");
jsonWriteStr(tmp, "class", "pop-up");
}
} else {
@@ -53,11 +44,18 @@ void initUpgrade() {
}
request->send(200, "text/text", tmp);
});
server.on("/upgrade", HTTP_GET, [](AsyncWebServerRequest * request) {
upgrade = true;
String tmp = "{}";
//jsonWriteStr(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>Есть новая версия <a href=\"#\" onclick=\"setTimeout(function(){ location.href='/'; }, 5000);}\">Установить?</a>");
request->send(200, "text/text", "ok");
});
}
void handle_get_url() {
if (start_check_version) {
start_check_version = false;
void do_upgrade_url() {
if (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);
@@ -118,9 +116,9 @@ void upgrade_firmware() {
}
}
void handle_upgrade() {
if (upgrade_flag) {
upgrade_flag = false;
void do_upgrade() {
if (upgrade) {
upgrade = false;
upgrade_firmware();
}
}

View File

@@ -1,5 +1,5 @@
void WIFI_init() {
// --------------------Получаем ssid password со страницы
server.on("/ssid", HTTP_GET, [](AsyncWebServerRequest * request) {
if (request->hasArg("ssid")) {
@@ -42,12 +42,12 @@ void WIFI_init() {
}
request->send(200, "text/text", "OK"); // отправляем ответ о выполнении
});
ROUTER_Connecting();
}
// Попытка подключения к точке доступа
void ROUTER_Connecting() {
WiFi.mode(WIFI_STA);
// WiFi.mode(WIFI_NONE_SLEEP);
byte tries = 20;
String _ssid = jsonRead(configSetup, "ssid");
@@ -92,6 +92,8 @@ void WIFI_init() {
Serial.print(WiFi.localIP());
Serial.println("");
jsonWriteStr(configJson, "ip", WiFi.localIP().toString());
//add_dev_in_list("dev.txt", chipID, WiFi.localIP().toString());
}
}
@@ -115,8 +117,8 @@ bool StartAPMode() {
Serial.println("->try find router");
if (RouterFind(jsonRead(configSetup, "ssid"))) {
ts.remove(ROUTER_SEARCHING);
WIFI_init();
MQTT_init();
ROUTER_Connecting();
MQTT_Connecting();
}
}, nullptr, true);
}
@@ -164,8 +166,9 @@ boolean RouterFind(String ssid) {
return false;
}
}
/*
String scanWIFI() {
String scanWIFI() {
uint8_t n = WiFi.scanNetworks();
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.createObject();
@@ -184,7 +187,7 @@ String scanWIFI() {
String root;
json.printTo(root);
return root;
}
}
*/
/*
{

18
data/config-all.json Normal file
View File

@@ -0,0 +1,18 @@
{
"name": "IoTmanager",
"chipID": "",
"ssidAP": "WiFi",
"passwordAP": "",
"ssid": "your_ssid",
"password": "your_password",
"timezone": 3,
"mqttServer": "",
"mqttPort": 0,
"mqttPrefix": "/IoTmanager",
"mqttUser": "",
"mqttPass": "",
"scenario": "1",
"pushingbox_id": "",
"web_login": "admin",
"web_pass": "admin"
}

View File

@@ -1,18 +0,0 @@
{
"SSDP": "IoTmanager",
"chipID": "",
"ssidAP": "WiFi",
"passwordAP": "",
"ssid": "rise",
"password": "hostel3333",
"timezone": 2,
"mqttServer": "mqtt.ioty.ru",
"mqttPort": 1883,
"mqttPrefix": "/rise",
"mqttUser": "test",
"mqttPass": "test",
"scenario": "1",
"pushingbox_id": "",
"web_login": "admin",
"web_pass": "admin"
}

View File

@@ -1,16 +1,16 @@
{
"SSDP": "MODULES",
"name": "IoTmanager",
"chipID": "",
"ssidAP": "WiFi",
"passwordAP": "",
"ssid": "your_ssid",
"password": "your_password",
"timezone": 3,
"mqttServer": "",
"mqttPort": 0,
"mqttPrefix": "/IoTmanager",
"mqttUser": "",
"mqttPass": "",
"ssid": "rise",
"password": "hostel3333",
"timezone": 2,
"mqttServer": "mqtt.ioty.ru",
"mqttPort": 1883,
"mqttPrefix": "/rise",
"mqttUser": "test",
"mqttPass": "test",
"scenario": "1",
"pushingbox_id": "",
"web_login": "admin",

View File

@@ -8,7 +8,7 @@
"content": [
{
"type": "h5",
"title": "{{SSDP}}",
"title": "{{name}}",
"class": "alert-warning"
},
{
@@ -62,7 +62,7 @@
"state": "firmware.c.txt",
"style": "width:100%;height:400px",
"title": "Сохранить",
"action": "/all_modules_init",
"action": "/init?arg=2",
"class": "btn btn-block btn-success"
},
{
@@ -79,7 +79,7 @@
"type": "checkbox",
"name": "scenario",
"title": "Включить сценарии",
"action": "/scenario?status=[[scenario]]",
"action": "/init?arg=[[scenario]]",
"state": "{{scenario}}"
},
{
@@ -90,8 +90,8 @@
"type": "file",
"state": "firmware.s.txt",
"style": "width:100%;height:400px",
"title": "Сохранить и включить",
"action": "/scenario?status=1",
"title": "Сохранить",
"action": "/init?arg=4",
"class": "btn btn-block btn-success"
},
{
@@ -100,13 +100,13 @@
{
"type": "link",
"title": "Очистить логи сенсоров",
"action": "/cleanlog",
"action": "/init?arg=3",
"class": "btn btn-block btn-success"
},
{
"type": "link",
"title": "Главная",
"action": "/page.htm?index",
"action": "/",
"class": "btn btn-block btn-danger btn-sm"
}
]

65
data/dev.json Normal file
View File

@@ -0,0 +1,65 @@
{
"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=2",
"class": "btn btn-block btn-success"
},
{
"type": "link",
"title": "Обновить страницу",
"action": "udp?arg=3",
"class": "btn btn-block btn-success"
},
{
"type": "hr"
},
{
"type": "text",
"class": "alert alert-warning",
"title": "После нажатия на кнопку 'Переформировать список устройств' ждите примерно минуту, а затем обновите страницу и список появится вновь"
},
{
"type": "hr"
},
{
"type": "link",
"title": "Главная",
"action": "/",
"class": "btn btn-block btn-danger"
}
]
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

View File

@@ -8,7 +8,7 @@
"content": [
{
"type": "h5",
"title": "{{SSDP}}",
"title": "{{name}}",
"class": "alert-warning"
},
{
@@ -37,28 +37,37 @@
{
"type": "link",
"title": "Конфигурация устройства",
"action": "/page.htm?configuration",
"action": "/?configuration",
"class": "btn btn-block btn-primary"
},
{
"type": "hr"
},
{
"type": "link",
"title": "Список других устройств в сети",
"action": "/?dev",
"class": "btn btn-block btn-warning"
},
{
"type": "hr"
},
{
"type": "link",
"title": "Конфигурация WIFI",
"action": "/page.htm?setup",
"action": "/?setup",
"class": "btn btn-block btn-success"
},
{
"type": "link",
"title": "Конфигурация MQTT",
"action": "/page.htm?mqtt",
"action": "/?mqtt",
"class": "btn btn-block btn-success"
},
{
"type": "link",
"title": "Конфигурация push",
"action": "/page.htm?pushingbox",
"action": "/?pushingbox",
"class": "btn btn-block btn-success"
},
{
@@ -73,7 +82,7 @@
{
"type": "button",
"title": "Обновить прошивку",
"action": "/upgrade",
"action": "/check",
"response": "[[my-block]]",
"class": "btn btn-block btn-success"
},

Binary file not shown.

Binary file not shown.

View File

@@ -1,96 +1,106 @@
{
"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": "{{SSDP}}",
"class":"alert-warning"
},
{
"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": "button",
"title":"Сохранить",
"action": "mqttSave?mqttServer=[[1]]&mqttPort=[[2]]&mqttPrefix=[[3]]&mqttUser=[[4]]&mqttPass=[[5]]",
"class": "btn btn-block btn-success",
"style": "width:100%;display:inline"
},
{
"type": "button",
"title":"Проверить соединение с MQTT",
"action": "mqttCheck",
"response":"[[my-block]]",
"class": "btn btn-block btn-success",
"style": "width:100%;display:inline"
},
{
"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": "/page.htm?index",
"class": "btn btn-block btn-danger btn-sm"
}
]
}
"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": "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=1",
"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"
}
]
}

View File

@@ -6,7 +6,7 @@
"content": [
{
"type": "h5",
"title": "{{SSDP}}",
"title": "{{name}}",
"class":"alert-warning"
},
{
@@ -39,7 +39,7 @@
{
"type": "link",
"title": "Главная",
"action": "/page.htm?index",
"action": "/",
"class": "btn btn-block btn-danger btn-sm"
}
]

View File

@@ -7,7 +7,7 @@
"content": [
{
"type": "h5",
"title": "{{SSDP}}",
"title": "{{name}}",
"class":"alert-warning"
},
{
@@ -26,14 +26,14 @@
{
"type": "input",
"title": "Имя устройства",
"name":"ssdp",
"state": "{{SSDP}}",
"name":"dev_name",
"state": "{{name}}",
"pattern": "[0-9a-zA-Zа-яА-Я.\\- ]{1,20}"
},
{
"type": "button",
"title": "Сохранить",
"action": "ssdp?ssdp=[[ssdp]]",
"action": "name?arg=[[dev_name]]",
"class": "btn btn-block btn-success"
},
{

BIN
date_excess/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -32,14 +32,22 @@ void setup() {
Push_init();
Serial.println("[V] Push_init");
//--------------------------------------------------------------
SSDP_init();
Serial.println("[V] SSDP_init");
UDP_init();
Serial.println("[V] UDP_init");
//--------------------------------------------------------------
ts.add(TEST, 10000, [&](void*) {
ts.add(TEST, 5000, [&](void*) {
getMemoryLoad("[i] periodic check of");
//String json = "{}";
//jsonWriteStr(json, "test6", GetTime());
//ws.textAll(json);
}, nullptr, true);
just_load = false;
}
@@ -54,15 +62,21 @@ void loop() {
ws.cleanupClients();
#endif
not_async_actions();
handleMQTT();
handle_connection();
handle_get_url();
handleCMD_loop();
handleButton();
handleScenario();
handleUdp();
ts.update();
handle_upgrade();
}
void not_async_actions() {
do_mqtt_connection();
do_upgrade_url();
do_upgrade();
do_udp_data_parse();
do_mqtt_send_settings_to_udp();
}

View File

@@ -38,7 +38,7 @@ void MQTT_init() {
jsonWriteStr(configSetup, "mqttPass", request->getParam("mqttPass")->value());
}
saveConfig();
start_connecting_to_mqtt = true;
mqtt_connection = true;
request->send(200, "text/text", "ok");
});
@@ -49,11 +49,20 @@ void MQTT_init() {
jsonWriteStr(tmp, "class", "pop-up");
request->send(200, "text/text", tmp);
});
}
void handle_connection() {
if (start_connecting_to_mqtt) {
start_connecting_to_mqtt = false;
void do_mqtt_send_settings_to_udp() {
if (mqtt_send_settings_to_udp) {
mqtt_send_settings_to_udp = false;
send_mqtt_to_udp();
}
}
void do_mqtt_connection() {
if (mqtt_connection) {
mqtt_connection = false;
client.disconnect();
MQTT_Connecting();
}
@@ -76,14 +85,14 @@ boolean MQTT_Connecting() {
//ssl//espClient.setCACert(local_root_ca1);
client.setServer(mqtt_server.c_str(), jsonReadtoInt(configSetup, "mqttPort"));
if (WiFi.status() == WL_CONNECTED) {
if (!client.connected()) {
if (!client.connected()) {
Serial.println("[V] Connecting to MQTT server commenced");
if (client.connect(chipID.c_str(), jsonRead(configSetup, "mqttUser").c_str(), jsonRead(configSetup, "mqttPass").c_str())) {
if (client.connect(chipID.c_str(), jsonRead(configSetup, "mqttUser").c_str(), jsonRead(configSetup, "mqttPass").c_str())) {
Serial.println("[V] MQTT connected");
client.setCallback(callback);
client.subscribe(jsonRead(configSetup, "mqttPrefix").c_str()); // Для приема получения HELLOW и подтверждения связи
client.subscribe((jsonRead(configSetup, "mqttPrefix") + "/" + chipID + "/+/control").c_str()); // Подписываемся на топики control
client.subscribe((jsonRead(configSetup, "mqttPrefix") + "/" + chipID + "/order").c_str()); // Подписываемся на топики order
client.subscribe((jsonRead(configSetup, "mqttPrefix") + "/" + chipID + "/order").c_str()); // Подписываемся на топики order
Serial.println("[V] Callback set, subscribe done");
return true;
} else {
@@ -99,7 +108,7 @@ boolean MQTT_Connecting() {
}
//=====================================================ВХОДЯЩИЕ ДАННЫЕ========================================================
void callback(char* topic, byte* payload, unsigned int length) {
void callback(char* topic, byte * payload, unsigned int length) {
Serial.print("[MQTT] ");
Serial.print(topic);
String topic_str = String(topic);
@@ -228,7 +237,7 @@ void sendAllData() { //берет строку json и ключи превра
topic.replace("\"", "");
String state = selectToMarkerLast (tmp, ":");
state.replace("\"", "");
if (topic != ssdpS && topic != "lang" && topic != "ip" && topic.indexOf("_in") < 0) {
if (topic != "name" && topic != "lang" && topic != "ip" && topic.indexOf("_in") < 0) {
sendSTATUS(topic, state);
//Serial.println("-->" + topic + " " + state);
}

31
set.h
View File

@@ -1,7 +1,8 @@
String firmware_version = "2.3.2";
String firmware_version = "2.3.1";
//-----------------------------------------------------------------
boolean mb_4_of_memory = true;
String last_version;
boolean start_check_version = false;
//#define OTA_enable
//#define MDNS_enable
@@ -79,11 +80,14 @@ AsyncEventSource events("/events");
//---------------------------------------------------------------
#include <TickerScheduler.h>
TickerScheduler ts(30);
enum {ROUTER_SEARCHING, WIFI_MQTT_CONNECTION_CHECK, LEVEL, ANALOG_, DALLAS, DHTT, DHTH, DHTC, DHTP, DHTD, STEPPER1, STEPPER2, ANALOG_LOG, LEVEL_LOG, DALLAS_LOG, dhtT_LOG, dhtH_LOG, CMD, TIMER_COUNTDOWN, TIMERS, TIME, TIME_SYNC, STATISTICS, TEST};
enum {ROUTER_SEARCHING, WIFI_MQTT_CONNECTION_CHECK, LEVEL, ANALOG_, DALLAS, DHTT, DHTH, DHTC, DHTP, DHTD, STEPPER1, STEPPER2, ANALOG_LOG, LEVEL_LOG, DALLAS_LOG, dhtT_LOG, dhtH_LOG, CMD, TIMER_COUNTDOWN, TIMERS, TIME, TIME_SYNC, STATISTICS, UDP, UDP_DB, TEST};
//---------------------------------------------------------------
//ssl//#include "dependencies/WiFiClientSecure/WiFiClientSecure.h" //using older WiFiClientSecure
//#include "Ticker_for_TickerScheduler/Ticker/Ticker.h"
//---------------------------------------------------------------
#include <WiFiUdp.h>
WiFiUDP Udp;
//---------------------------------------------------------------
#include <PubSubClient.h>
WiFiClient espClient;
//ssl//WiFiClientSecure espClient;
@@ -145,7 +149,6 @@ const char* ntpServer = "pool.ntp.org";
const long gmtOffset_sec = 3600;
const int daylightOffset_sec = 3600;
const String ssdpS = "SSDP";
String current_time;
int scenario_line_status [] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
@@ -154,11 +157,25 @@ int wifi_lost_error = 0;
int mqtt_lost_error = 0;
String var;
boolean upgrade_flag = false;
boolean get_url_flag = false;
boolean start_connecting_to_mqtt = false;
//flags for not async actions
boolean upgrade_url = false;
boolean upgrade = false;
boolean mqtt_connection = false;
boolean udp_data_parse = false;
boolean mqtt_send_settings_to_udp = false;
boolean udp_busy = false;
String test;
boolean chart_data_in_solid_array;
unsigned int udp_port = 4210;
char udp_incomingPacket[255];
//char udp_replyPacket[] = "Multicast packet 1";
IPAddress udp_multicastIP (255, 255, 255, 255);
String received_ip;
String received_udp_line;

122
udp.ino Normal file
View File

@@ -0,0 +1,122 @@
void UDP_init() {
server.on("/udp", HTTP_GET, [](AsyncWebServerRequest * request) {
String value;
if (request->hasArg("arg")) {
value = request->getParam("arg")->value();
}
if (value == "1") {
mqtt_send_settings_to_udp = true;
request->send(200, "text/text", "ok");
}
if (value == "2") {
SPIFFS.remove("/dev.csv");
request->redirect("/?dev");
}
if (value == "3") {
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");
Udp.begin(udp_port);
ts.add(UDP, 30000, [&](void*) {
if (WiFi.status() == WL_CONNECTED) {
if (!udp_busy) {
String line_to_send = chipID + ";" + jsonRead(configSetup, "SSDP");
#ifdef ESP8266
Udp.beginPacketMulticast(udp_multicastIP, udp_port, WiFi.localIP());
Udp.write(line_to_send.c_str());
#endif
#ifdef ESP32
Udp.beginMulticast(udp_multicastIP, udp_port);
#endif
Udp.endPacket();
Serial.println("[UDP<=] dev info send");
}
}
}, nullptr, false);
}
void add_dev_in_list(String fileName, String id, String dev_name, String ip) {
File configFile = SPIFFS.open("/" + fileName, "r");
if (!configFile) {
addFile(fileName, "device id;device name;ip adress");
}
if (!configFile.find(id.c_str())) {
addFile(fileName, id + ";" + dev_name + "; <a href=\"http://" + ip + "\" target=\"_blank\"\">" + ip + "</a>");
}
}
void handleUdp() {
if (WiFi.status() == WL_CONNECTED) {
int packetSize = Udp.parsePacket();
if (packetSize) {
//Serial.printf("Received %d bytes from %s, port %d\n", packetSize, Udp.remoteIP().toString().c_str(), Udp.remotePort());
received_ip = Udp.remoteIP().toString();
int len = Udp.read(udp_incomingPacket, 255);
if (len > 0) {
udp_incomingPacket[len] = 0;
}
received_udp_line = String(udp_incomingPacket);
udp_data_parse = true;
}
}
}
void do_udp_data_parse() {
if (udp_data_parse) {
udp_data_parse = false;
Serial.print("[UDP=>] " + received_ip);
Serial.print(" ");
Serial.println(received_udp_line);
if (received_udp_line.indexOf("mqttServer") > 0) {
jsonWriteStr(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"));
saveConfig();
Serial.println("[V] new mqtt setting received from udp and saved");
mqtt_connection = true;
} else {
add_dev_in_list("dev.csv", selectFromMarkerToMarker(received_udp_line, ";", 0), selectFromMarkerToMarker(received_udp_line, ";", 1), received_ip);
}
}
}
void send_mqtt_to_udp() {
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"));
Serial.println(mqtt_data);
#ifdef ESP8266
Udp.beginPacketMulticast(udp_multicastIP, udp_port, WiFi.localIP());
Udp.write(mqtt_data.c_str());
#endif
#ifdef ESP32
Udp.beginMulticast(udp_multicastIP, udp_port);
int size_of = sizeof(mqtt_data);
uint8_t msg[10] = (uint8_t)atoi(mqtt_data.c_str());
//Udp.write(msg, sizeof(mqtt_data));
//Udp.write(mqtt_data.c_str(), strlen(mqtt_data.c_str()));
#endif
Udp.endPacket();
Serial.println("[UDP<=] mqtt info send");
udp_busy = false;
}
}