Skip to content

Commit ad49544

Browse files
KrX3Dclaude
andcommitted
ina2xx_v2: address CodeRabbit review on wled#4237
- INA226: apply the correction factor after setResistorRange(), which rewrote the calibration register with the uncorrected value - MQTT restore: plain wait tick plus flag (millis()|1 could time out at once), only restore with a valid total, republish once restored - Validate energy from the JSON API; reject shunt_resistor <= 0 - Integrate unrounded power, keep the day/month rollover for negative power, do not integrate across a re-init or disabled period - INA226: refresh the overflow flag on every sample - Re-create the sensor in loop() instead of the web task (use-after-free), subscribe when enabled while MQTT is connected, drop "enabled" from the JSON state API (re-enabling there could never work) - Readme: ina2xx_v2 name, nodemcuv2 example, check_interval range, heartbeat vs check_interval, energy only after NTP sync Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 4ec12fd commit ad49544

3 files changed

Lines changed: 98 additions & 51 deletions

File tree

‎usermods/ina2xx_v2/Readme.md‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ This Usermod integrates the INA219 **and** INA226 sensors with WLED to monitor e
4242
|-------------------------------|------------------------------------------------------------|----------------|--------------------------------------------------------|
4343
| `INA2XX_ENABLED` | Enable or disable the INA2XX Usermod | `false` | `true`, `false` |
4444
| `INA2XX_I2C_ADDRESS` | I2C address of the INA2XX sensor | `0x40` | See options below for available addresses. |
45-
| `INA2XX_CHECK_INTERVAL` | Interval for checking sensor values (seconds) | `5` | Any positive integer |
45+
| `INA2XX_CHECK_INTERVAL` | Interval for checking sensor values (seconds) | `5` | `1` to `600` (web UI) |
4646
| `INA2XX_CONVERSION_TIME` | ADC conversion time | `BIT_MODE_12` (219)<br>`CONV_TIME_1100` (226) | Sensor-specific (see below) |
4747
| `INA2XX_DECIMAL_FACTOR` | Number of decimal places for current and power readings | `3` | See options below for decimal places. |
4848
| `INA2XX_SHUNT_RESISTOR` | Value of the shunt resistor in ohms | `0.1` | Any positive float value matching your INA2XX resistor |
@@ -127,17 +127,17 @@ The sensor is read every `check_interval` seconds. A new MQTT message is only se
127127
- after boot or an MQTT reconnect, or
128128
- `mqtt_publish_always` is enabled.
129129
130-
> **Note:** Home Assistant discovery sets `expire_after` to 1800 s, so the sensors become unavailable after 30 minutes without a message. Keep `heartbeat_interval` below 1800. With `0`, sensors whose readings stay steady go unavailable after 30 minutes.
130+
> **Note:** Home Assistant discovery sets `expire_after` to 1800 s, so the sensors become unavailable after 30 minutes without a message. The heartbeat is only checked when the sensor is read, so a message can be up to `check_interval` late: keep `heartbeat_interval` + `check_interval` below 1800. With `0`, sensors whose readings stay steady go unavailable after 30 minutes.
131131
132132
---
133133
134134
# Compiling
135135
136-
To enable, add `INA2XX_v2` to your `custom_usermods` (e.g. in `platformio_override.ini`)
136+
To enable, add `ina2xx_v2` to your `custom_usermods` (e.g. in `platformio_override.ini`). The name is case-sensitive.
137137
```ini
138-
[env:usermod_ina2xx_d1_mini]
139-
extends = env:d1_mini
140-
custom_usermods = ${env:d1_mini.custom_usermods} INA2XX_v2
138+
[env:usermod_ina2xx_nodemcuv2]
139+
extends = env:nodemcuv2
140+
custom_usermods = ${env:nodemcuv2.custom_usermods} ina2xx_v2
141141
```
142142
143143
## Usage
@@ -178,6 +178,8 @@ custom_usermods = ${env:d1_mini.custom_usermods} INA2XX_v2
178178
179179
## Energy Calculation
180180
181+
Energy is only counted once the time is synced (NTP); readings before that are not added.
182+
181183
- **Total Energy** is calculated continuously.
182184
- **Daily Energy** resets after 24 hours.
183185
- **Monthly Energy** resets on the first day of each month.

‎usermods/ina2xx_v2/ina2xx_v2.cpp‎

