From 638bbf8b4da984979ab38882d52e065b0cc595c5 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sat, 28 Mar 2026 13:25:28 -1000 Subject: [PATCH] [bl0942] Fix energy counter jump on chip reset --- esphome/components/bl0942/bl0942.cpp | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/esphome/components/bl0942/bl0942.cpp b/esphome/components/bl0942/bl0942.cpp index 7d38597423..c83f671c7f 100644 --- a/esphome/components/bl0942/bl0942.cpp +++ b/esphome/components/bl0942/bl0942.cpp @@ -163,9 +163,20 @@ void BL0942::received_package_(DataPacket *data) { // cf_cnt is only 24 bits, so track overflows uint32_t cf_cnt = (uint24_t) data->cf_cnt; + uint32_t prev_cf_cnt_24 = this->prev_cf_cnt_ & 0x00ffffff; cf_cnt |= this->prev_cf_cnt_ & 0xff000000; if (cf_cnt < this->prev_cf_cnt_) { - cf_cnt += 0x1000000; + if (prev_cf_cnt_24 > 0x800000) { + // Previous value was in the upper half of the 24-bit range, + // so this is likely a genuine overflow from 0xFFFFFF to 0x000000. + cf_cnt += 0x1000000; + } else { + // Previous value was low, so the BL0942 chip likely reset its + // counter (e.g. due to electrical disturbance). Don't treat as + // overflow — just continue from the new value to avoid a ~3MWh jump. + ESP_LOGW(TAG, "BL0942 energy counter unexpectedly decreased from %" PRIu32 " to %" PRIu32 ", assuming chip reset", + this->prev_cf_cnt_, cf_cnt); + } } this->prev_cf_cnt_ = cf_cnt;