ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
renogy_inverter_ble.cpp
Go to the documentation of this file.
2
3#ifdef USE_ESP32
4
5#include <cstring>
7#include "esphome/core/log.h"
8
10
11ESPHOME_LOG_TAG(TAG, "renogy_inverter_ble");
12
13static constexpr uint16_t SERVICE_NOTIFY_UUID = 0xFFF0;
14static constexpr uint16_t CHAR_NOTIFY_UUID = 0xFFF1;
15static constexpr uint16_t SERVICE_WRITE_UUID = 0xFFD0;
16static constexpr uint16_t CHAR_WRITE_UUID = 0xFFD1;
17static constexpr uint16_t CHAR_INIT_UUID = 0xFFD4;
18
19static constexpr uint8_t MODBUS_DEVICE_ID = 0x20;
20static constexpr uint8_t MODBUS_READ_HOLDING = 0x03;
21static constexpr uint16_t REG_MAIN = 4000;
22static constexpr uint16_t REG_MAIN_WORDS = 32;
23static constexpr uint16_t REG_LOAD = 4408;
24static constexpr uint16_t REG_LOAD_WORDS = 6;
25
26// Watchdog: returns the cycle to IDLE when the inverter stops answering
27static constexpr uint32_t CYCLE_TIMEOUT_MS = 3000;
28// Gap the inverter needs between two consecutive register reads
29static constexpr uint32_t LOAD_READ_DELAY_MS = 300;
30
31static constexpr uint32_t CYCLE_TIMEOUT_ID = 0;
32static constexpr uint32_t LOAD_READ_ID = 1;
33
35 ESP_LOGCONFIG(TAG, "Renogy Inverter BLE:");
36 LOG_UPDATE_INTERVAL(this);
37 LOG_SENSOR(" ", "AC input voltage", this->ac_input_voltage_sensor_);
38 LOG_SENSOR(" ", "AC output voltage", this->ac_output_voltage_sensor_);
39 LOG_SENSOR(" ", "AC output current", this->ac_output_current_sensor_);
40 LOG_SENSOR(" ", "AC output frequency", this->ac_output_frequency_sensor_);
41 LOG_SENSOR(" ", "Input frequency", this->input_frequency_sensor_);
42 LOG_SENSOR(" ", "Battery voltage", this->battery_voltage_sensor_);
43 LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
44 LOG_SENSOR(" ", "Load current", this->load_current_sensor_);
45 LOG_SENSOR(" ", "Load active power", this->load_active_power_sensor_);
46 LOG_SENSOR(" ", "Load apparent power", this->load_apparent_power_sensor_);
47}
48
50 this->cancel_timeout(CYCLE_TIMEOUT_ID);
51 this->cancel_timeout(LOAD_READ_ID);
52 this->frame_len_ = 0;
53 this->state_ = State::IDLE;
54}
55
56void RenogyInverterBle::read_register_(uint16_t start_register, uint16_t word_count) {
57 std::array<uint8_t, 8> req{MODBUS_DEVICE_ID,
58 MODBUS_READ_HOLDING,
59 static_cast<uint8_t>(start_register >> 8),
60 static_cast<uint8_t>(start_register),
61 static_cast<uint8_t>(word_count >> 8),
62 static_cast<uint8_t>(word_count)};
63 const uint16_t crc = crc16(req.data(), 6);
64 req[6] = crc & 0xFF; // Modbus sends the CRC low byte first
65 req[7] = crc >> 8;
66
67 this->frame_len_ = 0;
68 const esp_err_t status =
69 esp_ble_gattc_write_char(this->parent_->get_gattc_if(), this->parent_->get_conn_id(), this->write_handle_,
70 req.size(), req.data(), ESP_GATT_WRITE_TYPE_NO_RSP, ESP_GATT_AUTH_REQ_NONE);
71 if (status != ESP_OK) {
72 ESP_LOGW(TAG, "write_char (reg %u) failed, status=%d", start_register, status);
73 this->abort_cycle_();
74 }
75}
76
78 this->set_timeout(CYCLE_TIMEOUT_ID, CYCLE_TIMEOUT_MS, [this]() {
79 ESP_LOGW(TAG, "Read cycle timed out (state=%u); resetting", static_cast<uint8_t>(this->state_));
80 this->abort_cycle_();
81 });
82 if (this->init_handle_ == 0) {
83 // No init characteristic discovered; try the main read directly
84 this->state_ = State::MAIN;
85 this->read_register_(REG_MAIN, REG_MAIN_WORDS);
86 return;
87 }
88 this->state_ = State::INIT;
89 const esp_err_t status = esp_ble_gattc_read_char(this->parent_->get_gattc_if(), this->parent_->get_conn_id(),
90 this->init_handle_, ESP_GATT_AUTH_REQ_NONE);
91 if (status != ESP_OK) {
92 ESP_LOGW(TAG, "init read_char failed, status=%d", status);
93 this->abort_cycle_();
94 }
95}
96
97void RenogyInverterBle::update() {
98 if (this->node_state != espbt::ClientState::ESTABLISHED) {
99 ESP_LOGD(TAG, "Not connected yet; skipping poll");
100 return;
101 }
102 if (this->state_ != State::IDLE) {
103 ESP_LOGD(TAG, "Previous read cycle still in progress; skipping");
104 return;
105 }
106 this->start_cycle_();
107}
108
110 // A Modbus frame with its CRC appended checks to zero
111 if (len < 5 || crc16(this->frame_.data(), len) != 0) {
112 ESP_LOGW(TAG, "CRC mismatch (state=%u, len=%u)", static_cast<uint8_t>(this->state_), len);
113 this->abort_cycle_();
114 return;
115 }
116 // Exception response: function code with the high bit set, third byte is the exception code
117 if ((this->frame_[1] & 0x80) != 0) {
118 ESP_LOGW(TAG, "Modbus exception 0x%02X (state=%u)", this->frame_[2], static_cast<uint8_t>(this->state_));
119 this->abort_cycle_();
120 return;
121 }
122 // Only the reply to the outstanding read is accepted: same device, same function, the requested word count
123 const bool awaiting_reply = this->state_ == State::MAIN || this->state_ == State::LOAD;
124 const uint16_t expected_words = this->state_ == State::MAIN ? REG_MAIN_WORDS : REG_LOAD_WORDS;
125 if (!awaiting_reply || this->frame_[0] != MODBUS_DEVICE_ID || this->frame_[1] != MODBUS_READ_HOLDING ||
126 this->frame_[2] != 2 * expected_words) {
127 ESP_LOGW(TAG, "Unexpected response %02X %02X %02X (state=%u)", this->frame_[0], this->frame_[1], this->frame_[2],
128 static_cast<uint8_t>(this->state_));
129 this->abort_cycle_();
130 return;
131 }
132 auto reg16 = [this](uint8_t i) { return encode_uint16(this->frame_[3 + 2 * i], this->frame_[4 + 2 * i]); };
133
134 if (this->state_ == State::MAIN) {
135 PUBLISH_STATE(this->ac_input_voltage_sensor_, reg16(0) * 0.1f);
136 PUBLISH_STATE(this->ac_output_voltage_sensor_, reg16(2) * 0.1f);
137 PUBLISH_STATE(this->ac_output_current_sensor_, reg16(3) * 0.01f);
138 PUBLISH_STATE(this->ac_output_frequency_sensor_, reg16(4) * 0.01f);
139 PUBLISH_STATE(this->battery_voltage_sensor_, reg16(5) * 0.1f);
140 PUBLISH_STATE(this->temperature_sensor_, reg16(6) * 0.1f);
141 PUBLISH_STATE(this->input_frequency_sensor_, reg16(9) * 0.01f);
142 this->frame_len_ = 0;
143 this->set_timeout(LOAD_READ_ID, LOAD_READ_DELAY_MS, [this]() {
144 this->state_ = State::LOAD;
145 this->read_register_(REG_LOAD, REG_LOAD_WORDS);
146 });
147 return;
148 }
149 PUBLISH_STATE(this->load_current_sensor_, reg16(0) * 0.01f);
150 PUBLISH_STATE(this->load_active_power_sensor_, static_cast<float>(reg16(1)));
151 PUBLISH_STATE(this->load_apparent_power_sensor_, static_cast<float>(reg16(2)));
152 this->abort_cycle_();
153}
154
155void RenogyInverterBle::gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
156 esp_ble_gattc_cb_param_t *param) {
157 switch (event) {
158 case ESP_GATTC_DISCONNECT_EVT: {
159 this->abort_cycle_();
160 this->node_state = espbt::ClientState::IDLE;
161 break;
162 }
163 case ESP_GATTC_SEARCH_CMPL_EVT: {
164 auto *notify_chr = this->parent_->get_characteristic(espbt::ESPBTUUID::from_uint16(SERVICE_NOTIFY_UUID),
165 espbt::ESPBTUUID::from_uint16(CHAR_NOTIFY_UUID));
166 auto *write_chr = this->parent_->get_characteristic(espbt::ESPBTUUID::from_uint16(SERVICE_WRITE_UUID),
167 espbt::ESPBTUUID::from_uint16(CHAR_WRITE_UUID));
168 auto *init_chr = this->parent_->get_characteristic(espbt::ESPBTUUID::from_uint16(SERVICE_WRITE_UUID),
169 espbt::ESPBTUUID::from_uint16(CHAR_INIT_UUID));
170 if (notify_chr == nullptr || write_chr == nullptr) {
171 ESP_LOGE(TAG, "Required characteristics not found; not a Renogy inverter?");
172 break;
173 }
174 this->notify_handle_ = notify_chr->handle;
175 this->write_handle_ = write_chr->handle;
176 this->init_handle_ = (init_chr != nullptr) ? init_chr->handle : 0;
177 ESP_LOGI(TAG, "handles: notify=%u write=%u init=%u", this->notify_handle_, this->write_handle_,
178 this->init_handle_);
179 const esp_err_t status = this->parent_->register_for_notify(this->notify_handle_);
180 if (status != ESP_OK) {
181 ESP_LOGW(TAG, "register_for_notify failed, status=%d", status);
182 }
183 break;
184 }
185 case ESP_GATTC_REG_FOR_NOTIFY_EVT: {
186 // Other nodes on the same client see this event too
187 if (param->reg_for_notify.handle != this->notify_handle_) {
188 break;
189 }
190 if (param->reg_for_notify.status != ESP_GATT_OK) {
191 ESP_LOGW(TAG, "Notification registration failed, status=%d", param->reg_for_notify.status);
192 break;
193 }
194 this->node_state = espbt::ClientState::ESTABLISHED;
195 ESP_LOGI(TAG, "Connected; will poll the inverter every update interval");
196 break;
197 }
198 case ESP_GATTC_READ_CHAR_EVT: {
199 if (this->state_ != State::INIT || param->read.handle != this->init_handle_) {
200 break;
201 }
202 if (param->read.status != ESP_GATT_OK) {
203 ESP_LOGW(TAG, "init read failed, status=%d", param->read.status);
204 this->abort_cycle_();
205 break;
206 }
207 // Init handshake done; the inverter now answers Modbus reads
208 this->state_ = State::MAIN;
209 this->read_register_(REG_MAIN, REG_MAIN_WORDS);
210 break;
211 }
212 case ESP_GATTC_NOTIFY_EVT: {
213 if (param->notify.handle != this->notify_handle_) {
214 break;
215 }
216 const uint16_t value_len = param->notify.value_len;
217 if (this->frame_len_ + value_len > MAX_FRAME) {
218 ESP_LOGW(TAG, "Frame overflow; resetting");
219 this->abort_cycle_();
220 break;
221 }
222 memcpy(&this->frame_[this->frame_len_], param->notify.value, value_len);
223 this->frame_len_ += value_len;
224 if (this->frame_len_ < 3) {
225 break;
226 }
227 // An exception frame ([id][func|0x80][exc][crc][crc]) is 5 bytes; a normal response is
228 // [id][func][byte_count][...data][crc][crc]
229 const uint16_t expected_len = ((this->frame_[1] & 0x80) != 0) ? 5 : 3 + this->frame_[2] + 2;
230 if (this->frame_len_ >= expected_len) {
231 this->on_frame_complete_(expected_len);
232 }
233 break;
234 }
235 default:
236 break;
237 }
238}
239
240} // namespace esphome::renogy_inverter_ble
241
242#endif // USE_ESP32
uint8_t status
Definition bl0942.h:8
bool cancel_timeout(const char *name)
Cancel a timeout function.
virtual void dump_config()
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
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)
void read_register_(uint16_t start_register, uint16_t word_count)
ESPHOME_LOG_TAG(TAG, "renogy_inverter_ble")
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