Skip to content

Commit 98f303c

Browse files
authored
[docs] Document wake_loop_threadsafe() for low-latency background thread events (#63)
1 parent 76ab806 commit 98f303c

File tree

1 file changed

+54
-2
lines changed

1 file changed

+54
-2
lines changed

docs/architecture/components/advanced.md

Lines changed: 54 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,58 @@ To debug loop control issues:
253253

254254
3. Use the Logger component's async support as a reference implementation
255255

256-
### See Also
256+
## Waking the Main Loop from Background Threads
257257

258-
- Source: [`esphome/core/component.h`](https://github.com/esphome/esphome/blob/dev/esphome/core/component.h) and [`esphome/core/component.cpp`](https://github.com/esphome/esphome/blob/dev/esphome/core/component.cpp)
258+
For components that receive events in background threads/FreeRTOS tasks (BLE callbacks, network events, platform callbacks, etc.) and need low-latency processing, use `App.wake_loop_threadsafe()` to immediately wake the main loop instead of waiting 0-16ms for the next select() timeout.
259+
260+
**Platform Support:** ESP32 (ESP-IDF) and LibreTiny only.
261+
262+
### Setup
263+
264+
Add socket dependency in your component's `__init__.py`:
265+
266+
```python
267+
AUTO_LOAD = ["socket"]
268+
269+
from esphome.components import socket
270+
271+
async def to_code(config):
272+
# Enable wake support
273+
socket.require_wake_loop_threadsafe()
274+
```
275+
276+
### Usage
277+
278+
Call from background thread/FreeRTOS task context (not ISR context):
279+
280+
```cpp
281+
#include "esphome/core/application.h"
282+
283+
void MyComponent::background_callback(Event event) {
284+
this->pending_events_.push_back(event);
285+
286+
// Only wake for time-critical events
287+
if (event.is_time_critical()) {
288+
#if defined(USE_SOCKET_SELECT_SUPPORT) && defined(USE_WAKE_LOOP_THREADSAFE)
289+
App.wake_loop_threadsafe();
290+
#endif
291+
}
292+
}
293+
```
294+
295+
**When to wake:**
296+
- Interactive events (user pairing, passkey requests) - need immediate response
297+
- Time-critical operations - latency matters for correctness
298+
- Low-frequency events - won't cause wake storms
299+
300+
**When NOT to wake:**
301+
- High-frequency events (scan results, RSSI reads) - avoid socket churning
302+
- Non-time-critical operations - can wait for next loop iteration
303+
- Events that batch well - queue multiple before processing
304+
305+
**Important:** Only call from FreeRTOS task context, not from ISR handlers (not ISR-safe).
306+
307+
## See Also
308+
309+
- Component Loop Control: [`esphome/core/component.h`](https://github.com/esphome/esphome/blob/dev/esphome/core/component.h) and [`esphome/core/component.cpp`](https://github.com/esphome/esphome/blob/dev/esphome/core/component.cpp)
310+
- Wake Loop Threadsafe: PR [#11681](https://github.com/esphome/esphome/pull/11681)

0 commit comments

Comments
 (0)