ESPHome 2026.5.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][...]
22static constexpr uint8_t ZWAVE_COMMAND_TYPE_RESPONSE = 0x01; // Response type field value
23static constexpr uint8_t ZWAVE_MIN_GET_NETWORK_IDS_LENGTH = 9; // TYPE + CMD + HOME_ID(4) + NODE_ID + checksum
24static constexpr uint32_t HOME_ID_TIMEOUT_MS = 100; // Timeout for waiting for home ID during setup
25static constexpr uint32_t RECONNECT_DELAY_MS = 500; // Delay between home ID query attempts after reconnect
26static constexpr uint8_t MAX_QUERY_RETRIES = 5; // Max attempts to query home ID after reconnect
27
28static uint8_t calculate_frame_checksum(const uint8_t *data, uint8_t length) {
29 // Calculate Z-Wave frame checksum
30 // XOR all bytes between SOF and checksum position (exclusive)
31 // Initial value is 0xFF per Z-Wave protocol specification
32 uint8_t checksum = 0xFF;
33 for (uint8_t i = 1; i < length - 1; i++) {
34 checksum ^= data[i];
35 }
36 return checksum;
37}
38
40
43 this->was_connected_ = this->parent_->is_connected();
44 if (this->was_connected_) {
45 this->send_simple_command_(ZWAVE_COMMAND_GET_NETWORK_IDS);
46 }
47}
48
50 // Set up before API so home ID is ready when API starts
52}
53
55 // If we already have the home ID, we can proceed
56 if (this->home_id_ready_) {
57 return true;
58 }
59
60 // Handle any pending responses
61 if (this->response_handler_()) {
62 ESP_LOGV(TAG, "Handled response during setup");
63 }
64
65 // Process UART data to check for home ID
66 this->process_uart_();
67
68 // Check if we got the home ID after processing
69 if (this->home_id_ready_) {
70 return true;
71 }
72
73 // Wait up to HOME_ID_TIMEOUT_MS for home ID response
75 if (now - this->setup_time_ > HOME_ID_TIMEOUT_MS) {
76 ESP_LOGW(TAG, "Timeout reading Home ID during setup");
77 return true; // Proceed anyway after timeout
78 }
79
80 return false; // Keep waiting
81}
82
84 if (this->response_handler_()) {
85 ESP_LOGV(TAG, "Handled late response");
86 }
87 if (this->api_connection_ != nullptr && (!this->api_connection_->is_connection_setup() || !api_is_connected())) {
88 ESP_LOGW(TAG, "Subscriber disconnected");
89 this->api_connection_ = nullptr; // Unsubscribe if disconnected
90 }
91
92 const bool connected = this->parent_->is_connected();
93 if (this->was_connected_ != connected) {
94 this->on_connection_changed_(connected);
95 }
96 if (this->reconnect_time_ != 0) {
98 }
99
100 this->process_uart_();
101 this->status_clear_warning();
102}
103
105 while (this->available()) {
106 uint8_t byte;
107 if (!this->read_byte(&byte)) {
108 this->status_set_warning(LOG_STR("UART read failed"));
109 return;
110 }
111 if (this->parse_byte_(byte)) {
112 // Check if this is a GET_NETWORK_IDS response frame
113 // Frame format: [SOF][LENGTH][TYPE][CMD][HOME_ID(4)][NODE_ID][...]
114 // We verify:
115 // - buffer_[0]: Start of frame marker (0x01)
116 // - buffer_[1]: Length field must be >= 9 to contain all required data
117 // - buffer_[2]: Command type (0x01 for response)
118 // - buffer_[3]: Command ID (0x20 for GET_NETWORK_IDS)
119 if (this->buffer_[3] == ZWAVE_COMMAND_GET_NETWORK_IDS && this->buffer_[2] == ZWAVE_COMMAND_TYPE_RESPONSE &&
120 this->buffer_[1] >= ZWAVE_MIN_GET_NETWORK_IDS_LENGTH && this->buffer_[0] == ZWAVE_FRAME_TYPE_START) {
121 // Store the 4-byte Home ID, which starts at offset 4, and notify connected clients if it changed
122 // The frame parser has already validated the checksum and ensured all bytes are present
123 if (this->set_home_id_(&this->buffer_[4])) {
125 }
126 }
127 ESP_LOGV(TAG, "Sending to client: %s", YESNO(this->api_connection_ != nullptr));
128 if (this->api_connection_ != nullptr) {
129 // Zero-copy: point directly to our buffer
130 this->outgoing_proto_msg_.data = this->buffer_.data();
131 if (this->in_bootloader_) {
133 } else {
134 // If this is a data frame, use frame length indicator + 2 (for SoF + checksum), else assume 1 for ACK/NAK/CAN
135 this->outgoing_proto_msg_.data_len = this->buffer_[0] == ZWAVE_FRAME_TYPE_START ? this->buffer_[1] + 2 : 1;
136 }
138 }
139 }
140 }
141}
142
144 char hex_buf[format_hex_pretty_size(ZWAVE_HOME_ID_SIZE)];
145 ESP_LOGCONFIG(TAG,
146 "Z-Wave Proxy:\n"
147 " Home ID: %s",
148 format_hex_pretty_to(hex_buf, this->home_id_.data(), this->home_id_.size()));
149}
150
152 if (this->home_id_ready_) {
153 // If a client just authenticated & HomeID is ready, send the current HomeID
154 this->send_homeid_changed_msg_(conn);
155 }
156}
157
159 switch (type) {
161 if (this->api_connection_ != nullptr) {
162 ESP_LOGE(TAG, "Only one API subscription is allowed at a time");
163 return;
164 }
165 this->api_connection_ = api_connection;
166 ESP_LOGV(TAG, "API connection is now subscribed");
167 break;
168
170 if (this->api_connection_ != api_connection) {
171 ESP_LOGV(TAG, "API connection is not subscribed");
172 return;
173 }
174 this->api_connection_ = nullptr;
175 break;
176
177 default:
178 ESP_LOGW(TAG, "Unknown request type: %" PRIu32, static_cast<uint32_t>(type));
179 break;
180 }
181}
182
184 this->was_connected_ = connected;
185 if (connected) {
186 ESP_LOGD(TAG, "Modem reconnected");
188 this->buffer_index_ = 0;
189 this->last_response_ = 0;
190 this->in_bootloader_ = false;
191 // Defer the query — the modem needs time to initialize after power is applied
193 this->query_retries_ = 0;
194 } else {
195 ESP_LOGW(TAG, "Modem disconnected");
196 this->clear_home_id_();
197 }
198}
199
201 if (this->home_id_ready_) {
202 // Got the home ID, cancel remaining retries
203 this->reconnect_time_ = 0;
204 return;
205 }
206 if (App.get_loop_component_start_time() - this->reconnect_time_ <= RECONNECT_DELAY_MS) {
207 return; // Not yet time for next attempt
208 }
209 this->reconnect_time_ = App.get_loop_component_start_time(); // Reset timer for next retry
210 this->query_retries_++;
211 if (this->query_retries_ <= MAX_QUERY_RETRIES) {
212 ESP_LOGD(TAG, "Querying Home ID (attempt %u)", this->query_retries_);
213 this->send_simple_command_(ZWAVE_COMMAND_GET_NETWORK_IDS);
214 } else {
215 ESP_LOGW(TAG, "Failed to read Home ID after %u attempts", MAX_QUERY_RETRIES);
216 this->reconnect_time_ = 0;
217 }
218}
219
221 static constexpr uint8_t ZERO_HOME_ID[ZWAVE_HOME_ID_SIZE] = {};
222 if (this->set_home_id_(ZERO_HOME_ID)) {
224 }
225 this->home_id_ready_ = false;
227 this->buffer_index_ = 0;
228 this->last_response_ = 0;
229 this->in_bootloader_ = false;
230}
231
232bool ZWaveProxy::set_home_id_(const uint8_t *new_home_id) {
233 if (std::memcmp(this->home_id_.data(), new_home_id, this->home_id_.size()) == 0) {
234 ESP_LOGV(TAG, "Home ID unchanged");
235 return false; // No change
236 }
237 std::memcpy(this->home_id_.data(), new_home_id, this->home_id_.size());
238 char hex_buf[format_hex_pretty_size(ZWAVE_HOME_ID_SIZE)];
239 ESP_LOGI(TAG, "Home ID: %s", format_hex_pretty_to(hex_buf, this->home_id_.data(), this->home_id_.size()));
240 this->home_id_ready_ = true;
241 return true; // Home ID was changed
242}
243
244void ZWaveProxy::send_frame(const uint8_t *data, size_t length) {
245 // Safety: validate pointer before any access
246 if (data == nullptr) {
247 ESP_LOGE(TAG, "Null data pointer");
248 return;
249 }
250 if (length == 0) {
251 ESP_LOGE(TAG, "Length 0");
252 return;
253 }
254
255 // Skip duplicate single-byte responses (ACK/NAK/CAN)
256 if (length == 1 && data[0] == this->last_response_) {
257 ESP_LOGV(TAG, "Response already sent: 0x%02X", data[0]);
258 return;
259 }
260
261#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
262 char hex_buf[format_hex_pretty_size(ZWAVE_MAX_LOG_BYTES)];
263#endif
264 ESP_LOGVV(TAG, "Sending: %s", format_hex_pretty_to(hex_buf, data, length));
265
266 this->write_array(data, length);
267}
268
272 msg.data = this->home_id_.data();
273 msg.data_len = this->home_id_.size();
274 if (conn != nullptr) {
275 // Send to specific connection
276 conn->send_message(msg);
277 } else if (api::global_api_server != nullptr) {
278 // We could add code to manage a second subscription type, but, since this message is
279 // very infrequent and small, we simply send it to all clients
281 }
282}
283
284void ZWaveProxy::send_simple_command_(const uint8_t command_id) {
285 // Send a simple Z-Wave command with no parameters
286 // Frame format: [SOF][LENGTH][TYPE][CMD][CHECKSUM]
287 // Where LENGTH=0x03 (3 bytes: TYPE + CMD + CHECKSUM)
288 uint8_t cmd[] = {0x01, 0x03, 0x00, command_id, 0x00};
289 cmd[4] = calculate_frame_checksum(cmd, sizeof(cmd));
290 this->send_frame(cmd, sizeof(cmd));
291}
292
293bool ZWaveProxy::parse_byte_(uint8_t byte) {
294 bool frame_completed = false;
295 // Basic parsing logic for received frames
296 switch (this->parsing_state_) {
298 this->parse_start_(byte);
299 break;
301 if (!byte) {
302 ESP_LOGW(TAG, "Invalid LENGTH: %u", byte);
304 return false;
305 }
306 ESP_LOGVV(TAG, "Received LENGTH: %u", byte);
307 this->end_frame_after_ = this->buffer_index_ + byte;
308 ESP_LOGVV(TAG, "Calculated EOF: %u", this->end_frame_after_);
309 this->buffer_[this->buffer_index_++] = byte;
311 break;
313 this->buffer_[this->buffer_index_++] = byte;
314 ESP_LOGVV(TAG, "Received TYPE: 0x%02X", byte);
316 break;
318 this->buffer_[this->buffer_index_++] = byte;
319 ESP_LOGVV(TAG, "Received COMMAND ID: 0x%02X", byte);
321 break;
323 this->buffer_[this->buffer_index_++] = byte;
324 ESP_LOGVV(TAG, "Received PAYLOAD: 0x%02X", byte);
325 if (this->buffer_index_ >= this->end_frame_after_) {
327 }
328 break;
330 this->buffer_[this->buffer_index_++] = byte;
331 auto checksum = calculate_frame_checksum(this->buffer_.data(), this->buffer_index_);
332 ESP_LOGVV(TAG, "CHECKSUM Received: 0x%02X - Calculated: 0x%02X", byte, checksum);
333 if (checksum != byte) {
334 ESP_LOGW(TAG, "Bad checksum: expected 0x%02X, got 0x%02X", checksum, byte);
336 } else {
338#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
339 char hex_buf[format_hex_pretty_size(ZWAVE_MAX_LOG_BYTES)];
340#endif
341 ESP_LOGVV(TAG, "Received frame: %s", format_hex_pretty_to(hex_buf, this->buffer_.data(), this->buffer_index_));
342 frame_completed = true;
343 }
344 this->response_handler_();
345 break;
346 }
348 if (this->buffer_index_ >= this->buffer_.size()) {
350 break;
351 }
352 this->buffer_[this->buffer_index_++] = byte;
353 if (!byte) {
355 frame_completed = true;
356 }
357 break;
360 break; // Should not happen, handled in loop()
361 default:
362 ESP_LOGW(TAG, "Bad parsing state; resetting");
364 break;
365 }
366 return frame_completed;
367}
368
369void ZWaveProxy::parse_start_(uint8_t byte) {
370 this->buffer_index_ = 0;
372 switch (byte) {
374 ESP_LOGV(TAG, "Received START");
375 if (this->in_bootloader_) {
376 ESP_LOGD(TAG, "Exited bootloader mode");
377 this->in_bootloader_ = false;
378 }
379 this->buffer_[this->buffer_index_++] = byte;
381 return;
383 ESP_LOGV(TAG, "Received BL_MENU");
384 if (!this->in_bootloader_) {
385 ESP_LOGD(TAG, "Entered bootloader mode");
386 this->in_bootloader_ = true;
387 }
388 this->buffer_[this->buffer_index_++] = byte;
390 return;
392 ESP_LOGV(TAG, "Received BL_BEGIN_UPLOAD");
393 break;
395 ESP_LOGV(TAG, "Received ACK");
396 break;
398 ESP_LOGV(TAG, "Received NAK");
399 break;
401 ESP_LOGV(TAG, "Received CAN");
402 break;
403 default:
404 ESP_LOGW(TAG, "Unrecognized START: 0x%02X", byte);
405 return;
406 }
407 // Forward response (ACK/NAK/CAN) back to client for processing
408 if (this->api_connection_ != nullptr) {
409 // Store single byte in buffer and point to it
410 this->buffer_[0] = byte;
411 this->outgoing_proto_msg_.data = this->buffer_.data();
414 }
415}
416
418 switch (this->parsing_state_) {
421 break;
424 break;
427 break;
428 default:
429 return false; // No response handled
430 }
431
432 ESP_LOGVV(TAG, "Sending %s (0x%02X)", this->last_response_ == ZWAVE_FRAME_TYPE_ACK ? "ACK" : "NAK/CAN",
433 this->last_response_);
434 this->write_byte(this->last_response_);
436 return true;
437}
438
439ZWaveProxy *global_zwave_proxy = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
440
441} // namespace esphome::zwave_proxy
442
443#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:306
bool send_message(const T &msg)
void on_zwave_proxy_request(const ZWaveProxyRequest &msg)
enums::ZWaveProxyRequestType type
Definition api_pb2.h:3024
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_
Definition zwave_proxy.h:79
void send_frame(const uint8_t *data, size_t length)
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)
void api_connection_authenticated(api::APIConnection *conn)
ZWaveParsingState parsing_state_
Definition zwave_proxy.h:93
std::array< uint8_t, MAX_ZWAVE_FRAME_SIZE > buffer_
Definition zwave_proxy.h:80
api::APIConnection * api_connection_
Definition zwave_proxy.h:84
float get_setup_priority() const override
void on_connection_changed_(bool connected)
std::array< uint8_t, ZWAVE_HOME_ID_SIZE > home_id_
Definition zwave_proxy.h:81
uint16_t type
@ ZWAVE_PROXY_REQUEST_TYPE_SUBSCRIBE
Definition api_pb2.h:320
@ ZWAVE_PROXY_REQUEST_TYPE_UNSUBSCRIBE
Definition api_pb2.h:321
@ ZWAVE_PROXY_REQUEST_TYPE_HOME_ID_CHANGE
Definition api_pb2.h:322
APIServer * global_api_server
constexpr float BEFORE_CONNECTION
For components that should be initialized after WiFi and before API is connected.
Definition component.h:50
ZWaveProxy * global_zwave_proxy
bool api_is_connected()
Return whether the node has at least one client connected to the native API.
Definition util.cpp:17
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:409
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:1368
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
uint16_t length
Definition tt21100.cpp:0