Skip to content

Commit 4a901d2

Browse files
committed
fix(config): detect single NVS write failures, store sensor mapping atomically
save() ignored the result of every put*, so it only failed when the NVS namespace could not be opened. A single failed write reported success and left a mix of new and old keys after reboot. save() now checks each write. The factory reset, command batch and calibration rollbacks rewrite the previous values after restoring RAM, so NVS matches the running configuration again. The sensor mapping was two putBytes() calls: a failed pool write left a new solar ROM next to the old pool ROM. Both roles are now one 16-byte record written in a single NVS operation. The legacy solar_adr/pool_adr keys are still read and removed on the next save; boot loads the mapping through ConfigManager instead of reading the keys directly. New native suite test/native/config_persistence builds the real ConfigManager against the Preferences mock with per-key write fault injection. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012JY8RZscs5W8tLQMuZB95K
1 parent b4eba68 commit 4a901d2

11 files changed

Lines changed: 316 additions & 52 deletions

File tree

‎.github/workflows/native-tests.yml‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,18 @@ jobs:
6868
working-directory: test/native/relay_safety
6969
run: ASAN_OPTIONS="detect_stack_use_after_return=1" ./build/test_relay_safety
7070

71+
- name: Configure CMake (config persistence tests)
72+
working-directory: test/native/config_persistence
73+
run: cmake -B build -S .
74+
75+
- name: Build config persistence tests
76+
working-directory: test/native/config_persistence
77+
run: cmake --build build
78+
79+
- name: Run config persistence tests
80+
working-directory: test/native/config_persistence
81+
run: ASAN_OPTIONS="detect_stack_use_after_return=1" ./build/test_config_persistence
82+
7183
- name: Generate lcov coverage report
7284
if: always()
7385
run: |

‎docs/norvi-ae01-r.de.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,10 @@ identifizierst du, welche Adresse zu Solar und welche zu Pool gehört.
168168
#### Funktionsweise
169169
170170
Die 8-Byte-ROM-Adresse jedes Sensors wird im NVS gespeichert (Preferences-Namespace
171-
`ds18b20`, Keys `solar_adr` und `pool_adr`). Bei jedem folgenden Boot sucht die
171+
`ds18b20`, Key `mapping`: Solar-ROM gefolgt von Pool-ROM, in einem einzigen
172+
NVS-Schreibvorgang gespeichert, damit das Paar nie halb aktualisiert ist; ältere
173+
Firmware nutzte die Keys `solar_adr` und `pool_adr`, die weiterhin gelesen
174+
werden). Bei jedem folgenden Boot sucht die
172175
Firmware auf dem Bus nach einem Gerät mit der gespeicherten Adresse. Wird es
173176
gefunden, wird es unabhängig von der Scan-Reihenfolge verwendet. Wird es nicht
174177
gefunden (z. B. nach Austausch), erscheint eine Warnung und die Rolle meldet

‎docs/norvi-ae01-r.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,9 @@ you can find the ROM addresses in the boot log and configure them via the Web UI
169169
#### How the Mapping Works
170170
171171
The 8-byte ROM address of each sensor is stored in NVS (Preferences namespace
172-
`ds18b20`, keys `solar_adr` and `pool_adr`). On every subsequent boot, the
172+
`ds18b20`, key `mapping`: solar ROM followed by pool ROM, written in one NVS
173+
operation so the pair is never half updated; older firmware used the keys
174+
`solar_adr` and `pool_adr`, which are still read). On every subsequent boot, the
173175
firmware scans the bus for a device matching the stored address. If found, that
174176
device is used — regardless of its bus scan position. If the stored sensor is
175177
not found (e.g., it was replaced), the firmware prints a warning and reports

