ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
zwave_proxy.cpp
Go to the documentation of this file.
1#include "zwave_proxy.h"
2
3#ifdef USE_API
4
6
7#include <cinttypes>
10#include "esphome/core/log.h"
11#include "esphome/core/util.h"
12
14
15ESPHOME_LOG_TAG(TAG, "zwave_proxy");
16
17// Maximum bytes to log in very verbose hex output (168 * 3 = 504, under TX buffer size of 512)
18static constexpr size_t ZWAVE_MAX_LOG_BYTES = 168;
19
20static constexpr uint8_t ZWAVE_COMMAND_GET_NETWORK_IDS = 0x20;
21// GET_NETWORK_IDS response: [SOF][LENGTH][TYPE][CMD][HOME_ID(4)][NODE_ID(1 or 2)][...]
22// We only read the home ID, so the node ID (1 byte in 8-bit mode, 2 bytes in 16-bit mode) and
23// anything after it are not required to be present
24static constexpr uint8_t ZWAVE_COMMAND_TYPE_RESPONSE = 0x01; // Response type field value
25static constexpr uint8_t ZWAVE_MIN_GET_NETWORK_IDS_LENGTH = 7; // TYPE + CMD + HOME_ID(4) + checksum
26static constexpr uint8_t ZWAVE_MIN_FRAME_LENGTH = 3; // TYPE + CMD + checksum (zero-payload frame)
27static constexpr uint32_t ZWAVE_FRAME_TIMEOUT_MS = 1500; // Abandon a frame this long after its start (SOF) byte
28static constexpr uint32_t HOME_ID_TIMEOUT_MS = 100; // Timeout for waiting for home ID during setup
29static constexpr uint32_t RECONNECT_DELAY_MS = 500; // Delay between home ID query attempts after reconnect
30static constexpr uint8_t MAX_QUERY_RETRIES = 5; // Max attempts to query home ID after reconnect
31
32static constexpr bool is_bootloader_menu_byte(uint8_t byte) {
33 // Bootloader menu output is printable ASCII plus CR/LF, ending with a NUL terminator
34 return byte == 0 || byte == '\r' || byte == '\n' || (byte >= 0x20 && byte <= 0x7E);
35}
36
37static uint8_t calculate_frame_checksum(const uint8_t *data, size_t length) {
38 // Initial value is 0xFF per Z-Wave protocol specification
39 return xor_bytes(data + 1, length - 2, 0xFF);
40}
41
43
46 this->was_connected_ = this->parent_->is_connected();
47 if (this->was_connected_) {
48 this->send_simple_command_(ZWAVE_COMMAND_GET_NETWORK_IDS);
49 }
50}
51
53 // Set up before API so home ID is ready when API starts
55}
56
58 // If we already have the home ID, we can proceed
59 if (this->home_id_ready_) {
60 return true;
61 }
62
63 // Handle any pending responses
64 if (this->response_handler_()) {
65 ESP_LOGV(TAG, "Handled response during setup");
66 }
67
68 // Process UART data to check for home ID
69 this->process_uart_();
70
71 // Check if we got the home ID after processing
72 if (this->home_id_ready_) {
73 return true;
74 }
75
76 // Wait up to HOME_ID_TIMEOUT_MS for home ID response
78 if (now - this->setup_time_ > HOME_ID_TIMEOUT_MS) {
79 ESP_LOGW(TAG, "Timeout reading Home ID during setup");
80 // The modem may simply still be booting; keep querying from loop() using the same retry
81 // machinery as a reconnect. This adds no setup delay — clients are notified of the home ID
82 // via the HOME_ID_CHANGE message whenever it finally arrives.
83 this->reconnect_time_ = now;
84 this->query_retries_ = 0;
85 return true; // Proceed anyway after timeout
86 }
87
88 return false; // Keep waiting
89}
90
92 if (this->response_handler_()) {
93 ESP_LOGV(TAG, "Handled late response");
94 }
95 if (this->api_connection_ != nullptr && (!this->api_connection_->is_connection_setup() || !api_is_connected())) {
96 ESP_LOGW(TAG, "Subscriber disconnected");
97 this->api_connection_ = nullptr; // Unsubscribe if disconnected
98 }
99
100 const bool connected = this->parent_->is_connected();
101 if (this->was_connected_ != connected) {
102 this->on_connection_changed_(connected);
103 }
104 if (this->reconnect_time_ != 0) {
105 this->retry_home_id_query_();
106 }
107
108 this->process_uart_();
109
110 // Abandon a stalled frame reception. The Z-Wave API specification requires a receiver to abort
111 // a data frame reception lasting more than 1500 ms after the SOF byte, without sending a NAK.
112 // Without this, the stale bytes would silently corrupt the next frame. Any SEND_* state was
113 // already resolved by response_handler_() above, so a state other than WAIT_START here always
114 // means we are mid-frame.
116 App.get_loop_component_start_time() - this->frame_start_time_ > ZWAVE_FRAME_TIMEOUT_MS) {
117 ESP_LOGW(TAG, "Timeout waiting for frame data; resetting parser");
119 this->buffer_index_ = 0;
120 }
121}
122
124 // Caller (inline process_uart_) has already confirmed available() > 0, so use do/while to
125 // drain bytes — available() is still checked at the tail, but not redundantly on entry.
126 do {
127 uint8_t byte;
128 if (!this->read_byte(&byte)) {
129 this->status_set_warning(LOG_STR("UART read failed"));
130 return;
131 }
132 if (this->parse_byte_(byte)) {
133 // Check if this is a GET_NETWORK_IDS response frame
134 // Frame format: [SOF][LENGTH][TYPE][CMD][HOME_ID(4)][NODE_ID(1 or 2)][...]
135 // Bootloader output is excluded up front: a completed bootloader "frame" is menu text, so
136 // buffer_[1..3] would be meaningless (and possibly never written). Outside bootloader mode,
137 // the parser guarantees a completed frame starts with SOF, so buffer_[0] needs no check.
138 // We verify:
139 // - buffer_[1]: Length field must be >= 7 so the frame contains the full home ID
140 // - buffer_[2]: Command type (0x01 for response)
141 // - buffer_[3]: Command ID (0x20 for GET_NETWORK_IDS)
142 if (!this->in_bootloader_ && this->buffer_[1] >= ZWAVE_MIN_GET_NETWORK_IDS_LENGTH &&
143 this->buffer_[2] == ZWAVE_COMMAND_TYPE_RESPONSE && this->buffer_[3] == ZWAVE_COMMAND_GET_NETWORK_IDS) {
144 // Store the 4-byte Home ID, which starts at offset 4, and notify connected clients if it changed
145 // The frame parser has already validated the checksum and ensured all bytes are present
146 if (this->set_home_id_(&this->buffer_[4])) {
147 char hex_buf[format_hex_pretty_size(ZWAVE_HOME_ID_SIZE)];
148 ESP_LOGI(TAG, "Home ID: %s", format_hex_pretty_to(hex_buf, this->home_id_.data(), this->home_id_.size()));
150 }
151 this->home_id_ready_ = true;
152 }
153 ESP_LOGV(TAG, "Sending to client: %s", YESNO(this->api_connection_ != nullptr));
154 if (this->api_connection_ != nullptr) {
155 // Zero-copy: point directly to our buffer
156 this->outgoing_proto_msg_.data = this->buffer_.data();
157 if (this->in_bootloader_) {
159 } else {
160 // If this is a data frame, use frame length indicator + 2 (for SoF + checksum), else assume 1 for ACK/NAK/CAN
161 this->outgoing_proto_msg_.data_len = this->buffer_[0] == ZWAVE_FRAME_TYPE_START ? this->buffer_[1] + 2 : 1;
162 }
163 if (!this->api_connection_->send_message(this->outgoing_proto_msg_)) {
164 ESP_LOGV(TAG, "Frame dropped, TCP buffer full");
165 }
166 }
167 }
168 } while (this->available());
169 // Reaching here means every read succeeded, so clear any earlier read-failure warning.
170 // (An early return on read failure skips this, leaving the warning visible until the
171 // next successful drain.)
172 this->status_clear_warning();
173}
174
176 char hex_buf[format_hex_pretty_size(ZWAVE_HOME_ID_SIZE)];
177 ESP_LOGCONFIG(TAG,
178 "Z-Wave Proxy:\n"
179 " Home ID: %s",
180 this->home_id_ready_ ? format_hex_pretty_to(hex_buf, this->home_id_.data(), this->home_id_.size())
181 : LOG_STR_LITERAL("unknown"));
182}
183
185 if (this->home_id_ready_) {
186 // If a client just authenticated & HomeID is ready, send the current HomeID
187 this->send_homeid_changed_msg_(conn);
188 }
189}
190
193 switch (type) {
195 if (this->api_connection_ == api_connection) {
196 ESP_LOGV(TAG, "API connection is already subscribed");
198 }
199 if (this->api_connection_ != nullptr) {
200 // A living subscriber keeps exclusive access. Its connection may be dead without
201 // loop() having noticed yet (e.g. the client crashed and reconnected quickly);
202 // in that case let the new client take over instead of locking it out.
204 ESP_LOGE(TAG, "Only one API subscription is allowed at a time");
206 }
207 ESP_LOGW(TAG, "Previous subscriber disconnected; taking over subscription");
208 }
209 this->api_connection_ = api_connection;
210 ESP_LOGV(TAG, "API connection is now subscribed");
212
214 // Unsubscribe is idempotent: not being subscribed is not an error
215 if (this->api_connection_ != api_connection) {
216 ESP_LOGV(TAG, "API connection is not subscribed");
218 }
219 this->api_connection_ = nullptr;
221
222 default:
223 ESP_LOGW(TAG, "Unknown request type: %" PRIu32, static_cast<uint32_t>(type));
225 }
226}
227
229 this->was_connected_ = connected;
230 if (connected) {
231 ESP_LOGD(TAG, "Modem reconnected");
233 this->buffer_index_ = 0;
234 this->last_response_ = 0;
235 this->in_bootloader_ = false;
236 // Defer the query — the modem needs time to initialize after power is applied
238 this->query_retries_ = 0;
239 } else {
240 ESP_LOGW(TAG, "Modem disconnected");
241 this->clear_home_id_();
242 }
243}
244
246 if (this->home_id_ready_) {
247 // Got the home ID, cancel remaining retries
248 this->reconnect_time_ = 0;
249 return;
250 }
251 if (App.get_loop_component_start_time() - this->reconnect_time_ <= RECONNECT_DELAY_MS) {
252 return; // Not yet time for next attempt
253 }
254 this->reconnect_time_ = App.get_loop_component_start_time(); // Reset timer for next retry
255 this->query_retries_++;
256 if (this->query_retries_ <= MAX_QUERY_RETRIES) {
257 ESP_LOGD(TAG, "Querying Home ID (attempt %u)", this->query_retries_);
258 this->send_simple_command_(ZWAVE_COMMAND_GET_NETWORK_IDS);
259 } else {
260 ESP_LOGW(TAG, "Failed to read Home ID after %u attempts", MAX_QUERY_RETRIES);
261 this->reconnect_time_ = 0;
262 }
263}
264
266 static constexpr uint8_t ZERO_HOME_ID[ZWAVE_HOME_ID_SIZE] = {};
267 if (this->set_home_id_(ZERO_HOME_ID)) {
268 ESP_LOGV(TAG, "Home ID cleared");
270 }
271 this->home_id_ready_ = false;
273 this->buffer_index_ = 0;
274 this->last_response_ = 0;
275 this->in_bootloader_ = false;
276}
277
278bool ZWaveProxy::set_home_id_(const uint8_t *new_home_id) {
279 if (std::memcmp(this->home_id_.data(), new_home_id, this->home_id_.size()) == 0) {
280 ESP_LOGV(TAG, "Home ID unchanged");
281 return false; // No change
282 }
283 std::memcpy(this->home_id_.data(), new_home_id, this->home_id_.size());
284 return true; // Home ID was changed
285}
286
287void ZWaveProxy::send_frame(api::APIConnection *api_connection, const uint8_t *data, size_t length) {
288 // Only the subscribed client may talk to the Z-Wave module; a frame from any other
289 // (authenticated but unsubscribed) client would interleave with the subscriber's traffic
290 if (api_connection != this->api_connection_) {
291 ESP_LOGW(TAG, "Ignoring frame from unsubscribed client");
292 return;
293 }
294 this->send_frame_(data, length);
295}
296
297void ZWaveProxy::send_frame_(const uint8_t *data, size_t length) {
298 // Safety: validate pointer before any access
299 if (data == nullptr) {
300 ESP_LOGE(TAG, "Null data pointer");
301 return;
302 }
303 if (length == 0) {
304 ESP_LOGE(TAG, "Length 0");
305 return;
306 }
307
308 // Skip duplicate single-byte responses (ACK/NAK/CAN)
309 if (length == 1 && data[0] == this->last_response_) {
310 ESP_LOGV(TAG, "Response already sent: 0x%02X", data[0]);
311 return;
312 }
313
314 ESP_LOGVV_HEX(TAG, data, length, ZWAVE_MAX_LOG_BYTES, "Sending: %s");
315
316 this->write_array(data, length);
317}
318
322 msg.data = this->home_id_.data();
323 msg.data_len = this->home_id_.size();
324 if (conn != nullptr) {
325 // Send to specific connection
326 if (!conn->send_message(msg)) {
327 API_LOG_MSG_DROPPED(TAG, "Home ID notification");
328 }
329 } else if (api::global_api_server != nullptr) {
330 // We could add code to manage a second subscription type, but, since this message is
331 // very infrequent and small, we simply send it to all clients
333 }
334}
335
336void ZWaveProxy::send_simple_command_(const uint8_t command_id) {
337 // Send a simple Z-Wave command with no parameters
338 // Frame format: [SOF][LENGTH][TYPE][CMD][CHECKSUM]
339 // Where LENGTH=0x03 (3 bytes: TYPE + CMD + CHECKSUM)
340 uint8_t cmd[] = {0x01, 0x03, 0x00, command_id, 0x00};
341 cmd[4] = calculate_frame_checksum(cmd, sizeof(cmd));
342 this->send_frame_(cmd, sizeof(cmd));
343}
344
345bool ZWaveProxy::parse_byte_(uint8_t byte) {
346 bool frame_completed = false;
347 // Basic parsing logic for received frames
348 switch (this->parsing_state_) {
350 this->parse_start_(byte);
351 break;
353 if (byte < ZWAVE_MIN_FRAME_LENGTH) {
354 ESP_LOGW(TAG, "Invalid LENGTH: %u", byte);
356 // Send the NAK now; otherwise any bytes already buffered behind this one would be
357 // silently discarded by the SEND_NAK case below until the next loop() iteration
358 this->response_handler_();
359 return false;
360 }
361 ESP_LOGVV(TAG, "Received LENGTH: %u", byte);
362 this->end_frame_after_ = this->buffer_index_ + byte;
363 ESP_LOGVV(TAG, "Calculated EOF: %u", this->end_frame_after_);
364 this->buffer_[this->buffer_index_++] = byte;
366 break;
368 this->buffer_[this->buffer_index_++] = byte;
369 ESP_LOGVV(TAG, "Received TYPE: 0x%02X", byte);
371 break;
373 this->buffer_[this->buffer_index_++] = byte;
374 ESP_LOGVV(TAG, "Received COMMAND ID: 0x%02X", byte);
375 // A zero-payload frame (LENGTH == 3) has its checksum immediately after the command ID
378 break;
380 this->buffer_[this->buffer_index_++] = byte;
381 ESP_LOGVV(TAG, "Received PAYLOAD: 0x%02X", byte);
382 if (this->buffer_index_ >= this->end_frame_after_) {
384 }
385 break;
387 this->buffer_[this->buffer_index_++] = byte;
388 auto checksum = calculate_frame_checksum(this->buffer_.data(), this->buffer_index_);
389 ESP_LOGVV(TAG, "CHECKSUM Received: 0x%02X - Calculated: 0x%02X", byte, checksum);
390 if (checksum != byte) {
391 ESP_LOGW(TAG, "Bad checksum: expected 0x%02X, got 0x%02X", checksum, byte);
393 } else {
395 ESP_LOGVV_HEX(TAG, this->buffer_.data(), this->buffer_index_, ZWAVE_MAX_LOG_BYTES, "Received frame: %s");
396 frame_completed = true;
397 }
398 this->response_handler_();
399 break;
400 }
402 // This state is tentative (see parse_start_): bootloader mode is committed only when a
403 // plausible menu — printable text ending in a NUL terminator — completes. A byte that
404 // cannot be menu text means the 0x0D that started this state was not a menu after all,
405 // so re-parse that byte as a frame start; it may be the SOF/ACK/NAK of real traffic.
406 if (this->buffer_index_ >= this->buffer_.size() || !is_bootloader_menu_byte(byte)) {
408 this->parse_start_(byte);
409 break;
410 }
411 this->buffer_[this->buffer_index_++] = byte;
412 if (!byte) {
413 if (!this->in_bootloader_) {
414 ESP_LOGD(TAG, "Entered bootloader mode");
415 this->in_bootloader_ = true;
416 // Reset response deduplication: in bootloader mode, single-byte client writes (XMODEM
417 // ACK/NAK/CAN) are raw data and must never be suppressed as duplicate responses
418 this->last_response_ = 0;
419 }
421 frame_completed = true;
422 }
423 break;
426 break; // Should not happen, handled in loop()
427 default:
428 ESP_LOGW(TAG, "Bad parsing state; resetting");
430 break;
431 }
432 return frame_completed;
433}
434
435void ZWaveProxy::parse_start_(uint8_t byte) {
436 this->buffer_index_ = 0;
438 switch (byte) {
440 ESP_LOGV(TAG, "Received START");
441 if (this->in_bootloader_) {
442 ESP_LOGD(TAG, "Exited bootloader mode");
443 this->in_bootloader_ = false;
444 }
446 this->buffer_[this->buffer_index_++] = byte;
448 return;
450 ESP_LOGV(TAG, "Received BL_MENU");
451 // Read the menu tentatively: a stray 0x0D can equally appear in garbled data after the
452 // parser loses frame alignment, so bootloader mode is only committed once a plausible
453 // menu completes (see READ_BL_MENU handling in parse_byte_)
455 this->buffer_[this->buffer_index_++] = byte;
457 return;
459 ESP_LOGV(TAG, "Received BL_BEGIN_UPLOAD");
460 break;
462 ESP_LOGV(TAG, "Received ACK");
463 break;
465 ESP_LOGV(TAG, "Received NAK");
466 break;
468 ESP_LOGV(TAG, "Received CAN");
469 break;
470 default:
471 ESP_LOGV(TAG, "Unrecognized START: 0x%02X", byte);
472 return;
473 }
474 // Forward response (ACK/NAK/CAN) back to client for processing
475 if (this->api_connection_ != nullptr) {
476 // Store single byte in buffer and point to it
477 this->buffer_[0] = byte;
478 this->outgoing_proto_msg_.data = this->buffer_.data();
480 if (!this->api_connection_->send_message(this->outgoing_proto_msg_)) {
481 ESP_LOGV(TAG, "Frame dropped, TCP buffer full");
482 }
483 }
484}
485
487 switch (this->parsing_state_) {
490 break;
493 break;
496 break;
497 default:
498 return false; // No response handled
499 }
500
501 ESP_LOGVV(TAG, "Sending %s (0x%02X)",
502 this->last_response_ == ZWAVE_FRAME_TYPE_ACK ? LOG_STR_LITERAL("ACK") : LOG_STR_LITERAL("NAK/CAN"),
503 this->last_response_);
504 this->write_byte(this->last_response_);
506 return true;
507}
508
509ZWaveProxy *global_zwave_proxy = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
510
511} // namespace esphome::zwave_proxy
512
513#endif // USE_API
uint8_t checksum
Definition bl0906.h:3
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
void status_clear_warning()
Definition component.h:296
bool send_message(const T &msg)
Returns false as soon as the TCP buffer is full.
void on_zwave_proxy_request(const ZWaveProxyRequest &msg)
enums::ZWaveProxyRequestType type
Definition api_pb2.h:3741
UARTComponent * parent_
Definition uart.h:134
bool read_byte(uint8_t *data)
Definition uart.h:39
void write_byte(uint8_t data)
Definition uart.h:22
void write_array(const uint8_t *data, size_t len)
Definition uart.h:30
api::ZWaveProxyFrame outgoing_proto_msg_
void send_homeid_changed_msg_(api::APIConnection *conn=nullptr)
bool set_home_id_(const uint8_t *new_home_id)
void send_simple_command_(uint8_t command_id)
ESPHOME_ALWAYS_INLINE void process_uart_()
void send_frame(api::APIConnection *api_connection, const uint8_t *data, size_t length)
void send_frame_(const uint8_t *data, size_t length)
void api_connection_authenticated(api::APIConnection *conn)
std::array< uint8_t, MAX_ZWAVE_FRAME_SIZE > buffer_
ESPHOME_ALWAYS_INLINE bool response_handler_()
Definition zwave_proxy.h:90
api::enums::ZWaveProxyStatus zwave_proxy_request(api::APIConnection *api_connection, api::enums::ZWaveProxyRequestType type)
api::APIConnection * api_connection_
float get_setup_priority() const override
void on_connection_changed_(bool connected)
std::array< uint8_t, ZWAVE_HOME_ID_SIZE > home_id_
uint8_t type
@ ZWAVE_PROXY_STATUS_NOT_SUPPORTED
Definition api_pb2.h:349
@ ZWAVE_PROXY_REQUEST_TYPE_SUBSCRIBE
Definition api_pb2.h:342
@ ZWAVE_PROXY_REQUEST_TYPE_UNSUBSCRIBE
Definition api_pb2.h:343
@ ZWAVE_PROXY_REQUEST_TYPE_HOME_ID_CHANGE
Definition api_pb2.h:344
APIServer * global_api_server
constexpr float BEFORE_CONNECTION
For components that should be initialized after WiFi and before API is connected.
Definition component.h:53
ESPHOME_LOG_TAG(TAG, "zwave_proxy")
ZWaveProxy * global_zwave_proxy
constexpr uint8_t xor_bytes(const uint8_t *data, size_t len, uint8_t init=0)
XOR the bytes of data with size len, starting from init.
Definition helpers.h:904
ESPHOME_ALWAYS_INLINE bool api_is_connected()
Return whether the node has at least one client connected to the native API.
Definition util.h:20
char * format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator)
Format byte array as uppercase hex to buffer (base implementation).
Definition helpers.cpp:498
constexpr size_t format_hex_pretty_size(size_t byte_count)
Calculate buffer size needed for format_hex_pretty_to with separator: "XX:XX:...:XX\0".
Definition helpers.h:1609
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
uint16_t length
Definition tt21100.cpp:0