ESPHome 2025.12.3
Loading...
Searching...
No Matches
zwave_proxy.cpp
Go to the documentation of this file.
1#include "zwave_proxy.h"
5#include "esphome/core/log.h"
6#include "esphome/core/util.h"
7
9
10static const char *const TAG = "zwave_proxy";
11
12static constexpr uint8_t ZWAVE_COMMAND_GET_NETWORK_IDS = 0x20;
13// GET_NETWORK_IDS response: [SOF][LENGTH][TYPE][CMD][HOME_ID(4)][NODE_ID][...]
14static constexpr uint8_t ZWAVE_COMMAND_TYPE_RESPONSE = 0x01; // Response type field value
15static constexpr uint8_t ZWAVE_MIN_GET_NETWORK_IDS_LENGTH = 9; // TYPE + CMD + HOME_ID(4) + NODE_ID + checksum
16static constexpr uint32_t HOME_ID_TIMEOUT_MS = 100; // Timeout for waiting for home ID during setup
17
18static uint8_t calculate_frame_checksum(const uint8_t *data, uint8_t length) {
19 // Calculate Z-Wave frame checksum
20 // XOR all bytes between SOF and checksum position (exclusive)
21 // Initial value is 0xFF per Z-Wave protocol specification
22 uint8_t checksum = 0xFF;
23 for (uint8_t i = 1; i < length - 1; i++) {
24 checksum ^= data[i];
25 }
26 return checksum;
27}
28
30
33 this->send_simple_command_(ZWAVE_COMMAND_GET_NETWORK_IDS);
34}
35
37 // Set up before API so home ID is ready when API starts
39}
40
42 // If we already have the home ID, we can proceed
43 if (this->home_id_ready_) {
44 return true;
45 }
46
47 // Handle any pending responses
48 if (this->response_handler_()) {
49 ESP_LOGV(TAG, "Handled response during setup");
50 }
51
52 // Process UART data to check for home ID
53 this->process_uart_();
54
55 // Check if we got the home ID after processing
56 if (this->home_id_ready_) {
57 return true;
58 }
59
60 // Wait up to HOME_ID_TIMEOUT_MS for home ID response
61 const uint32_t now = App.get_loop_component_start_time();
62 if (now - this->setup_time_ > HOME_ID_TIMEOUT_MS) {
63 ESP_LOGW(TAG, "Timeout reading Home ID during setup");
64 return true; // Proceed anyway after timeout
65 }
66
67 return false; // Keep waiting
68}
69
71 if (this->response_handler_()) {
72 ESP_LOGV(TAG, "Handled late response");
73 }
74 if (this->api_connection_ != nullptr && (!this->api_connection_->is_connection_setup() || !api_is_connected())) {
75 ESP_LOGW(TAG, "Subscriber disconnected");
76 this->api_connection_ = nullptr; // Unsubscribe if disconnected
77 }
78
79 this->process_uart_();
81}
82
84 while (this->available()) {
85 uint8_t byte;
86 if (!this->read_byte(&byte)) {
87 this->status_set_warning("UART read failed");
88 return;
89 }
90 if (this->parse_byte_(byte)) {
91 // Check if this is a GET_NETWORK_IDS response frame
92 // Frame format: [SOF][LENGTH][TYPE][CMD][HOME_ID(4)][NODE_ID][...]
93 // We verify:
94 // - buffer_[0]: Start of frame marker (0x01)
95 // - buffer_[1]: Length field must be >= 9 to contain all required data
96 // - buffer_[2]: Command type (0x01 for response)
97 // - buffer_[3]: Command ID (0x20 for GET_NETWORK_IDS)
98 if (this->buffer_[3] == ZWAVE_COMMAND_GET_NETWORK_IDS && this->buffer_[2] == ZWAVE_COMMAND_TYPE_RESPONSE &&
99 this->buffer_[1] >= ZWAVE_MIN_GET_NETWORK_IDS_LENGTH && this->buffer_[0] == ZWAVE_FRAME_TYPE_START) {
100 // Store the 4-byte Home ID, which starts at offset 4, and notify connected clients if it changed
101 // The frame parser has already validated the checksum and ensured all bytes are present
102 if (this->set_home_id(&this->buffer_[4])) {
104 }
105 }
106 ESP_LOGV(TAG, "Sending to client: %s", YESNO(this->api_connection_ != nullptr));
107 if (this->api_connection_ != nullptr) {
108 // Zero-copy: point directly to our buffer
109 this->outgoing_proto_msg_.data = this->buffer_.data();
110 if (this->in_bootloader_) {
112 } else {
113 // If this is a data frame, use frame length indicator + 2 (for SoF + checksum), else assume 1 for ACK/NAK/CAN
114 this->outgoing_proto_msg_.data_len = this->buffer_[0] == ZWAVE_FRAME_TYPE_START ? this->buffer_[1] + 2 : 1;
115 }
117 }
118 }
119 }
120}
121
123 ESP_LOGCONFIG(TAG,
124 "Z-Wave Proxy:\n"
125 " Home ID: %s",
126 format_hex_pretty(this->home_id_.data(), this->home_id_.size(), ':', false).c_str());
127}
128
130 if (this->home_id_ready_) {
131 // If a client just authenticated & HomeID is ready, send the current HomeID
132 this->send_homeid_changed_msg_(conn);
133 }
134}
135
137 switch (type) {
139 if (this->api_connection_ != nullptr) {
140 ESP_LOGE(TAG, "Only one API subscription is allowed at a time");
141 return;
142 }
143 this->api_connection_ = api_connection;
144 ESP_LOGV(TAG, "API connection is now subscribed");
145 break;
146
148 if (this->api_connection_ != api_connection) {
149 ESP_LOGV(TAG, "API connection is not subscribed");
150 return;
151 }
152 this->api_connection_ = nullptr;
153 break;
154
155 default:
156 ESP_LOGW(TAG, "Unknown request type: %d", type);
157 break;
158 }
159}
160
161bool ZWaveProxy::set_home_id(const uint8_t *new_home_id) {
162 if (std::memcmp(this->home_id_.data(), new_home_id, this->home_id_.size()) == 0) {
163 ESP_LOGV(TAG, "Home ID unchanged");
164 return false; // No change
165 }
166 std::memcpy(this->home_id_.data(), new_home_id, this->home_id_.size());
167 ESP_LOGI(TAG, "Home ID: %s", format_hex_pretty(this->home_id_.data(), this->home_id_.size(), ':', false).c_str());
168 this->home_id_ready_ = true;
169 return true; // Home ID was changed
170}
171
172void ZWaveProxy::send_frame(const uint8_t *data, size_t length) {
173 if (length == 1 && data[0] == this->last_response_) {
174 ESP_LOGV(TAG, "Skipping sending duplicate response: 0x%02X", data[0]);
175 return;
176 }
177 ESP_LOGVV(TAG, "Sending: %s", format_hex_pretty(data, length).c_str());
178 this->write_array(data, length);
179}
180
184 msg.data = this->home_id_.data();
185 msg.data_len = this->home_id_.size();
186 if (conn != nullptr) {
187 // Send to specific connection
189 } else if (api::global_api_server != nullptr) {
190 // We could add code to manage a second subscription type, but, since this message is
191 // very infrequent and small, we simply send it to all clients
193 }
194}
195
196void ZWaveProxy::send_simple_command_(const uint8_t command_id) {
197 // Send a simple Z-Wave command with no parameters
198 // Frame format: [SOF][LENGTH][TYPE][CMD][CHECKSUM]
199 // Where LENGTH=0x03 (3 bytes: TYPE + CMD + CHECKSUM)
200 uint8_t cmd[] = {0x01, 0x03, 0x00, command_id, 0x00};
201 cmd[4] = calculate_frame_checksum(cmd, sizeof(cmd));
202 this->send_frame(cmd, sizeof(cmd));
203}
204
205bool ZWaveProxy::parse_byte_(uint8_t byte) {
206 bool frame_completed = false;
207 // Basic parsing logic for received frames
208 switch (this->parsing_state_) {
210 this->parse_start_(byte);
211 break;
213 if (!byte) {
214 ESP_LOGW(TAG, "Invalid LENGTH: %u", byte);
216 return false;
217 }
218 ESP_LOGVV(TAG, "Received LENGTH: %u", byte);
219 this->end_frame_after_ = this->buffer_index_ + byte;
220 ESP_LOGVV(TAG, "Calculated EOF: %u", this->end_frame_after_);
221 this->buffer_[this->buffer_index_++] = byte;
223 break;
225 this->buffer_[this->buffer_index_++] = byte;
226 ESP_LOGVV(TAG, "Received TYPE: 0x%02X", byte);
228 break;
230 this->buffer_[this->buffer_index_++] = byte;
231 ESP_LOGVV(TAG, "Received COMMAND ID: 0x%02X", byte);
233 break;
235 this->buffer_[this->buffer_index_++] = byte;
236 ESP_LOGVV(TAG, "Received PAYLOAD: 0x%02X", byte);
237 if (this->buffer_index_ >= this->end_frame_after_) {
239 }
240 break;
242 this->buffer_[this->buffer_index_++] = byte;
243 auto checksum = calculate_frame_checksum(this->buffer_.data(), this->buffer_index_);
244 ESP_LOGVV(TAG, "CHECKSUM Received: 0x%02X - Calculated: 0x%02X", byte, checksum);
245 if (checksum != byte) {
246 ESP_LOGW(TAG, "Bad checksum: expected 0x%02X, got 0x%02X", checksum, byte);
248 } else {
250 ESP_LOGVV(TAG, "Received frame: %s", format_hex_pretty(this->buffer_.data(), this->buffer_index_).c_str());
251 frame_completed = true;
252 }
253 this->response_handler_();
254 break;
255 }
257 this->buffer_[this->buffer_index_++] = byte;
258 if (!byte) {
260 frame_completed = true;
261 }
262 break;
265 break; // Should not happen, handled in loop()
266 default:
267 ESP_LOGW(TAG, "Bad parsing state; resetting");
269 break;
270 }
271 return frame_completed;
272}
273
274void ZWaveProxy::parse_start_(uint8_t byte) {
275 this->buffer_index_ = 0;
277 switch (byte) {
279 ESP_LOGVV(TAG, "Received START");
280 if (this->in_bootloader_) {
281 ESP_LOGD(TAG, "Exited bootloader mode");
282 this->in_bootloader_ = false;
283 }
284 this->buffer_[this->buffer_index_++] = byte;
286 return;
288 ESP_LOGVV(TAG, "Received BL_MENU");
289 if (!this->in_bootloader_) {
290 ESP_LOGD(TAG, "Entered bootloader mode");
291 this->in_bootloader_ = true;
292 }
293 this->buffer_[this->buffer_index_++] = byte;
295 return;
297 ESP_LOGVV(TAG, "Received BL_BEGIN_UPLOAD");
298 break;
300 ESP_LOGVV(TAG, "Received ACK");
301 break;
303 ESP_LOGW(TAG, "Received NAK");
304 break;
306 ESP_LOGW(TAG, "Received CAN");
307 break;
308 default:
309 ESP_LOGW(TAG, "Unrecognized START: 0x%02X", byte);
310 return;
311 }
312 // Forward response (ACK/NAK/CAN) back to client for processing
313 if (this->api_connection_ != nullptr) {
314 // Store single byte in buffer and point to it
315 this->buffer_[0] = byte;
316 this->outgoing_proto_msg_.data = this->buffer_.data();
319 }
320}
321
323 switch (this->parsing_state_) {
326 break;
329 break;
332 break;
333 default:
334 return false; // No response handled
335 }
336
337 ESP_LOGVV(TAG, "Sending %s (0x%02X)", this->last_response_ == ZWAVE_FRAME_TYPE_ACK ? "ACK" : "NAK/CAN",
338 this->last_response_);
339 this->write_byte(this->last_response_);
341 return true;
342}
343
344ZWaveProxy *global_zwave_proxy = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
345
346} // namespace esphome::zwave_proxy
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:3034
static constexpr uint8_t MESSAGE_TYPE
Definition api_pb2.h:3052
enums::ZWaveProxyRequestType type
Definition api_pb2.h:3057
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:72
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:84
std::array< uint8_t, MAX_ZWAVE_FRAME_SIZE > buffer_
Definition zwave_proxy.h:73
std::array< uint8_t, 4 > home_id_
Definition zwave_proxy.h:74
api::APIConnection * api_connection_
Definition zwave_proxy.h:77
float get_setup_priority() const override
uint16_t type
@ ZWAVE_PROXY_REQUEST_TYPE_SUBSCRIBE
Definition api_pb2.h:288
@ ZWAVE_PROXY_REQUEST_TYPE_UNSUBSCRIBE
Definition api_pb2.h:289
@ ZWAVE_PROXY_REQUEST_TYPE_HOME_ID_CHANGE
Definition api_pb2.h:290
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
std::string format_hex_pretty(const uint8_t *data, size_t length, char separator, bool show_length)
Format a byte array in pretty-printed, human-readable hex format.
Definition helpers.cpp:321
Application App
Global storage of Application pointer - only one Application can exist.
uint16_t length
Definition tt21100.cpp:0