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;
23static constexpr size_t READ_RESPONSE_OVERHEAD = 5;
24static constexpr size_t WRITE_RESPONSE_LEN = 8;
25static constexpr size_t EXCEPTION_RESPONSE_LEN = 5;
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;
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;
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};
58static constexpr uint16_t REG_MAX_CURRENT = 0x0112;
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");
65 "DeltaStateStrings must list every DeltaState");
67 return DeltaStateStrings::get_log_str(
static_cast<uint8_t
>(
state), DeltaStateStrings::LAST_INDEX);
79 return FC_WRITE_MULTIPLE_REGISTERS;
81 return FC_READ_HOLDING_REGISTERS;
86static const esp32_ble_tracker::ESPBTUUID SERVICE_UUID =
88static const esp32_ble_tracker::ESPBTUUID TX_UUID =
90static const esp32_ble_tracker::ESPBTUUID RX_UUID =
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);
101static bool verify_crc(
const uint8_t *data,
size_t len) {
102 if (
len < EXCEPTION_RESPONSE_LEN)
104 const uint16_t calculated =
crc16(data,
static_cast<uint16_t
>(
len - 2));
106 return calculated == received;
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,
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));
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]));
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);
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);
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);
146 static_cast<uint8_t
>(
year % 100),
147 static_cast<uint8_t
>(
month),
149 static_cast<uint8_t
>(
day),
150 static_cast<uint8_t
>(
hour),
151 static_cast<uint8_t
>(
minute),
152 static_cast<uint8_t
>(
second),
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);
167 ESP_LOGD(TAG,
"Polling charging info...");
168 this->
send_frame_(CMD_POLL_CHARGING,
sizeof(CMD_POLL_CHARGING));
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);
178 ESP_LOGD(TAG,
"Sending %u-byte frame in state %s (conn_id=%u, tx_handle=0x%04X).", (
unsigned int)
len,
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);
190 std::array<uint8_t, MAX_FRAME_LEN> frame{};
191 std::copy_n(body,
len, frame.begin());
202 ESP_LOGD(TAG,
"Preparing command for state %s.", LOG_STR_ARG(delta_state_to_string(this->
state_)));
205 ESP_LOGI(TAG,
"Requesting charger model name...");
206 this->
send_frame_(CMD_GET_MODEL,
sizeof(CMD_GET_MODEL));
209 ESP_LOGI(TAG,
"Requesting BT firmware version...");
210 this->
send_frame_(CMD_GET_BT_FW_VERSION,
sizeof(CMD_GET_BT_FW_VERSION));
213 ESP_LOGI(TAG,
"Checking pairing status...");
214 this->
send_frame_(CMD_CHECK_PAIRING,
sizeof(CMD_CHECK_PAIRING));
217 ESP_LOGI(TAG,
"Querying user profile...");
218 this->
send_frame_(CMD_GET_LOGIN_USER,
sizeof(CMD_GET_LOGIN_USER));
221 ESP_LOGI(TAG,
"Checking pre-login status register...");
222 this->
send_frame_(CMD_READ_LOGIN_STATUS,
sizeof(CMD_READ_LOGIN_STATUS));
225 ESP_LOGI(TAG,
"Transmitting login credentials...");
231 ESP_LOGI(TAG,
"Verifying login result...");
232 this->
send_frame_(CMD_READ_LOGIN_STATUS,
sizeof(CMD_READ_LOGIN_STATUS));
235 ESP_LOGI(TAG,
"Checking role privileges...");
236 this->
send_frame_(CMD_GET_LOGIN_ROLE,
sizeof(CMD_GET_LOGIN_ROLE));
244 ESP_LOGI(TAG,
"Synchronizing wallbox clock...");
246 const auto body = build_time_sync_body(tm.year, tm.month, tm.day_of_month, tm.hour, tm.minute, tm.second,
257 ESP_LOGI(TAG,
"Requesting charger main firmware version...");
258 this->
send_frame_(CMD_GET_CHARGER_FW_VERSION,
sizeof(CMD_GET_CHARGER_FW_VERSION));
261 ESP_LOGI(TAG,
"Requesting wallbox serial number...");
262 this->
send_frame_(CMD_GET_SERIAL_NUMBER,
sizeof(CMD_GET_SERIAL_NUMBER));
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);
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)));
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]);
292 ESP_LOGW(TAG,
"Charger refused the clock sync; continuing without it");
294 }
else if (expected_function_code(this->
state_) != 0) {
296 this->
halt_(LOG_STR(
"Modbus exception during login"));
300 const uint8_t expected = expected_function_code(this->
state_);
301 if (expected != 0 && frame[1] != expected) {
303 ESP_LOGD(TAG,
"Ignoring func=0x%02X reply while waiting for 0x%02X", frame[1], expected);
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]);
318 model[model_len] =
'\0';
319 ESP_LOGI(TAG,
"Discovered Wallbox Model Name: %s", model);
320 PUBLISH_STATE(this->model_name_text_sensor_, model);
325 if (frame[2] >= REGISTER_BYTE_COUNT) {
326 uint8_t major = frame[3] % 16;
327 uint8_t minor = frame[4];
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);
337 if (frame[2] >= REGISTER_BYTE_COUNT) {
339 ESP_LOGI(TAG,
"Pairing Status Register: 0x%04X",
status);
340 if (
status == PAIRING_STATUS_READY) {
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).",
351 ESP_LOGI(TAG,
"Initiating BLE pairing with wallbox.");
354 ESP_LOGW(TAG,
"Failed to initiate BLE pairing, err=%d", err);
360 ESP_LOGW(TAG,
"Unexpected pairing status 0x%04X",
status);
364 this->
halt_(LOG_STR(
"Too many failed/waiting pairing checks"));
367 ESP_LOGW(TAG,
"Pairing status response too short: byte_count=%u frame_len=%u", frame[2], (
unsigned int)
len);
376 if (frame[2] == REGISTER_BYTE_COUNT) {
387 if (frame[2] == REGISTER_BYTE_COUNT) {
388 uint8_t login_val = frame[4];
389 if (login_val == LOGIN_ACCEPTED) {
390 ESP_LOGI(TAG,
"Credentials accepted! Logged in as %s.", this->
user_.
c_str());
393 ESP_LOGE(TAG,
"Login validation failed (0x%02X). Check password.", login_val);
394 this->
halt_(LOG_STR(
"Bad credentials"));
403 if (frame[2] == REGISTER_BYTE_COUNT) {
413 if (frame[2] >= TWO_REGISTER_BYTE_COUNT) {
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);
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]);
431 serial[serial_len] =
'\0';
432 ESP_LOGI(TAG,
"Wallbox serial text: %s", serial);
433 PUBLISH_STATE(this->serial_number_text_sensor_, serial);
436 ESP_LOGI(TAG,
"Authentication complete. Core parameters loaded.");
443 if (frame[1] == FC_READ_HOLDING_REGISTERS) {
444 uint8_t byte_count = frame[2];
445 if (byte_count == CHARGING_INFO_BYTE_COUNT) {
448 PUBLISH_STATE(this->power_sensor_, info.
power_kw);
449 PUBLISH_STATE(this->energy_sensor_, info.
energy_kwh);
451 PUBLISH_STATE(this->charger_state_sensor_, info.
state);
454 this->
send_frame_(CMD_GET_MAX_CURRENT,
sizeof(CMD_GET_MAX_CURRENT));
455 }
else if (byte_count == TWO_REGISTER_BYTE_COUNT) {
460 PUBLISH_STATE(this->max_current_sensor_, frame[5]);
461 PUBLISH_STATE(this->max_current_number_, frame[5]);
464 this->
send_frame_(CMD_GET_ERROR_CODE,
sizeof(CMD_GET_ERROR_CODE));
465 }
else if (byte_count == REGISTER_BYTE_COUNT) {
469 snprintf(hex_str,
sizeof(hex_str),
"%04X", reg_val);
470 PUBLISH_STATE(this->error_code_text_sensor_, hex_str);
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]);
479 ESP_LOGI(TAG,
"Wallbox charging command successfully acknowledged.");
488 ESP_LOGW(TAG,
"Resetting component state from %s. pairing_attempts=%u, pairing_in_progress=%s, rx_buffer=%u bytes",
501 ESP_LOGE(TAG,
"Halting authentication: %s. A reconnect is required to retry.", LOG_STR_ARG(reason));
510void DeltaWallbox::set_charging_state(
bool state) {
512 ESP_LOGW(TAG,
"Cannot send charging command while wallbox is not fully connected.");
517 ESP_LOGI(TAG,
"Sending remote START charging command...");
518 this->
send_frame_(CMD_START_CHARGING,
sizeof(CMD_START_CHARGING));
520 ESP_LOGI(TAG,
"Sending remote STOP charging command...");
521 this->
send_frame_(CMD_STOP_CHARGING,
sizeof(CMD_STOP_CHARGING));
527 ESP_LOGW(TAG,
"Cannot set maximum current while wallbox is not fully connected.");
532 ESP_LOGW(TAG,
"Wallbox current limit not read yet; refusing to set %.0f A", current);
535 const int32_t rounded = std::lround(current);
537 ESP_LOGW(TAG,
"Rejecting maximum current %d A",
static_cast<int>(rounded));
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);
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),
559 esp_ble_gattc_cb_param_t *param) {
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);
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);
572 case ESP_GATTC_SEARCH_CMPL_EVT: {
573 ESP_LOGI(TAG,
"GATT service discovery completed: status=%d", param->search_cmpl.status);
576 if (tx_char ==
nullptr || rx_char ==
nullptr) {
577 ESP_LOGE(TAG,
"Could not discover matching NUS TX/RX service on this BLE device.");
586 ESP_LOGW(TAG,
"register_for_notify failed, status=%d", err);
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.");
603 case ESP_GATTC_NOTIFY_EVT: {
604 if (param->notify.handle != this->rx_char_handle_)
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);
614 if (value_len > MAX_FRAME_LEN)
617 std::memcpy(this->
rx_buffer_.data() + this->rx_len_, param->notify.value, value_len);
620 bool progress =
true;
621 while (progress && this->
rx_len_ >= 3) {
624 size_t expected_len = 0;
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;
636 if (expected_len > 0) {
637 if (this->
rx_len_ >= expected_len) {
638 if (verify_crc(this->
rx_buffer_.data(), expected_len)) {
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_)));
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_)));
668 case ESP_GAP_BLE_PASSKEY_REQ_EVT: {
673 ESP_LOGW(TAG,
"Wallbox requested a BLE passkey, but no pin is configured. Set pin: under delta_wallbox:.");
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_);
680 ESP_LOGW(TAG,
"Failed to send BLE passkey reply: %s", esp_err_to_name(err));
684 case ESP_GAP_BLE_AUTH_CMPL_EVT:
689 if (param->ble_security.auth_cmpl.success) {
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);
699 ESP_LOGW(TAG,
"BLE pairing failed, reason=%d", param->ble_security.auth_cmpl.fail_reason);
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")