Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extend the UDP message sender Cookbook with 8266 example #3924

Open
wants to merge 8 commits into
base: current
Choose a base branch
from
20 changes: 17 additions & 3 deletions cookbook/lambda_magic.rst
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,27 @@ You can send such UDP commands from ESPHome using a Lambda in a script.

.. code-block:: yaml

esphome:
...
includes: # only needed in case of ESP8266
- WiFiUdp.h

script:
- id: send_udp
parameters:
msg: string
host: string
port: int
then:
# in case of ESP8266:
- lambda: |-
WiFiUDP Udp;
Udp.beginPacket(host.c_str(), port);
Udp.write(msg.c_str());
Udp.endPacket();
ESP_LOGD("lambda", "Sent %s to %s:%d", msg.c_str(), host.c_str(), port);

# in case of ESP32:
- lambda: |-
int sock = ::socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in destination, source;
Expand All @@ -76,15 +90,15 @@ You can send such UDP commands from ESPHome using a Lambda in a script.
destination.sin_port = htons(port);
destination.sin_addr.s_addr = inet_addr(host.c_str());

// you can remove the next 4 lines if you don't want to set the source port for outgoing packets
// you can remove the next 4 lines if you don't need to set the source port for outgoing packets
source.sin_family = AF_INET;
source.sin_addr.s_addr = htonl(INADDR_ANY);
source.sin_port = htons(64998); // the source port number
bind(sock, (struct sockaddr*)&source, sizeof(source));

int n_bytes = ::sendto(sock, msg.c_str(), msg.length(), 0, reinterpret_cast<sockaddr*>(&destination), sizeof(destination));
ESP_LOGD("lambda", "Sent %s to %s:%d in %d bytes", msg.c_str(), host.c_str(), port, n_bytes);
::close(sock);
ESP_LOGD("lambda", "Sent %s to %s:%d in %d bytes", msg.c_str(), host.c_str(), port, n_bytes);

button:
- platform: template
Expand All @@ -97,7 +111,7 @@ You can send such UDP commands from ESPHome using a Lambda in a script.
host: "192.168.1.10"
port: 5000

Tested on both `arduino` and `esp-idf` platforms.
Tested on ESP32 ``arduino`` and ``esp-idf`` platforms. In case of ESP8266 get ``WiFiUdp.h`` from `here <https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/src/WiFiUdp.h>`__ and place it in your configuration directory.

.. _lambda_magic_uart_text_sensor:

Expand Down