ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
cse7766.cpp
Go to the documentation of this file.
1#include "cse7766.h"
4#include "esphome/core/log.h"
5#include <cmath>
6
7namespace esphome::cse7766 {
8
9ESPHOME_LOG_TAG(TAG, "cse7766");
10
11// The chip only sends the time since the last pulse once a cycle is longer than 1 s (in us)
12static constexpr uint32_t MIN_HELD_POWER_CYCLE = 1000000;
13
16 if (now - this->last_transmission_ >= 500) {
17 // last transmission too long ago. Reset RX index.
18 this->raw_data_index_ = 0;
19 }
20
21 // Early return prevents updating last_transmission_ when no data is available.
22 size_t avail = this->available();
23 if (avail == 0) {
24 return;
25 }
26
27 this->last_transmission_ = now;
28
29 // Read all available bytes in batches to reduce UART call overhead.
30 // At 4800 baud (~480 bytes/sec) with ~122 Hz loop rate, typically ~4 bytes per call.
32 [this](uint8_t byte) {
33 this->raw_data_[this->raw_data_index_] = byte;
34 if (!this->check_byte_()) {
35 this->raw_data_index_ = 0;
36 this->status_set_warning();
37 return;
38 }
39
40 if (this->raw_data_index_ == CSE7766_RAW_DATA_SIZE - 1) {
41 this->parse_data_();
43 }
44
45 this->raw_data_index_ = (this->raw_data_index_ + 1) % CSE7766_RAW_DATA_SIZE;
46 },
47 avail);
48}
49
51 uint8_t index = this->raw_data_index_;
52 uint8_t byte = this->raw_data_[index];
53 if (index == 0) {
54 return (byte == 0x55) || ((byte & 0xF0) == 0xF0) || (byte == 0xAA);
55 }
56
57 if (index == 1) {
58 if (byte != 0x5A) {
59 ESP_LOGV(TAG, "Invalid Header 2 Start: 0x%02X!", byte);
60 return false;
61 }
62 return true;
63 }
64
65 if (index == CSE7766_RAW_DATA_SIZE - 1) {
66 const uint8_t checksum = sum_bytes(this->raw_data_ + 2, CSE7766_RAW_DATA_SIZE - 3);
67
68 if (checksum != this->raw_data_[CSE7766_RAW_DATA_SIZE - 1]) {
69 ESP_LOGW(TAG, "Invalid checksum from CSE7766: 0x%02X != 0x%02X", checksum,
70 this->raw_data_[CSE7766_RAW_DATA_SIZE - 1]);
71 return false;
72 }
73 return true;
74 }
75
76 return true;
77}
79#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
80 {
81 char hex_buf[format_hex_pretty_size(CSE7766_RAW_DATA_SIZE)];
82 ESP_LOGVV(TAG, "Raw data: %s", format_hex_pretty_to(hex_buf, this->raw_data_, sizeof(this->raw_data_)));
83 }
84#endif
85
86 // Parse header
87 uint8_t header1 = this->raw_data_[0];
88
89 if (header1 == 0xAA) {
90 ESP_LOGE(TAG, "CSE7766 not calibrated!");
91 return;
92 }
93
94 bool power_cycle_exceeds_range = false;
95 if ((header1 & 0xF0) == 0xF0) {
96 if (header1 & 0xD) {
97 ESP_LOGE(TAG, "CSE7766 reports abnormal external circuit or chip damage: (0x%02X)", header1);
98 if (header1 & (1 << 3)) {
99 ESP_LOGE(TAG, " Voltage cycle exceeds range.");
100 }
101 if (header1 & (1 << 2)) {
102 ESP_LOGE(TAG, " Current cycle exceeds range.");
103 }
104 if (header1 & (1 << 0)) {
105 ESP_LOGE(TAG, " Coefficient storage area is abnormal.");
106 }
107
108 // Datasheet: voltage or current cycle exceeding range means invalid values
109 return;
110 }
111
112 power_cycle_exceeds_range = header1 & (1 << 1);
113 }
114
115 // Parse data frame
116 uint32_t voltage_coeff = this->get_24_bit_uint_(2);
117 uint32_t voltage_cycle = this->get_24_bit_uint_(5);
118 uint32_t current_coeff = this->get_24_bit_uint_(8);
119 uint32_t current_cycle = this->get_24_bit_uint_(11);
120 uint32_t power_coeff = this->get_24_bit_uint_(14);
121 uint32_t power_cycle = this->get_24_bit_uint_(17);
122 uint8_t adj = this->raw_data_[20];
123 uint16_t cf_pulses = (this->raw_data_[21] << 8) + this->raw_data_[22];
124
125 bool have_power = adj & 0x10;
126 bool have_current = adj & 0x20;
127 bool have_voltage = adj & 0x40;
128
129 float voltage = 0.0f;
130 if (have_voltage) {
131 voltage = voltage_coeff / float(voltage_cycle);
132 PUBLISH_STATE(this->voltage_sensor_, voltage);
133 }
134
135 float energy = 0.0;
136 if (this->energy_sensor_ != nullptr) {
137 if (this->cf_pulses_last_ == 0 && !this->energy_sensor_->has_state()) {
138 this->cf_pulses_last_ = cf_pulses;
139 }
140 uint16_t cf_diff = cf_pulses - this->cf_pulses_last_;
141 this->cf_pulses_total_ += cf_diff;
142 this->cf_pulses_last_ = cf_pulses;
143 energy = this->cf_pulses_total_ * float(power_coeff) / 1000000.0f / 3600.0f;
144 this->energy_sensor_->publish_state(energy);
145 }
146
147 float power = 0.0f;
148 if (power_cycle_exceeds_range) {
149 // Datasheet: power cycle exceeding range means active power is 0
150 have_power = true;
151 this->last_power_cycle_ = 0;
152 PUBLISH_STATE(this->power_sensor_, 0.0f);
153 } else if (have_power) {
154 power = power_coeff / float(power_cycle);
155 this->last_power_cycle_ = power_cycle;
156 PUBLISH_STATE(this->power_sensor_, power);
157 } else if (this->last_power_cycle_ > MIN_HELD_POWER_CYCLE && power_cycle <= 2 * this->last_power_cycle_) {
158 // No new measurement in this frame. With cycles over 1 s the register holds the last
159 // cycle or the time elapsed since the last pulse. While that time is within twice the
160 // last cycle, the next pulse is not overdue, so the last measurement still applies.
161 // Shorter cycles never get here in normal operation and keep the previous behaviour.
162 have_power = true;
163 power = power_coeff / float(this->last_power_cycle_);
164 PUBLISH_STATE(this->power_sensor_, power);
165 } else {
166 // The next pulse is overdue: the load has dropped, report 0 W. A load that drops to less
167 // than half also reads 0 W here until its first new pulse arrives.
168 this->last_power_cycle_ = 0;
169 PUBLISH_STATE(this->power_sensor_, 0.0f);
170 }
171
172 float current = 0.0f;
173 float calculated_current = 0.0f;
174 if (have_current) {
175 // Assumption: if we don't have power measurement, then current is likely below 50mA
176 if (have_power && voltage > 1.0f) {
177 calculated_current = power / voltage;
178 }
179 // Datasheet: minimum measured current is 50mA
180 if (calculated_current > 0.05f) {
181 current = current_coeff / float(current_cycle);
182 }
183 PUBLISH_STATE(this->current_sensor_, current);
184 }
185
186 if (have_voltage && have_current) {
187 const float apparent_power = voltage * current;
188 PUBLISH_STATE(this->apparent_power_sensor_, apparent_power);
189 if (have_power && this->reactive_power_sensor_ != nullptr) {
190 const float q_squared = apparent_power * apparent_power - power * power;
191 if (q_squared < 0.0f) {
192 // From the same noise as a power factor above 1 (below)
193 ESP_LOGV(TAG, "Impossible reactive power: S^2-P^2 is negative (%.4f)", q_squared);
194 this->reactive_power_sensor_->publish_state(0.0f);
195 } else {
196 this->reactive_power_sensor_->publish_state(std::sqrt(q_squared));
197 }
198 }
199 if (this->power_factor_sensor_ != nullptr && (have_power || power_cycle_exceeds_range)) {
200 float pf = NAN;
201 if (apparent_power > 0) {
202 pf = power / apparent_power;
203 if (pf > 1) {
204 // Noise near the chip's resolution limit pushes the ratio past unity: during inrush, and on
205 // nearly every frame of a steady resistive load, so it is logged only at verbose level
206 ESP_LOGV(TAG, "Power factor %.4f above 1, clamped", pf);
207 pf = 1.0f;
208 }
209 } else if (apparent_power == 0 && power == 0) {
210 // No load, report ideal power factor
211 pf = 1.0f;
212 } else if (current == 0 && calculated_current <= 0.05f) {
213 // Datasheet: minimum measured current is 50mA
214 ESP_LOGV(TAG, "Can't calculate power factor (current below minimum for CSE7766)");
215 } else {
216 ESP_LOGW(TAG, "Can't calculate power factor from P = %.4f W, S = %.4f VA", power, apparent_power);
217 }
218 this->power_factor_sensor_->publish_state(pf);
219 }
220 }
221
222#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
223 {
224 // Buffer: 7 + 15 + 33 + 15 + 25 = 95 chars max + null, rounded to 128 for safety margin.
225 // Float sizes with %.4f can be up to 11 chars for large values (e.g., 999999.9999).
226 char buf[128];
227 size_t pos = buf_append_printf(buf, sizeof(buf), 0, "Parsed:");
228 if (have_voltage) {
229 pos = buf_append_printf(buf, sizeof(buf), pos, " V=%.4fV", voltage);
230 }
231 if (have_current) {
232 pos = buf_append_printf(buf, sizeof(buf), pos, " I=%.4fmA (~%.4fmA)", current * 1000.0f,
233 calculated_current * 1000.0f);
234 }
235 if (have_power) {
236 pos = buf_append_printf(buf, sizeof(buf), pos, " P=%.4fW", power);
237 }
238 if (energy != 0.0f) {
239 buf_append_printf(buf, sizeof(buf), pos, " E=%.4fkWh (%u)", energy, cf_pulses);
240 }
241 ESP_LOGVV(TAG, "%s", buf);
242 }
243#endif
244}
245
246void CSE7766Component::dump_config() {
247 ESP_LOGCONFIG(TAG, "CSE7766:");
248 LOG_SENSOR(" ", "Voltage", this->voltage_sensor_);
249 LOG_SENSOR(" ", "Current", this->current_sensor_);
250 LOG_SENSOR(" ", "Power", this->power_sensor_);
251 LOG_SENSOR(" ", "Energy", this->energy_sensor_);
252 LOG_SENSOR(" ", "Apparent Power", this->apparent_power_sensor_);
253 LOG_SENSOR(" ", "Reactive Power", this->reactive_power_sensor_);
254 LOG_SENSOR(" ", "Power Factor", this->power_factor_sensor_);
255}
256
257} // namespace esphome::cse7766
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.
virtual void loop()
This method will be called repeatedly.
Definition component.cpp:86
void status_clear_warning()
Definition component.h:309
uint32_t get_24_bit_uint_(uint8_t start_index) const
Definition cse7766.h:28
uint8_t raw_data_[CSE7766_RAW_DATA_SIZE]
Definition cse7766.h:33
bool read_available(F &&on_byte)
Same as read_available_chunks(), calling on_byte(uint8_t) once per byte.
Definition uart.h:77
ESPHOME_LOG_TAG(TAG, "cse7766")
constexpr uint8_t sum_bytes(const uint8_t *data, size_t len, uint8_t sum=0)
Add up the bytes of data with size len, truncated to 8 bits: the checksum many serial and IR protocol...
Definition helpers.h:939
char * format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator)
Format byte array as uppercase hex to buffer (base implementation).
Definition helpers.cpp:498
size_t size_t pos
Definition helpers.h:1333
constexpr size_t format_hex_pretty_size(size_t byte_count)
Calculate buffer size needed for format_hex_pretty_to with separator: "XX:XX:...:XX\0".
Definition helpers.h:1687
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t