From 6f00ea1457f5fc9216c2cd3f3b251073250486ec Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Thu, 23 Apr 2026 05:53:10 +0200 Subject: [PATCH 1/4] [core] Move host socket-select wake mechanism into wake.h/wake.cpp (#15931) --- .../components/socket/bsd_sockets_impl.cpp | 7 +- .../components/socket/lwip_sockets_impl.cpp | 7 +- esphome/components/socket/socket.cpp | 7 +- esphome/core/application.cpp | 167 +--------------- esphome/core/application.h | 100 +--------- esphome/core/wake.cpp | 188 +++++++++++++++++- esphome/core/wake.h | 56 ++++++ 7 files changed, 263 insertions(+), 269 deletions(-) diff --git a/esphome/components/socket/bsd_sockets_impl.cpp b/esphome/components/socket/bsd_sockets_impl.cpp index 92691b17ab..8e9968e05c 100644 --- a/esphome/components/socket/bsd_sockets_impl.cpp +++ b/esphome/components/socket/bsd_sockets_impl.cpp @@ -6,6 +6,9 @@ #include #include "esphome/core/application.h" +#ifdef USE_HOST +#include "esphome/core/wake.h" +#endif namespace esphome::socket { @@ -16,7 +19,7 @@ BSDSocketImpl::BSDSocketImpl(int fd, bool monitor_loop) { #ifdef USE_LWIP_FAST_SELECT this->cached_sock_ = hook_fd_for_fast_select(this->fd_); #else - this->loop_monitored_ = App.register_socket_fd(this->fd_); + this->loop_monitored_ = wake_register_fd(this->fd_); #endif } @@ -36,7 +39,7 @@ int BSDSocketImpl::close() { this->cached_sock_ = nullptr; #else if (this->loop_monitored_) { - App.unregister_socket_fd(this->fd_); + wake_unregister_fd(this->fd_); } #endif int ret = ::close(this->fd_); diff --git a/esphome/components/socket/lwip_sockets_impl.cpp b/esphome/components/socket/lwip_sockets_impl.cpp index b4eba3febf..a6bd639c10 100644 --- a/esphome/components/socket/lwip_sockets_impl.cpp +++ b/esphome/components/socket/lwip_sockets_impl.cpp @@ -6,6 +6,9 @@ #include #include "esphome/core/application.h" +#ifdef USE_HOST +#include "esphome/core/wake.h" +#endif namespace esphome::socket { @@ -16,7 +19,7 @@ LwIPSocketImpl::LwIPSocketImpl(int fd, bool monitor_loop) { #ifdef USE_LWIP_FAST_SELECT this->cached_sock_ = hook_fd_for_fast_select(this->fd_); #else - this->loop_monitored_ = App.register_socket_fd(this->fd_); + this->loop_monitored_ = wake_register_fd(this->fd_); #endif } @@ -36,7 +39,7 @@ int LwIPSocketImpl::close() { this->cached_sock_ = nullptr; #else if (this->loop_monitored_) { - App.unregister_socket_fd(this->fd_); + wake_unregister_fd(this->fd_); } #endif int ret = lwip_close(this->fd_); diff --git a/esphome/components/socket/socket.cpp b/esphome/components/socket/socket.cpp index bc43b2746e..f14ac1e2d5 100644 --- a/esphome/components/socket/socket.cpp +++ b/esphome/components/socket/socket.cpp @@ -5,13 +5,16 @@ #include #include "esphome/core/log.h" #include "esphome/core/application.h" +#ifdef USE_HOST +#include "esphome/core/wake.h" +#endif namespace esphome::socket { #ifdef USE_HOST // Shared ready() implementation for fd-based socket implementations (BSD and LWIP sockets). -// Checks if the Application's select() loop has marked this fd as ready. -bool socket_ready_fd(int fd, bool loop_monitored) { return !loop_monitored || App.is_socket_ready_(fd); } +// Checks if the host wake select() loop has marked this fd as ready. +bool socket_ready_fd(int fd, bool loop_monitored) { return !loop_monitored || wake_fd_ready(fd); } #endif // Platform-specific inet_ntop wrappers diff --git a/esphome/core/application.cpp b/esphome/core/application.cpp index 8612782d95..3105ff2e8b 100644 --- a/esphome/core/application.cpp +++ b/esphome/core/application.cpp @@ -28,10 +28,6 @@ #include "esphome/components/socket/socket.h" #endif -#ifdef USE_HOST -#include -#endif - namespace esphome { static const char *const TAG = "app"; @@ -133,8 +129,8 @@ void Application::setup() { esphome_main_task_handle = xTaskGetCurrentTaskHandle(); #endif #ifdef USE_HOST - // Set up wake socket for waking main loop from tasks (platforms without fast select only) - this->setup_wake_loop_threadsafe_(); + // Set up wake socket for waking main loop from tasks (host platform select() loop). + wake_setup(); #endif // Ensure all active looping components are in LOOP state. @@ -510,105 +506,6 @@ void Application::enable_pending_loops_() { } } -#ifdef USE_HOST -bool Application::register_socket_fd(int fd) { - // WARNING: This function is NOT thread-safe and must only be called from the main loop - // It modifies socket_fds_ and related variables without locking - if (fd < 0) - return false; - - if (fd >= FD_SETSIZE) { - ESP_LOGE(TAG, "fd %d exceeds FD_SETSIZE %d", fd, FD_SETSIZE); - return false; - } - - this->socket_fds_.push_back(fd); - this->socket_fds_changed_ = true; - if (fd > this->max_fd_) { - this->max_fd_ = fd; - } - - return true; -} - -void Application::unregister_socket_fd(int fd) { - // WARNING: This function is NOT thread-safe and must only be called from the main loop - // It modifies socket_fds_ and related variables without locking - if (fd < 0) - return; - - for (size_t i = 0; i < this->socket_fds_.size(); i++) { - if (this->socket_fds_[i] != fd) - continue; - - // Swap with last element and pop - O(1) removal since order doesn't matter. - if (i < this->socket_fds_.size() - 1) - this->socket_fds_[i] = this->socket_fds_.back(); - this->socket_fds_.pop_back(); - this->socket_fds_changed_ = true; - // Only recalculate max_fd if we removed the current max - if (fd == this->max_fd_) { - this->max_fd_ = -1; - for (int sock_fd : this->socket_fds_) { - if (sock_fd > this->max_fd_) - this->max_fd_ = sock_fd; - } - } - return; - } -} - -#endif - -// Only the select() fallback path remains in the .cpp — all other paths are inlined in application.h -#ifdef USE_HOST -void Application::yield_with_select_(uint32_t delay_ms) { - // Fallback select() path (host platform and any future platforms without fast select). - if (!this->socket_fds_.empty()) [[likely]] { - // Update fd_set if socket list has changed - if (this->socket_fds_changed_) [[unlikely]] { - FD_ZERO(&this->base_read_fds_); - // fd bounds are validated in register_socket_fd() - for (int fd : this->socket_fds_) { - FD_SET(fd, &this->base_read_fds_); - } - this->socket_fds_changed_ = false; - } - - // Copy base fd_set before each select - this->read_fds_ = this->base_read_fds_; - - // Convert delay_ms to timeval - struct timeval tv; - tv.tv_sec = delay_ms / 1000; - tv.tv_usec = (delay_ms - tv.tv_sec * 1000) * 1000; - - // Call select with timeout - int ret = ::select(this->max_fd_ + 1, &this->read_fds_, nullptr, nullptr, &tv); - - // Process select() result: - // ret > 0: socket(s) have data ready - normal and expected - // ret == 0: timeout occurred - normal and expected - if (ret >= 0) [[likely]] { - // Yield if zero timeout since select(0) only polls without yielding - if (delay_ms == 0) [[unlikely]] { - yield(); - } - return; - } - // ret < 0: error (EINTR is normal, anything else is unexpected) - const int err = errno; - if (err == EINTR) { - return; - } - // select() error - log and fall through to delay() - ESP_LOGW(TAG, "select() failed with errno %d", err); - } - // No sockets registered or select() failed - use regular delay - delay(delay_ms); -} -#endif // USE_HOST - // App storage — asm label shares the linker symbol with "extern Application App". // char[] is trivially destructible, so no __cxa_atexit or destructor chain is emitted. // Constructed via placement new in the generated setup(). @@ -628,66 +525,6 @@ alignas(Application) char app_storage[sizeof(Application)] asm( #undef ESPHOME_STRINGIFY_ #undef ESPHOME_STRINGIFY_IMPL_ -// Host platform wake_loop_threadsafe() and setup — needs wake_socket_fd_ -// ESP32/LibreTiny/ESP8266/RP2040 implementations are in wake.cpp -#ifdef USE_HOST - -void Application::setup_wake_loop_threadsafe_() { - // Create UDP socket for wake notifications - this->wake_socket_fd_ = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); - if (this->wake_socket_fd_ < 0) { - ESP_LOGW(TAG, "Wake socket create failed: %d", errno); - return; - } - - // Bind to loopback with auto-assigned port - struct sockaddr_in addr = {}; - addr.sin_family = AF_INET; - addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); - addr.sin_port = 0; // Auto-assign port - - if (::bind(this->wake_socket_fd_, (struct sockaddr *) &addr, sizeof(addr)) < 0) { - ESP_LOGW(TAG, "Wake socket bind failed: %d", errno); - ::close(this->wake_socket_fd_); - this->wake_socket_fd_ = -1; - return; - } - - // Get the assigned address and connect to it - // Connecting a UDP socket allows using send() instead of sendto() for better performance - struct sockaddr_in wake_addr; - socklen_t len = sizeof(wake_addr); - if (::getsockname(this->wake_socket_fd_, (struct sockaddr *) &wake_addr, &len) < 0) { - ESP_LOGW(TAG, "Wake socket address failed: %d", errno); - ::close(this->wake_socket_fd_); - this->wake_socket_fd_ = -1; - return; - } - - // Connect to self (loopback) - allows using send() instead of sendto() - // After connect(), no need to store wake_addr - the socket remembers it - if (::connect(this->wake_socket_fd_, (struct sockaddr *) &wake_addr, sizeof(wake_addr)) < 0) { - ESP_LOGW(TAG, "Wake socket connect failed: %d", errno); - ::close(this->wake_socket_fd_); - this->wake_socket_fd_ = -1; - return; - } - - // Set non-blocking mode - int flags = ::fcntl(this->wake_socket_fd_, F_GETFL, 0); - ::fcntl(this->wake_socket_fd_, F_SETFL, flags | O_NONBLOCK); - - // Register with application's select() loop - if (!this->register_socket_fd(this->wake_socket_fd_)) { - ESP_LOGW(TAG, "Wake socket register failed"); - ::close(this->wake_socket_fd_); - this->wake_socket_fd_ = -1; - return; - } -} - -#endif // USE_HOST - void Application::get_build_time_string(std::span buffer) { ESPHOME_strncpy_P(buffer.data(), ESPHOME_BUILD_TIME_STR, buffer.size()); buffer[buffer.size() - 1] = '\0'; diff --git a/esphome/core/application.h b/esphome/core/application.h index 3d8df88d2a..8280b3bd4b 100644 --- a/esphome/core/application.h +++ b/esphome/core/application.h @@ -27,27 +27,12 @@ #ifdef USE_LWIP_FAST_SELECT #include "esphome/core/lwip_fast_select.h" #endif -#ifdef USE_HOST -#include -#include -#include -#include -#include -#include -#endif #ifdef USE_RUNTIME_STATS #include "esphome/components/runtime_stats/runtime_stats.h" #endif #include "esphome/core/wake.h" #include "esphome/core/entity_includes.h" -namespace esphome::socket { -#ifdef USE_HOST -/// Shared ready() helper for fd-based socket implementations. -bool socket_ready_fd(int fd, bool loop_monitored); // NOLINT(readability-redundant-declaration) -#endif -} // namespace esphome::socket - #ifdef USE_RUNTIME_STATS namespace esphome::runtime_stats { class RuntimeStatsCollector; @@ -343,18 +328,6 @@ class Application { Scheduler scheduler; -#ifdef USE_HOST - /// Register/unregister a socket file descriptor with the host select() fallback loop. - /// USE_LWIP_FAST_SELECT builds do not use this API — sockets hook the lwIP netconn - /// event_callback directly (see socket.h hook_fd_for_fast_select) and rely on FreeRTOS - /// task notifications for wake-up. - /// NOTE: File descriptors >= FD_SETSIZE (typically 10 on ESP) will be rejected with an error. - /// WARNING: These functions are NOT thread-safe. They must only be called from the main loop. - /// @return true if registration was successful, false if fd exceeds limits - bool register_socket_fd(int fd); - void unregister_socket_fd(int fd); -#endif - /// Wake the main event loop from another thread or callback. /// @see esphome::wake_loop_threadsafe() in wake.h for platform details. void wake_loop_threadsafe() { esphome::wake_loop_threadsafe(); } @@ -372,21 +345,11 @@ class Application { protected: friend Component; -#ifdef USE_HOST - friend bool socket::socket_ready_fd(int fd, bool loop_monitored); -#endif #ifdef USE_RUNTIME_STATS friend class runtime_stats::RuntimeStatsCollector; #endif friend void ::setup(); friend void ::original_setup(); -#ifdef USE_HOST - friend void wake_loop_threadsafe(); // Host platform accesses wake_socket_fd_ -#endif - -#ifdef USE_HOST - bool is_socket_ready_(int fd) const { return FD_ISSET(fd, &this->read_fds_); } -#endif /// Walk all registered components looking for any whose component_state_ /// has the given flag set. Used by Component::status_clear_*_slow_path_() @@ -460,18 +423,9 @@ class Application { void service_status_led_slow_(uint32_t time); #endif - /// Perform a delay while also monitoring socket file descriptors for readiness -#ifdef USE_HOST - // select() fallback path is too complex to inline (host platform) - void yield_with_select_(uint32_t delay_ms); -#else + /// Sleep for up to delay_ms, returning early if a wake event arrives. + /// Thin wrapper over the platform wake primitive in wake.h. inline void ESPHOME_ALWAYS_INLINE yield_with_select_(uint32_t delay_ms); -#endif - -#ifdef USE_HOST - void setup_wake_loop_threadsafe_(); // Create wake notification socket - inline void drain_wake_notifications_(); // Read pending wake notifications in main loop (hot path - inlined) -#endif // === Member variables ordered by size to minimize padding === @@ -496,9 +450,6 @@ class Application { // and active_end_ is incremented // - This eliminates branch mispredictions from flag checking in the hot loop FixedVector looping_components_{}; -#ifdef USE_HOST - std::vector socket_fds_; // Vector of all monitored socket file descriptors -#endif // StringRef members (8 bytes each: pointer + size) StringRef name_; @@ -513,11 +464,6 @@ class Application { uint32_t last_status_led_service_{0}; #endif -#ifdef USE_HOST - int max_fd_{-1}; // Highest file descriptor number for select() - int wake_socket_fd_{-1}; // Shared wake notification socket for waking main loop from tasks -#endif - // 2-byte members (grouped together for alignment) uint16_t dump_config_at_{std::numeric_limits::max()}; // Index into components_ for dump_config progress uint16_t loop_interval_{16}; // Loop interval in ms (max 65535ms = 65.5 seconds) @@ -530,14 +476,6 @@ class Application { bool in_loop_{false}; volatile bool has_pending_enable_loop_requests_{false}; -#ifdef USE_HOST - bool socket_fds_changed_{false}; // Flag to rebuild base_read_fds_ when socket_fds_ changes - - // Variable-sized members (not needed with fast select — is_socket_ready_ reads rcvevent directly) - fd_set read_fds_{}; // Working fd_set: populated by select() - fd_set base_read_fds_{}; // Cached fd_set rebuilt only when socket_fds_ changes -#endif - // StaticVectors (largest members - contain actual array data inline) StaticVector components_{}; @@ -565,30 +503,6 @@ class Application { /// Global storage of Application pointer - only one Application can exist. extern Application App; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) -#ifdef USE_HOST -// Inline implementations for hot-path functions -// drain_wake_notifications_() is called on every loop iteration - -// Small buffer for draining wake notification bytes (1 byte sent per wake) -// Size allows draining multiple notifications per recvfrom() without wasting stack -static constexpr size_t WAKE_NOTIFY_DRAIN_BUFFER_SIZE = 16; - -inline void Application::drain_wake_notifications_() { - // Called from main loop to drain any pending wake notifications - // Must check is_socket_ready_() to avoid blocking on empty socket - if (this->wake_socket_fd_ >= 0 && this->is_socket_ready_(this->wake_socket_fd_)) { - char buffer[WAKE_NOTIFY_DRAIN_BUFFER_SIZE]; - // Drain all pending notifications with non-blocking reads - // Multiple wake events may have triggered multiple writes, so drain until EWOULDBLOCK - // We control both ends of this loopback socket (always write 1 byte per wake), - // so no error checking needed - any errors indicate catastrophic system failure - while (::recvfrom(this->wake_socket_fd_, buffer, sizeof(buffer), 0, nullptr, nullptr) > 0) { - // Just draining, no action needed - wake has already occurred - } - } -} -#endif // USE_HOST - // Phase A: drain wake notifications and run the scheduler. Invoked on every // Application::loop() tick regardless of whether a component phase runs, so // scheduler items fire at their requested cadence even when the caller has @@ -598,8 +512,8 @@ inline void Application::drain_wake_notifications_() { // per-item feeds inside scheduler.call() without an extra millis(). inline uint32_t ESPHOME_ALWAYS_INLINE Application::scheduler_tick_(uint32_t now) { #ifdef USE_HOST - // Drain wake notifications first to clear socket for next wake - this->drain_wake_notifications_(); + // Drain wake notifications first to clear socket for next wake. + wake_drain_notifications(); #endif return this->scheduler.call(now); } @@ -757,11 +671,11 @@ inline void ESPHOME_ALWAYS_INLINE Application::loop() { } } -// Inline yield_with_select_ for all paths except the select() fallback -#ifndef USE_HOST +// All platforms route loop yields through the platform wake primitive. +// On host this drains the loopback wake socket via select(); on FreeRTOS +// targets it uses task notifications; on ESP8266/RP2040 it uses esp_delay/WFE. inline void ESPHOME_ALWAYS_INLINE Application::yield_with_select_(uint32_t delay_ms) { esphome::internal::wakeable_delay(delay_ms); } -#endif // !USE_HOST } // namespace esphome diff --git a/esphome/core/wake.cpp b/esphome/core/wake.cpp index 00b08b7b91..cac88ae91e 100644 --- a/esphome/core/wake.cpp +++ b/esphome/core/wake.cpp @@ -1,13 +1,20 @@ #include "esphome/core/wake.h" #include "esphome/core/hal.h" +#include "esphome/core/log.h" #ifdef USE_ESP8266 #include #endif #ifdef USE_HOST -#include "esphome/core/application.h" +#include +#include +#include +#include +#include #include +#include +#include #endif namespace esphome { @@ -82,17 +89,188 @@ void wakeable_delay(uint32_t ms) { } // namespace internal #endif // USE_RP2040 -// === Host (UDP loopback socket) === +// === Host (UDP loopback socket + select() based fd watcher) === #ifdef USE_HOST + +static const char *const TAG = "wake"; + +namespace internal { +// File-scope state — referenced inline by wake_drain_notifications() and +// wake_fd_ready() in wake.h, and by the bodies in this file. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +int g_wake_socket_fd = -1; +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +fd_set g_read_fds{}; +} // namespace internal + +namespace { +// File-local state owned entirely by the select() loop. +// NOLINTBEGIN(cppcoreguidelines-avoid-non-const-global-variables) +std::vector s_socket_fds; +int s_max_fd = -1; +bool s_socket_fds_changed = false; +fd_set s_base_read_fds{}; +// NOLINTEND(cppcoreguidelines-avoid-non-const-global-variables) +} // namespace + +bool wake_register_fd(int fd) { + // WARNING: not thread-safe — must be called only from the main loop. + if (fd < 0) + return false; + + if (fd >= FD_SETSIZE) { + ESP_LOGE(TAG, "fd %d exceeds FD_SETSIZE %d", fd, FD_SETSIZE); + return false; + } + + s_socket_fds.push_back(fd); + s_socket_fds_changed = true; + if (fd > s_max_fd) { + s_max_fd = fd; + } + + return true; +} + +void wake_unregister_fd(int fd) { + // WARNING: not thread-safe — must be called only from the main loop. + if (fd < 0) + return; + + for (size_t i = 0; i < s_socket_fds.size(); i++) { + if (s_socket_fds[i] != fd) + continue; + + // Swap with last element and pop — O(1) removal since order doesn't matter. + if (i < s_socket_fds.size() - 1) + s_socket_fds[i] = s_socket_fds.back(); + s_socket_fds.pop_back(); + s_socket_fds_changed = true; + // Only recalculate max_fd if we removed the current max. + if (fd == s_max_fd) { + s_max_fd = -1; + for (int sock_fd : s_socket_fds) { + if (sock_fd > s_max_fd) + s_max_fd = sock_fd; + } + } + return; + } +} + +namespace internal { +void wakeable_delay(uint32_t ms) { + // Fallback select() path for the host platform (and any future platform + // without fast select). select() is the host equivalent of FreeRTOS task + // notify / esp_delay / WFE used on the embedded targets. + if (!s_socket_fds.empty()) [[likely]] { + // Update fd_set if socket list has changed. + if (s_socket_fds_changed) [[unlikely]] { + FD_ZERO(&s_base_read_fds); + // fd bounds are validated in wake_register_fd(). + for (int fd : s_socket_fds) { + FD_SET(fd, &s_base_read_fds); + } + s_socket_fds_changed = false; + } + + // Copy base fd_set before each select. + g_read_fds = s_base_read_fds; + + // Convert ms to timeval. + struct timeval tv; + tv.tv_sec = ms / 1000; + tv.tv_usec = (ms - tv.tv_sec * 1000) * 1000; + + // Call select with timeout. + int ret = ::select(s_max_fd + 1, &g_read_fds, nullptr, nullptr, &tv); + + // Process select() result: + // ret > 0: socket(s) have data ready - normal and expected + // ret == 0: timeout occurred - normal and expected + if (ret >= 0) [[likely]] { + // Yield if zero timeout since select(0) only polls without yielding. + if (ms == 0) [[unlikely]] { + yield(); + } + return; + } + // ret < 0: error (EINTR is normal, anything else is unexpected). + const int err = errno; + if (err == EINTR) { + return; + } + // select() error - log and fall through to delay(). + ESP_LOGW(TAG, "select() failed with errno %d", err); + } + // No sockets registered or select() failed - use regular delay. + delay(ms); +} +} // namespace internal + void wake_loop_threadsafe() { // Set flag before sending so the consumer's gate check on the next loop() // entry observes the wake regardless of select() scheduling. wake_request_set(); - if (App.wake_socket_fd_ >= 0) { + if (internal::g_wake_socket_fd >= 0) { const char dummy = 1; - ::send(App.wake_socket_fd_, &dummy, 1, 0); + ::send(internal::g_wake_socket_fd, &dummy, 1, 0); } } -#endif + +void wake_setup() { + // Create UDP socket for wake notifications. + internal::g_wake_socket_fd = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (internal::g_wake_socket_fd < 0) { + ESP_LOGW(TAG, "Wake socket create failed: %d", errno); + return; + } + + // Bind to loopback with auto-assigned port. + struct sockaddr_in addr = {}; + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + addr.sin_port = 0; // Auto-assign port + + if (::bind(internal::g_wake_socket_fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) { + ESP_LOGW(TAG, "Wake socket bind failed: %d", errno); + ::close(internal::g_wake_socket_fd); + internal::g_wake_socket_fd = -1; + return; + } + + // Get the assigned address and connect to it. + // Connecting a UDP socket allows using send() instead of sendto() for better performance. + struct sockaddr_in wake_addr; + socklen_t len = sizeof(wake_addr); + if (::getsockname(internal::g_wake_socket_fd, (struct sockaddr *) &wake_addr, &len) < 0) { + ESP_LOGW(TAG, "Wake socket address failed: %d", errno); + ::close(internal::g_wake_socket_fd); + internal::g_wake_socket_fd = -1; + return; + } + + // Connect to self (loopback) — allows using send() instead of sendto(). + // After connect(), no need to store wake_addr — the socket remembers it. + if (::connect(internal::g_wake_socket_fd, (struct sockaddr *) &wake_addr, sizeof(wake_addr)) < 0) { + ESP_LOGW(TAG, "Wake socket connect failed: %d", errno); + ::close(internal::g_wake_socket_fd); + internal::g_wake_socket_fd = -1; + return; + } + + // Set non-blocking mode. + int flags = ::fcntl(internal::g_wake_socket_fd, F_GETFL, 0); + ::fcntl(internal::g_wake_socket_fd, F_SETFL, flags | O_NONBLOCK); + + // Register with the select() loop. + if (!wake_register_fd(internal::g_wake_socket_fd)) { + ESP_LOGW(TAG, "Wake socket register failed"); + ::close(internal::g_wake_socket_fd); + internal::g_wake_socket_fd = -1; + return; + } +} +#endif // USE_HOST } // namespace esphome diff --git a/esphome/core/wake.h b/esphome/core/wake.h index 15b882b306..0cfca94a78 100644 --- a/esphome/core/wake.h +++ b/esphome/core/wake.h @@ -21,6 +21,11 @@ #include #endif +#ifdef USE_HOST +#include +#include +#endif + namespace esphome { // === Wake flag for ESP8266/RP2040 === @@ -170,6 +175,21 @@ void wakeable_delay(uint32_t ms); #ifdef USE_HOST /// Host: wakes select() via UDP loopback socket. Defined in wake.cpp. void wake_loop_threadsafe(); + +/// Register a socket file descriptor with the host select() loop. Not +/// thread-safe — main loop only. Returns false if fd is invalid or +/// >= FD_SETSIZE. +bool wake_register_fd(int fd); + +/// Unregister a socket file descriptor. Not thread-safe — main loop only. +void wake_unregister_fd(int fd); + +/// One-time setup of the loopback wake socket. Called from Application::setup(). +void wake_setup(); + +// wake_fd_ready() and wake_drain_notifications() are defined inline at the +// bottom of this file — they need internal::g_read_fds / g_wake_socket_fd in +// scope, which depend on USE_HOST-only includes pulled in above. #else /// Zephyr is currently the only platform without a wake mechanism. /// wake_loop_threadsafe() is a no-op and wakeable_delay() falls back to delay(). @@ -180,6 +200,10 @@ inline void wake_loop_threadsafe() {} inline void wake_loop_any_context() { wake_loop_threadsafe(); } namespace internal { +#ifdef USE_HOST +/// Host wakeable_delay uses select() over the registered fds — defined in wake.cpp. +void wakeable_delay(uint32_t ms); +#else inline void ESPHOME_ALWAYS_INLINE wakeable_delay(uint32_t ms) { if (ms == 0) [[unlikely]] { yield(); @@ -187,8 +211,40 @@ inline void ESPHOME_ALWAYS_INLINE wakeable_delay(uint32_t ms) { } delay(ms); } +#endif } // namespace internal #endif +#ifdef USE_HOST +namespace internal { +// File-scope state owned by wake.cpp. Accessed inline by wake_drain_notifications() +// and wake_fd_ready() so the hot path stays in the header. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +extern int g_wake_socket_fd; +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +extern fd_set g_read_fds; +} // namespace internal + +inline bool ESPHOME_ALWAYS_INLINE wake_fd_ready(int fd) { return FD_ISSET(fd, &internal::g_read_fds); } + +// Small buffer for draining wake notification bytes (1 byte sent per wake). +// Sized to drain multiple notifications per recvfrom() without wasting stack. +inline constexpr size_t WAKE_NOTIFY_DRAIN_BUFFER_SIZE = 16; + +inline void ESPHOME_ALWAYS_INLINE wake_drain_notifications() { + // Called from main loop to drain any pending wake notifications. + // Must check wake_fd_ready() to avoid blocking on empty socket. + if (internal::g_wake_socket_fd >= 0 && wake_fd_ready(internal::g_wake_socket_fd)) { + char buffer[WAKE_NOTIFY_DRAIN_BUFFER_SIZE]; + // Drain all pending notifications with non-blocking reads. Multiple wake events + // may have triggered multiple writes, so drain until EWOULDBLOCK. We control + // both ends of this loopback socket (always 1 byte per wake), so no error + // checking — any error indicates catastrophic system failure. + while (::recvfrom(internal::g_wake_socket_fd, buffer, sizeof(buffer), 0, nullptr, nullptr) > 0) { + } + } +} +#endif // USE_HOST + } // namespace esphome From 4c2efd41651cf2bd78a961eed42a6f9f35829f21 Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Thu, 23 Apr 2026 01:15:25 -0500 Subject: [PATCH 2/4] [radio_frequency] Add experimental `radio_frequency` entity type (base component + API) (#15556) --- CODEOWNERS | 1 + esphome/components/api/api.proto | 35 +++- esphome/components/api/api_connection.cpp | 64 +++++- esphome/components/api/api_connection.h | 5 +- esphome/components/api/api_pb2.cpp | 45 ++++- esphome/components/api/api_pb2.h | 26 ++- esphome/components/api/api_pb2_dump.cpp | 24 ++- esphome/components/api/api_pb2_service.cpp | 2 +- esphome/components/api/api_pb2_service.h | 2 +- esphome/components/api/api_server.cpp | 2 +- esphome/components/api/api_server.h | 2 +- esphome/components/api/list_entities.cpp | 3 + esphome/components/api/list_entities.h | 3 + esphome/components/api/subscribe_state.h | 3 + .../components/radio_frequency/__init__.py | 77 ++++++++ .../radio_frequency/radio_frequency.cpp | 109 ++++++++++ .../radio_frequency/radio_frequency.h | 187 ++++++++++++++++++ .../components/web_server/list_entities.cpp | 6 + esphome/components/web_server/list_entities.h | 3 + esphome/components/web_server/web_server.cpp | 110 +++++++++++ esphome/components/web_server/web_server.h | 9 + esphome/core/component_iterator.h | 5 + esphome/core/defines.h | 2 + esphome/core/entity_includes.h | 3 + esphome/core/entity_types.h | 4 + tests/components/web_server/common.yaml | 1 + 26 files changed, 710 insertions(+), 23 deletions(-) create mode 100644 esphome/components/radio_frequency/__init__.py create mode 100644 esphome/components/radio_frequency/radio_frequency.cpp create mode 100644 esphome/components/radio_frequency/radio_frequency.h diff --git a/CODEOWNERS b/CODEOWNERS index 5b1ae65f1b..92efe4da4e 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -403,6 +403,7 @@ esphome/components/qmp6988/* @andrewpc esphome/components/qr_code/* @wjtje esphome/components/qspi_dbi/* @clydebarrow esphome/components/qwiic_pir/* @kahrendt +esphome/components/radio_frequency/* @kbx81 esphome/components/radon_eye_ble/* @jeffeb3 esphome/components/radon_eye_rd200/* @jeffeb3 esphome/components/rc522/* @glmnet diff --git a/esphome/components/api/api.proto b/esphome/components/api/api.proto index f906cfb8d7..c3e4c38633 100644 --- a/esphome/components/api/api.proto +++ b/esphome/components/api/api.proto @@ -2544,27 +2544,50 @@ message ListEntitiesInfraredResponse { message InfraredRFTransmitRawTimingsRequest { option (id) = 136; option (source) = SOURCE_CLIENT; - option (ifdef) = "USE_IR_RF"; + option (ifdef) = "USE_IR_RF || USE_RADIO_FREQUENCY"; uint32 device_id = 1 [(field_ifdef) = "USE_DEVICES"]; - fixed32 key = 2 [(force) = true]; // Key identifying the transmitter instance - uint32 carrier_frequency = 3; // Carrier frequency in Hz - uint32 repeat_count = 4; // Number of times to transmit (1 = once, 2 = twice, etc.) + fixed32 key = 2 [(force) = true]; // Key identifying the transmitter instance + uint32 carrier_frequency = 3; // Carrier frequency in Hz + uint32 repeat_count = 4; // Number of times to transmit (1 = once, 2 = twice, etc.) repeated sint32 timings = 5 [packed = true, (packed_buffer) = true]; // Raw timings in microseconds (zigzag-encoded): positive = mark (LED/TX on), negative = space (LED/TX off) + uint32 modulation = 6; // RadioFrequencyModulation enum value (0 = OOK; ignored for IR entities) } // Event message for received infrared/RF data message InfraredRFReceiveEvent { option (id) = 137; option (source) = SOURCE_SERVER; - option (ifdef) = "USE_IR_RF"; + option (ifdef) = "USE_IR_RF || USE_RADIO_FREQUENCY"; option (no_delay) = true; uint32 device_id = 1 [(field_ifdef) = "USE_DEVICES"]; - fixed32 key = 2 [(force) = true]; // Key identifying the receiver instance + fixed32 key = 2 [(force) = true]; // Key identifying the receiver instance repeated sint32 timings = 3 [packed = true, (container_pointer_no_template) = "std::vector"]; // Raw timings in microseconds (zigzag-encoded): alternating mark/space periods } +// ==================== RADIO FREQUENCY ==================== + +// Lists available radio frequency entity instances +message ListEntitiesRadioFrequencyResponse { + option (id) = 148; + option (base_class) = "InfoResponseProtoMessage"; + option (source) = SOURCE_SERVER; + option (ifdef) = "USE_RADIO_FREQUENCY"; + + string object_id = 1 [(max_data_length) = 120, (force) = true]; + fixed32 key = 2 [(force) = true]; + string name = 3 [(max_data_length) = 120, (force) = true]; + string icon = 4 [(field_ifdef) = "USE_ENTITY_ICON", (max_data_length) = 63]; + bool disabled_by_default = 5; + EntityCategory entity_category = 6; + uint32 device_id = 7 [(field_ifdef) = "USE_DEVICES"]; + uint32 capabilities = 8; // Bitmask of RadioFrequencyCapabilityFlags: bit 0 = transmitter, bit 1 = receiver + uint32 frequency_min = 9; // Minimum tunable frequency in Hz; if min == max (non-zero): fixed frequency; 0 = unspecified + uint32 frequency_max = 10; // Maximum tunable frequency in Hz; 0 = unspecified + uint32 supported_modulations = 11; // Bitmask of supported RadioFrequencyModulation values (bit N = modulation N supported) +} + // ==================== SERIAL PROXY ==================== enum SerialProxyParity { diff --git a/esphome/components/api/api_connection.cpp b/esphome/components/api/api_connection.cpp index 4663456da6..b6f4aa2141 100644 --- a/esphome/components/api/api_connection.cpp +++ b/esphome/components/api/api_connection.cpp @@ -49,6 +49,9 @@ #ifdef USE_INFRARED #include "esphome/components/infrared/infrared.h" #endif +#ifdef USE_RADIO_FREQUENCY +#include "esphome/components/radio_frequency/radio_frequency.h" +#endif namespace esphome::api { @@ -100,6 +103,12 @@ static const int CAMERA_STOP_STREAM = 5000; entity_type *entity_var = App.get_##getter_name##_by_key(msg.key, msg.device_id); \ if ((entity_var) == nullptr) \ return; + +// Helper macro for multi-entity dispatch: looks up an entity by key and device_id without early return or make_call(). +// Use when multiple entity types must be checked in sequence (at most one will match). +#define ENTITY_COMMAND_LOOKUP(entity_type, entity_var, getter_name) \ + entity_type *entity_var = App.get_##getter_name##_by_key(msg.key, msg.device_id) + #else // No device support, use simpler macros // Helper macro for entity command handlers - gets entity by key, returns if not found, and creates call // object @@ -115,6 +124,12 @@ static const int CAMERA_STOP_STREAM = 5000; entity_type *entity_var = App.get_##getter_name##_by_key(msg.key); \ if ((entity_var) == nullptr) \ return; + +// Helper macro for multi-entity dispatch: looks up an entity by key without early return or make_call(). +// Use when multiple entity types must be checked in sequence (at most one will match). +#define ENTITY_COMMAND_LOOKUP(entity_type, entity_var, getter_name) \ + entity_type *entity_var = App.get_##getter_name##_by_key(msg.key) + #endif // USE_DEVICES APIConnection::APIConnection(std::unique_ptr sock, APIServer *parent) : parent_(parent) { @@ -1471,19 +1486,36 @@ uint16_t APIConnection::try_send_event_info(EntityBase *entity, APIConnection *c } #endif -#ifdef USE_IR_RF +#if defined(USE_IR_RF) || defined(USE_RADIO_FREQUENCY) void APIConnection::on_infrared_rf_transmit_raw_timings_request(const InfraredRFTransmitRawTimingsRequest &msg) { - // TODO: When RF is implemented, add a field to the message to distinguish IR vs RF - // and dispatch to the appropriate entity type based on that field. + // Dispatch by key: infrared entities are checked first, then radio frequency entities. + // The key is unique across all entity instances on a device, so at most one lookup will succeed. #ifdef USE_INFRARED - ENTITY_COMMAND_MAKE_CALL(infrared::Infrared, infrared, infrared) - call.set_carrier_frequency(msg.carrier_frequency); - call.set_raw_timings_packed(msg.timings_data_, msg.timings_length_, msg.timings_count_); - call.set_repeat_count(msg.repeat_count); - call.perform(); + ENTITY_COMMAND_LOOKUP(infrared::Infrared, infrared, infrared); + if (infrared != nullptr) { + auto call = infrared->make_call(); + call.set_carrier_frequency(msg.carrier_frequency); + call.set_raw_timings_packed(msg.timings_data_, msg.timings_length_, msg.timings_count_); + call.set_repeat_count(msg.repeat_count); + call.perform(); + return; + } +#endif +#ifdef USE_RADIO_FREQUENCY + ENTITY_COMMAND_LOOKUP(radio_frequency::RadioFrequency, radio_frequency, radio_frequency); + if (radio_frequency != nullptr) { + auto call = radio_frequency->make_call(); + call.set_frequency(msg.carrier_frequency); + call.set_modulation(static_cast(msg.modulation)); + call.set_repeat_count(msg.repeat_count); + call.set_raw_timings_packed(msg.timings_data_, msg.timings_length_, msg.timings_count_); + call.perform(); + } #endif } +#endif +#if defined(USE_IR_RF) || defined(USE_RADIO_FREQUENCY) void APIConnection::send_infrared_rf_receive_event(const InfraredRFReceiveEvent &msg) { this->send_message(msg); } #endif @@ -1580,6 +1612,19 @@ uint16_t APIConnection::try_send_infrared_info(EntityBase *entity, APIConnection } #endif +#ifdef USE_RADIO_FREQUENCY +uint16_t APIConnection::try_send_radio_frequency_info(EntityBase *entity, APIConnection *conn, + uint32_t remaining_size) { + auto *rf = static_cast(entity); + ListEntitiesRadioFrequencyResponse msg; + msg.capabilities = rf->get_capability_flags(); + msg.frequency_min = rf->get_traits().get_frequency_min_hz(); + msg.frequency_max = rf->get_traits().get_frequency_max_hz(); + msg.supported_modulations = rf->get_traits().get_supported_modulations(); + return fill_and_encode_entity_info(rf, msg, conn, remaining_size); +} +#endif + #ifdef USE_UPDATE bool APIConnection::send_update_state(update::UpdateEntity *update) { return this->send_message_smart_(update, UpdateStateResponse::MESSAGE_TYPE, UpdateStateResponse::ESTIMATED_SIZE); @@ -2341,6 +2386,9 @@ uint16_t APIConnection::dispatch_message_(const DeferredBatch::BatchItem &item, #ifdef USE_INFRARED CASE_INFO_ONLY(infrared, ListEntitiesInfraredResponse) #endif +#ifdef USE_RADIO_FREQUENCY + CASE_INFO_ONLY(radio_frequency, ListEntitiesRadioFrequencyResponse) +#endif #ifdef USE_EVENT CASE_INFO_ONLY(event, ListEntitiesEventResponse) #endif diff --git a/esphome/components/api/api_connection.h b/esphome/components/api/api_connection.h index 7d08797090..4165b7f3a2 100644 --- a/esphome/components/api/api_connection.h +++ b/esphome/components/api/api_connection.h @@ -223,7 +223,7 @@ class APIConnection final : public APIServerConnectionBase { void on_water_heater_command_request(const WaterHeaterCommandRequest &msg); #endif -#ifdef USE_IR_RF +#if defined(USE_IR_RF) || defined(USE_RADIO_FREQUENCY) void on_infrared_rf_transmit_raw_timings_request(const InfraredRFTransmitRawTimingsRequest &msg); void send_infrared_rf_receive_event(const InfraredRFReceiveEvent &msg); #endif @@ -612,6 +612,9 @@ class APIConnection final : public APIServerConnectionBase { #ifdef USE_INFRARED static uint16_t try_send_infrared_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size); #endif +#ifdef USE_RADIO_FREQUENCY + static uint16_t try_send_radio_frequency_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size); +#endif #ifdef USE_EVENT static uint16_t try_send_event_response(event::Event *event, StringRef event_type, APIConnection *conn, uint32_t remaining_size); diff --git a/esphome/components/api/api_pb2.cpp b/esphome/components/api/api_pb2.cpp index f304c85282..3d12453939 100644 --- a/esphome/components/api/api_pb2.cpp +++ b/esphome/components/api/api_pb2.cpp @@ -3861,7 +3861,7 @@ uint32_t ListEntitiesInfraredResponse::calculate_size() const { return size; } #endif -#ifdef USE_IR_RF +#if defined(USE_IR_RF) || defined(USE_RADIO_FREQUENCY) bool InfraredRFTransmitRawTimingsRequest::decode_varint(uint32_t field_id, proto_varint_value_t value) { switch (field_id) { #ifdef USE_DEVICES @@ -3875,6 +3875,9 @@ bool InfraredRFTransmitRawTimingsRequest::decode_varint(uint32_t field_id, proto case 4: this->repeat_count = value; break; + case 6: + this->modulation = value; + break; default: return false; } @@ -3928,6 +3931,46 @@ uint32_t InfraredRFReceiveEvent::calculate_size() const { return size; } #endif +#ifdef USE_RADIO_FREQUENCY +uint8_t *ListEntitiesRadioFrequencyResponse::encode(ProtoWriteBuffer &buffer PROTO_ENCODE_DEBUG_PARAM) const { + uint8_t *__restrict__ pos = buffer.get_pos(); + ProtoEncode::encode_short_string_force(pos PROTO_ENCODE_DEBUG_ARG, 10, this->object_id); + ProtoEncode::write_tag_and_fixed32(pos PROTO_ENCODE_DEBUG_ARG, 21, this->key); + ProtoEncode::encode_short_string_force(pos PROTO_ENCODE_DEBUG_ARG, 26, this->name); +#ifdef USE_ENTITY_ICON + ProtoEncode::encode_string(pos PROTO_ENCODE_DEBUG_ARG, 4, this->icon); +#endif + ProtoEncode::encode_bool(pos PROTO_ENCODE_DEBUG_ARG, 5, this->disabled_by_default); + ProtoEncode::encode_uint32(pos PROTO_ENCODE_DEBUG_ARG, 6, static_cast(this->entity_category)); +#ifdef USE_DEVICES + ProtoEncode::encode_uint32(pos PROTO_ENCODE_DEBUG_ARG, 7, this->device_id); +#endif + ProtoEncode::encode_uint32(pos PROTO_ENCODE_DEBUG_ARG, 8, this->capabilities); + ProtoEncode::encode_uint32(pos PROTO_ENCODE_DEBUG_ARG, 9, this->frequency_min); + ProtoEncode::encode_uint32(pos PROTO_ENCODE_DEBUG_ARG, 10, this->frequency_max); + ProtoEncode::encode_uint32(pos PROTO_ENCODE_DEBUG_ARG, 11, this->supported_modulations); + return pos; +} +uint32_t ListEntitiesRadioFrequencyResponse::calculate_size() const { + uint32_t size = 0; + size += 2 + this->object_id.size(); + size += 5; + size += 2 + this->name.size(); +#ifdef USE_ENTITY_ICON + size += !this->icon.empty() ? 2 + this->icon.size() : 0; +#endif + size += ProtoSize::calc_bool(1, this->disabled_by_default); + size += this->entity_category ? 2 : 0; +#ifdef USE_DEVICES + size += ProtoSize::calc_uint32(1, this->device_id); +#endif + size += ProtoSize::calc_uint32(1, this->capabilities); + size += ProtoSize::calc_uint32(1, this->frequency_min); + size += ProtoSize::calc_uint32(1, this->frequency_max); + size += ProtoSize::calc_uint32(1, this->supported_modulations); + return size; +} +#endif #ifdef USE_SERIAL_PROXY bool SerialProxyConfigureRequest::decode_varint(uint32_t field_id, proto_varint_value_t value) { switch (field_id) { diff --git a/esphome/components/api/api_pb2.h b/esphome/components/api/api_pb2.h index 5827a8728e..5aa592e4fa 100644 --- a/esphome/components/api/api_pb2.h +++ b/esphome/components/api/api_pb2.h @@ -3054,11 +3054,11 @@ class ListEntitiesInfraredResponse final : public InfoResponseProtoMessage { protected: }; #endif -#ifdef USE_IR_RF +#if defined(USE_IR_RF) || defined(USE_RADIO_FREQUENCY) class InfraredRFTransmitRawTimingsRequest final : public ProtoDecodableMessage { public: static constexpr uint8_t MESSAGE_TYPE = 136; - static constexpr uint8_t ESTIMATED_SIZE = 220; + static constexpr uint8_t ESTIMATED_SIZE = 224; #ifdef HAS_PROTO_MESSAGE_DUMP const LogString *message_name() const override { return LOG_STR("infrared_rf_transmit_raw_timings_request"); } #endif @@ -3071,6 +3071,7 @@ class InfraredRFTransmitRawTimingsRequest final : public ProtoDecodableMessage { const uint8_t *timings_data_{nullptr}; uint16_t timings_length_{0}; uint16_t timings_count_{0}; + uint32_t modulation{0}; #ifdef HAS_PROTO_MESSAGE_DUMP const char *dump_to(DumpBuffer &out) const override; #endif @@ -3101,6 +3102,27 @@ class InfraredRFReceiveEvent final : public ProtoMessage { protected: }; #endif +#ifdef USE_RADIO_FREQUENCY +class ListEntitiesRadioFrequencyResponse final : public InfoResponseProtoMessage { + public: + static constexpr uint8_t MESSAGE_TYPE = 148; + static constexpr uint8_t ESTIMATED_SIZE = 56; +#ifdef HAS_PROTO_MESSAGE_DUMP + const LogString *message_name() const override { return LOG_STR("list_entities_radio_frequency_response"); } +#endif + uint32_t capabilities{0}; + uint32_t frequency_min{0}; + uint32_t frequency_max{0}; + uint32_t supported_modulations{0}; + uint8_t *encode(ProtoWriteBuffer &buffer PROTO_ENCODE_DEBUG_PARAM) const; + uint32_t calculate_size() const; +#ifdef HAS_PROTO_MESSAGE_DUMP + const char *dump_to(DumpBuffer &out) const override; +#endif + + protected: +}; +#endif #ifdef USE_SERIAL_PROXY class SerialProxyConfigureRequest final : public ProtoDecodableMessage { public: diff --git a/esphome/components/api/api_pb2_dump.cpp b/esphome/components/api/api_pb2_dump.cpp index 640c347371..bdcb6d4146 100644 --- a/esphome/components/api/api_pb2_dump.cpp +++ b/esphome/components/api/api_pb2_dump.cpp @@ -2576,7 +2576,7 @@ const char *ListEntitiesInfraredResponse::dump_to(DumpBuffer &out) const { return out.c_str(); } #endif -#ifdef USE_IR_RF +#if defined(USE_IR_RF) || defined(USE_RADIO_FREQUENCY) const char *InfraredRFTransmitRawTimingsRequest::dump_to(DumpBuffer &out) const { MessageDumpHelper helper(out, ESPHOME_PSTR("InfraredRFTransmitRawTimingsRequest")); #ifdef USE_DEVICES @@ -2591,6 +2591,7 @@ const char *InfraredRFTransmitRawTimingsRequest::dump_to(DumpBuffer &out) const out.append_p(ESPHOME_PSTR(" values, ")); append_uint(out, this->timings_length_); out.append_p(ESPHOME_PSTR(" bytes]\n")); + dump_field(out, ESPHOME_PSTR("modulation"), this->modulation); return out.c_str(); } const char *InfraredRFReceiveEvent::dump_to(DumpBuffer &out) const { @@ -2605,6 +2606,27 @@ const char *InfraredRFReceiveEvent::dump_to(DumpBuffer &out) const { return out.c_str(); } #endif +#ifdef USE_RADIO_FREQUENCY +const char *ListEntitiesRadioFrequencyResponse::dump_to(DumpBuffer &out) const { + MessageDumpHelper helper(out, ESPHOME_PSTR("ListEntitiesRadioFrequencyResponse")); + dump_field(out, ESPHOME_PSTR("object_id"), this->object_id); + dump_field(out, ESPHOME_PSTR("key"), this->key); + dump_field(out, ESPHOME_PSTR("name"), this->name); +#ifdef USE_ENTITY_ICON + dump_field(out, ESPHOME_PSTR("icon"), this->icon); +#endif + dump_field(out, ESPHOME_PSTR("disabled_by_default"), this->disabled_by_default); + dump_field(out, ESPHOME_PSTR("entity_category"), static_cast(this->entity_category)); +#ifdef USE_DEVICES + dump_field(out, ESPHOME_PSTR("device_id"), this->device_id); +#endif + dump_field(out, ESPHOME_PSTR("capabilities"), this->capabilities); + dump_field(out, ESPHOME_PSTR("frequency_min"), this->frequency_min); + dump_field(out, ESPHOME_PSTR("frequency_max"), this->frequency_max); + dump_field(out, ESPHOME_PSTR("supported_modulations"), this->supported_modulations); + return out.c_str(); +} +#endif #ifdef USE_SERIAL_PROXY const char *SerialProxyConfigureRequest::dump_to(DumpBuffer &out) const { MessageDumpHelper helper(out, ESPHOME_PSTR("SerialProxyConfigureRequest")); diff --git a/esphome/components/api/api_pb2_service.cpp b/esphome/components/api/api_pb2_service.cpp index b41233eddd..6ae2a3e369 100644 --- a/esphome/components/api/api_pb2_service.cpp +++ b/esphome/components/api/api_pb2_service.cpp @@ -625,7 +625,7 @@ void APIConnection::read_message_(uint32_t msg_size, uint32_t msg_type, const ui break; } #endif -#ifdef USE_IR_RF +#if defined(USE_IR_RF) || defined(USE_RADIO_FREQUENCY) case InfraredRFTransmitRawTimingsRequest::MESSAGE_TYPE: { InfraredRFTransmitRawTimingsRequest msg; msg.decode(msg_data, msg_size); diff --git a/esphome/components/api/api_pb2_service.h b/esphome/components/api/api_pb2_service.h index 6ff988902f..aca42ca303 100644 --- a/esphome/components/api/api_pb2_service.h +++ b/esphome/components/api/api_pb2_service.h @@ -211,7 +211,7 @@ class APIServerConnectionBase { void on_z_wave_proxy_request(const ZWaveProxyRequest &value){}; #endif -#ifdef USE_IR_RF +#if defined(USE_IR_RF) || defined(USE_RADIO_FREQUENCY) void on_infrared_rf_transmit_raw_timings_request(const InfraredRFTransmitRawTimingsRequest &value){}; #endif diff --git a/esphome/components/api/api_server.cpp b/esphome/components/api/api_server.cpp index 4559168ece..c30bd2e612 100644 --- a/esphome/components/api/api_server.cpp +++ b/esphome/components/api/api_server.cpp @@ -368,7 +368,7 @@ void APIServer::on_zwave_proxy_request(const ZWaveProxyRequest &msg) { } #endif -#ifdef USE_IR_RF +#if defined(USE_IR_RF) || defined(USE_RADIO_FREQUENCY) void APIServer::send_infrared_rf_receive_event([[maybe_unused]] uint32_t device_id, uint32_t key, const std::vector *timings) { InfraredRFReceiveEvent resp{}; diff --git a/esphome/components/api/api_server.h b/esphome/components/api/api_server.h index d6ac1a6d5d..e662d78eba 100644 --- a/esphome/components/api/api_server.h +++ b/esphome/components/api/api_server.h @@ -183,7 +183,7 @@ class APIServer final : public Component, #ifdef USE_ZWAVE_PROXY void on_zwave_proxy_request(const ZWaveProxyRequest &msg); #endif -#ifdef USE_IR_RF +#if defined(USE_IR_RF) || defined(USE_RADIO_FREQUENCY) void send_infrared_rf_receive_event(uint32_t device_id, uint32_t key, const std::vector *timings); #endif diff --git a/esphome/components/api/list_entities.cpp b/esphome/components/api/list_entities.cpp index 0a94c1699b..f9e645b506 100644 --- a/esphome/components/api/list_entities.cpp +++ b/esphome/components/api/list_entities.cpp @@ -79,6 +79,9 @@ LIST_ENTITIES_HANDLER(water_heater, water_heater::WaterHeater, ListEntitiesWater #ifdef USE_INFRARED LIST_ENTITIES_HANDLER(infrared, infrared::Infrared, ListEntitiesInfraredResponse) #endif +#ifdef USE_RADIO_FREQUENCY +LIST_ENTITIES_HANDLER(radio_frequency, radio_frequency::RadioFrequency, ListEntitiesRadioFrequencyResponse) +#endif #ifdef USE_EVENT LIST_ENTITIES_HANDLER(event, event::Event, ListEntitiesEventResponse) #endif diff --git a/esphome/components/api/list_entities.h b/esphome/components/api/list_entities.h index 7d0eb5bb13..95c626feb1 100644 --- a/esphome/components/api/list_entities.h +++ b/esphome/components/api/list_entities.h @@ -87,6 +87,9 @@ class ListEntitiesIterator final : public ComponentIterator { #ifdef USE_INFRARED bool on_infrared(infrared::Infrared *entity) override; #endif +#ifdef USE_RADIO_FREQUENCY + bool on_radio_frequency(radio_frequency::RadioFrequency *entity) override; +#endif #ifdef USE_EVENT bool on_event(event::Event *entity) override; #endif diff --git a/esphome/components/api/subscribe_state.h b/esphome/components/api/subscribe_state.h index 9edf0f0f0c..f20611e06a 100644 --- a/esphome/components/api/subscribe_state.h +++ b/esphome/components/api/subscribe_state.h @@ -82,6 +82,9 @@ class InitialStateIterator final : public ComponentIterator { #ifdef USE_INFRARED bool on_infrared(infrared::Infrared *infrared) override { return true; }; #endif +#ifdef USE_RADIO_FREQUENCY + bool on_radio_frequency(radio_frequency::RadioFrequency *radio_frequency) override { return true; }; +#endif #ifdef USE_EVENT bool on_event(event::Event *event) override { return true; }; #endif diff --git a/esphome/components/radio_frequency/__init__.py b/esphome/components/radio_frequency/__init__.py new file mode 100644 index 0000000000..b00590ceb5 --- /dev/null +++ b/esphome/components/radio_frequency/__init__.py @@ -0,0 +1,77 @@ +""" +Radio Frequency component for ESPHome. + +WARNING: This component is EXPERIMENTAL. The API (both Python configuration +and C++ interfaces) may change at any time without following the normal +breaking changes policy. Use at your own risk. + +Once the API is considered stable, this warning will be removed. +""" + +import esphome.codegen as cg +import esphome.config_validation as cv +from esphome.const import CONF_ID +from esphome.core import CORE, coroutine_with_priority +from esphome.core.entity_helpers import setup_entity +from esphome.coroutine import CoroPriority +from esphome.types import ConfigType + +CODEOWNERS = ["@kbx81"] +AUTO_LOAD = ["remote_base"] + +IS_PLATFORM_COMPONENT = True + +radio_frequency_ns = cg.esphome_ns.namespace("radio_frequency") +RadioFrequency = radio_frequency_ns.class_( + "RadioFrequency", cg.EntityBase, cg.Component +) +RadioFrequencyCall = radio_frequency_ns.class_("RadioFrequencyCall") +RadioFrequencyTraits = radio_frequency_ns.class_("RadioFrequencyTraits") +RadioFrequencyModulation = radio_frequency_ns.enum("RadioFrequencyModulation") + +CONF_RADIO_FREQUENCY_ID = "radio_frequency_id" + + +def radio_frequency_schema(class_: type[cg.MockObjClass]) -> cv.Schema: + """Create a schema for a radio frequency platform. + + :param class_: The radio frequency class to use for this schema. + :return: An extended schema for radio frequency configuration. + """ + entity_schema = cv.ENTITY_BASE_SCHEMA.extend(cv.COMPONENT_SCHEMA) + return entity_schema.extend( + { + cv.GenerateID(): cv.declare_id(class_), + } + ) + + +@setup_entity("radio_frequency") +async def setup_radio_frequency_core_(var: cg.Pvariable, config: ConfigType) -> None: + """Set up core radio frequency configuration.""" + + +async def register_radio_frequency(var: cg.Pvariable, config: ConfigType) -> None: + """Register a radio frequency device with the core.""" + cg.add_define("USE_RADIO_FREQUENCY") + await cg.register_component(var, config) + await setup_radio_frequency_core_(var, config) + cg.add(cg.App.register_radio_frequency(var)) + CORE.register_platform_component("radio_frequency", var) + + +async def new_radio_frequency(config: ConfigType, *args) -> cg.Pvariable: + """Create a new RadioFrequency instance. + + :param config: Configuration dictionary. + :param args: Additional arguments to pass to new_Pvariable. + :return: The created RadioFrequency instance. + """ + var = cg.new_Pvariable(config[CONF_ID], *args) + await register_radio_frequency(var, config) + return var + + +@coroutine_with_priority(CoroPriority.CORE) +async def to_code(config: ConfigType) -> None: + cg.add_global(radio_frequency_ns.using) diff --git a/esphome/components/radio_frequency/radio_frequency.cpp b/esphome/components/radio_frequency/radio_frequency.cpp new file mode 100644 index 0000000000..3c000ae1ca --- /dev/null +++ b/esphome/components/radio_frequency/radio_frequency.cpp @@ -0,0 +1,109 @@ +#include "radio_frequency.h" + +#include + +#include "esphome/core/log.h" + +#ifdef USE_API +#include "esphome/components/api/api_server.h" +#endif + +namespace esphome::radio_frequency { + +static const char *const TAG = "radio_frequency"; + +// ========== RadioFrequencyCall ========== + +RadioFrequencyCall &RadioFrequencyCall::set_frequency(uint32_t frequency_hz) { + this->frequency_hz_ = frequency_hz; + return *this; +} + +RadioFrequencyCall &RadioFrequencyCall::set_modulation(RadioFrequencyModulation modulation) { + this->modulation_ = modulation; + return *this; +} + +RadioFrequencyCall &RadioFrequencyCall::set_raw_timings(const std::vector &timings) { + this->raw_timings_ = &timings; + this->packed_data_ = nullptr; + this->base64url_ptr_ = nullptr; + return *this; +} + +RadioFrequencyCall &RadioFrequencyCall::set_raw_timings_base64url(const std::string &base64url) { + this->base64url_ptr_ = &base64url; + this->raw_timings_ = nullptr; + this->packed_data_ = nullptr; + return *this; +} + +RadioFrequencyCall &RadioFrequencyCall::set_raw_timings_packed(const uint8_t *data, uint16_t length, uint16_t count) { + this->packed_data_ = data; + this->packed_length_ = length; + this->packed_count_ = count; + this->raw_timings_ = nullptr; + this->base64url_ptr_ = nullptr; + return *this; +} + +RadioFrequencyCall &RadioFrequencyCall::set_repeat_count(uint32_t count) { + this->repeat_count_ = count; + return *this; +} + +void RadioFrequencyCall::perform() { + if (this->parent_ != nullptr) { + this->parent_->control(*this); + } +} + +// ========== RadioFrequency ========== + +void RadioFrequency::dump_config() { + ESP_LOGCONFIG(TAG, + "Radio Frequency '%s'\n" + " Supports Transmitter: %s\n" + " Supports Receiver: %s", + this->get_name().c_str(), YESNO(this->traits_.get_supports_transmitter()), + YESNO(this->traits_.get_supports_receiver())); + if (this->traits_.get_frequency_min_hz() > 0) { + if (this->traits_.get_frequency_min_hz() == this->traits_.get_frequency_max_hz()) { + ESP_LOGCONFIG(TAG, " Frequency: %" PRIu32 " Hz (fixed)", this->traits_.get_frequency_min_hz()); + } else { + ESP_LOGCONFIG(TAG, " Frequency Range: %" PRIu32 " - %" PRIu32 " Hz", this->traits_.get_frequency_min_hz(), + this->traits_.get_frequency_max_hz()); + } + } +} + +RadioFrequencyCall RadioFrequency::make_call() { return RadioFrequencyCall(this); } + +uint32_t RadioFrequency::get_capability_flags() const { + uint32_t flags = 0; + if (this->traits_.get_supports_transmitter()) + flags |= RadioFrequencyCapability::CAPABILITY_TRANSMITTER; + if (this->traits_.get_supports_receiver()) + flags |= RadioFrequencyCapability::CAPABILITY_RECEIVER; + return flags; +} + +bool RadioFrequency::on_receive(remote_base::RemoteReceiveData data) { + // Invoke local callbacks + this->receive_callback_.call(data); + + // Forward received RF data to API server +#if defined(USE_API) && defined(USE_RADIO_FREQUENCY) + if (api::global_api_server != nullptr) { +#ifdef USE_DEVICES + uint32_t device_id = this->get_device_id(); +#else + uint32_t device_id = 0; +#endif + api::global_api_server->send_infrared_rf_receive_event(device_id, this->get_object_id_hash(), &data.get_raw_data()); + } +#endif + return false; // Don't consume the event, allow other listeners to process it +} + +} // namespace esphome::radio_frequency diff --git a/esphome/components/radio_frequency/radio_frequency.h b/esphome/components/radio_frequency/radio_frequency.h new file mode 100644 index 0000000000..db73a844ed --- /dev/null +++ b/esphome/components/radio_frequency/radio_frequency.h @@ -0,0 +1,187 @@ +#pragma once + +// WARNING: This component is EXPERIMENTAL. The API may change at any time +// without following the normal breaking changes policy. Use at your own risk. +// Once the API is considered stable, this warning will be removed. + +#include "esphome/core/component.h" +#include "esphome/core/entity_base.h" +#include "esphome/core/helpers.h" +#include "esphome/components/remote_base/remote_base.h" + +#include + +namespace esphome::radio_frequency { + +/// Capability flags for individual radio frequency instances +enum RadioFrequencyCapability : uint32_t { + CAPABILITY_TRANSMITTER = 1 << 0, // Can transmit signals + CAPABILITY_RECEIVER = 1 << 1, // Can receive signals +}; + +/// Modulation types supported by radio frequency implementations +enum RadioFrequencyModulation : uint8_t { + RADIO_FREQUENCY_MODULATION_OOK = 0, // On-Off Keying / Amplitude Shift Keying + // Future: RADIO_FREQUENCY_MODULATION_FSK, RADIO_FREQUENCY_MODULATION_GFSK, etc. +}; + +/// Forward declarations +class RadioFrequency; + +/// RadioFrequencyCall - Builder pattern for transmitting radio frequency signals +class RadioFrequencyCall { + public: + explicit RadioFrequencyCall(RadioFrequency *parent) : parent_(parent) {} + + /// Set the carrier frequency in Hz (e.g. 433920000 for 433.92 MHz) + RadioFrequencyCall &set_frequency(uint32_t frequency_hz); + + /// Set the modulation type (defaults to OOK) + RadioFrequencyCall &set_modulation(RadioFrequencyModulation modulation); + + // ===== Raw Timings Methods ===== + // All set_raw_timings_* methods store pointers/references to external data. + // The referenced data must remain valid until perform() completes. + // Safe pattern: call.set_raw_timings_xxx(data); call.perform(); // synchronous + // Unsafe pattern: call.set_raw_timings_xxx(data); defer([call]() { call.perform(); }); // data may be gone! + + /// Set the raw timings from a vector (positive = mark, negative = space) + /// @note Lifetime: Stores a pointer to the vector. The vector must outlive perform(). + /// @note Usage: Primarily for lambdas/automations where the vector is in scope. + RadioFrequencyCall &set_raw_timings(const std::vector &timings); + + /// Set the raw timings from base64url-encoded little-endian int32 data + /// @note Lifetime: Stores a pointer to the string. The string must outlive perform(). + /// @note Usage: For web_server - base64url is fully URL-safe (uses '-' and '_'). + /// @note Decoding happens at perform() time, directly into the transmit buffer. + RadioFrequencyCall &set_raw_timings_base64url(const std::string &base64url); + + /// Set the raw timings from packed protobuf sint32 data (zigzag + varint encoded) + /// @note Lifetime: Stores a pointer to the buffer. The buffer must outlive perform(). + /// @note Usage: For API component where data comes directly from the protobuf message. + RadioFrequencyCall &set_raw_timings_packed(const uint8_t *data, uint16_t length, uint16_t count); + + /// Set the number of times to repeat transmission (1 = transmit once, 2 = transmit twice, etc.) + RadioFrequencyCall &set_repeat_count(uint32_t count); + + /// Perform the transmission + void perform(); + + /// Get the frequency in Hz + const optional &get_frequency() const { return this->frequency_hz_; } + /// Get the modulation type + RadioFrequencyModulation get_modulation() const { return this->modulation_; } + /// Get the raw timings (only valid if set via set_raw_timings) + const std::vector &get_raw_timings() const { return *this->raw_timings_; } + /// Check if raw timings have been set (any format) + bool has_raw_timings() const { + return this->raw_timings_ != nullptr || this->packed_data_ != nullptr || this->base64url_ptr_ != nullptr; + } + /// Check if using packed data format + bool is_packed() const { return this->packed_data_ != nullptr; } + /// Check if using base64url data format + bool is_base64url() const { return this->base64url_ptr_ != nullptr; } + /// Get the base64url data string + const std::string &get_base64url_data() const { return *this->base64url_ptr_; } + /// Get packed data (only valid if set via set_raw_timings_packed) + const uint8_t *get_packed_data() const { return this->packed_data_; } + uint16_t get_packed_length() const { return this->packed_length_; } + uint16_t get_packed_count() const { return this->packed_count_; } + /// Get the repeat count + uint32_t get_repeat_count() const { return this->repeat_count_; } + + protected: + optional frequency_hz_{}; + uint32_t repeat_count_{1}; + RadioFrequency *parent_; + // Pointer to vector-based timings (caller-owned, must outlive perform()) + const std::vector *raw_timings_{nullptr}; + // Pointer to base64url-encoded string (caller-owned, must outlive perform()) + const std::string *base64url_ptr_{nullptr}; + // Pointer to packed protobuf buffer (caller-owned, must outlive perform()) + const uint8_t *packed_data_{nullptr}; + uint16_t packed_length_{0}; + uint16_t packed_count_{0}; + RadioFrequencyModulation modulation_{RADIO_FREQUENCY_MODULATION_OOK}; +}; + +/// RadioFrequencyTraits - Describes the capabilities of a radio frequency implementation +class RadioFrequencyTraits { + public: + bool get_supports_transmitter() const { return this->supports_transmitter_; } + void set_supports_transmitter(bool supports) { this->supports_transmitter_ = supports; } + + bool get_supports_receiver() const { return this->supports_receiver_; } + void set_supports_receiver(bool supports) { this->supports_receiver_ = supports; } + + /// Hardware-supported tunable frequency range in Hz. + /// If min == max (and both non-zero): fixed-frequency hardware. + /// If both 0: range unspecified. + uint32_t get_frequency_min_hz() const { return this->frequency_min_hz_; } + void set_frequency_min_hz(uint32_t freq) { this->frequency_min_hz_ = freq; } + + uint32_t get_frequency_max_hz() const { return this->frequency_max_hz_; } + void set_frequency_max_hz(uint32_t freq) { this->frequency_max_hz_ = freq; } + + /// Convenience setter for fixed-frequency hardware (sets min == max). + void set_fixed_frequency_hz(uint32_t freq) { + this->frequency_min_hz_ = freq; + this->frequency_max_hz_ = freq; + } + + /// Bitmask of supported RadioFrequencyModulation values (bit N = modulation value N supported). + uint32_t get_supported_modulations() const { return this->supported_modulations_; } + void set_supported_modulations(uint32_t mask) { this->supported_modulations_ = mask; } + void add_supported_modulation(RadioFrequencyModulation mod) { + this->supported_modulations_ |= (1u << static_cast(mod)); + } + + protected: + uint32_t frequency_min_hz_{0}; // Minimum tunable frequency in Hz (0 = unspecified) + uint32_t frequency_max_hz_{0}; // Maximum tunable frequency in Hz (0 = unspecified) + uint32_t supported_modulations_{0}; // Bitmask of supported RadioFrequencyModulation values + bool supports_transmitter_{false}; + bool supports_receiver_{false}; +}; + +/// RadioFrequency - Base class for radio frequency implementations +class RadioFrequency : public Component, public EntityBase, public remote_base::RemoteReceiverListener { + public: + RadioFrequency() = default; + + void dump_config() override; + float get_setup_priority() const override { return setup_priority::AFTER_CONNECTION; } + + /// Get the traits for this radio frequency implementation + RadioFrequencyTraits &get_traits() { return this->traits_; } + const RadioFrequencyTraits &get_traits() const { return this->traits_; } + + /// Create a call object for transmitting + RadioFrequencyCall make_call(); + + /// Get capability flags for this radio frequency instance + uint32_t get_capability_flags() const; + + /// Called when RF data is received (from RemoteReceiverListener) + bool on_receive(remote_base::RemoteReceiveData data) override; + + /// Add a callback to invoke when RF data is received + template void add_on_receive_callback(F &&callback) { + this->receive_callback_.add(std::forward(callback)); + } + + protected: + friend class RadioFrequencyCall; + + /// Perform the actual transmission (called by RadioFrequencyCall::perform()) + /// Platforms must override this to implement hardware-specific transmission. + virtual void control(const RadioFrequencyCall &call) = 0; + + // Traits describing capabilities + RadioFrequencyTraits traits_; + + // Callback manager for receive events (lazy: saves memory when no callbacks registered) + LazyCallbackManager receive_callback_; +}; + +} // namespace esphome::radio_frequency diff --git a/esphome/components/web_server/list_entities.cpp b/esphome/components/web_server/list_entities.cpp index ebe7bf4450..c1e7599c7e 100644 --- a/esphome/components/web_server/list_entities.cpp +++ b/esphome/components/web_server/list_entities.cpp @@ -145,6 +145,12 @@ bool ListEntitiesIterator::on_infrared(infrared::Infrared *obj) { return true; } #endif +#ifdef USE_RADIO_FREQUENCY +bool ListEntitiesIterator::on_radio_frequency(radio_frequency::RadioFrequency *obj) { + this->events_->deferrable_send_state(obj, "state_detail_all", WebServer::radio_frequency_all_json_generator); + return true; +} +#endif #ifdef USE_EVENT bool ListEntitiesIterator::on_event(event::Event *obj) { diff --git a/esphome/components/web_server/list_entities.h b/esphome/components/web_server/list_entities.h index 8c22d757b6..9cfc6c7e33 100644 --- a/esphome/components/web_server/list_entities.h +++ b/esphome/components/web_server/list_entities.h @@ -87,6 +87,9 @@ class ListEntitiesIterator final : public ComponentIterator { #ifdef USE_INFRARED bool on_infrared(infrared::Infrared *obj) override; #endif +#ifdef USE_RADIO_FREQUENCY + bool on_radio_frequency(radio_frequency::RadioFrequency *obj) override; +#endif #ifdef USE_EVENT bool on_event(event::Event *obj) override; #endif diff --git a/esphome/components/web_server/web_server.cpp b/esphome/components/web_server/web_server.cpp index 1daec1786d..198267204d 100644 --- a/esphome/components/web_server/web_server.cpp +++ b/esphome/components/web_server/web_server.cpp @@ -40,6 +40,9 @@ #ifdef USE_INFRARED #include "esphome/components/infrared/infrared.h" #endif +#ifdef USE_RADIO_FREQUENCY +#include "esphome/components/radio_frequency/radio_frequency.h" +#endif #ifdef USE_WEBSERVER_LOCAL #if USE_WEBSERVER_VERSION == 2 @@ -2102,6 +2105,104 @@ json::SerializationBuffer<> WebServer::infrared_json_(infrared::Infrared *obj, J } #endif +#ifdef USE_RADIO_FREQUENCY +void WebServer::handle_radio_frequency_request(AsyncWebServerRequest *request, const UrlMatch &match) { + for (radio_frequency::RadioFrequency *obj : App.get_radio_frequencies()) { + auto entity_match = match.match_entity(obj); + if (!entity_match.matched) + continue; + + if (request->method() == HTTP_GET && entity_match.action_is_empty) { + auto detail = get_request_detail(request); + auto data = this->radio_frequency_json_(obj, detail); + request->send(200, ESPHOME_F("application/json"), data.c_str()); + return; + } + if (!match.method_equals(ESPHOME_F("transmit"))) { + request->send(404); + return; + } + + // Only allow transmit if the device supports it + if (!(obj->get_capability_flags() & radio_frequency::CAPABILITY_TRANSMITTER)) { + request->send(400, ESPHOME_F("text/plain"), ESPHOME_F("Device does not support transmission")); + return; + } + + auto call = obj->make_call(); + + // Parse carrier frequency (optional — overrides IC default) + { + auto value = parse_number(request->arg(ESPHOME_F("frequency")).c_str()); + if (value.has_value()) { + call.set_frequency(*value); + } + } + + // Parse repeat count (optional, defaults to 1) + { + auto value = parse_number(request->arg(ESPHOME_F("repeat_count")).c_str()); + if (value.has_value()) { + call.set_repeat_count(*value); + } + } + + // Parse base64url-encoded raw timings (required) + // Base64url is URL-safe: uses A-Za-z0-9-_ (no special characters needing escaping) + const auto &data_arg = request->arg(ESPHOME_F("data")); + + // Validate base64url is not empty (also catches missing parameter since arg() returns empty string) + // Arduino String has isEmpty() not empty(), use length() for cross-platform compatibility + if (data_arg.length() == 0) { // NOLINT(readability-container-size-empty) + request->send(400, ESPHOME_F("text/plain"), ESPHOME_F("Missing or empty 'data' parameter")); + return; + } + + // Defer to main loop for thread safety. Move encoded string into lambda to ensure + // it outlives the call - set_raw_timings_base64url stores a pointer, so the string + // must remain valid until perform() completes. + // ESP8266 also needs this because ESPAsyncWebServer callbacks run in "sys" context. + this->defer([call, encoded = std::string(data_arg.c_str(), data_arg.length())]() mutable { + call.set_raw_timings_base64url(encoded); + call.perform(); + }); + + request->send(200); + return; + } + request->send(404); +} + +json::SerializationBuffer<> WebServer::radio_frequency_all_json_generator(WebServer *web_server, void *source) { + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson + return web_server->radio_frequency_json_(static_cast(source), DETAIL_ALL); +} + +json::SerializationBuffer<> WebServer::radio_frequency_json_(radio_frequency::RadioFrequency *obj, + JsonDetail start_config) { + json::JsonBuilder builder; + JsonObject root = builder.root(); + + set_json_icon_state_value(root, obj, "radio_frequency", "", 0, start_config); + + const auto &traits = obj->get_traits(); + auto caps = obj->get_capability_flags(); + + root[ESPHOME_F("supports_transmitter")] = bool(caps & radio_frequency::CAPABILITY_TRANSMITTER); + root[ESPHOME_F("supports_receiver")] = bool(caps & radio_frequency::CAPABILITY_RECEIVER); + if (traits.get_frequency_min_hz() != 0) { + root[ESPHOME_F("frequency_min")] = traits.get_frequency_min_hz(); + root[ESPHOME_F("frequency_max")] = traits.get_frequency_max_hz(); + } + + if (start_config == DETAIL_ALL) { + this->add_sorting_info_(root, obj); + } + + return builder.serialize(); +} +#endif + #ifdef USE_EVENT void WebServer::on_event(event::Event *obj) { if (!this->include_internal_ && obj->is_internal()) @@ -2357,6 +2458,10 @@ bool WebServer::canHandle(AsyncWebServerRequest *request) const { #ifdef USE_INFRARED if (match.domain_equals(ESPHOME_F("infrared"))) return true; +#endif +#ifdef USE_RADIO_FREQUENCY + if (match.domain_equals(ESPHOME_F("radio_frequency"))) + return true; #endif } @@ -2516,6 +2621,11 @@ void WebServer::handleRequest(AsyncWebServerRequest *request) { else if (match.domain_equals(ESPHOME_F("infrared"))) { this->handle_infrared_request(request, match); } +#endif +#ifdef USE_RADIO_FREQUENCY + else if (match.domain_equals(ESPHOME_F("radio_frequency"))) { + this->handle_radio_frequency_request(request, match); + } #endif else { // No matching handler found - send 404 diff --git a/esphome/components/web_server/web_server.h b/esphome/components/web_server/web_server.h index 8e8b1de8c4..25f8f8212d 100644 --- a/esphome/components/web_server/web_server.h +++ b/esphome/components/web_server/web_server.h @@ -462,6 +462,12 @@ class WebServer final : public Controller, public Component, public AsyncWebHand static json::SerializationBuffer<> infrared_all_json_generator(WebServer *web_server, void *source); #endif +#ifdef USE_RADIO_FREQUENCY + /// Handle a radio frequency request under '/radio_frequency//transmit'. + void handle_radio_frequency_request(AsyncWebServerRequest *request, const UrlMatch &match); + + static json::SerializationBuffer<> radio_frequency_all_json_generator(WebServer *web_server, void *source); +#endif #ifdef USE_EVENT void on_event(event::Event *obj) override; @@ -654,6 +660,9 @@ class WebServer final : public Controller, public Component, public AsyncWebHand #ifdef USE_INFRARED json::SerializationBuffer<> infrared_json_(infrared::Infrared *obj, JsonDetail start_config); #endif +#ifdef USE_RADIO_FREQUENCY + json::SerializationBuffer<> radio_frequency_json_(radio_frequency::RadioFrequency *obj, JsonDetail start_config); +#endif #ifdef USE_UPDATE json::SerializationBuffer<> update_json_(update::UpdateEntity *obj, JsonDetail start_config); #endif diff --git a/esphome/core/component_iterator.h b/esphome/core/component_iterator.h index 9a1e5da351..d271fcfed0 100644 --- a/esphome/core/component_iterator.h +++ b/esphome/core/component_iterator.h @@ -21,6 +21,11 @@ namespace infrared { class Infrared; } // namespace infrared #endif +#ifdef USE_RADIO_FREQUENCY +namespace radio_frequency { +class RadioFrequency; +} // namespace radio_frequency +#endif class ComponentIterator { public: diff --git a/esphome/core/defines.h b/esphome/core/defines.h index 0978437039..63fe4e677e 100644 --- a/esphome/core/defines.h +++ b/esphome/core/defines.h @@ -65,6 +65,7 @@ #define USE_INFRARED #define USE_IR_RF #define USE_JSON +#define USE_RADIO_FREQUENCY #define USE_LIGHT #define USE_LIGHT_GAMMA_LUT #define USE_LOCK @@ -448,6 +449,7 @@ #define ESPHOME_ENTITY_LOCK_COUNT 1 #define ESPHOME_ENTITY_MEDIA_PLAYER_COUNT 1 #define ESPHOME_ENTITY_NUMBER_COUNT 1 +#define ESPHOME_ENTITY_RADIO_FREQUENCY_COUNT 1 #define ESPHOME_ENTITY_SELECT_COUNT 1 #define ESPHOME_ENTITY_SENSOR_COUNT 1 #define ESPHOME_ENTITY_SWITCH_COUNT 1 diff --git a/esphome/core/entity_includes.h b/esphome/core/entity_includes.h index f67887b30b..b1310e1142 100644 --- a/esphome/core/entity_includes.h +++ b/esphome/core/entity_includes.h @@ -68,6 +68,9 @@ #ifdef USE_INFRARED #include "esphome/components/infrared/infrared.h" #endif +#ifdef USE_RADIO_FREQUENCY +#include "esphome/components/radio_frequency/radio_frequency.h" +#endif #ifdef USE_SERIAL_PROXY #include "esphome/components/serial_proxy/serial_proxy.h" #endif diff --git a/esphome/core/entity_types.h b/esphome/core/entity_types.h index 04b490e10e..f830911c07 100644 --- a/esphome/core/entity_types.h +++ b/esphome/core/entity_types.h @@ -90,6 +90,10 @@ ENTITY_CONTROLLER_TYPE_(water_heater::WaterHeater, water_heater, water_heaters, #ifdef USE_INFRARED ENTITY_TYPE_(infrared::Infrared, infrared, infrareds, ESPHOME_ENTITY_INFRARED_COUNT, INFRARED) #endif +#ifdef USE_RADIO_FREQUENCY +ENTITY_TYPE_(radio_frequency::RadioFrequency, radio_frequency, radio_frequencies, ESPHOME_ENTITY_RADIO_FREQUENCY_COUNT, + RADIO_FREQUENCY) +#endif #ifdef USE_EVENT ENTITY_CONTROLLER_TYPE_(event::Event, event, events, ESPHOME_ENTITY_EVENT_COUNT, EVENT, event) #endif diff --git a/tests/components/web_server/common.yaml b/tests/components/web_server/common.yaml index 35a605484c..5a05a58c2d 100644 --- a/tests/components/web_server/common.yaml +++ b/tests/components/web_server/common.yaml @@ -38,3 +38,4 @@ event: update: water_heater: infrared: +radio_frequency: From 9685d4eb0b7e6f28ebff3d47d77f0ede58c1ffbc Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Thu, 23 Apr 2026 08:15:44 +0200 Subject: [PATCH 3/4] [core] feed_wdt wraps feed_wdt_with_time (#15932) --- esphome/core/application.cpp | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/esphome/core/application.cpp b/esphome/core/application.cpp index 3105ff2e8b..11381030a3 100644 --- a/esphome/core/application.cpp +++ b/esphome/core/application.cpp @@ -208,16 +208,8 @@ void Application::process_dump_config_() { void Application::feed_wdt() { // Cold entry: callers without a millis() timestamp in hand. Fetches the - // time and takes the same rate-limit paths as feed_wdt_with_time(). - uint32_t now = MillisInternal::get(); - if (now - this->last_wdt_feed_ > WDT_FEED_INTERVAL_MS) { - this->feed_wdt_slow_(now); - } -#ifdef USE_STATUS_LED - if (now - this->last_status_led_service_ > STATUS_LED_DISPATCH_INTERVAL_MS) { - this->service_status_led_slow_(now); - } -#endif + // time and defers to the hot path. + this->feed_wdt_with_time(MillisInternal::get()); } void HOT Application::feed_wdt_slow_(uint32_t time) { From 64290d32a1dd8289b04174905ec8e3c81f75fb94 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 23 Apr 2026 03:32:12 -0500 Subject: [PATCH 4/4] Bump aioesphomeapi from 44.20.0 to 44.21.0 (#15941) Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index e7ab9bc2ad..90b0693840 100644 --- a/requirements.txt +++ b/requirements.txt @@ -12,7 +12,7 @@ platformio==6.1.19 esptool==5.2.0 click==8.3.3 esphome-dashboard==20260408.1 -aioesphomeapi==44.20.0 +aioesphomeapi==44.21.0 zeroconf==0.148.0 puremagic==1.30 ruamel.yaml==0.19.1 # dashboard_import