ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
event_source.h
Go to the documentation of this file.
1#pragma once
2
4#if defined(USE_WEBSERVER) && (defined(USE_ESP32) || defined(USE_ARDUINO))
5
9#include "list_entities.h"
10#include "sse_chunk.h"
11
12#include <atomic>
13#include <cstdint>
14#include <vector>
15
16namespace esphome::web_server {
17
18class WebServer;
19class AsyncEventSource;
20class AsyncEventSourceResponse;
21
23
24/*
25 This class holds a pointer to the source component that wants to publish a state event, and a pointer to a function
26 that will lazily generate that event. The two pointers allow dedup in the deferred queue if multiple publishes for
27 the same component are backed up, and take up only two pointers of memory. The entry in the deferred queue (a
28 std::vector) is the DeferredEvent instance itself (not a pointer to one elsewhere in heap) so still only two pointers
29 per entry (and no heap fragmentation). Even 100 backed up events (you'd have to have at least 100 sensors publishing
30 because of dedup) would take up only 0.8 kB.
31*/
34
35 protected:
36 void *source_;
38
39 public:
40 DeferredEvent(void *source, message_generator_t *message_generator)
41 : source_(source), message_generator_(message_generator) {}
42 bool operator==(const DeferredEvent &test) const {
43 return (source_ == test.source_ && message_generator_ == test.message_generator_);
44 }
45};
46static_assert(sizeof(DeferredEvent) == sizeof(void *) + sizeof(message_generator_t *),
47 "DeferredEvent should have no padding");
48
50 friend class AsyncEventSource;
51
52 public:
53 bool try_send_nodefer(const char *message, size_t message_len, const char *event = nullptr, uint32_t id = 0,
54 uint32_t reconnect = 0);
55 // detail_all events go out while entities are still being listed; state events wait until listing is done
56 void deferrable_send_state(void *source, bool detail_all, message_generator_t *message_generator);
57 // The old event name argument would otherwise convert to true
58 void deferrable_send_state(void *source, const char *event_type, message_generator_t *message_generator) = delete;
59 void loop();
60
61 protected:
63
64 // Main-loop only: sends initial ping/config/sorting_groups, starts entity iterator.
66
67 void deq_push_back_with_dedup_(void *source, message_generator_t *message_generator);
69 // Not re-entered from a log line and the session is alive after pushing the tail
70 bool drain_if_idle_();
71 // Push what is left of the chunk in tail_ to the socket
72 void drain_tail_();
73 // Grow tail_ to hold len bytes, kept at its high-water mark. False on OOM.
74 bool reserve_tail_(size_t len);
75 // Keep the whole chunk in tail_ and continue from sent; false when the tail cannot be allocated.
76 bool stash_chunk_(const char *prefix, size_t prefix_len, const char *message, size_t message_len, size_t total,
77 size_t sent);
78 // Queue a whole chunk behind the unsent part of the tail; false when it does not fit TAIL_QUEUE_SIZE or OOM
79 bool append_chunk_(const char *prefix, size_t prefix_len, const char *message, size_t message_len, size_t total);
80 // Send a state event; JSON too large for the stack buffer is serialized into tail_ instead
81 bool send_json_(void *source, message_generator_t *generator);
88 // Keep the arena out of the caller's frame so it is gone before the state send.
89 // size_out: BUFFER = JSON length, NO_MEMORY = requested tail capacity, TOO_LARGE = available JSON room;
90 // unused for TAIL.
91 JsonPrepareResult __attribute__((noinline)) prepare_json_(void *source, message_generator_t *generator, char *buffer,
92 size_t *size_out);
93 // Warn once per stall, and close the session once the stall timeout passes with no memory for the tail
94 void tail_alloc_failed_(size_t cap);
95
96 // A log line emitted inside a send re-enters try_send_nodefer on this session; refuse it
102 // Frees the tail and the queue's storage once the session is closing
103 void release_buffers_();
104
105 std::vector<DeferredEvent> deferred_queue_;
107 // Next session in AsyncEventSource's sessions or pending list
110 // Chunks the socket did not take yet, allocated on the first stall; the only heap use on the
111 // send path
113 uint16_t tail_cap_{0};
114 uint16_t tail_len_{0}; // Zero means nothing pending
115 uint16_t tail_sent_{0};
116 bool sending_{false};
117 // The no-memory warning went out during the current stall; cleared on send progress
118 bool no_memory_logged_{false};
119#ifdef USE_ESP8266
120 // The 4 KB loop stack: smaller send frames, anything larger goes through the tail
121 static constexpr size_t MAX_SEND_LINES = 8;
122 static constexpr size_t JSON_BUF_SIZE = 512;
123#else
124 // The longest multi line log message in the tree (a climate dump_config) has 22 lines; a
125 // longer one goes through the tail
126 static constexpr size_t MAX_SEND_LINES = 22;
127 // Stack buffer for a state event's JSON; a larger document is serialized into the tail
128 static constexpr size_t JSON_BUF_SIZE = 1024;
129#endif
130 static constexpr size_t MAX_SEND_IOV = 1 + 2 * MAX_SEND_LINES;
131 // Chunk header, retry/id/event lines and the first "data: "
132 static constexpr size_t PREFIX_BUF_SIZE = 128;
133 // Same ceiling JsonBuilder::serialize() applies (max_heap_size in json_util.cpp); a larger
134 // document is dropped before anything is on the wire
135 static constexpr size_t JSON_MAX_SIZE = 5120;
136 // Most an unsent chunk and the events queued behind it may hold: about one TCP segment
137 static constexpr size_t TAIL_QUEUE_SIZE = 1460;
138 // Most RAM a stalled session keeps: the largest state document plus any accepted framing
140};
141
142// Not an AsyncWebHandler: WebServer routes /events here, which keeps the handler base and its guard out of RAM
144 public:
145 AsyncEventSource() = default;
146 void handle_request(AsyncWebServerRequest *request, WebServer *ws);
147 void try_send_nodefer(const char *message, size_t message_len, const char *event = nullptr, uint32_t id = 0,
148 uint32_t reconnect = 0);
149 // State events to every session; each session's own listing sends the detail_all events
150 void deferrable_send_state(void *source, message_generator_t *message_generator);
152 bool loop();
153 bool empty() const { return this->sessions_ == nullptr; }
154
155 protected:
156 // Cold path: move sessions from the pending list into sessions_ and greet each one.
157 void __attribute__((noinline, cold)) adopt_pending_sessions_main_loop_();
158 // Network context: queue a new session for the main loop
160
161 // Main-loop only; intrusive list through AsyncEventSourceResponse::next_
163 // Network-context intake, guarded by pending_mutex_; non-null means work to adopt
164 std::atomic<AsyncEventSourceResponse *> pending_sessions_{nullptr};
165 [[no_unique_address]] Mutex pending_mutex_;
166};
167
168} // namespace esphome::web_server
169
170#endif // USE_WEBSERVER && (USE_ESP32 || USE_ARDUINO)
Mutex implementation, with API based on the unavailable std::mutex.
Definition helpers.h:2455
Builder class for creating JSON documents without lambdas.
Definition json_util.h:286
void handle_request(AsyncWebServerRequest *request, WebServer *ws)
void push_pending_(AsyncEventSourceResponse *rsp)
std::atomic< AsyncEventSourceResponse * > pending_sessions_
void __attribute__((noinline, cold)) adopt_pending_sessions_main_loop_()
AsyncEventSourceResponse * sessions_
bool loop()
Returns true if there are sessions remaining (including pending cleanup).
void deferrable_send_state(void *source, message_generator_t *message_generator)
void try_send_nodefer(const char *message, size_t message_len, const char *event=nullptr, uint32_t id=0, uint32_t reconnect=0)
void deferrable_send_state(void *source, const char *event_type, message_generator_t *message_generator)=delete
std::vector< DeferredEvent > deferred_queue_
bool try_send_nodefer(const char *message, size_t message_len, const char *event=nullptr, uint32_t id=0, uint32_t reconnect=0)
JsonPrepareResult __attribute__((noinline)) prepare_json_(void *source
JsonPrepareResult message_generator_t * generator
void deq_push_back_with_dedup_(void *source, message_generator_t *message_generator)
bool append_chunk_(const char *prefix, size_t prefix_len, const char *message, size_t message_len, size_t total)
JsonPrepareResult message_generator_t char * buffer
void deferrable_send_state(void *source, bool detail_all, message_generator_t *message_generator)
bool stash_chunk_(const char *prefix, size_t prefix_len, const char *message, size_t message_len, size_t total, size_t sent)
JsonPrepareResult message_generator_t char size_t * size_out
bool send_json_(void *source, message_generator_t *generator)
This class allows users to create a web server with their ESP nodes.
Definition web_server.h:121
const LogString * message
Definition component.cpp:35
void(WebServer *, void *, json::JsonBuilder &) message_generator_t
constexpr size_t SSE_SUFFIX_LEN
Definition sse_chunk.h:28
std::unique_ptr< T, RAMDeleter< T > > RAMUniquePtr
unique_ptr over RAMAllocator storage
Definition helpers.h:2659
const void size_t len
Definition hal.h:68
static void uint32_t
DeferredEvent(void *source, message_generator_t *message_generator)
bool operator==(const DeferredEvent &test) const
message_generator_t * message_generator_