NodeMCU en español
NodeMCU - Juan Antonio Villalpando
-- Tutorial de NodeMCU en español --
Volver al índice del tutorial NodeMCU
____________________________
118B.- Wemos D1 R32 ESP32. Envía y recibe por UDP. App Inventor. Extensión UDP.
p118B_ESP32_UDP.aia
- El envío de información por el protocolo UDP no tiene confirmación de llegada, en el TCP/IP el receptor comprueba si han llegado todos los paquetes y en caso de que falte alguno, se lo vuelve a pedir al transmisor.
- El UDP tiene varias modalidades.
- En Unicast se envía la información a un cliente.
- En Broadcast a toda la red.
- En Multicast a algunos clientes.
https://www.redeszone.net/tutoriales/internet/tcp-udp-caracteristicas-uso-diferencias/
Consulta: 118_Wemos_UDP.htm
_______________________________________________________
1.- App Inventor envía texto a ESP32 por UDP. Enciende/Apaga LED2. Consulta estado.
- Extensión:
https://ullisroboterseite.de/android-AI2-UDP-en.html de Ulrich_Bien
- Adaptación de:
https://github.com/espressif/arduino-esp32/blob/master/libraries/AsyncUDP/examples/AsyncUDPServer/AsyncUDPServer.ino
- Conecta con nuestra red WiFi.
- El puerto de este Servidor lo establecemos en: 1234
- Si recibe "on", enciende el LED2 y devuelve el mensaje "Received: on".
- Si recibe "off", apaga el LED2 y devuelve el mensaje "Received: off".
- Si recibe "consulta", devuelve el mensaje "Now LED2 is HIGH (LOW)".
- En este ejemplo la aplicación enviará el mensaje a toda la red "Broadcast" (255.255.255.255) y lo recibirá todos los dispositivos que tengan abierto el puerto 1234 con UDP.
https://stackoverflow.com/questions/1098897/what-is-the-largest-safe-udp-packet-size-on-the-internet
- Experimentalmente he comprobado que se puede enviar hasta 65507 caracteres, pero se reciben 4096.
ESP32_AsyncUDPServer.ino |
#include "WiFi.h"
#include "AsyncUDP.h"
const char * ssid = "Nombre_WiFi";
const char * password = "Clave_WiFi";
AsyncUDP udp;
void setup(){
pinMode(2, OUTPUT); // HERE LED2
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println("WiFi Failed");
while(1) {
delay(1000);
}
}
if(udp.listen(1234)) {
Serial.print("UDP Listening on IP: ");
Serial.println(WiFi.localIP());
udp.onPacket([](AsyncUDPPacket packet) {
Serial.print("UDP Packet Type: ");
Serial.print(packet.isBroadcast()?"Broadcast":packet.isMulticast()?"Multicast":"Unicast");
Serial.print(", From: ");
Serial.print(packet.remoteIP());
Serial.print(":");
Serial.print(packet.remotePort());
Serial.print(", To: ");
Serial.print(packet.localIP());
Serial.print(":");
Serial.print(packet.localPort());
Serial.print(", Length: ");
Serial.print(packet.length());
Serial.print(", Data: ");
Serial.write(packet.data(), packet.length());
Serial.println();
// https://stackoverflow.com/questions/58253174/saving-packet-data-to-string-with-asyncudp-on-esp32
// String mensaje = (char*)(packet.data());
char* tmpStr = (char*) malloc(packet.length() + 1);
memcpy(tmpStr, packet.data(), packet.length());
tmpStr[packet.length()] = '\0'; // ensure null termination
String mensaje = String(tmpStr);
free(tmpStr); // Strign(char*) creates a copy so we can delete our one
Serial.println(mensaje);
if(mensaje == "on"){
digitalWrite(2, HIGH);
packet.print("Received: on");
}
if(mensaje == "off"){
digitalWrite(2, LOW);
packet.print("Received: off");
}
if(mensaje == "consulta"){
if(digitalRead(2 == HIGH)){packet.print("Now LED2 is HIGH");}
if(digitalRead(2 == LOW)) {packet.print("Now LED2 is LOW");}
}
//reply to the client
//packet.printf("Got %u bytes of data", packet.length());
});
}
}
void loop(){
delay(1000);
//Send broadcast
udp.broadcast("Anyone here?");
}
|
Mediante String mensaje = (char*)(packet.data());
se puede recibir el texto del mensaje, pero a veces hay problemas ya que es necesario que el mensaje termine en caracter nulo '\0'
para mayor seguridad utilizamos el código indicado en:
https://stackoverflow.com/questions/58253174/saving-packet-data-to-string-with-asyncudp-on-esp32
_______________________________________________________
- Diseño.
_______________________________________________________
- Bloques.
- Si en FromPort ponemos 0, envía desde un puerto aleatorio.
- Si en ToIP ponemos 255.255.255.255 (Broadcast), lo envía a todos los dispositivos de la red y los recibe aquellos que tengan abierto el puerto 1234 a UDP.
- Si en ToIP ponemos 192.168.1.12, solo lo recibirá ese dispositivo.
_______________________________________________________
2.- Chat con dos móviles.
_______________________________________________________
3.- Desde Windows enviamos un paquete UDP al ESP32.
- Bajamos esta aplicación: https://packetsender.com/download#show
_______________________________
|