add udp support for esp32

Device can see each other esp32 and esp8266 and send date
This commit is contained in:
Dmitry Borisenko
2020-04-21 01:20:56 +02:00
parent 285a898ba9
commit 990bd6fb47
6 changed files with 107 additions and 96 deletions

View File

@@ -23,7 +23,7 @@ void initUpgrade() {
jsonWriteStr(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>Последняя версия прошивки уже установлена."); jsonWriteStr(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>Последняя версия прошивки уже установлена.");
jsonWriteStr(tmp, "class", "pop-up"); jsonWriteStr(tmp, "class", "pop-up");
} else { } 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, "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='/'; }, 90000);html('my-block','<span class=loader></span>Идет обновление прошивки, после обновления страница перезагрузится автоматически...')\">Установить</a>");
jsonWriteStr(tmp, "class", "pop-up"); jsonWriteStr(tmp, "class", "pop-up");
} }
} else { } else {

View File

@@ -0,0 +1,18 @@
{
"name": "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

@@ -38,9 +38,10 @@ void setup() {
ts.add(TEST, 5000, [&](void*) { ts.add(TEST, 10000, [&](void*) {
getMemoryLoad("[i] periodic check of"); getMemoryLoad("[i] periodic check of");
//String json = "{}"; //String json = "{}";
//jsonWriteStr(json, "test6", GetTime()); //jsonWriteStr(json, "test6", GetTime());
//ws.textAll(json); //ws.textAll(json);

128
set.h
View File

@@ -1,175 +1,153 @@
String firmware_version = "2.3.1"; //===============FIRMWARE SETTINGS=====================================
//----------------------------------------------------------------- String firmware_version = "2.3.2";
boolean mb_4_of_memory = true; boolean mb_4_of_memory = true;
String last_version;
//#define OTA_enable //#define OTA_enable
//#define MDNS_enable //#define MDNS_enable
//#define WS_enable //#define WS_enable
//#define layout_in_ram //#define layout_in_ram
#define TIME_COMPILING String(__TIME__)
#define DATE_COMPILING String(__DATE__)
//-----------------------------------------------------------------
#define wifi_mqtt_reconnecting 20000 #define wifi_mqtt_reconnecting 20000
//-----------------------------------------------------------------
#define analog_update_int 5000 #define analog_update_int 5000
//-----------------------------------------------------------------
#define temp_update_int 5000 #define temp_update_int 5000
//-----------------------------------------------------------------
#define tank_level_shooting_interval 500 //интервал выстрела датчика #define tank_level_shooting_interval 500 //интервал выстрела датчика
#define tank_level_times_to_send 20 //после скольки выстрелов делать отправку данных #define tank_level_times_to_send 20 //после скольки выстрелов делать отправку данных
//-----------------------------------------------------------------
#define dhtT_update_int 10000 #define dhtT_update_int 10000
#define dhtH_update_int 10000 #define dhtH_update_int 10000
#define dht_calculation_update_int 10000 #define dht_calculation_update_int 10000
//-----------------------------------------------------------------
#define statistics_update 1000 * 60 * 60 * 2 #define statistics_update 1000 * 60 * 60 * 2
//----------------------------------------------------------------- //======================================================================
#define TIME_COMPILING String(__TIME__)
#define DATE_COMPILING String(__DATE__)
//==библиотеки и объекты для ESP8266==// //===============библиотеки и объекты для ESP8266========================
#ifdef ESP8266 #ifdef ESP8266
#include <ESP8266WiFi.h> #include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h> #include <ESP8266HTTPClient.h>
#ifdef MDNS_enable
#include <ESP8266mDNS.h>
#endif
#include <ESP8266httpUpdate.h> #include <ESP8266httpUpdate.h>
#include <ESP8266HTTPUpdateServer.h> #include <ESP8266HTTPUpdateServer.h>
ESP8266HTTPUpdateServer httpUpdater; ESP8266HTTPUpdateServer httpUpdater;
#include <WiFiUdp.h>
WiFiUDP Udp;
#ifdef MDNS_enable
#include <ESP8266mDNS.h>
#endif #endif
//==библиотеки и объекты для ESP32==// #endif
//===============библиотеки и объекты для ESP32===========================
#ifdef ESP32 #ifdef ESP32
#include <WiFi.h> #include <WiFi.h>
#include <SPIFFS.h> #include <SPIFFS.h>
#ifdef MDNS_enable
#include <ESPmDNS.h>
#endif
#include <AsyncTCP.h> #include <AsyncTCP.h>
#include <analogWrite.h> #include <analogWrite.h>
#include <HTTPUpdate.h> #include <HTTPUpdate.h>
#include <HTTPClient.h> #include <HTTPClient.h>
#include "AsyncUDP.h"
AsyncUDP udp;
#ifdef MDNS_enable
#include <ESPmDNS.h>
#endif #endif
//==общие библиотеки и объекты==// #endif
//===============общие библиотеки и объекты===============================
#include <Arduino.h> #include <Arduino.h>
#include "time.h" #include "time.h"
#ifdef OTA_enable #ifdef OTA_enable
#include <ArduinoOTA.h> #include <ArduinoOTA.h>
#endif #endif
#include <FS.h> #include <FS.h>
#include <ArduinoJson.h> #include <ArduinoJson.h>
#include <ESPAsyncWebServer.h> #include <ESPAsyncWebServer.h>
#include <SPIFFSEditor.h> #include <SPIFFSEditor.h>
AsyncWebServer server(80); AsyncWebServer server(80);
#ifdef WS_enable #ifdef WS_enable
AsyncWebSocket ws("/ws"); AsyncWebSocket ws("/ws");
#endif #endif
AsyncEventSource events("/events"); AsyncEventSource events("/events");
//---------------------------------------------------------------
#include <time.h> #include <time.h>
//---------------------------------------------------------------
#include <TickerScheduler.h> #include <TickerScheduler.h>
TickerScheduler ts(30); 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, UDP, UDP_DB, 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 <WiFiUdp.h>
WiFiUDP Udp;
//---------------------------------------------------------------
#include <PubSubClient.h> #include <PubSubClient.h>
WiFiClient espClient; WiFiClient espClient;
//ssl//WiFiClientSecure espClient;
PubSubClient client(espClient); PubSubClient client(espClient);
//---------------------------------------------------------------
#include <StringCommand.h> #include <StringCommand.h>
StringCommand sCmd; StringCommand sCmd;
//---------------------------------------------------------------
#include <Bounce2.h> #include <Bounce2.h>
#define NUM_BUTTONS 6 #define NUM_BUTTONS 6
boolean but[NUM_BUTTONS]; boolean but[NUM_BUTTONS];
Bounce * buttons = new Bounce[NUM_BUTTONS]; Bounce * buttons = new Bounce[NUM_BUTTONS];
//----------------------------------------------------------------
#include "GyverFilters.h" //настраивается в GyverHacks.h - MEDIAN_FILTER_SIZE #include "GyverFilters.h" //настраивается в GyverHacks.h - MEDIAN_FILTER_SIZE
GMedian medianFilter; GMedian medianFilter;
//----------------------------------------------------------------
#include <OneWire.h> #include <OneWire.h>
#include <DallasTemperature.h> #include <DallasTemperature.h>
OneWire *oneWire; OneWire *oneWire;
DallasTemperature sensors; DallasTemperature sensors;
//----------------------------------------------------------------
#include <DHTesp.h> #include <DHTesp.h>
DHTesp dht; DHTesp dht;
//----------------------------------------------------------------
//#include <ModbusMaster.h>
//#include "SoftwareSerial.h"
//SoftwareSerial SoftSerial(12, 13, false, 128);
//ModbusMaster modbus;
//swSer.begin(9600);
//modbus.begin(1, SoftSerial);
//-----------------------------------------------------------------
//===============FIRMWARE VARS========================
boolean just_load = true; boolean just_load = true;
const char* hostName = "IoT Manager"; const char* hostName = "IoT Manager";
//JSON
String configSetup = "{}"; //setup String configSetup = "{}";
String configJson = "{}"; //live String configJson = "{}";
String optionJson = "{}"; String optionJson = "{}";
//MQTT
String json = "{}";
String chipID = ""; String chipID = "";
String prex; String prex;
String ids;
String all_widgets = ""; String all_widgets = "";
String scenario; String scenario;
String order_loop; String order_loop;
//SENSORS
boolean flagLoggingAnalog = false; boolean flagLoggingAnalog = false;
boolean flagLoggingLevel = false; boolean flagLoggingLevel = false;
boolean flagLoggingDallas = false; boolean flagLoggingDallas = false;
boolean flagLoggingdhtT = false; boolean flagLoggingdhtT = false;
boolean flagLoggingdhtH = false; boolean flagLoggingdhtH = false;
//NTP
const char* ntpServer = "pool.ntp.org"; const char* ntpServer = "pool.ntp.org";
const long gmtOffset_sec = 3600; const long gmtOffset_sec = 3600;
const int daylightOffset_sec = 3600; const int daylightOffset_sec = 3600;
String current_time; String current_time;
//SCENARIO
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}; 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};
//ERRORS
int wifi_lost_error = 0; int wifi_lost_error = 0;
int mqtt_lost_error = 0; int mqtt_lost_error = 0;
String last_version;
String var; //ASYNC ACTIONS
//flags for not async actions
boolean upgrade_url = false; boolean upgrade_url = false;
boolean upgrade = false; boolean upgrade = false;
boolean mqtt_connection = false; boolean mqtt_connection = false;
boolean udp_data_parse = false; boolean udp_data_parse = false;
boolean mqtt_send_settings_to_udp = false; boolean mqtt_send_settings_to_udp = false;
//UDP
boolean udp_busy = false; boolean udp_busy = false;
String test;
boolean chart_data_in_solid_array; boolean chart_data_in_solid_array;
unsigned int udp_port = 4210; unsigned int udp_port = 4210;
char udp_incomingPacket[255]; #ifdef ESP8266
//char udp_replyPacket[] = "Multicast packet 1";
IPAddress udp_multicastIP (255, 255, 255, 255); IPAddress udp_multicastIP (255, 255, 255, 255);
#endif
#ifdef ESP32
IPAddress udp_multicastIP (239, 255, 255, 255);
#endif
String received_ip; String received_ip;
String received_udp_line; String received_udp_line;

52
udp.ino
View File

@@ -10,6 +10,7 @@ void UDP_init() {
} }
if (value == "2") { if (value == "2") {
SPIFFS.remove("/dev.csv"); SPIFFS.remove("/dev.csv");
addFile("dev.csv", "device id;device name;ip address");
request->redirect("/?dev"); request->redirect("/?dev");
} }
if (value == "3") { if (value == "3") {
@@ -26,8 +27,13 @@ void UDP_init() {
}); });
SPIFFS.remove("/dev.csv"); SPIFFS.remove("/dev.csv");
addFile("dev.csv", "device id;device name;ip address");
#ifdef ESP8266
Udp.begin(udp_port); Udp.begin(udp_port);
#endif
handleUdp_esp32();
ts.add(UDP, 30000, [&](void*) { ts.add(UDP, 30000, [&](void*) {
if (WiFi.status() == WL_CONNECTED) { if (WiFi.status() == WL_CONNECTED) {
@@ -36,32 +42,24 @@ void UDP_init() {
#ifdef ESP8266 #ifdef ESP8266
Udp.beginPacketMulticast(udp_multicastIP, udp_port, WiFi.localIP()); Udp.beginPacketMulticast(udp_multicastIP, udp_port, WiFi.localIP());
Udp.write(line_to_send.c_str()); Udp.write(line_to_send.c_str());
Udp.endPacket();
#endif #endif
#ifdef ESP32 #ifdef ESP32
Udp.beginMulticast(udp_multicastIP, udp_port); udp.broadcast(line_to_send.c_str());
#endif #endif
Udp.endPacket();
Serial.println("[UDP<=] dev info send"); Serial.println("[UDP<=] dev info send");
} }
} }
}, nullptr, false); }, 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() { void handleUdp() {
#ifdef ESP8266
if (WiFi.status() == WL_CONNECTED) { if (WiFi.status() == WL_CONNECTED) {
int packetSize = Udp.parsePacket(); int packetSize = Udp.parsePacket();
if (packetSize) { if (packetSize) {
//Serial.printf("Received %d bytes from %s, port %d\n", packetSize, Udp.remoteIP().toString().c_str(), Udp.remotePort()); char udp_incomingPacket[255];
Serial.printf("[UDP=>] Received %d bytes from %s, port %d\n", packetSize, Udp.remoteIP().toString().c_str(), Udp.remotePort());
received_ip = Udp.remoteIP().toString(); received_ip = Udp.remoteIP().toString();
int len = Udp.read(udp_incomingPacket, 255); int len = Udp.read(udp_incomingPacket, 255);
if (len > 0) { if (len > 0) {
@@ -71,6 +69,19 @@ void handleUdp() {
udp_data_parse = true; udp_data_parse = true;
} }
} }
#endif
}
void handleUdp_esp32() {
#ifdef ESP32
if (udp.listenMulticast(udp_multicastIP, udp_port)) {
udp.onPacket([](AsyncUDPPacket packet) {
received_udp_line = (char*)packet.data();
received_ip = packet.remoteIP().toString();
udp_data_parse = true;
});
}
#endif
} }
void do_udp_data_parse() { void do_udp_data_parse() {
@@ -94,6 +105,13 @@ void do_udp_data_parse() {
} }
} }
void add_dev_in_list(String fileName, String id, String dev_name, String ip) {
File configFile = SPIFFS.open("/" + fileName, "r");
if (!configFile.find(id.c_str())) {
addFile(fileName, id + ";" + dev_name + "; <a href=\"http://" + ip + "\" target=\"_blank\"\">" + ip + "</a>");
}
}
void send_mqtt_to_udp() { void send_mqtt_to_udp() {
if (WiFi.status() == WL_CONNECTED) { if (WiFi.status() == WL_CONNECTED) {
udp_busy = true; udp_busy = true;
@@ -107,15 +125,11 @@ void send_mqtt_to_udp() {
#ifdef ESP8266 #ifdef ESP8266
Udp.beginPacketMulticast(udp_multicastIP, udp_port, WiFi.localIP()); Udp.beginPacketMulticast(udp_multicastIP, udp_port, WiFi.localIP());
Udp.write(mqtt_data.c_str()); Udp.write(mqtt_data.c_str());
Udp.endPacket();
#endif #endif
#ifdef ESP32 #ifdef ESP32
Udp.beginMulticast(udp_multicastIP, udp_port); udp.broadcast(mqtt_data.c_str());
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 #endif
Udp.endPacket();
Serial.println("[UDP<=] mqtt info send"); Serial.println("[UDP<=] mqtt info send");
udp_busy = false; udp_busy = false;
} }