‎src/CalibrationManager.cpp‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,7 @@ void CalibrationManager::saveThresholds() {
265265
s.btn3Min = prevBtn3Min;
266266
s.btn3Max = prevBtn3Max;
267267
s.btnNoPress = prevBtnNoPress;
268+
ConfigManager::save(); // best effort: undo keys a partial write already stored
268269

269270
status_.step = Step::ERROR;
270271
status_.message = "Failed to save thresholds — please retry";

‎src/ConfigManager.cpp‎

Lines changed: 78 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -134,48 +134,62 @@ bool ConfigManager::load() {
134134
return true;
135135
}
136136

137+
// Preferences::putString() returns the stored length, so 0 is a failure only
138+
// for a non-empty value; an empty string cannot be told apart from an error.
139+
static bool putStringChecked(Preferences &prefs, const char *key, const String &value) {
140+
return prefs.putString(key, value) == value.length();
141+
}
142+
137143
bool ConfigManager::save() {
138144
Preferences prefs;
139145
if (!prefs.begin(kNvsNamespace, false)) { // read-write mode
140146
LOG_ERROR("✖ Failed to open NVS config namespace for writing\n");
141147
return false;
142148
}
143149

144-
prefs.putString(kWifiSsid, wifi_.ssid);
145-
prefs.putString(kWifiPass, wifi_.password);
146-
147-
prefs.putString(kMqttHost, mqtt_.host);
148-
prefs.putUInt(kMqttPort, mqtt_.port);
149-
prefs.putString(kMqttUser, mqtt_.username);
150-
prefs.putString(kMqttPass, mqtt_.password);
151-
152-
prefs.putString(kNtpServer, ntp_.server);
153-
prefs.putLong(kNtpTz, ntp_.timezone);
154-
155-
prefs.putLong(kSetInterval, settings_.loopInterval);
156-
prefs.putDouble(kSetMaxPool, settings_.tempMaxPool);
157-
prefs.putDouble(kSetMinSolar, settings_.tempMinSolar);
158-
prefs.putDouble(kSetHyst, settings_.tempHysteresis);
159-
prefs.putString(kSetOpMode, settings_.opMode);
160-
prefs.putInt(kSetTzIdx, settings_.timezoneIndex);
161-
prefs.putUChar(kSetGreen, settings_.timeLossGreenHours);
162-
prefs.putUChar(kSetRed, settings_.timeLossRedHours);
163-
prefs.putDouble(kSetCircThresh, settings_.tempCircThreshold);
164-
prefs.putUShort(kSetCircFactor, settings_.tempCircFactor);
165-
prefs.putUShort(kSetCircMax, settings_.tempCircMaxRuntime);
166-
prefs.putUShort(kSetBtn1Min, settings_.btn1Min);
167-
prefs.putUShort(kSetBtn1Max, settings_.btn1Max);
168-
prefs.putUShort(kSetBtn2Min, settings_.btn2Min);
169-
prefs.putUShort(kSetBtn2Max, settings_.btn2Max);
170-
prefs.putUShort(kSetBtn3Min, settings_.btn3Min);
171-
prefs.putUShort(kSetBtn3Max, settings_.btn3Max);
172-
prefs.putUShort(kSetBtnNoPress, settings_.btnNoPress);
173-
174-
prefs.putString(kAdmPass, adminPasswordHash_);
175-
prefs.putBool(kCfgConfigured, configured_);
150+
// Every key is written even after a failure, so a retry or rollback rewrites
151+
// the whole namespace; the result reports whether all writes succeeded.
152+
bool ok = true;
153+
ok = putStringChecked(prefs, kWifiSsid, wifi_.ssid) && ok;
154+
ok = putStringChecked(prefs, kWifiPass, wifi_.password) && ok;
155+
156+
ok = putStringChecked(prefs, kMqttHost, mqtt_.host) && ok;
157+
ok = prefs.putUInt(kMqttPort, mqtt_.port) != 0 && ok;
158+
ok = putStringChecked(prefs, kMqttUser, mqtt_.username) && ok;
159+
ok = putStringChecked(prefs, kMqttPass, mqtt_.password) && ok;
160+
161+
ok = putStringChecked(prefs, kNtpServer, ntp_.server) && ok;
162+
ok = prefs.putLong(kNtpTz, ntp_.timezone) != 0 && ok;
163+
164+
ok = prefs.putLong(kSetInterval, settings_.loopInterval) != 0 && ok;
165+
ok = prefs.putDouble(kSetMaxPool, settings_.tempMaxPool) != 0 && ok;
166+
ok = prefs.putDouble(kSetMinSolar, settings_.tempMinSolar) != 0 && ok;
167+
ok = prefs.putDouble(kSetHyst, settings_.tempHysteresis) != 0 && ok;
168+
ok = putStringChecked(prefs, kSetOpMode, settings_.opMode) && ok;
169+
ok = prefs.putInt(kSetTzIdx, settings_.timezoneIndex) != 0 && ok;
170+
ok = prefs.putUChar(kSetGreen, settings_.timeLossGreenHours) != 0 && ok;
171+
ok = prefs.putUChar(kSetRed, settings_.timeLossRedHours) != 0 && ok;
172+
ok = prefs.putDouble(kSetCircThresh, settings_.tempCircThreshold) != 0 && ok;
173+
ok = prefs.putUShort(kSetCircFactor, settings_.tempCircFactor) != 0 && ok;
174+
ok = prefs.putUShort(kSetCircMax, settings_.tempCircMaxRuntime) != 0 && ok;
175+
ok = prefs.putUShort(kSetBtn1Min, settings_.btn1Min) != 0 && ok;
176+
ok = prefs.putUShort(kSetBtn1Max, settings_.btn1Max) != 0 && ok;
177+
ok = prefs.putUShort(kSetBtn2Min, settings_.btn2Min) != 0 && ok;
178+
ok = prefs.putUShort(kSetBtn2Max, settings_.btn2Max) != 0 && ok;
179+
ok = prefs.putUShort(kSetBtn3Min, settings_.btn3Min) != 0 && ok;
180+
ok = prefs.putUShort(kSetBtn3Max, settings_.btn3Max) != 0 && ok;
181+
ok = prefs.putUShort(kSetBtnNoPress, settings_.btnNoPress) != 0 && ok;
182+
183+
ok = putStringChecked(prefs, kAdmPass, adminPasswordHash_) && ok;
184+
ok = prefs.putBool(kCfgConfigured, configured_) != 0 && ok;
176185

177186
prefs.end();
178187

188+
if (!ok) {
189+
LOG_ERROR("✖ Failed to write configuration to NVS\n");
190+
return false;
191+
}
192+
179193
LOG_INFO("✓ Configuration saved to NVS\n");
180194
return true;
181195
}
@@ -221,6 +235,10 @@ bool ConfigManager::resetToDefaults() {
221235
settings_ = previousSettings;
222236
adminPasswordHash_ = previousAdminHash;
223237
configured_ = previousConfigured;
238+
// A single failed put may have left some keys at their defaults.
239+
if (!save()) {
240+
LOG_ERROR("✖ Could not restore the previous configuration in NVS\n");
241+
}
224242
return false;
225243
}
226244
LOG_INFO("✓ Configuration reset to factory defaults\n");
@@ -271,6 +289,10 @@ bool s_mappingCacheValid = false;
271289
std::uint8_t s_cachedSolarAddress[8] = {0};
272290
std::uint8_t s_cachedPoolAddress[8] = {0};
273291

292+
// Both roles in one value: solar ROM followed by pool ROM.
293+
constexpr const char *kSensorMappingKey = "mapping";
294+
constexpr size_t kSensorMappingRecordSize = 16;
295+
274296
struct SensorMappingReadResult final {
275297
bool readSucceeded{false};
276298
bool hasMapping{false};
@@ -285,6 +307,19 @@ SensorMappingReadResult readSensorMappingFromNvs(uint8_t solarAddr[8], uint8_t p
285307
return {};
286308
}
287309

310+
// The combined record is written in one NVS operation, so it always holds a
311+
// consistent pair. The legacy per-role keys are read only when it is absent.
312+
std::uint8_t record[kSensorMappingRecordSize] = {0};
313+
if (prefs.getBytes(kSensorMappingKey, record, sizeof(record)) == sizeof(record)) {
314+
prefs.end();
315+
memcpy(solarAddr, record, 8);
316+
memcpy(poolAddr, record + 8, 8);
317+
SensorMappingReadResult result;
318+
result.readSucceeded = true;
319+
result.hasMapping = true;
320+
return result;
321+
}
322+
288323
const size_t solarLength = prefs.getBytes("solar_adr", solarAddr, 8);
289324
const size_t poolLength = prefs.getBytes("pool_adr", poolAddr, 8);
290325
prefs.end();
@@ -310,7 +345,17 @@ bool ConfigManager::saveSensorMapping(const uint8_t solarAddr[8], const uint8_t
310345
LOG_ERROR("✖ Failed to open NVS sensor-mapping namespace for writing\n");
311346
return false;
312347
}
313-
const bool written = prefs.putBytes("solar_adr", solarAddr, 8) == 8 && prefs.putBytes("pool_adr", poolAddr, 8) == 8;
348+
// A single putBytes() is all-or-nothing in NVS, so a failed write leaves the
349+
// previous pair in place instead of a new solar and an old pool ROM.
350+
std::uint8_t record[kSensorMappingRecordSize];
351+
memcpy(record, solarAddr, 8);
352+
memcpy(record + 8, poolAddr, 8);
353+
const bool written = prefs.putBytes(kSensorMappingKey, record, sizeof(record)) == sizeof(record);
354+
if (written) {
355+
// The record takes precedence; dropping the legacy keys only tidies up.
356+
prefs.remove("solar_adr");
357+
prefs.remove("pool_adr");
358+
}
314359
prefs.end();
315360
if (!written) {
316361
LOG_ERROR("✖ Failed to write sensor mapping to NVS\n");

‎src/ControllerCommandHandler.cpp‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,11 @@ CommandStatus ControllerCommandHandler::execute(
145145
LOG_ERROR("Controller command: failed to persist runtime settings\n");
146146
liveSettings = previousSettings;
147147
liveNtp = previousNtp;
148+
// A single failed put may have stored part of the batch; rewrite the
149+
// previous values so NVS matches the unchanged runtime again.
150+
if (!ConfigManager::save()) {
151+
LOG_ERROR("Controller command: could not restore previous settings in NVS\n");
152+
}
148153
if (plan.mappingChanged && !ConfigManager::saveSensorMapping(previousSolar, previousPool)) {
149154
LOG_ERROR("Controller command: could not restore previous sensor mapping\n");
150155
}

‎src/PoolController.cpp‎

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -111,30 +111,26 @@ static void addressToString(const uint8_t addr[8], char *buf, size_t size) {
111111
* can resolve the address filter during bus scan.
112112
*/
113113
static void loadSensorAddressMapping() {
114-
Preferences prefs;
115-
prefs.begin("ds18b20", true); // read-only
116-
114+
// ConfigManager reads the combined record and falls back to the legacy keys;
115+
// an absent role is returned as an all-zero address.
117116
uint8_t solarAddr[8], poolAddr[8];
118-
size_t slen = prefs.getBytes("solar_adr", solarAddr, 8);
119-
size_t plen = prefs.getBytes("pool_adr", poolAddr, 8);
120-
121-
prefs.end();
117+
ConfigManager::loadSensorMapping(solarAddr, poolAddr);
122118

123-
if (slen == 8 && !isAddressZero(solarAddr)) {
119+
if (!isAddressZero(solarAddr)) {
124120
solarTemperatureNode.setAddressFilter(solarAddr);
125121
char buf[17];
126122
addressToString(solarAddr, buf, sizeof(buf));
127123
LOG_INFO("• Sensor mapping: Solar address loaded [%s]\n", buf);
128124
}
129125

130-
if (plen == 8 && !isAddressZero(poolAddr)) {
126+
if (!isAddressZero(poolAddr)) {
131127
poolTemperatureNode.setAddressFilter(poolAddr);
132128
char buf[17];
133129
addressToString(poolAddr, buf, sizeof(buf));
134130
LOG_INFO("• Sensor mapping: Pool address loaded [%s]\n", buf);
135131
}
136132

137-
if ((slen == 8 && !isAddressZero(solarAddr)) || (plen == 8 && !isAddressZero(poolAddr))) {
133+
if (!isAddressZero(solarAddr) || !isAddressZero(poolAddr)) {
138134
LOG_INFO("• Sensor mapping: address filters applied (one or both sensors)\n");
139135
} else {
140136
LOG_WARN("• Sensor mapping: no addresses configured — using default device indices\n");
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
cmake_minimum_required(VERSION 3.16)
2+
project(pool_controller_config_persistence_tests CXX)
3+
set(CMAKE_CXX_STANDARD 17)
4+
set(CMAKE_CXX_STANDARD_REQUIRED ON)
5+
6+
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -O0 -fsanitize=address -fno-omit-frame-pointer")
7+
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fsanitize=address -fno-omit-frame-pointer")
8+
9+
set(PROJ_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../../..")
10+
11+
# The real ConfigManager is compiled from src/ against the Preferences mock,
12+
# whose fault injection lets a single put fail. src/ comes before mocks/ so the
13+
# test sees the production header, not the ConfigManager mock used by
14+
# test_runner.
15+
include_directories(
16+
${PROJ_ROOT}/src
17+
${CMAKE_CURRENT_SOURCE_DIR}/../mocks
18+
)
19+
20+
add_executable(test_config_persistence
21+
${PROJ_ROOT}/src/ConfigManager.cpp
22+
${PROJ_ROOT}/src/LogCapture.cpp
23+
${CMAKE_CURRENT_SOURCE_DIR}/stubs.cpp
24+
${CMAKE_CURRENT_SOURCE_DIR}/test_config_persistence.cpp
25+
)
26+
27+
add_test(NAME config_persistence_test COMMAND test_config_persistence)
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// Copyright (c) 2018-2026 Smart Swimming Pool, Stephan Strittmatter
2+
// SPDX-License-Identifier: MIT
3+
4+
// Mock statics this suite links without the full test_runner captures.
5+
6+
#include <map>
7+
#include <set>
8+
#include <string>
9+
10+
#include "Arduino.h"
11+
12+
uint32_t g_millisOffset = 0;
13+
std::string SerialClass::s_capture;
14+
bool SerialClass::s_captureEnabled = false;
15+
std::map<std::string, std::string> Preferences::s_data;

0 commit comments

Comments
 (0)