ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
delta_wallbox.cpp
Go to the documentation of this file.
1#include "delta_wallbox.h"
2#include "esphome/core/log.h"
4#include <algorithm>
5#include <array>
6#include <cctype>
7#include <cmath>
8#include <cstdio>
9#include <cstdlib>
10#include <cstring>
11
12#ifdef USE_ESP32
13
15ESPHOME_LOG_TAG(TAG, "delta_wallbox");
16// Modbus function codes
17static constexpr uint8_t FC_READ_HOLDING_REGISTERS = 0x03;
18static constexpr uint8_t FC_WRITE_SINGLE_REGISTER = 0x06;
19static constexpr uint8_t FC_WRITE_MULTIPLE_REGISTERS = 0x10;
20static constexpr uint8_t FC_EXCEPTION_FLAG = 0x80;
21
22// Response lengths in bytes, CRC included
23static constexpr size_t READ_RESPONSE_OVERHEAD = 5;
24static constexpr size_t WRITE_RESPONSE_LEN = 8;
25static constexpr size_t EXCEPTION_RESPONSE_LEN = 5;
26
27// Frame bodies without CRC
28static constexpr size_t LOGIN_BODY_LEN = 35;
29static constexpr size_t LOGIN_PASS_LEN = 22;
30static constexpr size_t LOGIN_USER_LEN = 6;
31static constexpr size_t TIME_SYNC_BODY_LEN = 15;
32
33static constexpr uint8_t REGISTER_BYTE_COUNT = 2;
34static constexpr uint8_t TWO_REGISTER_BYTE_COUNT = 4;
35static constexpr uint8_t CHARGING_INFO_BYTE_COUNT = 18;
36static constexpr uint8_t SERIAL_TEXT_BYTE_COUNT = 14;
37static constexpr uint32_t RETRANSMIT_TIMEOUT_MS = 4000;
38static constexpr uint32_t RETRANSMIT_TIMEOUT_ID = 0;
39static constexpr uint8_t MAX_PAIRING_ATTEMPTS = 5;
40static constexpr uint16_t PAIRING_STATUS_READY = 0x0007;
41static constexpr uint16_t PAIRING_STATUS_WAITING = 0x0008;
42static constexpr uint8_t LOGIN_ACCEPTED = 0x01;
43
44static constexpr uint8_t CMD_POLL_CHARGING[] = {0x01, 0x03, 0x01, 0x1B, 0x00, 0x09};
45static constexpr uint8_t CMD_GET_MODEL[] = {0x01, 0x03, 0x01, 0x85, 0x00, 0x0E};
46static constexpr uint8_t CMD_GET_BT_FW_VERSION[] = {0x02, 0x03, 0x01, 0x00, 0x00, 0x01};
47static constexpr uint8_t CMD_CHECK_PAIRING[] = {0x02, 0x03, 0x01, 0x00, 0x00, 0x03};
48static constexpr uint8_t CMD_GET_LOGIN_USER[] = {0x01, 0x03, 0x01, 0x7D, 0x00, 0x03};
49static constexpr uint8_t CMD_READ_LOGIN_STATUS[] = {0x01, 0x03, 0x01, 0x80, 0x00, 0x01};
50static constexpr uint8_t CMD_GET_LOGIN_ROLE[] = {0x01, 0x03, 0x01, 0x81, 0x00, 0x01};
51static constexpr uint8_t CMD_GET_CHARGER_FW_VERSION[] = {0x01, 0x03, 0x01, 0x10, 0x00, 0x02};
52static constexpr uint8_t CMD_GET_MAX_CURRENT[] = {0x01, 0x03, 0x01, 0x12, 0x00, 0x02};
53static constexpr uint8_t CMD_GET_SERIAL_NUMBER[] = {0x01, 0x03, 0x01, 0x09, 0x00, 0x01};
54static constexpr uint8_t CMD_GET_ERROR_CODE[] = {0x01, 0x03, 0x01, 0xB5, 0x00, 0x01};
55static constexpr uint8_t CMD_START_CHARGING[] = {0x01, 0x06, 0x01, 0x02, 0x00, 0x01};
56static constexpr uint8_t CMD_STOP_CHARGING[] = {0x01, 0x06, 0x01, 0x03, 0x00, 0x01};
57
58static constexpr uint16_t REG_MAX_CURRENT = 0x0112;
59
60// Indexed by DeltaState
61PROGMEM_STRING_TABLE(DeltaStateStrings, "CHECK_PAIRING", "CONNECTED", "GET_CHARGER_FW_VERSION", "GET_BT_FW_VERSION",
62 "GET_LOGIN_RESULT", "GET_LOGIN_RESULT0", "GET_LOGIN_ROLE", "GET_LOGIN_USER", "GET_MODEL",
63 "GET_SERIAL_NUMBER", "HALTED", "IDLE", "SEND_LOGIN_CREDENTIALS", "TIME_SYNC");
64static_assert(DeltaStateStrings::LAST_INDEX == static_cast<uint8_t>(DeltaState::DELTA_STATE_TIME_SYNC),
65 "DeltaStateStrings must list every DeltaState");
66static const LogString *delta_state_to_string(DeltaState state) {
67 return DeltaStateStrings::get_log_str(static_cast<uint8_t>(state), DeltaStateStrings::LAST_INDEX);
68}
69
70// The function code a handshake step waits for; 0 where any frame is handled
71static uint8_t expected_function_code(DeltaState state) {
72 switch (state) {
76 return 0;
79 return FC_WRITE_MULTIPLE_REGISTERS;
80 default:
81 return FC_READ_HOLDING_REGISTERS;
82 }
83}
84
85// UUID references
86static const esp32_ble_tracker::ESPBTUUID SERVICE_UUID =
87 esp32_ble_tracker::ESPBTUUID::from_raw("6e400001-b5a3-f393-e0a9-e50e24dcca9e");
88static const esp32_ble_tracker::ESPBTUUID TX_UUID =
89 esp32_ble_tracker::ESPBTUUID::from_raw("6e400002-b5a3-f393-e0a9-e50e24dcca9e");
90static const esp32_ble_tracker::ESPBTUUID RX_UUID =
91 esp32_ble_tracker::ESPBTUUID::from_raw("6e400003-b5a3-f393-e0a9-e50e24dcca9e");
92
93// Appends the little-endian Modbus CRC-16 to the len bytes in frame and returns the new length.
94static size_t append_crc(uint8_t *frame, size_t len) {
95 const uint16_t crc = crc16(frame, static_cast<uint16_t>(len));
96 frame[len] = static_cast<uint8_t>(crc & 0xFF);
97 frame[len + 1] = static_cast<uint8_t>(crc >> 8);
98 return len + 2;
99}
100
101static bool verify_crc(const uint8_t *data, size_t len) {
102 if (len < EXCEPTION_RESPONSE_LEN)
103 return false;
104 const uint16_t calculated = crc16(data, static_cast<uint16_t>(len - 2));
105 const uint16_t received = encode_uint16(data[len - 1], data[len - 2]);
106 return calculated == received;
107}
108
109// Login write body: 22-byte password and 6-byte user, both left-padded with zeros
110static std::array<uint8_t, LOGIN_BODY_LEN> build_login_body(StringRef user, StringRef password) {
111 std::array<uint8_t, LOGIN_BODY_LEN> frame = {
112 0x01, 0x10, 0x01, 0x72, 0x00, 0x0E, 0x1C, // Unit, FC16, register 0x0172, 14 registers, 28 bytes
113 };
114
115 const size_t pass_len = std::min(password.size(), LOGIN_PASS_LEN);
116 std::copy_n(password.c_str(), pass_len, frame.begin() + 7 + (LOGIN_PASS_LEN - pass_len));
117
118 uint8_t *user_chunk = frame.data() + 7 + LOGIN_PASS_LEN;
119 bool is_digit = !user.empty();
120 for (size_t i = 0; i < user.size() && is_digit; i++) {
121 is_digit = isdigit(static_cast<unsigned char>(user.c_str()[i]));
122 }
123 if (is_digit) {
124 const uint64_t val = strtoull(user.c_str(), nullptr, 10);
125 for (size_t i = 0; i < LOGIN_USER_LEN; i++) {
126 user_chunk[LOGIN_USER_LEN - 1 - i] = static_cast<uint8_t>((val >> (8 * i)) & 0xFF);
127 }
128 } else {
129 const size_t user_len = std::min(user.size(), LOGIN_USER_LEN);
130 std::copy_n(user.c_str(), user_len, user_chunk + LOGIN_USER_LEN - user_len);
131 }
132 return frame;
133}
134
135static std::array<uint8_t, TIME_SYNC_BODY_LEN> build_time_sync_body(int year, int month, int day, int hour, int minute,
136 int second, int weekday) {
137 const uint8_t weekday_bitmap = static_cast<uint8_t>(1 << weekday); // Sunday=bit0, Mon=bit1...
138 return {
139 0x01,
140 0x10,
141 0x01,
142 0x14,
143 0x00,
144 0x04,
145 0x08, // Unit, FC16, register 0x0114, 4 registers, 8 bytes
146 static_cast<uint8_t>(year % 100),
147 static_cast<uint8_t>(month),
148 weekday_bitmap,
149 static_cast<uint8_t>(day),
150 static_cast<uint8_t>(hour),
151 static_cast<uint8_t>(minute),
152 static_cast<uint8_t>(second),
153 0x00,
154 };
155}
156
158 ESP_LOGCONFIG(TAG, "Delta Wallbox:");
159 ESP_LOGCONFIG(TAG, " User: %s", this->user_.c_str());
160 ESP_LOGCONFIG(TAG, " BLE PIN configured: %s", this->has_pin_ ? LOG_STR_LITERAL("YES") : LOG_STR_LITERAL("NO"));
161 LOG_UPDATE_INTERVAL(this);
162}
163
165 if (this->is_connected()) {
166 // Start poll flow sequence
167 ESP_LOGD(TAG, "Polling charging info...");
168 this->send_frame_(CMD_POLL_CHARGING, sizeof(CMD_POLL_CHARGING));
169 }
170}
171
172void DeltaWallbox::write_frame_(const uint8_t *frame, size_t len) {
173 if (this->tx_char_handle_ == 0) {
174 ESP_LOGW(TAG, "TX characteristic handle is not ready while in state %s. Dropping %u-byte frame.",
175 LOG_STR_ARG(delta_state_to_string(this->state_)), (unsigned int) len);
176 return;
177 }
178 ESP_LOGD(TAG, "Sending %u-byte frame in state %s (conn_id=%u, tx_handle=0x%04X).", (unsigned int) len,
179 LOG_STR_ARG(delta_state_to_string(this->state_)), this->parent_->get_conn_id(), this->tx_char_handle_);
180 auto status =
181 esp_ble_gattc_write_char(this->parent_->get_gattc_if(), this->parent_->get_conn_id(), this->tx_char_handle_, len,
182 const_cast<uint8_t *>(frame), ESP_GATT_WRITE_TYPE_NO_RSP, ESP_GATT_AUTH_REQ_NONE);
183 if (status != ESP_GATT_OK) {
184 ESP_LOGW(TAG, "esp_ble_gattc_write_char failed, status=%d", status);
185 }
186}
187
188// Copies body into a stack buffer, appends the CRC and writes the frame.
189void DeltaWallbox::send_frame_(const uint8_t *body, size_t len) {
190 std::array<uint8_t, MAX_FRAME_LEN> frame{};
191 std::copy_n(body, len, frame.begin());
192 this->write_frame_(frame.data(), append_crc(frame.data(), len));
193}
194
196 count = std::min(count, this->rx_len_);
197 std::memmove(this->rx_buffer_.data(), this->rx_buffer_.data() + count, this->rx_len_ - count);
198 this->rx_len_ -= count;
199}
200
202 ESP_LOGD(TAG, "Preparing command for state %s.", LOG_STR_ARG(delta_state_to_string(this->state_)));
203 switch (this->state_) {
205 ESP_LOGI(TAG, "Requesting charger model name...");
206 this->send_frame_(CMD_GET_MODEL, sizeof(CMD_GET_MODEL));
207 break;
209 ESP_LOGI(TAG, "Requesting BT firmware version...");
210 this->send_frame_(CMD_GET_BT_FW_VERSION, sizeof(CMD_GET_BT_FW_VERSION));
211 break;
213 ESP_LOGI(TAG, "Checking pairing status...");
214 this->send_frame_(CMD_CHECK_PAIRING, sizeof(CMD_CHECK_PAIRING));
215 break;
217 ESP_LOGI(TAG, "Querying user profile...");
218 this->send_frame_(CMD_GET_LOGIN_USER, sizeof(CMD_GET_LOGIN_USER));
219 break;
221 ESP_LOGI(TAG, "Checking pre-login status register...");
222 this->send_frame_(CMD_READ_LOGIN_STATUS, sizeof(CMD_READ_LOGIN_STATUS));
223 break;
225 ESP_LOGI(TAG, "Transmitting login credentials...");
226 const auto body = build_login_body(this->user_, this->password_);
227 this->send_frame_(body.data(), body.size());
228 break;
229 }
231 ESP_LOGI(TAG, "Verifying login result...");
232 this->send_frame_(CMD_READ_LOGIN_STATUS, sizeof(CMD_READ_LOGIN_STATUS));
233 break;
235 ESP_LOGI(TAG, "Checking role privileges...");
236 this->send_frame_(CMD_GET_LOGIN_ROLE, sizeof(CMD_GET_LOGIN_ROLE));
237 break;
239#ifdef USE_TIME
240 // Only a valid time is written; the charger keeps its own clock otherwise
241 if (this->time_id_ != nullptr) {
242 auto tm = this->time_id_->now();
243 if (tm.is_valid()) {
244 ESP_LOGI(TAG, "Synchronizing wallbox clock...");
245 // ESPTime day_of_week is 1 (Sunday) to 7 (Saturday); the charger counts from 0
246 const auto body = build_time_sync_body(tm.year, tm.month, tm.day_of_month, tm.hour, tm.minute, tm.second,
247 tm.day_of_week - 1);
248 this->send_frame_(body.data(), body.size());
249 break;
250 }
251 }
252#endif
254 break;
255 }
257 ESP_LOGI(TAG, "Requesting charger main firmware version...");
258 this->send_frame_(CMD_GET_CHARGER_FW_VERSION, sizeof(CMD_GET_CHARGER_FW_VERSION));
259 break;
261 ESP_LOGI(TAG, "Requesting wallbox serial number...");
262 this->send_frame_(CMD_GET_SERIAL_NUMBER, sizeof(CMD_GET_SERIAL_NUMBER));
263 break;
264 default:
265 this->cancel_timeout(RETRANSMIT_TIMEOUT_ID);
266 return;
267 }
268 this->set_timeout(RETRANSMIT_TIMEOUT_ID, RETRANSMIT_TIMEOUT_MS, [this]() { this->retransmit_(); });
269}
270
272 ESP_LOGW(TAG, "No answer in login state %s within %u ms. Sending the command again...",
273 LOG_STR_ARG(delta_state_to_string(this->state_)), (unsigned int) RETRANSMIT_TIMEOUT_MS);
275}
276
278 ESP_LOGD(TAG, "State transition: %s -> %s", LOG_STR_ARG(delta_state_to_string(this->state_)),
279 LOG_STR_ARG(delta_state_to_string(next)));
280 this->state_ = next;
282}
283
284void DeltaWallbox::handle_frame_(const uint8_t *frame, size_t len) {
285 ESP_LOGD(TAG, "Received valid frame in state %s: func=0x%02X len=%u",
286 LOG_STR_ARG(delta_state_to_string(this->state_)), frame[1], (unsigned int) len);
287 if (frame[1] & FC_EXCEPTION_FLAG) {
288 ESP_LOGE(TAG, "Modbus exception received in state %s! Error code: 0x%02X",
289 LOG_STR_ARG(delta_state_to_string(this->state_)), frame[2]);
291 // The clock write is optional, so a charger that refuses it is used without it
292 ESP_LOGW(TAG, "Charger refused the clock sync; continuing without it");
294 } else if (expected_function_code(this->state_) != 0) {
295 // The charger refused a handshake step; sending the same request again would not change that
296 this->halt_(LOG_STR("Modbus exception during login"));
297 }
298 return;
299 }
300 const uint8_t expected = expected_function_code(this->state_);
301 if (expected != 0 && frame[1] != expected) {
302 // A late answer to a retransmitted request; the pending one is answered or sent again by the timer
303 ESP_LOGD(TAG, "Ignoring func=0x%02X reply while waiting for 0x%02X", frame[1], expected);
304 return;
305 }
306
307 switch (this->state_) {
309 break; // No command is pending; ignore the frame.
311 char model[MAX_FRAME_LEN];
312 const size_t data_len = std::min<size_t>(frame[2], len - READ_RESPONSE_OVERHEAD);
313 size_t model_len = 0;
314 for (size_t i = 0; i < data_len; i++) {
315 if (frame[3 + i] != '\0')
316 model[model_len++] = static_cast<char>(frame[3 + i]);
317 }
318 model[model_len] = '\0';
319 ESP_LOGI(TAG, "Discovered Wallbox Model Name: %s", model);
320 PUBLISH_STATE(this->model_name_text_sensor_, model);
322 break;
323 }
325 if (frame[2] >= REGISTER_BYTE_COUNT) {
326 uint8_t major = frame[3] % 16;
327 uint8_t minor = frame[4];
328 char ver[16];
329 snprintf(ver, sizeof(ver), "%d.%d", major, minor);
330 ESP_LOGI(TAG, "Discovered Wallbox BT FW: %s", ver);
331 PUBLISH_STATE(this->bt_fw_version_text_sensor_, ver);
332 }
334 break;
335 }
337 if (frame[2] >= REGISTER_BYTE_COUNT) {
338 uint16_t status = encode_uint16(frame[3], frame[4]);
339 ESP_LOGI(TAG, "Pairing Status Register: 0x%04X", status);
340 if (status == PAIRING_STATUS_READY) {
341 this->pairing_in_progress_ = false;
342 this->pairing_attempts_ = 0;
343 ESP_LOGI(TAG, "Pairing ready and confirmed!");
345 } else if (status == PAIRING_STATUS_WAITING) {
346 ESP_LOGW(TAG, "Wallbox is waiting to be paired by the system controller (attempt %u, in_progress=%s).",
347 this->pairing_attempts_ + 1,
348 this->pairing_in_progress_ ? LOG_STR_LITERAL("YES") : LOG_STR_LITERAL("NO"));
349 this->pairing_attempts_++;
350 if (!this->pairing_in_progress_) {
351 ESP_LOGI(TAG, "Initiating BLE pairing with wallbox.");
352 auto err = this->parent_->pair();
353 if (err != ESP_OK) {
354 ESP_LOGW(TAG, "Failed to initiate BLE pairing, err=%d", err);
355 } else {
356 this->pairing_in_progress_ = true;
357 }
358 }
359 } else {
360 ESP_LOGW(TAG, "Unexpected pairing status 0x%04X", status);
361 this->pairing_attempts_++;
362 }
363 if (this->pairing_attempts_ >= MAX_PAIRING_ATTEMPTS) {
364 this->halt_(LOG_STR("Too many failed/waiting pairing checks"));
365 }
366 } else {
367 ESP_LOGW(TAG, "Pairing status response too short: byte_count=%u frame_len=%u", frame[2], (unsigned int) len);
368 }
369 break;
370 }
373 break;
374 }
376 if (frame[2] == REGISTER_BYTE_COUNT) {
378 }
379 break;
380 }
383 break;
384 }
386 // Only the one-register status answer counts; a late reply to another read has a different length
387 if (frame[2] == REGISTER_BYTE_COUNT) {
388 uint8_t login_val = frame[4]; // respondent data_lo
389 if (login_val == LOGIN_ACCEPTED) {
390 ESP_LOGI(TAG, "Credentials accepted! Logged in as %s.", this->user_.c_str());
392 } else {
393 ESP_LOGE(TAG, "Login validation failed (0x%02X). Check password.", login_val);
394 this->halt_(LOG_STR("Bad credentials"));
395 }
396 }
397 break;
398 }
400 break; // Authentication is halted; ignore any late replies.
401 }
403 if (frame[2] == REGISTER_BYTE_COUNT) {
405 }
406 break;
407 }
410 break;
411 }
413 if (frame[2] >= TWO_REGISTER_BYTE_COUNT) {
414 char ver[16];
415 snprintf(ver, sizeof(ver), "%d.%d", frame[3], frame[4]);
416 ESP_LOGI(TAG, "Discovered Charger Main FW: %s", ver);
417 PUBLISH_STATE(this->fw_version_text_sensor_, ver);
418 }
420 break;
421 }
423 // Serial read (0x0109) returns 14 ASCII bytes instead of one register
424 if (frame[2] >= SERIAL_TEXT_BYTE_COUNT) {
425 char serial[SERIAL_TEXT_BYTE_COUNT + 1];
426 size_t serial_len = 0;
427 for (size_t i = 0; i < SERIAL_TEXT_BYTE_COUNT; i++) {
428 if (frame[3 + i] != '\0')
429 serial[serial_len++] = static_cast<char>(frame[3 + i]);
430 }
431 serial[serial_len] = '\0';
432 ESP_LOGI(TAG, "Wallbox serial text: %s", serial);
433 PUBLISH_STATE(this->serial_number_text_sensor_, serial);
434 }
436 ESP_LOGI(TAG, "Authentication complete. Core parameters loaded.");
437 this->status_clear_warning();
438 this->update(); // perform first poll update immediately
439 break;
440 }
442 // Connected polling responses
443 if (frame[1] == FC_READ_HOLDING_REGISTERS) {
444 uint8_t byte_count = frame[2];
445 if (byte_count == CHARGING_INFO_BYTE_COUNT) {
446 // Parsing 0x011B charging info (9 registers)
447 const ChargingInfo info = decode_charging_info(frame);
448 PUBLISH_STATE(this->power_sensor_, info.power_kw);
449 PUBLISH_STATE(this->energy_sensor_, info.energy_kwh);
450 PUBLISH_STATE(this->charging_time_sensor_, info.charging_minutes);
451 PUBLISH_STATE(this->charger_state_sensor_, info.state);
452
453 // Retrieve maximum current output setting next
454 this->send_frame_(CMD_GET_MAX_CURRENT, sizeof(CMD_GET_MAX_CURRENT));
455 } else if (byte_count == TWO_REGISTER_BYTE_COUNT) {
456 // Parsing 0x0112 max output setting (2 registers)
457 // frame[4] is the configured max (set by DIP switch in device)
458 // frame[5] the active limit
459 this->max_current_limit_ = frame[4];
460 PUBLISH_STATE(this->max_current_sensor_, frame[5]);
461 PUBLISH_STATE(this->max_current_number_, frame[5]);
462
463 // Poll the error code register every cycle
464 this->send_frame_(CMD_GET_ERROR_CODE, sizeof(CMD_GET_ERROR_CODE));
465 } else if (byte_count == REGISTER_BYTE_COUNT) {
466 // Error status register (0x01B5)
467 uint16_t reg_val = encode_uint16(frame[3], frame[4]);
468 char hex_str[16];
469 snprintf(hex_str, sizeof(hex_str), "%04X", reg_val);
470 PUBLISH_STATE(this->error_code_text_sensor_, hex_str);
471 }
472 } else if (frame[1] == FC_WRITE_SINGLE_REGISTER) {
473 const uint16_t register_addr = encode_uint16(frame[2], frame[3]);
474 if (register_addr == REG_MAX_CURRENT) {
475 ESP_LOGI(TAG, "Wallbox max current command acknowledged: %u A", frame[5]);
476 PUBLISH_STATE(this->max_current_number_, frame[5]);
477 } else {
478 // Confirmation frame of Start/Stop write actions
479 ESP_LOGI(TAG, "Wallbox charging command successfully acknowledged.");
480 }
481 }
482 break;
483 }
484 }
485}
486
488 ESP_LOGW(TAG, "Resetting component state from %s. pairing_attempts=%u, pairing_in_progress=%s, rx_buffer=%u bytes",
489 LOG_STR_ARG(delta_state_to_string(this->state_)), this->pairing_attempts_,
490 this->pairing_in_progress_ ? LOG_STR_LITERAL("YES") : LOG_STR_LITERAL("NO"), (unsigned int) this->rx_len_);
491 this->cancel_timeout(RETRANSMIT_TIMEOUT_ID);
492 this->rx_len_ = 0;
494 this->max_current_limit_ = 0; // refuse writes until the next 0x0112 read
495 this->pairing_attempts_ = 0;
496 this->pairing_in_progress_ = false;
497 this->status_set_warning();
498}
499
500void DeltaWallbox::halt_(const LogString *reason) {
501 ESP_LOGE(TAG, "Halting authentication: %s. A reconnect is required to retry.", LOG_STR_ARG(reason));
502 this->cancel_timeout(RETRANSMIT_TIMEOUT_ID);
503 this->rx_len_ = 0;
505 this->pairing_attempts_ = 0;
506 this->pairing_in_progress_ = false;
507 this->status_set_warning(reason);
508}
509
510void DeltaWallbox::set_charging_state(bool state) {
511 if (!this->is_connected()) {
512 ESP_LOGW(TAG, "Cannot send charging command while wallbox is not fully connected.");
513 return;
514 }
515
516 if (state) {
517 ESP_LOGI(TAG, "Sending remote START charging command...");
518 this->send_frame_(CMD_START_CHARGING, sizeof(CMD_START_CHARGING));
519 } else {
520 ESP_LOGI(TAG, "Sending remote STOP charging command...");
521 this->send_frame_(CMD_STOP_CHARGING, sizeof(CMD_STOP_CHARGING));
522 }
523}
524
525void DeltaWallbox::set_max_current(float current) {
526 if (!this->is_connected()) {
527 ESP_LOGW(TAG, "Cannot set maximum current while wallbox is not fully connected.");
528 return;
529 }
530 const uint8_t upper = this->max_current_limit_;
531 if (upper == 0) {
532 ESP_LOGW(TAG, "Wallbox current limit not read yet; refusing to set %.0f A", current);
533 return;
534 }
535 const int32_t rounded = std::lround(current);
536 if (rounded < 1) {
537 ESP_LOGW(TAG, "Rejecting maximum current %d A", static_cast<int>(rounded));
538 return;
539 }
540 const uint8_t requested = static_cast<uint8_t>(std::min<int32_t>(rounded, upper));
541 if (rounded > upper) {
542 ESP_LOGW(TAG, "Requested %d A exceeds wallbox limit %u A; using %u A", static_cast<int>(rounded), upper, upper);
543 }
544 ESP_LOGI(TAG, "Setting wallbox maximum current to %u A", requested);
545 const std::array<uint8_t, 6> body = {0x01,
546 FC_WRITE_SINGLE_REGISTER,
547 static_cast<uint8_t>(REG_MAX_CURRENT >> 8),
548 static_cast<uint8_t>(REG_MAX_CURRENT & 0xFF),
549 0x00,
550 requested};
551 this->send_frame_(body.data(), body.size());
552}
553
554void DeltaWallbox::start_charging() { this->set_charging_state(true); }
555
556void DeltaWallbox::stop_charging() { this->set_charging_state(false); }
557
558void DeltaWallbox::gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
559 esp_ble_gattc_cb_param_t *param) {
560 switch (event) {
561 case ESP_GATTC_DISCONNECT_EVT: {
562 ESP_LOGW(TAG, "Disconnected from Bluetooth wallbox client (conn_id=%u, reason=%d). Resetting state.",
563 param->disconnect.conn_id, param->disconnect.reason);
564 this->reset_state_();
566 break;
567 }
568 case ESP_GATTC_OPEN_EVT: {
569 ESP_LOGI(TAG, "GATT open event received: status=%d conn_id=%u", param->open.status, param->open.conn_id);
570 break;
571 }
572 case ESP_GATTC_SEARCH_CMPL_EVT: {
573 ESP_LOGI(TAG, "GATT service discovery completed: status=%d", param->search_cmpl.status);
574 auto *tx_char = this->parent_->get_characteristic(SERVICE_UUID, TX_UUID);
575 auto *rx_char = this->parent_->get_characteristic(SERVICE_UUID, RX_UUID);
576 if (tx_char == nullptr || rx_char == nullptr) {
577 ESP_LOGE(TAG, "Could not discover matching NUS TX/RX service on this BLE device.");
578 this->reset_state_();
579 break;
580 }
581 this->tx_char_handle_ = tx_char->handle;
582 this->rx_char_handle_ = rx_char->handle;
583
584 esp_err_t err = this->parent_->register_for_notify(this->rx_char_handle_);
585 if (err != ESP_OK) {
586 ESP_LOGW(TAG, "register_for_notify failed, status=%d", err);
587 }
588 break;
589 }
590 case ESP_GATTC_REG_FOR_NOTIFY_EVT: {
591 ESP_LOGI(TAG, "Register-for-notify event: status=%d handle=0x%04X", param->reg_for_notify.status,
592 param->reg_for_notify.handle);
593 if (param->reg_for_notify.handle == this->rx_char_handle_) {
594 ESP_LOGI(TAG, "Subscribed to RX notification handle 0x%04X successfully.", this->rx_char_handle_);
597 ESP_LOGI(TAG, "GATT connection established. Starting authentication state machine.");
599 }
600 }
601 break;
602 }
603 case ESP_GATTC_NOTIFY_EVT: {
604 if (param->notify.handle != this->rx_char_handle_)
605 break;
606
607 const size_t value_len = param->notify.value_len;
608 ESP_LOGD(TAG, "Notification received on handle 0x%04X with %u bytes. Buffer before append=%u bytes.",
609 param->notify.handle, param->notify.value_len, (unsigned int) this->rx_len_);
610 if (value_len > MAX_FRAME_LEN - this->rx_len_) {
611 ESP_LOGW(TAG, "Notification overflows the %u-byte RX buffer. Discarding buffered data.",
612 (unsigned int) MAX_FRAME_LEN);
613 this->rx_len_ = 0;
614 if (value_len > MAX_FRAME_LEN)
615 break;
616 }
617 std::memcpy(this->rx_buffer_.data() + this->rx_len_, param->notify.value, value_len);
618 this->rx_len_ += value_len;
619
620 bool progress = true;
621 while (progress && this->rx_len_ >= 3) {
622 progress = false;
623 uint8_t func_code = this->rx_buffer_[1];
624 size_t expected_len = 0;
625
626 if (func_code == FC_READ_HOLDING_REGISTERS) {
627 expected_len = this->rx_buffer_[2] + READ_RESPONSE_OVERHEAD;
628 } else if (func_code == FC_WRITE_MULTIPLE_REGISTERS || func_code == FC_WRITE_SINGLE_REGISTER) {
629 expected_len = WRITE_RESPONSE_LEN;
630 } else if (func_code == (FC_EXCEPTION_FLAG | FC_READ_HOLDING_REGISTERS) ||
631 func_code == (FC_EXCEPTION_FLAG | FC_WRITE_MULTIPLE_REGISTERS) ||
632 func_code == (FC_EXCEPTION_FLAG | FC_WRITE_SINGLE_REGISTER)) {
633 expected_len = EXCEPTION_RESPONSE_LEN;
634 }
635
636 if (expected_len > 0) {
637 if (this->rx_len_ >= expected_len) {
638 if (verify_crc(this->rx_buffer_.data(), expected_len)) {
639 // The frame stays in rx_buffer_ during handle_frame_(); it is dropped afterwards.
640 this->handle_frame_(this->rx_buffer_.data(), expected_len);
641 this->drop_rx_bytes_(expected_len);
642 progress = true;
643 } else {
644 ESP_LOGW(TAG, "CRC mismatch while parsing notification data in state %s. Dropping one byte from buffer.",
645 LOG_STR_ARG(delta_state_to_string(this->state_)));
646 // Shift by one byte to realign with the next possible frame start
647 this->drop_rx_bytes_(1);
648 progress = true;
649 }
650 }
651 } else {
652 ESP_LOGW(TAG,
653 "Unsupported function code 0x%02X while parsing notification data in state %s. Advancing buffer.",
654 func_code, LOG_STR_ARG(delta_state_to_string(this->state_)));
655 this->drop_rx_bytes_(1);
656 progress = true;
657 }
658 }
659 break;
660 }
661 default:
662 break;
663 }
664}
665
666void DeltaWallbox::gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) {
667 switch (event) {
668 case ESP_GAP_BLE_PASSKEY_REQ_EVT: {
669 if (!this->parent_->check_addr(param->ble_security.ble_req.bd_addr))
670 return;
671
672 if (!this->has_pin_) {
673 ESP_LOGW(TAG, "Wallbox requested a BLE passkey, but no pin is configured. Set pin: under delta_wallbox:.");
674 return;
675 }
676
677 ESP_LOGI(TAG, "Wallbox requested a BLE passkey. Replying with configured YAML pin.");
678 esp_err_t err = esp_ble_passkey_reply(param->ble_security.ble_req.bd_addr, true, this->pin_);
679 if (err != ESP_OK) {
680 ESP_LOGW(TAG, "Failed to send BLE passkey reply: %s", esp_err_to_name(err));
681 }
682 break;
683 }
684 case ESP_GAP_BLE_AUTH_CMPL_EVT:
685 if (!this->parent_->check_addr(param->ble_security.auth_cmpl.bd_addr))
686 return;
687
688 this->pairing_in_progress_ = false;
689 if (param->ble_security.auth_cmpl.success) {
690 ESP_LOGI(TAG,
691 "BLE pairing completed successfully. auth_mode=%d addr_type=%d. Re-checking wallbox pairing status.",
692 param->ble_security.auth_cmpl.auth_mode, param->ble_security.auth_cmpl.addr_type);
693 this->pairing_attempts_ = 0;
697 }
698 } else {
699 ESP_LOGW(TAG, "BLE pairing failed, reason=%d", param->ble_security.auth_cmpl.fail_reason);
700 }
701 break;
702 default:
703 break;
704 }
705}
706
707} // namespace esphome::delta_wallbox
708
709#endif
uint8_t status
Definition bl0942.h:8
bool cancel_timeout(const char *name)
Cancel a timeout function.
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
void status_clear_warning()
Definition component.h:309
constexpr const char * c_str() const
Definition string_ref.h:78
static ESPBTUUID from_raw(const uint8_t *data)
Construct from raw 16-byte little-endian UUID.
void write_frame_(const uint8_t *frame, size_t len)
void halt_(const LogString *reason)
void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param) override
void handle_frame_(const uint8_t *frame, size_t len)
std::array< uint8_t, MAX_FRAME_LEN > rx_buffer_
void send_frame_(const uint8_t *body, size_t len)
void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) override
esp_err_t register_for_notify(uint16_t char_handle)
Register for notifications, holding the service release until the registration completes.
BLECharacteristic * get_characteristic(espbt::ESPBTUUID service, espbt::ESPBTUUID chr)
ESPTime now()
Get the time in the currently defined timezone.
uint8_t month
Definition date_entity.h:1
uint16_t year
Definition date_entity.h:0
uint8_t day
Definition date_entity.h:2
uint8_t second
uint8_t minute
uint8_t hour
NameCopy * next
bool state
Definition fan.h:2
unsigned count
Definition gif.cpp:51
mopeka_std_values val[3]
ESPHOME_LOG_TAG(TAG, "delta_wallbox")
PROGMEM_STRING_TABLE(DeltaStateStrings, "CHECK_PAIRING", "CONNECTED", "GET_CHARGER_FW_VERSION", "GET_BT_FW_VERSION", "GET_LOGIN_RESULT", "GET_LOGIN_RESULT0", "GET_LOGIN_ROLE", "GET_LOGIN_USER", "GET_MODEL", "GET_SERIAL_NUMBER", "HALTED", "IDLE", "SEND_LOGIN_CREDENTIALS", "TIME_SYNC")
ChargingInfo decode_charging_info(const uint8_t *frame)
uint16_t crc16(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t reverse_poly, bool refin, bool refout)
Calculate a CRC-16 checksum of data with size len.
Definition helpers.cpp:95
const void size_t len
Definition hal.h:68
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
Definition helpers.h:1043
static void uint32_t