Skip to content

Commit 3eaddbe

Browse files
committed
fix(safety): keep filter pump running on combined connectivity/sensor faults
Port of #205 onto the multicore architecture. Before, any two of WiFi loss, NTP loss and a sensor fault escalated to CRITICAL and switched all relays off. A WiFi outage plus a faulty probe therefore stopped the filter pump, which is the opposite of what water hygiene needs. Only a forced (boot-loop) safe mode or persistently low heap now leads to CRITICAL; the level rules move into the pure DegradationPolicy.hpp and get native tests. Safety-model and state-persistence docs follow the new policy. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012JY8RZscs5W8tLQMuZB95K
1 parent b51ea07 commit 3eaddbe

15 files changed

Lines changed: 285 additions & 92 deletions

‎.opencode/skills/cpp-memory-opt/SKILL.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ Optimizing memory for the ESP32-based pool-controller firmware (PlatformIO, Ardu
3030
- **Platform**: ESP32 (esp32dev), ~320KB SRAM, ~4MB flash
3131
- **Framework**: Arduino + ESP-IDF (FreeRTOS)
3232
- **Critical**: 24/7 operation with no memory leaks
33-
- **Heap threshold**: Warning at <16KB free, reboot at <8KB free (`SystemMonitor.hpp:26-27`)
33+
- **Heap threshold**: Safe mode at <16KB free (reboot if it persists for 5 min), immediate reboot at <8KB free (`SystemMonitor.hpp`)
3434
- **Watchdog**: TWDT with 30s timeout (`SystemMonitor.hpp:49-54`)
3535

3636
## Common Memory Issues & Fixes in This Project

‎.opencode/skills/esp32-reliability/SKILL.md‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -57,10 +57,14 @@ keywords:
5757

5858
**Location**: `SystemMonitor.hpp:72-105`
5959

60-
| Threshold | Value | Action |
61-
| --------- | ------------------- | ------------------------- |
62-
| Warning | <16384 bytes (16KB) | Log warning once |
63-
| Critical | <8192 bytes (8KB) | Immediate `ESP.restart()` |
60+
| Threshold | Value | Action |
61+
| --------- | ------------------- | --------------------------------------------------------------------------- |
62+
| Low | <16384 bytes (16KB) | Log warning once, safe mode (`CRITICAL`); reboot if it persists for 5 min |
63+
| Critical | <8192 bytes (8KB) | Immediate `ESP.restart()` |
64+
65+
**Persistent low memory**: `SystemMonitor::lowMemoryTimer` (`PersistentConditionTimer` from
66+
`DegradationPolicy.hpp`) reboots after `LOW_MEMORY_REBOOT_AFTER_MS` (5 min) below 16KB without
67+
interruption. Safe mode switches all relays off, so the controller must not stay there indefinitely.
6468

6569
**Check interval**: Every 10 seconds in `loop()`.
6670

@@ -108,7 +112,12 @@ Then reboot — serial should show:
108112
| `NO_WIFI` | 1 | WiFi/MQTT lost, local operation still works |
109113
| `NO_TIME` | 2 | NTP sync lost, timer scheduling degraded |
110114
| `NO_SENSOR` | 3 | Temperature sensor failure, cautious defaults |
111-
| `CRITICAL` | 4 | Multiple failures or critically low memory → safe mode |
115+
| `CRITICAL` | 4 | Low memory (<16KB) or forced (boot-loop) → safe mode |
116+
117+
**Classification**: `classifyDegradation()` in `DegradationPolicy.hpp` (pure, unit-tested).
118+
Only low memory leads to `CRITICAL`. WiFi, time and sensor problems — also in combination — never
119+
enter safe mode, because safe mode switches the filter pump off. The worst single condition wins
120+
(`NO_SENSOR` > `NO_TIME` > `NO_WIFI`). Do not reintroduce "multiple failures → CRITICAL" (#194).
112121

113122
**Evaluation**: `DegradationManager::evaluate()` runs every 5 seconds (`EVALUATION_INTERVAL_MS`).
114123

‎docs/safety-model.de.md‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -135,9 +135,16 @@ und das System kann Korrekturmaßnahmen ergreifen.
135135
- Bei **kritischem Schwellwert** (8 KB freier Heap):
136136
- Warnung wird protokolliert
137137
- Graceful-Auto-Reboot wird eingeleitet
138-
- Bei **Warnschwellwert** (15 KB freier Heap):
138+
- Bei **Warnschwellwert** (16 KB freier Heap):
139139
- Warnung wird protokolliert
140-
- Kein Neustart — Überwachung läuft weiter
140+
- Safe-Mode (Relais aus), solange der Heap unter dem Schwellwert bleibt
141+
- Automatischer Neustart, wenn der Heap 5 Minuten lang unter dem Schwellwert bleibt
142+
143+
### Degradation ohne Safe-Mode
144+
145+
Probleme mit WLAN, NTP oder Temperaturfühlern — auch mehrere gleichzeitig — führen **nicht** in den Safe-Mode.
146+
Die Filterpumpe läuft weiter nach Zeitplan (oder durchgehend, solange die Uhrzeit unbekannt ist); die Solarpumpe
147+
wird von den Regeln abgeschaltet, wenn die Temperaturwerte ungültig sind.
141148

142149
### Sensor-Auto-Wiederherstellung
143150

‎docs/safety-model.md‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,9 +132,16 @@ corrective action.
132132
- At **critical threshold** (8 KB free heap):
133133
- Warning logged
134134
- Graceful auto-reboot initiated
135-
- At **warning threshold** (15 KB free heap):
135+
- At **warning threshold** (16 KB free heap):
136136
- Warning logged
137-
- No reboot — system continues monitoring
137+
- Safe mode (relays off) while the heap stays below the threshold
138+
- Auto-reboot if the heap stays below the threshold for 5 minutes
139+
140+
### Degradation Without Safe Mode
141+
142+
WiFi, NTP or temperature sensor problems — also several at the same time — do **not** enter safe mode.
143+
The filter pump keeps running on its schedule (or continuously while the time is unknown); the solar pump
144+
is switched off by the rules when temperature readings are invalid.
138145

139146
### Sensor Auto-Recovery
140147

‎docs/state-persistence.de.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -94,13 +94,14 @@ durch Speichererschöpfung zu verhindern.
9494

9595
**ESP32**:
9696

97-
- **Speicherwarnung (niedrig)**: < 16 KB (16.384 Bytes)
97+
- **Niedriger Speicher**: < 16 KB (16.384 Bytes) → Safe-Mode; automatischer Neustart, wenn er 5 Minuten anhält
9898
- **Kritischer Speicher**: < 8 KB (8.192 Bytes) → Automatischer Neustart
9999

100100
#### Verhalten
101101

102102
1. **Alle 10 Sekunden**: Speicherprüfung wird durchgeführt
103-
2. **Niedriger Speicher**: Warnung wird an Seriell und MQTT protokolliert
103+
2. **Niedriger Speicher**: Warnung wird an Seriell und MQTT protokolliert, Safe-Mode solange unter dem
104+
Schwellwert, automatischer Neustart nach 5 Minuten ohne Erholung
104105
3. **Kritischer Speicher**: Controller startet automatisch neu
105106
4. **Minimum-Tracking**: Zeichnet den niedrigsten Speicherstand seit Boot auf
106107

@@ -145,7 +146,7 @@ Zustandsspeicherung und Systemüberwachung sind **automatisch aktiviert**. Keine
145146
Zum Anpassen der Speicherschwellwerte `src/SystemMonitor.hpp` ändern:
146147

147148
```cpp
148-
// Speicherschwelle (niedrig) — nur Warnung
149+
// Speicherschwelle (niedrig) — Safe-Mode, Neustart nach LOW_MEMORY_REBOOT_AFTER_MS
149150
static constexpr uint32_t LOW_MEMORY_THRESHOLD = 8192; // 8 KB
150151

151152
// Kritische Speicherschwelle (automatischer Neustart)

‎docs/state-persistence.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -91,13 +91,14 @@ memory exhaustion.
9191

9292
**ESP32**:
9393

94-
- **Low Memory Warning**: < 16 KB (16,384 bytes)
94+
- **Low Memory**: < 16 KB (16,384 bytes) → safe mode; auto-reboot if it persists for 5 minutes
9595
- **Critical Memory**: < 8 KB (8,192 bytes) → Auto-reboot
9696

9797
#### Behavior
9898

9999
1. **Every 10 seconds**: Memory check performed
100-
2. **Low memory**: Warning logged to serial and MQTT
100+
2. **Low memory**: Warning logged to serial and MQTT, safe mode while below the threshold,
101+
auto-reboot after 5 minutes without recovery
101102
3. **Critical memory**: Controller automatically reboots to recover
102103
4. **Minimum tracking**: Tracks lowest memory point since boot
103104

@@ -142,7 +143,7 @@ Both state persistence and system monitoring are **automatically enabled**. No c
142143
To customize memory thresholds, modify `src/SystemMonitor.hpp`:
143144

144145
```cpp
145-
// Low memory threshold (warning only)
146+
// Low memory threshold (safe mode, reboot after LOW_MEMORY_REBOOT_AFTER_MS)
146147
static constexpr uint32_t LOW_MEMORY_THRESHOLD = 8192; // 8 KB
147148

148149
// Critical memory threshold (auto-reboot)

‎src/DegradationManager.cpp‎

Lines changed: 8 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ void DegradationManager::onTransition() {
149149

150150
case DegradationLevel::NO_TIME:
151151
LOG_WARN("⚠ NTP time sync lost — timer scheduling degraded\n");
152-
LOG_WARN(" Timer mode falls back to auto mode\n");
152+
LOG_WARN(" Timer schedule unavailable — filter pump stays on in auto/timer mode\n");
153153
break;
154154

155155
case DegradationLevel::NO_SENSOR:
@@ -158,25 +158,12 @@ void DegradationManager::onTransition() {
158158
break;
159159

160160
case DegradationLevel::CRITICAL:
161-
// Log the concrete reason for entering safe mode. Priority mirrors
162-
// evaluateLevel(): forced (boot-loop) > low memory > multiple failures.
161+
// Log the concrete reason for entering safe mode: forced (boot-loop)
162+
// or critically low memory — see classifyDegradation().
163163
if (forcedSafeMode_) {
164164
LOG_ERROR("✖ SAFE MODE — reason: boot-loop detected (safe mode forced)\n");
165-
} else if (!SystemMonitor::isHealthy()) {
166-
LOG_ERROR("✖ SAFE MODE — reason: critically low free heap (%.1f KB)\n", ESP.getFreeHeap() / 1024.0f);
167165
} else {
168-
LOG_ERROR("✖ SAFE MODE — reason: multiple concurrent failures\n");
169-
if (!NetworkManager::isWiFiConnected()) {
170-
LOG_ERROR(" - WiFi/MQTT disconnected\n");
171-
}
172-
// NTP loss while WiFi is down is a consequence, not an independent
173-
// failure — mirror the counting logic in evaluateLevel().
174-
if (NetworkManager::isWiFiConnected() && getTimeDegradation() == TimeDegradation::RED) {
175-
LOG_ERROR(" - NTP time sync lost\n");
176-
}
177-
if (sensorsEverReported_ && !(poolSensorOk_ && solarSensorOk_)) {
178-
LOG_ERROR(" - temperature sensor fault\n");
179-
}
166+
LOG_ERROR("✖ SAFE MODE — reason: critically low free heap (%.1f KB)\n", ESP.getFreeHeap() / 1024.0f);
180167
}
181168
LOG_ERROR(" Entering safe mode — all relays off\n");
182169
// De-energize both relays immediately (P1 review fix)
@@ -193,53 +180,20 @@ void DegradationManager::onTransition() {
193180
}
194181

195182
DegradationLevel DegradationManager::evaluateLevel() {
196-
// Gather system health signals
197183
bool wifiOk = NetworkManager::isWiFiConnected();
198184

199-
// If time is RED (lost) but WiFi is up, try an NTP sync immediately.
200-
// The Time library only syncs every SYNC_INTERVAL (3600s), so without
201-
// this the system could stay in NO_TIME for an hour after NTP recovers.
185+
// Trigger an NTP retry when WiFi is up but time is RED
202186
if (wifiOk && (getTimeDegradation() == TimeDegradation::RED)) {
203187
forceNtpUpdate();
204188
}
205189

206-
// Time is OK for GREEN + YELLOW (millis() estimate is usable up to 24h)
207190
bool timeOk = (getTimeDegradation() != TimeDegradation::RED);
208191
bool memoryOk = SystemMonitor::isHealthy();
209192
bool sensorOk = sensorsEverReported_ ? (poolSensorOk_ && solarSensorOk_) : true; // Both probes must be healthy
210193

211-
// Count active failures (memory failure = CRITICAL immediately).
212-
// Time loss without WiFi is a consequence, not an independent failure —
213-
// counting both would escalate a plain WiFi outage to CRITICAL.
214-
uint8_t failureCount = 0;
215-
if (!wifiOk)
216-
failureCount++;
217-
if (!timeOk && wifiOk)
218-
failureCount++;
219-
if (!sensorOk)
220-
failureCount++;
221-
222-
// --- Decision logic ---
223-
224-
// Memory critical → always CRITICAL (may reboot soon anyway)
225-
if (!memoryOk) {
226-
return DegradationLevel::CRITICAL;
227-
}
228-
229-
// Multiple concurrent failures → CRITICAL
230-
if (failureCount >= 2) {
231-
return DegradationLevel::CRITICAL;
232-
}
233-
234-
// Single failures — return the most specific level
235-
if (!sensorOk)
236-
return DegradationLevel::NO_SENSOR;
237-
if (!timeOk)
238-
return DegradationLevel::NO_TIME;
239-
if (!wifiOk)
240-
return DegradationLevel::NO_WIFI;
241-
242-
return DegradationLevel::NORMAL;
194+
// Combinations of WiFi/time/sensor problems are not a reason to stop the
195+
// filter pump — see classifyDegradation().
196+
return classifyDegradation(wifiOk, timeOk, sensorOk, memoryOk);
243197
}
244198

245199
} // namespace PoolController

‎src/DegradationManager.hpp‎

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -31,19 +31,9 @@
3131

3232
#include <atomic>
3333

34-
namespace PoolController {
34+
#include "DegradationPolicy.hpp"
3535

36-
/**
37-
* System degradation levels.
38-
* Order matters: higher numeric value = worse state.
39-
*/
40-
enum class DegradationLevel : uint8_t {
41-
NORMAL = 0, // Everything nominal
42-
NO_WIFI = 1, // WiFi/MQTT disconnected — local operation still works
43-
NO_TIME = 2, // NTP sync lost — timer-based scheduling degraded
44-
NO_SENSOR = 3, // One or more temperature sensors failed — cautious defaults
45-
CRITICAL = 4, // Multiple failures or critically low memory — safe mode
46-
};
36+
namespace PoolController {
4737

4838
/**
4939
* Central health monitor.
@@ -76,8 +66,9 @@ class DegradationManager {
7666
static DegradationLevel getLevel();
7767

7868
/**
79-
* True when level >= CRITICAL — system should enter safe mode
80-
* (all relays off, minimal operations only).
69+
* True when level >= CRITICAL — system is in safe mode
70+
* (all relays off, minimal operations only). Only critically low memory
71+
* or a forced safe mode (boot loop) lead to CRITICAL.
8172
*/
8273
static bool isSafe();
8374

‎src/DegradationPolicy.hpp‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
// Copyright (c) 2018-2026 Smart Swimming Pool, Stephan Strittmatter
2+
//
3+
// SPDX-License-Identifier: MIT
4+
5+
/**
6+
* @file DegradationPolicy.hpp
7+
* @brief Pure, hardware-independent degradation rules (level classification
8+
* and persistent low-heap detection), shared by DegradationManager
9+
* and SystemMonitor and covered by native unit tests.
10+
*/
11+
12+
#pragma once
13+
14+
#include <cstdint>
15+
16+
namespace PoolController {
17+
18+
/**
19+
* System degradation levels.
20+
* Order matters: higher numeric value = worse state.
21+
*/
22+
enum class DegradationLevel : uint8_t {
23+
NORMAL = 0, // Everything nominal
24+
NO_WIFI = 1, // WiFi/MQTT disconnected — local operation still works
25+
NO_TIME = 2, // NTP sync lost — timer-based scheduling degraded
26+
NO_SENSOR = 3, // One or more temperature sensors failed — cautious defaults
27+
CRITICAL = 4, // Critically low memory or forced (boot-loop) — safe mode
28+
};
29+
30+
/**
31+
* @brief Classify the system state into a degradation level.
32+
*
33+
* Only conditions that make relay operation itself unsafe lead to CRITICAL
34+
* (safe mode, all relays off). Connectivity, time and sensor problems — also
35+
* in combination — never stop the filter pump: the rules already switch the
36+
* solar pump off on invalid temperatures, and the filter pump keeps following
37+
* the timer (or runs continuously when the time is unknown) for water hygiene.
38+
*
39+
* @param wifiOk WiFi connected
40+
* @param timeOk time degradation is not RED
41+
* @param sensorOk both temperature sensors healthy (or not yet reported)
42+
* @param memoryOk free heap above the low-memory threshold
43+
*/
44+
inline DegradationLevel classifyDegradation(bool wifiOk, bool timeOk, bool sensorOk, bool memoryOk) {
45+
if (!memoryOk) {
46+
return DegradationLevel::CRITICAL;
47+
}
48+
if (!sensorOk) {
49+
return DegradationLevel::NO_SENSOR;
50+
}
51+
if (!timeOk) {
52+
return DegradationLevel::NO_TIME;
53+
}
54+
if (!wifiOk) {
55+
return DegradationLevel::NO_WIFI;
56+
}
57+
return DegradationLevel::NORMAL;
58+
}
59+
60+
/**
61+
* @brief Detects a low-memory condition that persists for too long.
62+
*
63+
* Feed it periodically with the current low-memory state. update() returns
64+
* true once the condition has been active without interruption for at least
65+
* @p limitMs. Uses unsigned arithmetic, so millis() wrap-around is handled.
66+
*/
67+
class PersistentConditionTimer {
68+
public:
69+
bool update(uint32_t nowMs, bool conditionActive, uint32_t limitMs) {
70+
if (!conditionActive) {
71+
active_ = false;
72+
return false;
73+
}
74+
if (!active_) {
75+
active_ = true;
76+
sinceMs_ = nowMs;
77+
return false;
78+
}
79+
return (nowMs - sinceMs_) >= limitMs;
80+
}
81+
82+
void reset() { active_ = false; }
83+
84+
private:
85+
bool active_ = false;
86+
uint32_t sinceMs_ = 0;
87+
};
88+
89+
} // namespace PoolController

‎src/SystemMonitor.cpp‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,6 @@ namespace PoolController {
1515
uint32_t SystemMonitor::lastMemoryCheck = 0;
1616
uint32_t SystemMonitor::minFreeHeap = 0;
1717
bool SystemMonitor::lowMemoryWarning = false;
18+
PersistentConditionTimer SystemMonitor::lowMemoryTimer;
1819

1920
} // namespace PoolController

0 commit comments

Comments
 (0)