ESPHome 2026.1.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
8#include "esphome/core/log.h"
9#include "esphome/core/util.h"
10
12
13static const char *const TAG = "zwave_proxy";
14
15// Maximum bytes to log in very verbose hex output (168 * 3 = 504, under TX buffer size of 512)
16static constexpr size_t ZWAVE_MAX_LOG_BYTES = 168;
17
18static constexpr uint8_t ZWAVE_COMMAND_GET_NETWORK_IDS = 0x20;
19// GET_NETWORK_IDS response: [SOF][LENGTH][TYPE][CMD][HOME_ID(4)][NODE_ID][...]
20static constexpr uint8_t ZWAVE_COMMAND_TYPE_RESPONSE = 0x01; // Response type field value
21static constexpr uint8_t ZWAVE_MIN_GET_NETWORK_IDS_LENGTH = 9; // TYPE + CMD + HOME_ID(4) + NODE_ID + checksum
22static constexpr uint32_t HOME_ID_TIMEOUT_MS = 100; // Timeout for waiting for home ID during setup
23
24static uint8_t calculate_frame_checksum(const uint8_t *data, uint8_t length) {
25 // Calculate Z-Wave frame checksum
26 // XOR all bytes between SOF and checksum position (exclusive)
27 // Initial value is 0xFF per Z-Wave protocol specification
28 uint8_t checksum = 0xFF;
29 for (uint8_t i = 1; i < length - 1; i++) {
30 checksum ^= data[i];
31 }
32 return checksum;
33}
34
36
39 this->send_simple_command_(ZWAVE_COMMAND_GET_NETWORK_IDS);
40}
41
43 // Set up before API so home ID is ready when API starts
45}
46
48 // If we already have the home ID, we can proceed
49 if (this->home_id_ready_) {
50 return true;
51 }
52
53 // Handle any pending responses
54 if (this->response_handler_()) {
55 ESP_LOGV(TAG, "Handled response during setup");
56 }
57
58 // Process UART data to check for home ID
59 this->process_uart_();
60
61 // Check if we got the home ID after processing
62 if (this->home_id_ready_) {
63 return true;
64 }
65
66 // Wait up to HOME_ID_TIMEOUT_MS for home ID response
67 const uint32_t now = App.get_loop_component_start_time();
68 if (now - this->setup_time_ > HOME_ID_TIMEOUT_MS) {
69 ESP_LOGW(TAG, "Timeout reading Home ID during setup");
70 return true; // Proceed anyway after timeout
71 }
72
73 return false; // Keep waiting
74}
75
77 if (this->response_handler_()) {
78 ESP_LOGV(TAG, "Handled late response");
79 }
80 if (this->api_connection_ != nullptr && (!this->api_connection_->is_connection_setup() || !api_is_connected())) {
81 ESP_LOGW(TAG, "Subscriber disconnected");
82 this->api_connection_ = nullptr; // Unsubscribe if disconnected
83 }
84
85 this->process_uart_();
87}
88
90 while (this->available()) {
91 uint8_t byte;
92 if (!this->read_byte(&byte)) {
93 this->status_set_warning("UART read failed");
94 return;
95 }
96 if (this->parse_byte_(byte)) {
97 // Check if this is a GET_NETWORK_IDS response frame
98 // Frame format: [SOF][LENGTH][TYPE][CMD][HOME_ID(4)][NODE_ID][...]
99 // We verify:
100 // - buffer_[0]: Start of frame marker (0x01)
101 // - buffer_[1]: Length field must be >= 9 to contain all required data
102 // - buffer_[2]: Command type (0x01 for response)
103 // - buffer_[3]: Command ID (0x20 for GET_NETWORK_IDS)
104 if (this->buffer_[3] == ZWAVE_COMMAND_GET_NETWORK_IDS && this->buffer_[2] == ZWAVE_COMMAND_TYPE_RESPONSE &&
105 this->buffer_[1] >= ZWAVE_MIN_GET_NETWORK_IDS_LENGTH && this->buffer_[0] == ZWAVE_FRAME_TYPE_START) {
106 // Store the 4-byte Home ID, which starts at offset 4, and notify connected clients if it changed
107 // The frame parser has already validated the checksum and ensured all bytes are present
108 if (this->set_home_id(&this->buffer_[4])) {
110 }
111 }
112 ESP_LOGV(TAG, "Sending to client: %s", YESNO(this->api_connection_ != nullptr));
113 if (this->api_connection_ != nullptr) {
114 // Zero-copy: point directly to our buffer
115 this->outgoing_proto_msg_.data = this->buffer_.data();
116 if (this->in_bootloader_) {
118 } else {
119 // If this is a data frame, use frame length indicator + 2 (for SoF + checksum), else assume 1 for ACK/NAK/CAN
120 this->outgoing_proto_msg_.data_len = this->buffer_[0] == ZWAVE_FRAME_TYPE_START ? this->buffer_[1] + 2 : 1;
121 }
123 }
124 }
125 }
126}
127
129 char hex_buf[format_hex_pretty_size(ZWAVE_HOME_ID_SIZE)];
130 ESP_LOGCONFIG(TAG,
131 "Z-Wave Proxy:\n"
132 " Home ID: %s",
133 format_hex_pretty_to(hex_buf, this->home_id_.data(), this->home_id_.size()));
134}
135
137 if (this->home_id_ready_) {
138 // If a client just authenticated & HomeID is ready, send the current HomeID
139 this->send_homeid_changed_msg_(conn);
140 }
141}
142
144 switch (type) {
146 if (this->api_connection_ != nullptr) {
147 ESP_LOGE(TAG, "Only one API subscription is allowed at a time");
148 return;
149 }
150 this->api_connection_ = api_connection;
151 ESP_LOGV(TAG, "API connection is now subscribed");
152 break;
153
155 if (this->api_connection_ != api_connection) {
156 ESP_LOGV(TAG, "API connection is not subscribed");
157 return;
158 }
159 this->api_connection_ = nullptr;
160 break;
161
162 default:
163 ESP_LOGW(TAG, "Unknown request type: %d", type);
164 break;
165 }
166}
167
168bool ZWaveProxy::set_home_id(const uint8_t *new_home_id) {
169 if (std::memcmp(this->home_id_.data(), new_home_id, this->home_id_.size()) == 0) {
170 ESP_LOGV(TAG, "Home ID unchanged");
171 return false; // No change
172 }
173 std::memcpy(this->home_id_.data(), new_home_id, this->home_id_.size());
174 char hex_buf[format_hex_pretty_size(ZWAVE_HOME_ID_SIZE)];
175 ESP_LOGI(TAG, "Home ID: %s", format_hex_pretty_to(hex_buf, this->home_id_.data(), this->home_id_.size()));
176 this->home_id_ready_ = true;
177 return true; // Home ID was changed
178}
179
180void ZWaveProxy::send_frame(const uint8_t *data, size_t length) {
181 if (length == 1 && data[0] == this->last_response_) {
182 ESP_LOGV(TAG, "Skipping sending duplicate response: 0x%02X", data[0]);
183 return;
184 }
185#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
186 char hex_buf[format_hex_pretty_size(ZWAVE_MAX_LOG_BYTES)];
187#endif
188 ESP_LOGVV(TAG, "Sending: %s", format_hex_pretty_to(hex_buf, data, length));
189 this->write_array(data, length);
190}
191
195 msg.data = this->home_id_.data();
196 msg.data_len = this->home_id_.size();
197 if (conn != nullptr) {
198 // Send to specific connection
200 } else if (api::global_api_server != nullptr) {
201 // We could add code to manage a second subscription type, but, since this message is
202 // very infrequent and small, we simply send it to all clients
204 }
205}
206
207void ZWaveProxy::send_simple_command_(const uint8_t command_id) {
208 // Send a simple Z-Wave command with no parameters
209 // Frame format: [SOF][LENGTH][TYPE][CMD][CHECKSUM]
210 // Where LENGTH=0x03 (3 bytes: TYPE + CMD + CHECKSUM)
211 uint8_t cmd[] = {0x01, 0x03, 0x00, command_id, 0x00};
212 cmd[4] = calculate_frame_checksum(cmd, sizeof(cmd));
213 this->send_frame(cmd, sizeof(cmd));
214}
215
216bool ZWaveProxy::parse_byte_(uint8_t byte) {
217 bool frame_completed = false;
218 // Basic parsing logic for received frames
219 switch (this->parsing_state_) {
221 this->parse_start_(byte);
222 break;
224 if (!byte) {
225 ESP_LOGW(TAG, "Invalid LENGTH: %u", byte);
227 return false;
228 }
229 ESP_LOGVV(TAG, "Received LENGTH: %u", byte);
230 this->end_frame_after_ = this->buffer_index_ + byte;
231 ESP_LOGVV(TAG, "Calculated EOF: %u", this->end_frame_after_);
232 this->buffer_[this->buffer_index_++] = byte;
234 break;
236 this->buffer_[this->buffer_index_++] = byte;
237 ESP_LOGVV(TAG, "Received TYPE: 0x%02X", byte);
239 break;
241 this->buffer_[this->buffer_index_++] = byte;
242 ESP_LOGVV(TAG, "Received COMMAND ID: 0x%02X", byte);
244 break;
246 this->buffer_[this->buffer_index_++] = byte;
247 ESP_LOGVV(TAG, "Received PAYLOAD: 0x%02X", byte);
248 if (this->buffer_index_ >= this->end_frame_after_) {
250 }
251 break;
253 this->buffer_[this->buffer_index_++] = byte;
254 auto checksum = calculate_frame_checksum(this->buffer_.data(), this->buffer_index_);
255 ESP_LOGVV(TAG, "CHECKSUM Received: 0x%02X - Calculated: 0x%02X", byte, checksum);
256 if (checksum != byte) {
257 ESP_LOGW(TAG, "Bad checksum: expected 0x%02X, got 0x%02X", checksum, byte);
259 } else {
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, "Received frame: %s", format_hex_pretty_to(hex_buf, this->buffer_.data(), this->buffer_index_));
265 frame_completed = true;
266 }
267 this->response_handler_();
268 break;
269 }
271 this->buffer_[this->buffer_index_++] = byte;
272 if (!byte) {
274 frame_completed = true;
275 }
276 break;
279 break; // Should not happen, handled in loop()
280 default:
281 ESP_LOGW(TAG, "Bad parsing state; resetting");
283 break;
284 }
285 return frame_completed;
286}
287
288void ZWaveProxy::parse_start_(uint8_t byte) {
289 this->buffer_index_ = 0;
291 switch (byte) {
293 ESP_LOGVV(TAG, "Received START");
294 if (this->in_bootloader_) {
295 ESP_LOGD(TAG, "Exited bootloader mode");
296 this->in_bootloader_ = false;
297 }
298 this->buffer_[this->buffer_index_++] = byte;
300 return;
302 ESP_LOGVV(TAG, "Received BL_MENU");
303 if (!this->in_bootloader_) {
304 ESP_LOGD(TAG, "Entered bootloader mode");
305 this->in_bootloader_ = true;
306 }
307 this->buffer_[this->buffer_index_++] = byte;
309 return;
311 ESP_LOGVV(TAG, "Received BL_BEGIN_UPLOAD");
312 break;
314 ESP_LOGVV(TAG, "Received ACK");
315 break;
317 ESP_LOGW(TAG, "Received NAK");
318 break;
320 ESP_LOGW(TAG, "Received CAN");
321 break;
322 default:
323 ESP_LOGW(TAG, "Unrecognized START: 0x%02X", byte);
324 return;
325 }
326 // Forward response (ACK/NAK/CAN) back to client for processing
327 if (this->api_connection_ != nullptr) {
328 // Store single byte in buffer and point to it
329 this->buffer_[0] = byte;
330 this->outgoing_proto_msg_.data = this->buffer_.data();
333 }
334}
335
337 switch (this->parsing_state_) {
340 break;
343 break;
346 break;
347 default:
348 return false; // No response handled
349 }
350
351 ESP_LOGVV(TAG, "Sending %s (0x%02X)", this->last_response_ == ZWAVE_FRAME_TYPE_ACK ? "ACK" : "NAK/CAN",
352 this->last_response_);
353 this->write_byte(this->last_response_);
355 return true;
356}
357
358ZWaveProxy *global_zwave_proxy = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
359
360} // namespace esphome::zwave_proxy
361
362#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_set_warning(const char *message=nullptr)
void status_clear_warning()
bool is_connection_setup() override
bool send_message(const ProtoMessage &msg, uint8_t message_type)
void on_zwave_proxy_request(const esphome::api::ProtoMessage &msg)
static constexpr uint8_t MESSAGE_TYPE
Definition api_pb2.h:3124
static constexpr uint8_t MESSAGE_TYPE
Definition api_pb2.h:3142
enums::ZWaveProxyRequestType type
Definition api_pb2.h:3147
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:76
void send_frame(const uint8_t *data, size_t length)
void send_homeid_changed_msg_(api::APIConnection *conn=nullptr)
void send_simple_command_(uint8_t command_id)
bool set_home_id(const uint8_t *new_home_id)
void api_connection_authenticated(api::APIConnection *conn)
ZWaveParsingState parsing_state_
Definition zwave_proxy.h:88
std::array< uint8_t, MAX_ZWAVE_FRAME_SIZE > buffer_
Definition zwave_proxy.h:77
api::APIConnection * api_connection_
Definition zwave_proxy.h:81
float get_setup_priority() const override
std::array< uint8_t, ZWAVE_HOME_ID_SIZE > home_id_
Definition zwave_proxy.h:78
uint16_t type
@ ZWAVE_PROXY_REQUEST_TYPE_SUBSCRIBE
Definition api_pb2.h:307
@ ZWAVE_PROXY_REQUEST_TYPE_UNSUBSCRIBE
Definition api_pb2.h:308
@ ZWAVE_PROXY_REQUEST_TYPE_HOME_ID_CHANGE
Definition api_pb2.h:309
APIServer * global_api_server
const float BEFORE_CONNECTION
For components that should be initialized after WiFi and before API is connected.
Definition component.cpp:87
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:331
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:735
Application App
Global storage of Application pointer - only one Application can exist.
uint16_t length
Definition tt21100.cpp:0