ESPHome 2026.8.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
15static const char *const 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, uint8_t length) {
38 // Calculate Z-Wave frame checksum
39 // XOR all bytes between SOF and checksum position (exclusive)
40 // Initial value is 0xFF per Z-Wave protocol specification
41 uint8_t checksum = 0xFF;
42 for (uint8_t i = 1; i < length - 1; i++) {
43 checksum ^= data[i];
44 }
45 return checksum;
46}
47
49
52 this->was_connected_ = this->parent_->is_connected();
53 if (this->was_connected_) {
54 this->send_simple_command_(ZWAVE_COMMAND_GET_NETWORK_IDS);
55 }
56}
57
59 // Set up before API so home ID is ready when API starts
61}
62
64 // If we already have the home ID, we can proceed
65 if (this->home_id_ready_) {
66 return true;
67 }
68
69 // Handle any pending responses
70 if (this->response_handler_()) {
71 ESP_LOGV(TAG, "Handled response during setup");
72 }
73
74 // Process UART data to check for home ID
75 this->process_uart_();
76
77 // Check if we got the home ID after processing
78 if (this->home_id_ready_) {
79 return true;
80 }
81
82 // Wait up to HOME_ID_TIMEOUT_MS for home ID response
84 if (now - this->setup_time_ > HOME_ID_TIMEOUT_MS) {
85 ESP_LOGW(TAG, "Timeout reading Home ID during setup");
86 // The modem may simply still be booting; keep querying from loop() using the same retry
87 // machinery as a reconnect. This adds no setup delay — clients are notified of the home ID
88 // via the HOME_ID_CHANGE message whenever it finally arrives.
89 this->reconnect_time_ = now;
90 this->query_retries_ = 0;
91 return true; // Proceed anyway after timeout
92 }
93
94 return false; // Keep waiting
95}
96
98 if (this->response_handler_()) {
99 ESP_LOGV(TAG, "Handled late response");
100 }
101 if (this->api_connection_ != nullptr && (!this->api_connection_->is_connection_setup() || !api_is_connected())) {
102 ESP_LOGW(TAG, "Subscriber disconnected");
103 this->api_connection_ = nullptr; // Unsubscribe if disconnected
104 }
105
106 const bool connected = this->parent_->is_connected();
107 if (this->was_connected_ != connected) {
108 this->on_connection_changed_(connected);
109 }
110 if (this->reconnect_time_ != 0) {
111 this->retry_home_id_query_();
112 }
113
114 this->process_uart_();
115
116 // Abandon a stalled frame reception. The Z-Wave API specification requires a receiver to abort
117 // a data frame reception lasting more than 1500 ms after the SOF byte, without sending a NAK.
118 // Without this, the stale bytes would silently corrupt the next frame. Any SEND_* state was
119 // already resolved by response_handler_() above, so a state other than WAIT_START here always
120 // means we are mid-frame.
122 App.get_loop_component_start_time() - this->frame_start_time_ > ZWAVE_FRAME_TIMEOUT_MS) {
123 ESP_LOGW(TAG, "Timeout waiting for frame data; resetting parser");
125 this->buffer_index_ = 0;
126 }
127}
128
130 // Caller (inline process_uart_) has already confirmed available() > 0, so use do/while to
131 // drain bytes — available() is still checked at the tail, but not redundantly on entry.
132 do {
133 uint8_t byte;
134 if (!this->read_byte(&byte)) {
135 this->status_set_warning(LOG_STR("UART read failed"));
136 return;
137 }
138 if (this->parse_byte_(byte)) {
139 // Check if this is a GET_NETWORK_IDS response frame
140 // Frame format: [SOF][LENGTH][TYPE][CMD][HOME_ID(4)][NODE_ID(1 or 2)][...]
141 // Bootloader output is excluded up front: a completed bootloader "frame" is menu text, so
142 // buffer_[1..3] would be meaningless (and possibly never written). Outside bootloader mode,
143 // the parser guarantees a completed frame starts with SOF, so buffer_[0] needs no check.
144 // We verify:
145 // - buffer_[1]: Length field must be >= 7 so the frame contains the full home ID
146 // - buffer_[2]: Command type (0x01 for response)
147 // - buffer_[3]: Command ID (0x20 for GET_NETWORK_IDS)
148 if (!this->in_bootloader_ && this->buffer_[1] >= ZWAVE_MIN_GET_NETWORK_IDS_LENGTH &&
149 this->buffer_[2] == ZWAVE_COMMAND_TYPE_RESPONSE && this->buffer_[3] == ZWAVE_COMMAND_GET_NETWORK_IDS) {
150 // Store the 4-byte Home ID, which starts at offset 4, and notify connected clients if it changed
151 // The frame parser has already validated the checksum and ensured all bytes are present
152 if (this->set_home_id_(&this->buffer_[4])) {
153 char hex_buf[format_hex_pretty_size(ZWAVE_HOME_ID_SIZE)];
154 ESP_LOGI(TAG, "Home ID: %s", format_hex_pretty_to(hex_buf, this->home_id_.data(), this->home_id_.size()));
156 }
157 this->home_id_ready_ = true;
158 }
159 ESP_LOGV(TAG, "Sending to client: %s", YESNO(this->api_connection_ != nullptr));
160 if (this->api_connection_ != nullptr) {
161 // Zero-copy: point directly to our buffer
162 this->outgoing_proto_msg_.data = this->buffer_.data();
163 if (this->in_bootloader_) {
165 } else {
166 // If this is a data frame, use frame length indicator + 2 (for SoF + checksum), else assume 1 for ACK/NAK/CAN
167 this->outgoing_proto_msg_.data_len = this->buffer_[0] == ZWAVE_FRAME_TYPE_START ? this->buffer_[1] + 2 : 1;
168 }
170 }
171 }
172 } while (this->available());
173 // Reaching here means every read succeeded, so clear any earlier read-failure warning.
174 // (An early return on read failure skips this, leaving the warning visible until the
175 // next successful drain.)
176 this->status_clear_warning();
177}
178
180 char hex_buf[format_hex_pretty_size(ZWAVE_HOME_ID_SIZE)];
181 ESP_LOGCONFIG(
182 TAG,
183 "Z-Wave Proxy:\n"
184 " Home ID: %s",
185 this->home_id_ready_ ? format_hex_pretty_to(hex_buf, this->home_id_.data(), this->home_id_.size()) : "unknown");
186}
187
189 if (this->home_id_ready_) {
190 // If a client just authenticated & HomeID is ready, send the current HomeID
191 this->send_homeid_changed_msg_(conn);
192 }
193}
194
196 switch (type) {
198 if (this->api_connection_ == api_connection) {
199 ESP_LOGV(TAG, "API connection is already subscribed");
200 return;
201 }
202 if (this->api_connection_ != nullptr) {
203 // A living subscriber keeps exclusive access. Its connection may be dead without
204 // loop() having noticed yet (e.g. the client crashed and reconnected quickly);
205 // in that case let the new client take over instead of locking it out.
207 ESP_LOGE(TAG, "Only one API subscription is allowed at a time");
208 return;
209 }
210 ESP_LOGW(TAG, "Previous subscriber disconnected; taking over subscription");
211 }
212 this->api_connection_ = api_connection;
213 ESP_LOGV(TAG, "API connection is now subscribed");
214 break;
215
217 if (this->api_connection_ != api_connection) {
218 ESP_LOGV(TAG, "API connection is not subscribed");
219 return;
220 }
221 this->api_connection_ = nullptr;
222 break;
223
224 default:
225 ESP_LOGW(TAG, "Unknown request type: %" PRIu32, static_cast<uint32_t>(type));
226 break;
227 }
228}
229
231 this->was_connected_ = connected;
232 if (connected) {
233 ESP_LOGD(TAG, "Modem reconnected");
235 this->buffer_index_ = 0;
236 this->last_response_ = 0;
237 this->in_bootloader_ = false;
238 // Defer the query — the modem needs time to initialize after power is applied
240 this->query_retries_ = 0;
241 } else {
242 ESP_LOGW(TAG, "Modem disconnected");
243 this->clear_home_id_();
244 }
245}
246
248 if (this->home_id_ready_) {
249 // Got the home ID, cancel remaining retries
250 this->reconnect_time_ = 0;
251 return;
252 }
253 if (App.get_loop_component_start_time() - this->reconnect_time_ <= RECONNECT_DELAY_MS) {
254 return; // Not yet time for next attempt
255 }
256 this->reconnect_time_ = App.get_loop_component_start_time(); // Reset timer for next retry
257 this->query_retries_++;
258 if (this->query_retries_ <= MAX_QUERY_RETRIES) {
259 ESP_LOGD(TAG, "Querying Home ID (attempt %u)", this->query_retries_);
260 this->send_simple_command_(ZWAVE_COMMAND_GET_NETWORK_IDS);
261 } else {
262 ESP_LOGW(TAG, "Failed to read Home ID after %u attempts", MAX_QUERY_RETRIES);
263 this->reconnect_time_ = 0;
264 }
265}
266
268 static constexpr uint8_t ZERO_HOME_ID[ZWAVE_HOME_ID_SIZE] = {};
269 if (this->set_home_id_(ZERO_HOME_ID)) {
270 ESP_LOGV(TAG, "Home ID cleared");
272 }
273 this->home_id_ready_ = false;
275 this->buffer_index_ = 0;
276 this->last_response_ = 0;
277 this->in_bootloader_ = false;
278}
279
280bool ZWaveProxy::set_home_id_(const uint8_t *new_home_id) {
281 if (std::memcmp(this->home_id_.data(), new_home_id, this->home_id_.size()) == 0) {
282 ESP_LOGV(TAG, "Home ID unchanged");
283 return false; // No change
284 }
285 std::memcpy(this->home_id_.data(), new_home_id, this->home_id_.size());
286 return true; // Home ID was changed
287}
288
289void ZWaveProxy::send_frame(api::APIConnection *api_connection, const uint8_t *data, size_t length) {
290 // Only the subscribed client may talk to the Z-Wave module; a frame from any other
291 // (authenticated but unsubscribed) client would interleave with the subscriber's traffic
292 if (api_connection != this->api_connection_) {
293 ESP_LOGW(TAG, "Ignoring frame from unsubscribed client");
294 return;
295 }
296 this->send_frame_(data, length);
297}
298
299void ZWaveProxy::send_frame_(const uint8_t *data, size_t length) {
300 // Safety: validate pointer before any access
301 if (data == nullptr) {
302 ESP_LOGE(TAG, "Null data pointer");
303 return;
304 }
305 if (length == 0) {
306 ESP_LOGE(TAG, "Length 0");
307 return;
308 }
309
310 // Skip duplicate single-byte responses (ACK/NAK/CAN)
311 if (length == 1 && data[0] == this->last_response_) {
312 ESP_LOGV(TAG, "Response already sent: 0x%02X", data[0]);
313 return;
314 }
315
316#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
317 char hex_buf[format_hex_pretty_size(ZWAVE_MAX_LOG_BYTES)];
318#endif
319 ESP_LOGVV(TAG, "Sending: %s", format_hex_pretty_to(hex_buf, data, length));
320
321 this->write_array(data, length);
322}
323
327 msg.data = this->home_id_.data();
328 msg.data_len = this->home_id_.size();
329 if (conn != nullptr) {
330 // Send to specific connection
331 conn->send_message(msg);
332 } else if (api::global_api_server != nullptr) {
333 // We could add code to manage a second subscription type, but, since this message is
334 // very infrequent and small, we simply send it to all clients
336 }
337}
338
339void ZWaveProxy::send_simple_command_(const uint8_t command_id) {
340 // Send a simple Z-Wave command with no parameters
341 // Frame format: [SOF][LENGTH][TYPE][CMD][CHECKSUM]
342 // Where LENGTH=0x03 (3 bytes: TYPE + CMD + CHECKSUM)
343 uint8_t cmd[] = {0x01, 0x03, 0x00, command_id, 0x00};
344 cmd[4] = calculate_frame_checksum(cmd, sizeof(cmd));
345 this->send_frame_(cmd, sizeof(cmd));
346}
347
348bool ZWaveProxy::parse_byte_(uint8_t byte) {
349 bool frame_completed = false;
350 // Basic parsing logic for received frames
351 switch (this->parsing_state_) {
353 this->parse_start_(byte);
354 break;
356 if (byte < ZWAVE_MIN_FRAME_LENGTH) {
357 ESP_LOGW(TAG, "Invalid LENGTH: %u", byte);
359 // Send the NAK now; otherwise any bytes already buffered behind this one would be
360 // silently discarded by the SEND_NAK case below until the next loop() iteration
361 this->response_handler_();
362 return false;
363 }
364 ESP_LOGVV(TAG, "Received LENGTH: %u", byte);
365 this->end_frame_after_ = this->buffer_index_ + byte;
366 ESP_LOGVV(TAG, "Calculated EOF: %u", this->end_frame_after_);
367 this->buffer_[this->buffer_index_++] = byte;
369 break;
371 this->buffer_[this->buffer_index_++] = byte;
372 ESP_LOGVV(TAG, "Received TYPE: 0x%02X", byte);
374 break;
376 this->buffer_[this->buffer_index_++] = byte;
377 ESP_LOGVV(TAG, "Received COMMAND ID: 0x%02X", byte);
378 // A zero-payload frame (LENGTH == 3) has its checksum immediately after the command ID
381 break;
383 this->buffer_[this->buffer_index_++] = byte;
384 ESP_LOGVV(TAG, "Received PAYLOAD: 0x%02X", byte);
385 if (this->buffer_index_ >= this->end_frame_after_) {
387 }
388 break;
390 this->buffer_[this->buffer_index_++] = byte;
391 auto checksum = calculate_frame_checksum(this->buffer_.data(), this->buffer_index_);
392 ESP_LOGVV(TAG, "CHECKSUM Received: 0x%02X - Calculated: 0x%02X", byte, checksum);
393 if (checksum != byte) {
394 ESP_LOGW(TAG, "Bad checksum: expected 0x%02X, got 0x%02X", checksum, byte);
396 } else {
398#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
399 char hex_buf[format_hex_pretty_size(ZWAVE_MAX_LOG_BYTES)];
400#endif
401 ESP_LOGVV(TAG, "Received frame: %s", format_hex_pretty_to(hex_buf, this->buffer_.data(), this->buffer_index_));
402 frame_completed = true;
403 }
404 this->response_handler_();
405 break;
406 }
408 // This state is tentative (see parse_start_): bootloader mode is committed only when a
409 // plausible menu — printable text ending in a NUL terminator — completes. A byte that
410 // cannot be menu text means the 0x0D that started this state was not a menu after all,
411 // so re-parse that byte as a frame start; it may be the SOF/ACK/NAK of real traffic.
412 if (this->buffer_index_ >= this->buffer_.size() || !is_bootloader_menu_byte(byte)) {
414 this->parse_start_(byte);
415 break;
416 }
417 this->buffer_[this->buffer_index_++] = byte;
418 if (!byte) {
419 if (!this->in_bootloader_) {
420 ESP_LOGD(TAG, "Entered bootloader mode");
421 this->in_bootloader_ = true;
422 // Reset response deduplication: in bootloader mode, single-byte client writes (XMODEM
423 // ACK/NAK/CAN) are raw data and must never be suppressed as duplicate responses
424 this->last_response_ = 0;
425 }
427 frame_completed = true;
428 }
429 break;
432 break; // Should not happen, handled in loop()
433 default:
434 ESP_LOGW(TAG, "Bad parsing state; resetting");
436 break;
437 }
438 return frame_completed;
439}
440
441void ZWaveProxy::parse_start_(uint8_t byte) {
442 this->buffer_index_ = 0;
444 switch (byte) {
446 ESP_LOGV(TAG, "Received START");
447 if (this->in_bootloader_) {
448 ESP_LOGD(TAG, "Exited bootloader mode");
449 this->in_bootloader_ = false;
450 }
452 this->buffer_[this->buffer_index_++] = byte;
454 return;
456 ESP_LOGV(TAG, "Received BL_MENU");
457 // Read the menu tentatively: a stray 0x0D can equally appear in garbled data after the
458 // parser loses frame alignment, so bootloader mode is only committed once a plausible
459 // menu completes (see READ_BL_MENU handling in parse_byte_)
461 this->buffer_[this->buffer_index_++] = byte;
463 return;
465 ESP_LOGV(TAG, "Received BL_BEGIN_UPLOAD");
466 break;
468 ESP_LOGV(TAG, "Received ACK");
469 break;
471 ESP_LOGV(TAG, "Received NAK");
472 break;
474 ESP_LOGV(TAG, "Received CAN");
475 break;
476 default:
477 ESP_LOGV(TAG, "Unrecognized START: 0x%02X", byte);
478 return;
479 }
480 // Forward response (ACK/NAK/CAN) back to client for processing
481 if (this->api_connection_ != nullptr) {
482 // Store single byte in buffer and point to it
483 this->buffer_[0] = byte;
484 this->outgoing_proto_msg_.data = this->buffer_.data();
487 }
488}
489
491 switch (this->parsing_state_) {
494 break;
497 break;
500 break;
501 default:
502 return false; // No response handled
503 }
504
505 ESP_LOGVV(TAG, "Sending %s (0x%02X)", this->last_response_ == ZWAVE_FRAME_TYPE_ACK ? "ACK" : "NAK/CAN",
506 this->last_response_);
507 this->write_byte(this->last_response_);
509 return true;
510}
511
512ZWaveProxy *global_zwave_proxy = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
513
514} // namespace esphome::zwave_proxy
515
516#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:289
bool send_message(const T &msg)
void on_zwave_proxy_request(const ZWaveProxyRequest &msg)
enums::ZWaveProxyRequestType type
Definition api_pb2.h:3046
UARTComponent * parent_
Definition uart.h:73
bool read_byte(uint8_t *data)
Definition uart.h:34
void write_byte(uint8_t data)
Definition uart.h:18
void write_array(const uint8_t *data, size_t len)
Definition uart.h:26
void zwave_proxy_request(api::APIConnection *api_connection, api::enums::ZWaveProxyRequestType type)
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:89
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_
uint16_t type
@ ZWAVE_PROXY_REQUEST_TYPE_SUBSCRIBE
Definition api_pb2.h:331
@ ZWAVE_PROXY_REQUEST_TYPE_UNSUBSCRIBE
Definition api_pb2.h:332
@ ZWAVE_PROXY_REQUEST_TYPE_HOME_ID_CHANGE
Definition api_pb2.h:333
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
ZWaveProxy * global_zwave_proxy
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:340
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:1400
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
uint16_t length
Definition tt21100.cpp:0