ESPHome 2026.12.0-dev
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 put_le16(req.data() + 6, crc16(req.data(), 6)); // Modbus sends the CRC low byte first
64
65 this->frame_len_ = 0;
66 const esp_err_t status =
67 esp_ble_gattc_write_char(this->parent_->get_gattc_if(), this->parent_->get_conn_id(), this->write_handle_,
68 req.size(), req.data(), ESP_GATT_WRITE_TYPE_NO_RSP, ESP_GATT_AUTH_REQ_NONE);
69 if (status != ESP_OK) {
70 ESP_LOGW(TAG, "write_char (reg %u) failed, status=%d", start_register, status);
71 this->abort_cycle_();
72 }
73}
74
76 this->set_timeout(CYCLE_TIMEOUT_ID, CYCLE_TIMEOUT_MS, [this]() {
77 ESP_LOGW(TAG, "Read cycle timed out (state=%u); resetting", static_cast<uint8_t>(this->state_));
78 this->abort_cycle_();
79 });
80 if (this->init_handle_ == 0) {
81 // No init characteristic discovered; try the main read directly
82 this->state_ = State::MAIN;
83 this->read_register_(REG_MAIN, REG_MAIN_WORDS);
84 return;
85 }
86 this->state_ = State::INIT;
87 const esp_err_t status = esp_ble_gattc_read_char(this->parent_->get_gattc_if(), this->parent_->get_conn_id(),
88 this->init_handle_, ESP_GATT_AUTH_REQ_NONE);
89 if (status != ESP_OK) {
90 ESP_LOGW(TAG, "init read_char failed, status=%d", status);
91 this->abort_cycle_();
92 }
93}
94
95void RenogyInverterBle::update() {
96 if (this->node_state != espbt::ClientState::ESTABLISHED) {
97 ESP_LOGD(TAG, "Not connected yet; skipping poll");
98 return;
99 }
100 if (this->state_ != State::IDLE) {
101 ESP_LOGD(TAG, "Previous read cycle still in progress; skipping");
102 return;
103 }
104 this->start_cycle_();
105}
106
108 // A Modbus frame with its CRC appended checks to zero
109 if (len < 5 || crc16(this->frame_.data(), len) != 0) {
110 ESP_LOGW(TAG, "CRC mismatch (state=%u, len=%u)", static_cast<uint8_t>(this->state_), len);
111 this->abort_cycle_();
112 return;
113 }
114 // Exception response: function code with the high bit set, third byte is the exception code
115 if ((this->frame_[1] & 0x80) != 0) {
116 ESP_LOGW(TAG, "Modbus exception 0x%02X (state=%u)", this->frame_[2], static_cast<uint8_t>(this->state_));
117 this->abort_cycle_();
118 return;
119 }
120 // Only the reply to the outstanding read is accepted: same device, same function, the requested word count
121 const bool awaiting_reply = this->state_ == State::MAIN || this->state_ == State::LOAD;
122 const uint16_t expected_words = this->state_ == State::MAIN ? REG_MAIN_WORDS : REG_LOAD_WORDS;
123 if (!awaiting_reply || this->frame_[0] != MODBUS_DEVICE_ID || this->frame_[1] != MODBUS_READ_HOLDING ||
124 this->frame_[2] != 2 * expected_words) {
125 ESP_LOGW(TAG, "Unexpected response %02X %02X %02X (state=%u)", this->frame_[0], this->frame_[1], this->frame_[2],
126 static_cast<uint8_t>(this->state_));
127 this->abort_cycle_();
128 return;
129 }
130 auto reg16 = [this](uint8_t i) { return encode_uint16(this->frame_[3 + 2 * i], this->frame_[4 + 2 * i]); };
131
132 if (this->state_ == State::MAIN) {
133 PUBLISH_STATE(this->ac_input_voltage_sensor_, reg16(0) * 0.1f);
134 PUBLISH_STATE(this->ac_output_voltage_sensor_, reg16(2) * 0.1f);
135 PUBLISH_STATE(this->ac_output_current_sensor_, reg16(3) * 0.01f);
136 PUBLISH_STATE(this->ac_output_frequency_sensor_, reg16(4) * 0.01f);
137 PUBLISH_STATE(this->battery_voltage_sensor_, reg16(5) * 0.1f);
138 PUBLISH_STATE(this->temperature_sensor_, reg16(6) * 0.1f);
139 PUBLISH_STATE(this->input_frequency_sensor_, reg16(9) * 0.01f);
140 this->frame_len_ = 0;
141 this->set_timeout(LOAD_READ_ID, LOAD_READ_DELAY_MS, [this]() {
142 this->state_ = State::LOAD;
143 this->read_register_(REG_LOAD, REG_LOAD_WORDS);
144 });
145 return;
146 }
147 PUBLISH_STATE(this->load_current_sensor_, reg16(0) * 0.01f);
148 PUBLISH_STATE(this->load_active_power_sensor_, static_cast<float>(reg16(1)));
149 PUBLISH_STATE(this->load_apparent_power_sensor_, static_cast<float>(reg16(2)));
150 this->abort_cycle_();
151}
152
153void RenogyInverterBle::gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
154 esp_ble_gattc_cb_param_t *param) {
155 switch (event) {
156 case ESP_GATTC_DISCONNECT_EVT: {
157 this->abort_cycle_();
158 this->node_state = espbt::ClientState::IDLE;
159 break;
160 }
161 case ESP_GATTC_SEARCH_CMPL_EVT: {
162 auto *notify_chr = this->parent_->get_characteristic(espbt::ESPBTUUID::from_uint16(SERVICE_NOTIFY_UUID),
163 espbt::ESPBTUUID::from_uint16(CHAR_NOTIFY_UUID));
164 auto *write_chr = this->parent_->get_characteristic(espbt::ESPBTUUID::from_uint16(SERVICE_WRITE_UUID),
165 espbt::ESPBTUUID::from_uint16(CHAR_WRITE_UUID));
166 auto *init_chr = this->parent_->get_characteristic(espbt::ESPBTUUID::from_uint16(SERVICE_WRITE_UUID),
167 espbt::ESPBTUUID::from_uint16(CHAR_INIT_UUID));
168 if (notify_chr == nullptr || write_chr == nullptr) {
169 ESP_LOGE(TAG, "Required characteristics not found; not a Renogy inverter?");
170 break;
171 }
172 this->notify_handle_ = notify_chr->handle;
173 this->write_handle_ = write_chr->handle;
174 this->init_handle_ = (init_chr != nullptr) ? init_chr->handle : 0;
175 ESP_LOGI(TAG, "handles: notify=%u write=%u init=%u", this->notify_handle_, this->write_handle_,
176 this->init_handle_);
177 const esp_err_t status = this->parent_->register_for_notify(this->notify_handle_);
178 if (status != ESP_OK) {
179 ESP_LOGW(TAG, "register_for_notify failed, status=%d", status);
180 }
181 break;
182 }
183 case ESP_GATTC_REG_FOR_NOTIFY_EVT: {
184 // Other nodes on the same client see this event too
185 if (param->reg_for_notify.handle != this->notify_handle_) {
186 break;
187 }
188 if (param->reg_for_notify.status != ESP_GATT_OK) {
189 ESP_LOGW(TAG, "Notification registration failed, status=%d", param->reg_for_notify.status);
190 break;
191 }
192 this->node_state = espbt::ClientState::ESTABLISHED;
193 ESP_LOGI(TAG, "Connected; will poll the inverter every update interval");
194 break;
195 }
196 case ESP_GATTC_READ_CHAR_EVT: {
197 if (this->state_ != State::INIT || param->read.handle != this->init_handle_) {
198 break;
199 }
200 if (param->read.status != ESP_GATT_OK) {
201 ESP_LOGW(TAG, "init read failed, status=%d", param->read.status);
202 this->abort_cycle_();
203 break;
204 }
205 // Init handshake done; the inverter now answers Modbus reads
206 this->state_ = State::MAIN;
207 this->read_register_(REG_MAIN, REG_MAIN_WORDS);
208 break;
209 }
210 case ESP_GATTC_NOTIFY_EVT: {
211 if (param->notify.handle != this->notify_handle_) {
212 break;
213 }
214 const uint16_t value_len = param->notify.value_len;
215 if (this->frame_len_ + value_len > MAX_FRAME) {
216 ESP_LOGW(TAG, "Frame overflow; resetting");
217 this->abort_cycle_();
218 break;
219 }
220 memcpy(&this->frame_[this->frame_len_], param->notify.value, value_len);
221 this->frame_len_ += value_len;
222 if (this->frame_len_ < 3) {
223 break;
224 }
225 // An exception frame ([id][func|0x80][exc][crc][crc]) is 5 bytes; a normal response is
226 // [id][func][byte_count][...data][crc][crc]
227 const uint16_t expected_len = ((this->frame_[1] & 0x80) != 0) ? 5 : 3 + this->frame_[2] + 2;
228 if (this->frame_len_ >= expected_len) {
229 this->on_frame_complete_(expected_len);
230 }
231 break;
232 }
233 default:
234 break;
235 }
236}
237
238} // namespace esphome::renogy_inverter_ble
239
240#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, SchedulerCallback &&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:114
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:1227
constexpr uint8_t * put_le16(uint8_t *dst, uint16_t value)
Definition helpers.h:1314
static void uint32_t