Lines changed: 84 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -49,17 +49,22 @@ bool UsermodINA2xx::hasValueChanged() {
4949
return changed;
5050
}
5151

52+
// Energy values from MQTT or the JSON API must be finite, not negative and plausible
53+
static bool isPlausibleEnergy(double kWh) {
54+
return !isnan(kWh) && kWh >= 0.0 && kWh <= INA2XX_MAX_PLAUSIBLE_KWH; // inf fails the upper bound
55+
}
56+
5257
bool UsermodINA2xx::isTimeValid() const {
5358
return localTime >= 1577836800UL && localTime <= 4102444800UL;
5459
}
5560

5661
void UsermodINA2xx::applyMqttRestoreIfReady() {
5762
// No retained state with energy fields arrived (first boot, or it was deleted): count from the current values.
58-
unsigned long waitStart = mqttRestoreWaitStart;
59-
if (!mqttStateRestored && !mqttRestorePending && waitStart != 0 &&
60-
millis() - waitStart > INA2XX_RESTORE_TIMEOUT_MS) {
63+
if (!mqttStateRestored && !mqttRestorePending && mqttRestoreWaiting &&
64+
millis() - mqttRestoreWaitStart > INA2XX_RESTORE_TIMEOUT_MS) {
6165
mqttStateRestored = true;
62-
mqttRestoreWaitStart = 0;
66+
mqttRestoreWaiting = false;
67+
mqttDataPublished = false; // publish (retained, with energy fields) on the next check, also with heartbeat 0
6368
_logUsermodInaSensor("No retained energy state received, counting from current values");
6469
return;
6570
}
@@ -189,8 +194,9 @@ void UsermodINA2xx::applyMqttRestoreIfReady() {
189194

190195
mqttStateRestored = true;
191196
mqttRestorePending = false;
192-
mqttRestoreWaitStart = 0;
197+
mqttRestoreWaiting = false;
193198
mqttRestoreData = MqttRestoreData{};
199+
mqttDataPublished = false; // publish (retained, with energy fields) on the next check, also with heartbeat 0
194200
_logUsermodInaSensor("MQTT energy restore applied");
195201
}
196202

@@ -213,6 +219,7 @@ bool UsermodINA2xx::updateINA2xxSettings() {
213219
delete _ina2xx;
214220
_ina2xx = nullptr;
215221
}
222+
lastPublishTime = 0; // do not integrate energy across the gap
216223

217224
if (!enabled) return true;
218225

@@ -240,10 +247,10 @@ bool UsermodINA2xx::updateINA2xxSettings() {
240247
}
241248
initRetryDelay = 0;
242249

250+
#if INA_SENSOR_TYPE == 219
243251
_logUsermodInaSensor("Setting correction factor to %.4f", correctionFactor);
244-
_ina2xx->setCorrectionFactor(correctionFactor);
252+
_ina2xx->setCorrectionFactor(correctionFactor); // setPGain() re-applies it to the new calibration value
245253

246-
#if INA_SENSOR_TYPE == 219
247254
_logUsermodInaSensor("Setting shunt resistor to %.4f Ohms", shuntResistor);
248255
_ina2xx->setShuntSizeInOhms(shuntResistor);
249256

@@ -265,6 +272,9 @@ bool UsermodINA2xx::updateINA2xxSettings() {
265272
_ina2xx->setAverage(average);
266273
_ina2xx->setConversionTime(conversionTime);
267274
_ina2xx->setResistorRange(shuntResistor,currentRange); // choose resistor 100 mOhm (default )and gain range up to 10 A (1.3A default)
275+
// setResistorRange() writes the uncorrected calibration value, so the factor must come after it
276+
_logUsermodInaSensor("Setting correction factor to %.4f", correctionFactor);
277+
_ina2xx->setCorrectionFactor(correctionFactor);
268278

269279
_ina2xx->readAndClearFlags();
270280
#endif
@@ -629,21 +639,21 @@ bool UsermodINA2xx::onMqttMessage(char* topic, char* payload) {
629639

630640
if (jsonDoc.containsKey("daily_energy_kWh")) {
631641
double restored = jsonDoc["daily_energy_kWh"];
632-
if (!isnan(restored) && restored >= 0 && restored <= INA2XX_MAX_PLAUSIBLE_KWH) {
642+
if (isPlausibleEnergy(restored)) {
633643
mqttRestoreData.hasDailyEnergy = true;
634644
mqttRestoreData.dailyEnergy = restored;
635645
}
636646
}
637647
if (jsonDoc.containsKey("monthly_energy_kWh")) {
638648
double restored = jsonDoc["monthly_energy_kWh"];
639-
if (!isnan(restored) && restored >= 0 && restored <= INA2XX_MAX_PLAUSIBLE_KWH) {
649+
if (isPlausibleEnergy(restored)) {
640650
mqttRestoreData.hasMonthlyEnergy = true;
641651
mqttRestoreData.monthlyEnergy = restored;
642652
}
643653
}
644654
if (jsonDoc.containsKey("total_energy_kWh")) {
645655
double restored = jsonDoc["total_energy_kWh"];
646-
if (!isnan(restored) && restored >= 0 && restored <= INA2XX_MAX_PLAUSIBLE_KWH) {
656+
if (isPlausibleEnergy(restored)) {
647657
mqttRestoreData.hasTotalEnergy = true;
648658
mqttRestoreData.totalEnergy = restored;
649659
}
@@ -677,7 +687,11 @@ bool UsermodINA2xx::onMqttMessage(char* topic, char* payload) {
677687
}
678688
}
679689

680-
mqttRestorePending = true; // applied from loop()
690+
if (mqttRestoreData.hasTotalEnergy) {
691+
mqttRestorePending = true; // applied from loop()
692+
} else {
693+
_logUsermodInaSensor("Ignoring retained state with invalid total_energy_kWh");
694+
}
681695
}
682696
return true;
683697
}
@@ -696,7 +710,10 @@ void UsermodINA2xx::onMqttConnect(bool sessionPresent) {
696710
snprintf_P(subuf, sizeof(subuf), PSTR("%s/sensor/ina2xx"), mqttDeviceTopic);
697711
mqtt->subscribe(subuf, 0);
698712
_logUsermodInaSensor("Subscribed to MQTT topic: %s", subuf);
699-
if (!mqttStateRestored) mqttRestoreWaitStart = millis() | 1UL; // never 0 = not waiting
713+
if (!mqttStateRestored) {
714+
mqttRestoreWaitStart = millis();
715+
mqttRestoreWaiting = true;
716+
}
700717
}
701718
}
702719
}
@@ -715,6 +732,7 @@ UsermodINA2xx::~UsermodINA2xx() {
715732
void UsermodINA2xx::setup() {
716733
_logUsermodInaSensor("Setting up INA2xx sensor usermod");
717734
initDone = updateINA2xxSettings(); // Configure INA2xx settings
735+
reinitPending = false; // readFromConfig() before setup() already set it; this init covers it
718736
#if INA_SENSOR_TYPE == 226
719737
if (initDone && _ina2xx) {
720738
_ina2xx->waitUntilConversionCompleted(); // first data can be zero without this in continuous mode
@@ -793,6 +811,23 @@ bool UsermodINA2xx::checkForI2cErrors(){
793811
void UsermodINA2xx::loop() {
794812
applyMqttRestoreIfReady();
795813

814+
// Settings changed in the web UI: re-create the sensor here, not in the web task
815+
if (reinitPending) {
816+
reinitPending = false;
817+
bool prevInitDone = initDone;
818+
initDone = updateINA2xxSettings();
819+
if (prevInitDone != initDone) {
820+
_logUsermodInaSensor("Sensor initialization %s", initDone ? "succeeded" : "failed");
821+
}
822+
}
823+
#ifndef WLED_DISABLE_MQTT
824+
// Enabled while MQTT was already connected: onMqttConnect() will not run again by itself
825+
if (mqttSetupPending) {
826+
mqttSetupPending = false;
827+
if (enabled && WLED_MQTT_CONNECTED) onMqttConnect(false);
828+
}
829+
#endif
830+
796831
// Sensor missing at boot or dropped off the bus: retry instead of staying disabled
797832
if (enabled && !initDone && initRetryDelay != 0 && millis() - lastInitAttempt >= initRetryDelay) {
798833
_logUsermodInaSensor("Retrying INA2xx init");
@@ -822,12 +857,14 @@ void UsermodINA2xx::loop() {
822857
float rawPower_mW = _ina2xx->getBusPower();
823858
power_mW = roundDecimals(rawPower_mW);
824859
power = roundDecimals(rawPower_mW / 1000.0); // Convert from mW to W
860+
float rawPower_W = rawPower_mW / 1000.0f; // unrounded, for the energy integration
825861

826862
loadVoltage = roundDecimals(busVoltage + (shuntVoltage / 1000));
827863

828864
#if INA_SENSOR_TYPE == 219
829865
overflow = _ina2xx->getOverflow() != 0;
830866
#elif INA_SENSOR_TYPE == 226
867+
_ina2xx->readAndClearFlags(); // the overflow flag is only refreshed by this call
831868
overflow = _ina2xx->overflow;
832869
if (checkForI2cErrors()) return;
833870
#endif
@@ -838,15 +875,15 @@ void UsermodINA2xx::loop() {
838875

839876
// Update energy consumption
840877
if (lastPublishTime != 0) {
841-
if (power >= 0) {
842-
// Handle millis() overflow when calculating duration
843-
unsigned long duration = (lastCheck >= lastPublishTime)
844-
? (lastCheck - lastPublishTime)
845-
: (0xFFFFFFFFUL - lastPublishTime + lastCheck + 1);
846-
updateEnergy(power, duration);
847-
} else {
848-
_logUsermodInaSensor("Skipping energy update due to negative power: %.3f W", power);
878+
// Handle millis() overflow when calculating duration
879+
unsigned long duration = (lastCheck >= lastPublishTime)
880+
? (lastCheck - lastPublishTime)
881+
: (0xFFFFFFFFUL - lastPublishTime + lastCheck + 1);
882+
// Negative power adds no energy, but updateEnergy() must still run for the day/month rollover
883+
if (rawPower_W < 0.0f) {
884+
_logUsermodInaSensor("Negative power %.3f W, counting it as 0", rawPower_W);
849885
}
886+
updateEnergy(rawPower_W > 0.0f ? rawPower_W : 0.0f, duration);
850887
} else {
851888
_logUsermodInaSensor("First reading - establishing baseline for energy calculation");
852889
}
@@ -1015,35 +1052,34 @@ void UsermodINA2xx::readFromJsonState(JsonObject& root) {
10151052

10161053
JsonObject usermod = root[FPSTR(_name)];
10171054
if (!usermod.isNull()) {
1018-
// Read values from JSON or retain existing values if not present
1019-
if (usermod.containsKey("enabled")) {
1020-
bool prevEnabled = enabled;
1021-
enabled = usermod["enabled"] | enabled;
1022-
if (prevEnabled != enabled) {
1023-
_logUsermodInaSensor("Enabled state changed: %s", enabled ? "enabled" : "disabled");
1024-
}
1025-
}
1026-
1055+
// Read values from JSON or retain existing values if not present.
1056+
// "enabled" is not read here: enabling needs the sensor init, which the usermod settings do.
10271057
if (usermod.containsKey("totalEnergy_kWh")) {
1028-
double prevTotal = totalEnergy_kWh;
1029-
totalEnergy_kWh = usermod["totalEnergy_kWh"] | totalEnergy_kWh;
1030-
if (totalEnergy_kWh != prevTotal) {
1058+
double v = usermod["totalEnergy_kWh"] | totalEnergy_kWh;
1059+
if (!isPlausibleEnergy(v)) {
1060+
_logUsermodInaSensor("Rejected invalid total energy from JSON");
1061+
} else if (v != totalEnergy_kWh) {
1062+
totalEnergy_kWh = v;
10311063
_logUsermodInaSensor("Total energy updated from JSON: %.6f kWh", totalEnergy_kWh);
10321064
}
10331065
}
10341066

10351067
if (usermod.containsKey("dailyEnergy_kWh")) {
1036-
double prevDaily = dailyEnergy_kWh;
1037-
dailyEnergy_kWh = usermod["dailyEnergy_kWh"] | dailyEnergy_kWh;
1038-
if (dailyEnergy_kWh != prevDaily) {
1068+
double v = usermod["dailyEnergy_kWh"] | dailyEnergy_kWh;
1069+
if (!isPlausibleEnergy(v)) {
1070+
_logUsermodInaSensor("Rejected invalid daily energy from JSON");
1071+
} else if (v != dailyEnergy_kWh) {
1072+
dailyEnergy_kWh = v;
10391073
_logUsermodInaSensor("Daily energy updated from JSON: %.6f kWh", dailyEnergy_kWh);
10401074
}
10411075
}
10421076

10431077
if (usermod.containsKey("monthlyEnergy_kWh")) {
1044-
double prevMonthly = monthlyEnergy_kWh;
1045-
monthlyEnergy_kWh = usermod["monthlyEnergy_kWh"] | monthlyEnergy_kWh;
1046-
if (monthlyEnergy_kWh != prevMonthly) {
1078+
double v = usermod["monthlyEnergy_kWh"] | monthlyEnergy_kWh;
1079+
if (!isPlausibleEnergy(v)) {
1080+
_logUsermodInaSensor("Rejected invalid monthly energy from JSON");
1081+
} else if (v != monthlyEnergy_kWh) {
1082+
monthlyEnergy_kWh = v;
10471083
_logUsermodInaSensor("Monthly energy updated from JSON: %.6f kWh", monthlyEnergy_kWh);
10481084
}
10491085
}
@@ -1212,11 +1248,17 @@ bool UsermodINA2xx::readFromConfig(JsonObject& root) {
12121248
bool configComplete = !top.isNull();
12131249

12141250
_logUsermodInaSensor("Checking if configuration has changed:");
1251+
bool wasEnabled = enabled;
1252+
float prevShuntResistor = shuntResistor;
12151253
UPDATE_CONFIG(top, "Enabled", enabled, "%u");
12161254
UPDATE_CONFIG(top, "i2c_address", _i2cAddress, "0x%02X");
12171255
UPDATE_CONFIG(top, "conversion_time", conversionTime, "%u");
12181256
UPDATE_CONFIG(top, "decimals", _decimalFactor, "%u");
12191257
UPDATE_CONFIG(top, "shunt_resistor", shuntResistor, "%.6f Ohms");
1258+
if (!(shuntResistor > 0.0f) || isinf(shuntResistor)) { // also catches NaN; 0 would divide by zero
1259+
_logUsermodInaSensor("Invalid shunt_resistor; keeping %.6f Ohms", prevShuntResistor);
1260+
shuntResistor = prevShuntResistor;
1261+
}
12201262
UPDATE_CONFIG(top, "correction_factor", correctionFactor, "%.3f");
12211263
#if INA_SENSOR_TYPE == 219
12221264
UPDATE_CONFIG(top, "pga_gain", pGain, "%d");
@@ -1259,12 +1301,10 @@ bool UsermodINA2xx::readFromConfig(JsonObject& root) {
12591301
configComplete = false;
12601302
}
12611303

1262-
bool prevInitDone = initDone;
1263-
initDone = updateINA2xxSettings(); // Configure INA2xx settings
1264-
1265-
if (prevInitDone != initDone) {
1266-
_logUsermodInaSensor("Sensor initialization %s", initDone ? "succeeded" : "failed");
1267-
}
1304+
// This runs in the web server task when settings are saved; loop() may be using _ina2xx
1305+
// right now, so the sensor is re-created there. At boot, setup() does the first init.
1306+
reinitPending = true;
1307+
if (!wasEnabled && enabled) mqttSetupPending = true;
12681308

12691309
return configComplete;
12701310
}

‎usermods/ina2xx_v2/ina2xx_v2.h‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,8 +195,13 @@ class UsermodINA2xx : public Usermod {
195195
// Written by the MQTT callback (AsyncTCP task), consumed only by loop().
196196
volatile bool mqttRestorePending = false;
197197
bool mqttRestoreDeferredLogged = false;
198-
// millis() of the MQTT connect we are waiting on for the retained state; 0 = not waiting.
198+
// millis() of the MQTT connect we are waiting on for the retained state; only valid while mqttRestoreWaiting.
199199
volatile unsigned long mqttRestoreWaitStart = 0;
200+
volatile bool mqttRestoreWaiting = false;
201+
// Set by readFromConfig() (web task); loop() re-creates the sensor, so it never uses a freed _ina2xx.
202+
volatile bool reinitPending = false;
203+
// Set when the usermod gets enabled at runtime; loop() then subscribes if MQTT is already connected.
204+
volatile bool mqttSetupPending = false;
200205

201206
struct MqttRestoreData {
202207
bool hasDailyEnergy = false;

0 commit comments

Comments
 (0)