Compare commits

...
Author SHA1 Message Date
J. Nick Koston 4e82d88efe [cse7766] Name the error-frame warning, test it, and use ESP_LOGVV_HEX
Restores the direct helpers.h include, gives the warning for an error frame its own
message, adds tests that error frames keep the warning until a valid frame and that an
out-of-range power cycle does not set it, and logs the raw frame with ESP_LOGVV_HEX.
2026-11-17 15:56:06 -06:00
J. Nick Koston a7e64f4e88 [cse7766] Append the fixed log prefix with buf_append_str 2026-11-17 15:52:48 -06:00
J. Nick Koston 2dcd6128c0 [cse7766] Keep the warning for frames that report an error and tidy the parser
A frame that reports a calibration or circuit error now keeps the component warning instead
of clearing it. The idle loop returns before the receive timeout check, the per-byte modulo
and the read-back of the stored byte are gone, the energy and current paths drop two float
divisions per frame, and the 24-bit wrapper gives way to encode_uint24 and the nibble
helpers. The tests build all seven sensors with dict-style packages.
2026-11-17 15:49:28 -06:00
7 changed files with 141 additions and 145 deletions

No files matched your search

+83 -93
View File
@@ -10,121 +10,119 @@ ESPHOME_LOG_TAG(TAG, "cse7766");
// The chip only sends the time since the last pulse once a cycle is longer than 1 s (in us)
static constexpr uint32_t MIN_HELD_POWER_CYCLE = 1000000;
// A gap this long between bytes starts a new frame
static constexpr uint32_t RX_RESET_TIMEOUT_MS = 500;
// Datasheet: the smallest current the chip measures
static constexpr float MIN_CURRENT_A = 0.05f;
// Energy per CF pulse is the power coefficient in uW·s; this turns pulses × coefficient into Wh
static constexpr float PULSE_COEFF_TO_WH = 1.0f / (1000000.0f * 3600.0f);
static constexpr uint8_t HEADER_OK = 0x55;
static constexpr uint8_t HEADER_NOT_CALIBRATED = 0xAA;
static constexpr uint8_t HEADER_VOLTAGE_CYCLE_EXCEEDS = 1 << 3;
static constexpr uint8_t HEADER_CURRENT_CYCLE_EXCEEDS = 1 << 2;
static constexpr uint8_t HEADER_POWER_CYCLE_EXCEEDS = 1 << 1;
static constexpr uint8_t HEADER_COEFF_STORAGE_ABNORMAL = 1 << 0;
static constexpr uint8_t HEADER2 = 0x5A;
// Adjustment byte: which registers hold a new measurement
static constexpr uint8_t ADJ_POWER = 0x10;
static constexpr uint8_t ADJ_CURRENT = 0x20;
static constexpr uint8_t ADJ_VOLTAGE = 0x40;
void CSE7766Component::loop() {
const uint32_t now = App.get_loop_component_start_time();
if (now - this->last_transmission_ >= 500) {
// last transmission too long ago. Reset RX index.
this->raw_data_index_ = 0;
}
// Early return prevents updating last_transmission_ when no data is available.
size_t avail = this->available();
if (avail == 0) {
if (avail == 0)
return;
}
const uint32_t now = App.get_loop_component_start_time();
if (now - this->last_transmission_ >= RX_RESET_TIMEOUT_MS)
this->raw_data_index_ = 0;
this->last_transmission_ = now;
// Read all available bytes in batches to reduce UART call overhead.
// At 4800 baud (~480 bytes/sec) with ~122 Hz loop rate, typically ~4 bytes per call.
this->read_available<CSE7766_RAW_DATA_SIZE>(
// At 4800 baud (~480 bytes/sec) with ~122 Hz loop rate, typically ~4 bytes per call
this->read_available<RAW_DATA_SIZE>(
[this](uint8_t byte) {
this->raw_data_[this->raw_data_index_] = byte;
if (!this->check_byte_()) {
const uint8_t index = this->raw_data_index_;
this->raw_data_[index] = byte;
if (!this->check_byte_(index, byte)) {
this->raw_data_index_ = 0;
this->status_set_warning();
return;
}
if (this->raw_data_index_ == CSE7766_RAW_DATA_SIZE - 1) {
this->parse_data_();
this->status_clear_warning();
if (index == RAW_DATA_SIZE - 1) {
this->raw_data_index_ = 0;
this->status_comm_result(this->parse_data_(), LOG_STR("Chip reports an error"));
return;
}
this->raw_data_index_ = (this->raw_data_index_ + 1) % CSE7766_RAW_DATA_SIZE;
this->raw_data_index_ = index + 1;
},
avail);
}
bool CSE7766Component::check_byte_() {
uint8_t index = this->raw_data_index_;
uint8_t byte = this->raw_data_[index];
if (index == 0) {
return (byte == 0x55) || ((byte & 0xF0) == 0xF0) || (byte == 0xAA);
}
bool CSE7766Component::check_byte_(uint8_t index, uint8_t byte) const {
if (index == 0)
return byte == HEADER_OK || high_nibble(byte) == 0xF || byte == HEADER_NOT_CALIBRATED;
if (index == 1) {
if (byte != 0x5A) {
ESP_LOGV(TAG, "Invalid Header 2 Start: 0x%02X!", byte);
return false;
}
return true;
if (byte == HEADER2)
return true;
ESP_LOGV(TAG, "Invalid Header 2 Start: 0x%02X!", byte);
return false;
}
if (index == CSE7766_RAW_DATA_SIZE - 1) {
const uint8_t checksum = sum_bytes(this->raw_data_ + 2, CSE7766_RAW_DATA_SIZE - 3);
if (checksum != this->raw_data_[CSE7766_RAW_DATA_SIZE - 1]) {
ESP_LOGW(TAG, "Invalid checksum from CSE7766: 0x%02X != 0x%02X", checksum,
this->raw_data_[CSE7766_RAW_DATA_SIZE - 1]);
if (index == RAW_DATA_SIZE - 1) {
const uint8_t checksum = sum_bytes(this->raw_data_ + 2, RAW_DATA_SIZE - 3);
if (checksum != byte) {
ESP_LOGW(TAG, "Invalid checksum from CSE7766: 0x%02X != 0x%02X", checksum, byte);
return false;
}
return true;
}
return true;
}
void CSE7766Component::parse_data_() {
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
{
char hex_buf[format_hex_pretty_size(CSE7766_RAW_DATA_SIZE)];
ESP_LOGVV(TAG, "Raw data: %s", format_hex_pretty_to(hex_buf, this->raw_data_, sizeof(this->raw_data_)));
}
#endif
// Parse header
uint8_t header1 = this->raw_data_[0];
bool CSE7766Component::parse_data_() {
ESP_LOGVV_HEX(TAG, this->raw_data_, RAW_DATA_SIZE, RAW_DATA_SIZE, "Raw data: %s");
if (header1 == 0xAA) {
const uint8_t header1 = this->raw_data_[0];
if (header1 == HEADER_NOT_CALIBRATED) {
ESP_LOGE(TAG, "CSE7766 not calibrated!");
return;
return false;
}
bool power_cycle_exceeds_range = false;
if ((header1 & 0xF0) == 0xF0) {
if (header1 & 0xD) {
// 0xFx: the low nibble holds error bits
if (high_nibble(header1) == 0xF) {
if (header1 & (HEADER_VOLTAGE_CYCLE_EXCEEDS | HEADER_CURRENT_CYCLE_EXCEEDS | HEADER_COEFF_STORAGE_ABNORMAL)) {
ESP_LOGE(TAG, "CSE7766 reports abnormal external circuit or chip damage: (0x%02X)", header1);
if (header1 & (1 << 3)) {
if (header1 & HEADER_VOLTAGE_CYCLE_EXCEEDS) {
ESP_LOGE(TAG, " Voltage cycle exceeds range.");
}
if (header1 & (1 << 2)) {
if (header1 & HEADER_CURRENT_CYCLE_EXCEEDS) {
ESP_LOGE(TAG, " Current cycle exceeds range.");
}
if (header1 & (1 << 0)) {
if (header1 & HEADER_COEFF_STORAGE_ABNORMAL) {
ESP_LOGE(TAG, " Coefficient storage area is abnormal.");
}
// Datasheet: voltage or current cycle exceeding range means invalid values
return;
return false;
}
power_cycle_exceeds_range = header1 & (1 << 1);
power_cycle_exceeds_range = header1 & HEADER_POWER_CYCLE_EXCEEDS;
}
// Parse data frame
uint32_t voltage_coeff = this->get_24_bit_uint_(2);
uint32_t voltage_cycle = this->get_24_bit_uint_(5);
uint32_t current_coeff = this->get_24_bit_uint_(8);
uint32_t current_cycle = this->get_24_bit_uint_(11);
uint32_t power_coeff = this->get_24_bit_uint_(14);
uint32_t power_cycle = this->get_24_bit_uint_(17);
uint8_t adj = this->raw_data_[20];
uint16_t cf_pulses = (this->raw_data_[21] << 8) + this->raw_data_[22];
const uint8_t *d = this->raw_data_;
uint32_t voltage_coeff = encode_uint24(d[2], d[3], d[4]);
uint32_t voltage_cycle = encode_uint24(d[5], d[6], d[7]);
uint32_t current_coeff = encode_uint24(d[8], d[9], d[10]);
uint32_t current_cycle = encode_uint24(d[11], d[12], d[13]);
uint32_t power_coeff = encode_uint24(d[14], d[15], d[16]);
uint32_t power_cycle = encode_uint24(d[17], d[18], d[19]);
uint8_t adj = d[20];
uint16_t cf_pulses = encode_uint16(d[21], d[22]);
bool have_power = adj & 0x10;
bool have_current = adj & 0x20;
bool have_voltage = adj & 0x40;
bool have_power = adj & ADJ_POWER;
bool have_current = adj & ADJ_CURRENT;
bool have_voltage = adj & ADJ_VOLTAGE;
float voltage = 0.0f;
if (have_voltage) {
@@ -132,7 +130,7 @@ void CSE7766Component::parse_data_() {
PUBLISH_STATE(this->voltage_sensor_, voltage);
}
float energy = 0.0;
float energy = 0.0f;
if (this->energy_sensor_ != nullptr) {
if (this->cf_pulses_last_ == 0 && !this->energy_sensor_->has_state()) {
this->cf_pulses_last_ = cf_pulses;
@@ -140,7 +138,7 @@ void CSE7766Component::parse_data_() {
uint16_t cf_diff = cf_pulses - this->cf_pulses_last_;
this->cf_pulses_total_ += cf_diff;
this->cf_pulses_last_ = cf_pulses;
energy = this->cf_pulses_total_ * float(power_coeff) / 1000000.0f / 3600.0f;
energy = this->cf_pulses_total_ * float(power_coeff) * PULSE_COEFF_TO_WH;
this->energy_sensor_->publish_state(energy);
}
@@ -149,37 +147,30 @@ void CSE7766Component::parse_data_() {
// Datasheet: power cycle exceeding range means active power is 0
have_power = true;
this->last_power_cycle_ = 0;
PUBLISH_STATE(this->power_sensor_, 0.0f);
} else if (have_power) {
power = power_coeff / float(power_cycle);
this->last_power_cycle_ = power_cycle;
PUBLISH_STATE(this->power_sensor_, power);
} else if (this->last_power_cycle_ > MIN_HELD_POWER_CYCLE && power_cycle <= 2 * this->last_power_cycle_) {
// No new measurement in this frame. With cycles over 1 s the register holds the last
// cycle or the time elapsed since the last pulse. While that time is within twice the
// last cycle, the next pulse is not overdue, so the last measurement still applies.
// Shorter cycles never get here in normal operation and keep the previous behaviour.
// Shorter cycles never get here in normal operation.
have_power = true;
power = power_coeff / float(this->last_power_cycle_);
PUBLISH_STATE(this->power_sensor_, power);
} else {
// The next pulse is overdue: the load has dropped, report 0 W. A load that drops to less
// than half also reads 0 W here until its first new pulse arrives.
this->last_power_cycle_ = 0;
PUBLISH_STATE(this->power_sensor_, 0.0f);
}
PUBLISH_STATE(this->power_sensor_, power);
// Without a power measurement the current is likely below the 50 mA the chip can measure;
// P > I_min·U is P/U > I_min without the division
const bool current_measurable = have_power && voltage > 1.0f && power > MIN_CURRENT_A * voltage;
float current = 0.0f;
float calculated_current = 0.0f;
if (have_current) {
// Assumption: if we don't have power measurement, then current is likely below 50mA
if (have_power && voltage > 1.0f) {
calculated_current = power / voltage;
}
// Datasheet: minimum measured current is 50mA
if (calculated_current > 0.05f) {
if (current_measurable)
current = current_coeff / float(current_cycle);
}
PUBLISH_STATE(this->current_sensor_, current);
}
@@ -196,7 +187,7 @@ void CSE7766Component::parse_data_() {
this->reactive_power_sensor_->publish_state(std::sqrt(q_squared));
}
}
if (this->power_factor_sensor_ != nullptr && (have_power || power_cycle_exceeds_range)) {
if (this->power_factor_sensor_ != nullptr && have_power) {
float pf = NAN;
if (apparent_power > 0) {
pf = power / apparent_power;
@@ -209,8 +200,7 @@ void CSE7766Component::parse_data_() {
} else if (apparent_power == 0 && power == 0) {
// No load, report ideal power factor
pf = 1.0f;
} else if (current == 0 && calculated_current <= 0.05f) {
// Datasheet: minimum measured current is 50mA
} else if (current == 0 && !current_measurable) {
ESP_LOGV(TAG, "Can't calculate power factor (current below minimum for CSE7766)");
} else {
ESP_LOGW(TAG, "Can't calculate power factor from P = %.4f W, S = %.4f VA", power, apparent_power);
@@ -221,10 +211,9 @@ void CSE7766Component::parse_data_() {
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
{
// Buffer: 7 + 15 + 33 + 15 + 25 = 95 chars max + null, rounded to 128 for safety margin.
// Float sizes with %.4f can be up to 11 chars for large values (e.g., 999999.9999).
char buf[128];
size_t pos = buf_append_printf(buf, sizeof(buf), 0, "Parsed:");
const float calculated_current = have_power && voltage > 1.0f ? power / voltage : 0.0f;
char buf[128]; // five fields at %.4f fit with room to spare
size_t pos = buf_append_str(buf, sizeof(buf), 0, "Parsed:");
if (have_voltage) {
pos = buf_append_printf(buf, sizeof(buf), pos, " V=%.4fV", voltage);
}
@@ -241,6 +230,7 @@ void CSE7766Component::parse_data_() {
ESP_LOGVV(TAG, "%s", buf);
}
#endif
return true;
}
void CSE7766Component::dump_config() {
+6 -9
View File
@@ -7,8 +7,6 @@
namespace esphome::cse7766 {
static constexpr size_t CSE7766_RAW_DATA_SIZE = 24;
class CSE7766Component final : public Component, public uart::UARTDevice {
SUB_SENSOR(voltage)
SUB_SENSOR(current)
@@ -23,14 +21,13 @@ class CSE7766Component final : public Component, public uart::UARTDevice {
void dump_config() override;
protected:
bool check_byte_();
void parse_data_();
uint32_t get_24_bit_uint_(uint8_t start_index) const {
return encode_uint24(this->raw_data_[start_index], this->raw_data_[start_index + 1],
this->raw_data_[start_index + 2]);
}
static constexpr size_t RAW_DATA_SIZE = 24;
uint8_t raw_data_[CSE7766_RAW_DATA_SIZE];
bool check_byte_(uint8_t index, uint8_t byte) const;
/// Returns false when the frame reports an error instead of measurements.
bool parse_data_();
uint8_t raw_data_[RAW_DATA_SIZE];
uint8_t raw_data_index_{0};
uint16_t cf_pulses_last_{0};
uint32_t last_transmission_{0};
+9 -1
View File
@@ -5,4 +5,12 @@ sensor:
current:
name: CSE7766 Current
power:
name: CSE776 Power
name: CSE7766 Power
energy:
name: CSE7766 Energy
apparent_power:
name: CSE7766 Apparent Power
reactive_power:
name: CSE7766 Reactive Power
power_factor:
name: CSE7766 Power Factor
@@ -1,10 +1,11 @@
#include <gtest/gtest.h>
#include <array>
#include <cstdint>
#include <vector>
#include "esphome/components/cse7766/cse7766.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/core/helpers.h"
#include "../common.h"
namespace esphome::cse7766::testing {
@@ -21,34 +22,23 @@ constexpr uint32_t POWER_COEFF = 5425000;
constexpr uint32_t LOW_LOAD_CYCLE = 2507613;
constexpr uint32_t SHORT_CYCLE = 900000; // about 6 W, just under 1 s
constexpr uint32_t HIGH_LOAD_CYCLE = 2000;
constexpr uint32_t ONE_SECOND_WAIT = 1078140; // about one second since the last pulse
constexpr uint16_t CF_PULSES = 0x0B81;
constexpr uint8_t HEADER_OK = 0x55;
constexpr uint8_t HEADER_POWER_CYCLE_EXCEEDS_RANGE = 0xF2;
constexpr uint8_t HEADER_NOT_CALIBRATED = 0xAA;
constexpr uint8_t ADJ_NEW_POWER = 0x71;
constexpr uint8_t ADJ_NO_NEW_POWER = 0x61;
void put24(std::vector<uint8_t> &frame, uint32_t value) {
frame.push_back(value >> 16);
frame.push_back(value >> 8);
frame.push_back(value);
}
std::vector<uint8_t> make_frame(uint8_t header, uint32_t power_cycle, uint8_t adj) {
std::vector<uint8_t> frame{header, 0x5A};
put24(frame, VOLTAGE_COEFF);
put24(frame, VOLTAGE_CYCLE);
put24(frame, CURRENT_COEFF);
put24(frame, CURRENT_CYCLE);
put24(frame, POWER_COEFF);
put24(frame, power_cycle);
frame.push_back(adj);
frame.push_back(0x0B);
frame.push_back(0x81);
uint8_t checksum = 0;
for (size_t i = 2; i < frame.size(); i++) {
checksum += frame[i];
}
frame.push_back(checksum);
std::array<uint8_t, 24> make_frame(uint8_t header, uint32_t power_cycle, uint8_t adj) {
std::array<uint8_t, 24> frame{header, 0x5A};
uint8_t *p = frame.data() + 2;
for (uint32_t value : {VOLTAGE_COEFF, VOLTAGE_CYCLE, CURRENT_COEFF, CURRENT_CYCLE, POWER_COEFF, power_cycle})
p = put_be24(p, value);
*p++ = adj;
p = put_be16(p, CF_PULSES);
*p = sum_bytes(frame.data() + 2, 21);
return frame;
}
@@ -60,7 +50,8 @@ class CSE7766Test : public ::testing::Test {
}
float feed_(uint8_t header, uint32_t power_cycle, uint8_t adj) {
this->uart_.push_rx(make_frame(header, power_cycle, adj));
const auto frame = make_frame(header, power_cycle, adj);
this->uart_.push_rx({frame.begin(), frame.end()});
this->sut_.loop();
return this->power_.state;
}
@@ -81,12 +72,12 @@ TEST_F(CSE7766Test, NewMeasurementIsReported) {
TEST_F(CSE7766Test, LowLoadKeepsLastMeasurementBetweenPulses) {
this->feed_(HEADER_OK, LOW_LOAD_CYCLE, ADJ_NEW_POWER);
EXPECT_NEAR(this->feed_(HEADER_OK, LOW_LOAD_CYCLE, ADJ_NO_NEW_POWER), 2.163f, 0.001f);
EXPECT_NEAR(this->feed_(HEADER_OK, 1078140, ADJ_NO_NEW_POWER), 2.163f, 0.001f);
EXPECT_NEAR(this->feed_(HEADER_OK, ONE_SECOND_WAIT, ADJ_NO_NEW_POWER), 2.163f, 0.001f);
EXPECT_NEAR(this->feed_(HEADER_OK, 4900000, ADJ_NO_NEW_POWER), 2.163f, 0.001f);
}
// Below 1 s the chip does not send waiting times in normal operation, so such a frame
// means the pulse is overdue and 0 W is reported at once, as before
// means the pulse is overdue and 0 W is reported at once
TEST_F(CSE7766Test, ShortCycleReportsZeroWithoutNewMeasurement) {
this->feed_(HEADER_OK, SHORT_CYCLE, ADJ_NEW_POWER);
EXPECT_EQ(this->feed_(HEADER_OK, 1050000, ADJ_NO_NEW_POWER), 0.0f);
@@ -106,12 +97,33 @@ TEST_F(CSE7766Test, HighLoadSwitchingOffReportsZeroAtOnce) {
EXPECT_EQ(this->feed_(HEADER_OK, 1072601, ADJ_NO_NEW_POWER), 0.0f);
}
TEST_F(CSE7766Test, NoMeasurementYetReportsZero) { EXPECT_EQ(this->feed_(HEADER_OK, 1078140, ADJ_NO_NEW_POWER), 0.0f); }
TEST_F(CSE7766Test, NoMeasurementYetReportsZero) {
EXPECT_EQ(this->feed_(HEADER_OK, ONE_SECOND_WAIT, ADJ_NO_NEW_POWER), 0.0f);
}
TEST_F(CSE7766Test, PowerCycleExceedsRangeReportsZero) {
this->feed_(HEADER_OK, LOW_LOAD_CYCLE, ADJ_NEW_POWER);
EXPECT_EQ(this->feed_(HEADER_POWER_CYCLE_EXCEEDS_RANGE, 9000000, ADJ_NO_NEW_POWER), 0.0f);
EXPECT_EQ(this->feed_(HEADER_OK, 1078140, ADJ_NO_NEW_POWER), 0.0f);
EXPECT_EQ(this->feed_(HEADER_OK, ONE_SECOND_WAIT, ADJ_NO_NEW_POWER), 0.0f);
}
// Frames that report an error carry no measurements, so the warning stays set until a valid frame
TEST_F(CSE7766Test, ErrorFramesKeepTheWarningUntilAValidFrame) {
this->feed_(HEADER_NOT_CALIBRATED, LOW_LOAD_CYCLE, ADJ_NEW_POWER);
EXPECT_TRUE(this->sut_.status_has_warning());
// Voltage cycle, current cycle and coefficient storage faults
for (uint8_t header : {0xF8, 0xF4, 0xF1}) {
this->feed_(header, LOW_LOAD_CYCLE, ADJ_NEW_POWER);
EXPECT_TRUE(this->sut_.status_has_warning());
}
this->feed_(HEADER_OK, LOW_LOAD_CYCLE, ADJ_NEW_POWER);
EXPECT_FALSE(this->sut_.status_has_warning());
}
// A power cycle out of range is a valid frame meaning 0 W, not an error
TEST_F(CSE7766Test, PowerCycleExceedsRangeIsNotAWarning) {
this->feed_(HEADER_POWER_CYCLE_EXCEEDS_RANGE, 9000000, ADJ_NO_NEW_POWER);
EXPECT_FALSE(this->sut_.status_has_warning());
}
} // namespace esphome::cse7766::testing
+1 -2
View File
@@ -1,4 +1,3 @@
packages:
uart_4800_even: !include ../../test_build_components/common/uart_4800_even/esp32-idf.yaml
<<: !include common.yaml
cse7766: !include common.yaml
@@ -1,8 +1,3 @@
substitutions:
tx_pin: GPIO1
rx_pin: GPIO3
packages:
uart_4800_even: !include ../../test_build_components/common/uart_4800_even/esp8266-ard.yaml
<<: !include common.yaml
cse7766: !include common.yaml
@@ -1,8 +1,3 @@
substitutions:
tx_pin: GPIO4
rx_pin: GPIO5
packages:
uart_4800_even: !include ../../test_build_components/common/uart_4800_even/rp2040-ard.yaml
<<: !include common.yaml
cse7766: !include common.yaml