Skip to content

Commit 56c140e

Browse files
committed
fix(commands): clear emptied sensor roles, apply time-loss pair, report timer persistence
- Web sensor mapping: an empty role field now clears that role, so moving a probe between roles cannot leave one probe assigned to both. - Time-loss bounds: the runtime applies the validated green/red pair after the batch instead of replaying each bound against stale values. - Timer: persist the four timer keys before applying; a failed write returns PERSIST_FAILED and keeps the previous timer. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012JY8RZscs5W8tLQMuZB95K
1 parent c0d8c51 commit 56c140e

5 files changed

Lines changed: 148 additions & 17 deletions

File tree

‎src/ControllerCommandHandler.cpp‎

Lines changed: 50 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
#include "LogCapture.hpp"
1616
#include "OperationModeNode.hpp"
1717
#include "RelayModuleNode.hpp"
18+
#include "StateManager.hpp"
1819
#include "TimeClientHelper.hpp"
1920

2021
#ifdef NORVI_AE01_R
@@ -57,6 +58,16 @@ std::uint16_t *buttonThreshold(Settings &settings, ControllerCommandType type) {
5758
}
5859
}
5960

61+
/** @brief Writes the four timer keys; the timer lives outside the settings record. */
62+
bool persistTimer(const TimerSetting &timer) {
63+
bool ok = true;
64+
ok = StateManager::saveInt("timerStartH", timer.timerStartHour) && ok;
65+
ok = StateManager::saveInt("timerStartM", timer.timerStartMinutes) && ok;
66+
ok = StateManager::saveInt("timerEndH", timer.timerEndHour) && ok;
67+
ok = StateManager::saveInt("timerEndM", timer.timerEndMinutes) && ok;
68+
return ok;
69+
}
70+
6071
bool isValidTime(const ControllerCommand &command) {
6172
return command.hour <= 23 && command.minute <= 59;
6273
}
@@ -77,6 +88,8 @@ struct ControllerCommandHandler::Plan final {
7788
bool timeLossChanged{false};
7889
bool mappingLoaded{false};
7990
bool mappingChanged{false};
91+
bool timerChanged{false};
92+
TimerSetting timer{};
8093
std::uint8_t solarAddress[8]{};
8194
std::uint8_t poolAddress[8]{};
8295
};
@@ -136,6 +149,14 @@ CommandStatus ControllerCommandHandler::execute(
136149
return CommandStatus::PERSIST_FAILED;
137150
}
138151
}
152+
const TimerSetting previousTimer = dependencies_.operationMode.getTimerSetting();
153+
if (plan.timerChanged && !persistTimer(plan.timer)) {
154+
LOG_ERROR("Controller command: failed to persist timer\n");
155+
if (!persistTimer(previousTimer)) {
156+
LOG_ERROR("Controller command: could not restore the previous timer in NVS\n");
157+
}
158+
return CommandStatus::PERSIST_FAILED;
159+
}
139160
if (plan.settingsChanged) {
140161
const Settings previousSettings = liveSettings;
141162
const NtpSettings previousNtp = liveNtp;
@@ -150,6 +171,9 @@ CommandStatus ControllerCommandHandler::execute(
150171
if (!ConfigManager::save()) {
151172
LOG_ERROR("Controller command: could not restore previous settings in NVS\n");
152173
}
174+
if (plan.timerChanged && !persistTimer(previousTimer)) {
175+
LOG_ERROR("Controller command: could not restore the previous timer in NVS\n");
176+
}
153177
return CommandStatus::PERSIST_FAILED;
154178
}
155179
}
@@ -167,6 +191,15 @@ CommandStatus ControllerCommandHandler::execute(
167191
for (std::size_t i = 0; i < count; ++i) {
168192
applySensorMapping(commands[i], plan);
169193
}
194+
for (std::size_t i = 0; i < count; ++i) {
195+
if (commands[i].type == ControllerCommandType::SET_TIME_LOSS_GREEN_HOURS ||
196+
commands[i].type == ControllerCommandType::SET_TIME_LOSS_RED_HOURS) {
197+
// The validated pair from the plan, green first so red clamps against it.
198+
setTimeDegradationGreenHours(static_cast<std::uint8_t>(plan.settings.timeLossGreenHours));
199+
setTimeDegradationRedHours(static_cast<std::uint8_t>(plan.settings.timeLossRedHours));
200+
break;
201+
}
202+
}
170203
return CommandStatus::APPLIED;
171204
}
172205

@@ -240,7 +273,21 @@ CommandStatus ControllerCommandHandler::stage(const ControllerCommand &command,
240273

241274
case ControllerCommandType::SET_TIMER_START:
242275
case ControllerCommandType::SET_TIMER_END:
243-
return isValidTime(command) ? CommandStatus::APPLIED : CommandStatus::INVALID;
276+
if (!isValidTime(command)) {
277+
return CommandStatus::INVALID;
278+
}
279+
if (!plan.timerChanged) {
280+
plan.timer = dependencies_.operationMode.getTimerSetting();
281+
plan.timerChanged = true;
282+
}
283+
if (command.type == ControllerCommandType::SET_TIMER_START) {
284+
plan.timer.timerStartHour = command.hour;
285+
plan.timer.timerStartMinutes = command.minute;
286+
} else {
287+
plan.timer.timerEndHour = command.hour;
288+
plan.timer.timerEndMinutes = command.minute;
289+
}
290+
return CommandStatus::APPLIED;
244291

245292
case ControllerCommandType::SET_SENSOR_MAPPING:
246293
case ControllerCommandType::CLEAR_SENSOR_MAPPING:
@@ -318,10 +365,9 @@ void ControllerCommandHandler::applyRuntime(const ControllerCommand &command, Co
318365
setTimezoneIndex(command.integerValue);
319366
break;
320367
case ControllerCommandType::SET_TIME_LOSS_GREEN_HOURS:
321-
setTimeDegradationGreenHours(static_cast<std::uint8_t>(command.integerValue));
322-
break;
323368
case ControllerCommandType::SET_TIME_LOSS_RED_HOURS:
324-
setTimeDegradationRedHours(static_cast<std::uint8_t>(command.integerValue));
369+
// Applied as a pair once the whole batch is replayed (see execute()): the
370+
// runtime setters clamp each bound against the other one.
325371
break;
326372
case ControllerCommandType::SET_BUTTON_1_MIN:
327373
case ControllerCommandType::SET_BUTTON_1_MAX:

‎src/WebPortal.cpp‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1354,22 +1354,30 @@ void WebPortal::apiSaveSensorMapping() {
13541354
{"pool_addr", SensorRole::POOL, "Invalid pool address format"},
13551355
};
13561356

1357+
std::size_t assigned = 0;
13571358
for (const auto &role : roles) {
1358-
const String address = server_.hasArg(role.arg) ? server_.arg(role.arg) : String();
1359-
if (address.length() == 0) {
1360-
continue;
1359+
if (!server_.hasArg(role.arg)) {
1360+
continue; // role not part of this request
13611361
}
1362+
const String address = server_.arg(role.arg);
13621363
ControllerCommand &command = commands[count++];
1363-
command.type = ControllerCommandType::SET_SENSOR_MAPPING;
13641364
command.source = CommandSource::WEB;
13651365
command.sensorRole = role.role;
1366+
if (address.length() == 0) {
1367+
// An empty field is sent when the UI moved this role's probe elsewhere;
1368+
// keeping the old mapping would assign one probe to both roles.
1369+
command.type = ControllerCommandType::CLEAR_SENSOR_MAPPING;
1370+
continue;
1371+
}
1372+
command.type = ControllerCommandType::SET_SENSOR_MAPPING;
13661373
if (!CommandParsing::parseSensorAddress(address.c_str(), address.length(), command.sensorAddress)) {
13671374
server_.send(400, "application/json", jsonError(role.invalidMessage));
13681375
return;
13691376
}
1377+
++assigned;
13701378
}
13711379

1372-
if (count == 0) {
1380+
if (assigned == 0) {
13731381
server_.send(400, "application/json", jsonError("At least one sensor address required"));
13741382
return;
13751383
}

‎test/native/mocks/stubs.cpp‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -84,13 +84,21 @@ time_t getLastValidSyncTime() {
8484
bool forceNtpUpdate() {
8585
return true;
8686
}
87-
void setTimeDegradationGreenHours(uint8_t) {}
87+
// Mirrors the clamping of the real setters (red must stay above green).
88+
static uint8_t g_greenMaxHours = 1;
89+
static uint8_t g_redAfterHours = 24;
90+
void setTimeDegradationGreenHours(uint8_t hours) {
91+
g_greenMaxHours = (hours > 0) ? hours : 1;
92+
}
8893
uint8_t getTimeDegradationGreenHours() {
89-
return 1;
94+
return g_greenMaxHours;
95+
}
96+
void setTimeDegradationRedHours(uint8_t hours) {
97+
uint8_t minRed = g_greenMaxHours + 1;
98+
g_redAfterHours = (hours >= minRed && hours <= 72) ? hours : (minRed < 72 ? minRed : 72);
9099
}
91-
void setTimeDegradationRedHours(uint8_t) {}
92100
uint8_t getTimeDegradationRedHours() {
93-
return 24;
101+
return g_redAfterHours;
94102
}
95103

96104
// Controllable mock clock for timer-window tests. Defaults to epoch 0

‎test/native/tests/test_controller_command_handler.cpp‎

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
#include "ESP32TemperatureNode.hpp"
1111
#include "OperationModeNode.hpp"
1212
#include "RelayModuleNode.hpp"
13+
#include "TimeClientHelper.hpp"
1314
#include "test_assert.h"
1415

1516
extern void test_begin(const char *suite, const char *name);
@@ -461,6 +462,50 @@ static int test_time_loss_bounds_can_move_together() {
461462
return 0;
462463
}
463464

465+
static int test_time_loss_runtime_follows_validated_pair_in_any_order() {
466+
test_begin("ControllerCommandHandler", "RED listed before GREEN still leaves the runtime on the persisted pair");
467+
HandlerFixture fixture;
468+
auto &settings = PoolController::ConfigManager::getSettings();
469+
settings.timeLossGreenHours = 30;
470+
settings.timeLossRedHours = 48;
471+
setTimeDegradationGreenHours(30);
472+
setTimeDegradationRedHours(48);
473+
474+
ControllerCommand batch[2]{};
475+
batch[0].type = ControllerCommandType::SET_TIME_LOSS_RED_HOURS;
476+
batch[0].integerValue = 12;
477+
batch[1].type = ControllerCommandType::SET_TIME_LOSS_GREEN_HOURS;
478+
batch[1].integerValue = 10;
479+
ASSERT_EQ(fixture.handler.execute(batch, 2), CommandStatus::APPLIED);
480+
ASSERT_EQ(settings.timeLossGreenHours, 10);
481+
ASSERT_EQ(settings.timeLossRedHours, 12);
482+
ASSERT_EQ(getTimeDegradationGreenHours(), 10);
483+
ASSERT_EQ(getTimeDegradationRedHours(), 12);
484+
return 0;
485+
}
486+
487+
static int test_timer_persist_failure_is_reported_and_keeps_runtime() {
488+
test_begin("ControllerCommandHandler", "a failed timer write reports PERSIST_FAILED and keeps the previous timer");
489+
HandlerFixture fixture;
490+
TimerSetting before = fixture.operation.getTimerSetting();
491+
492+
ControllerCommand command{};
493+
command.type = ControllerCommandType::SET_TIMER_START;
494+
command.hour = (before.timerStartHour + 1) % 24;
495+
command.minute = 5;
496+
Preferences::s_failingPutKeys.insert("timerStartH");
497+
const CommandStatus failed = fixture.handler.execute(command);
498+
Preferences::s_failingPutKeys.clear();
499+
ASSERT_EQ(failed, CommandStatus::PERSIST_FAILED);
500+
ASSERT_EQ(fixture.operation.getTimerSetting().timerStartHour, before.timerStartHour);
501+
ASSERT_EQ(fixture.operation.getTimerSetting().timerStartMinutes, before.timerStartMinutes);
502+
503+
ASSERT_EQ(fixture.handler.execute(command), CommandStatus::APPLIED);
504+
ASSERT_EQ(fixture.operation.getTimerSetting().timerStartHour, command.hour);
505+
ASSERT_EQ(fixture.operation.getTimerSetting().timerStartMinutes, 5);
506+
return 0;
507+
}
508+
464509
static int test_factory_reset_keeps_relay_state_when_save_fails() {
465510
test_begin("ControllerCommandHandler", "factory reset clears relay/mode NVS only after the defaults were saved");
466511
HandlerFixture fixture;
@@ -562,7 +607,8 @@ int run_controller_command_handler_tests() {
562607
test_loop_interval_persistence_failure_keeps_runtime_unchanged, test_time_loss_thresholds_preserve_ordering,
563608
test_factory_reset_owns_runtime_reset_mutation, test_status_separates_invalid_rejected_and_persist_failures,
564609
test_batch_is_all_or_nothing, test_persist_failure_rolls_back_every_setting_kind, test_enter_manual_toggle_is_atomic,
565-
test_time_loss_bounds_can_move_together, test_factory_reset_keeps_relay_state_when_save_fails,
610+
test_time_loss_bounds_can_move_together, test_time_loss_runtime_follows_validated_pair_in_any_order,
611+
test_timer_persist_failure_is_reported_and_keeps_runtime, test_factory_reset_keeps_relay_state_when_save_fails,
566612
test_sensor_mapping_persist_failure_leaves_runtime_unchanged, test_mixed_mapping_and_settings_batch_is_rejected,
567613
test_factory_reset_failure_keeps_runtime_configuration};
568614
for (auto test : tests) {

‎test/native/tests/test_web_runtime_commands.cpp‎

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,29 @@ int test_absolute_mode() {
9595
return 0;
9696
}
9797

98+
int test_sensor_mapping_empty_role_clears_old_assignment() {
99+
test_begin("WebRuntimeCommands", "moving a probe to the other role clears the emptied role");
100+
resetRequest();
101+
wsCapture.args["solar_addr"] = "";
102+
wsCapture.args["pool_addr"] = "28AA000000000001";
103+
ASSERT_TRUE(PoolController::WebPortal::invokeRouteForTest("/api/sensors/map", HTTP_POST));
104+
ASSERT_EQ(wsCapture.lastStatusCode, 200);
105+
ASSERT_EQ(capturedCount, static_cast<std::size_t>(2));
106+
ASSERT_EQ(capturedCommands[0].type, ControllerCommandType::CLEAR_SENSOR_MAPPING);
107+
ASSERT_EQ(capturedCommands[0].sensorRole, PoolController::SensorRole::SOLAR);
108+
ASSERT_EQ(capturedCommands[1].type, ControllerCommandType::SET_SENSOR_MAPPING);
109+
ASSERT_EQ(capturedCommands[1].sensorRole, PoolController::SensorRole::POOL);
110+
111+
// Only empty fields would change nothing useful and stay rejected.
112+
resetRequest();
113+
wsCapture.args["solar_addr"] = "";
114+
wsCapture.args["pool_addr"] = "";
115+
ASSERT_TRUE(PoolController::WebPortal::invokeRouteForTest("/api/sensors/map", HTTP_POST));
116+
ASSERT_EQ(wsCapture.lastStatusCode, 400);
117+
ASSERT_TRUE(!dispatchCalled);
118+
return 0;
119+
}
120+
98121
int test_cycle_mode() {
99122
test_begin("WebRuntimeCommands", "cycle stays relative until the owner resolves it");
100123
resetRequest();
@@ -304,9 +327,9 @@ int run_web_runtime_command_tests() {
304327
PoolController::WebPortal::begin();
305328
int passed = 0;
306329
int failed = 0;
307-
int (*tests[])() = {test_mode_validation, test_absolute_mode, test_cycle_mode, test_pump_validation, test_relative_pumps,
308-
test_owner_rejection, test_status_codes_are_distinct, test_settings_form_is_one_batch,
309-
test_settings_form_rejects_malformed_numbers, test_factory_reset_restarts_only_when_applied,
330+
int (*tests[])() = {test_mode_validation, test_absolute_mode, test_sensor_mapping_empty_role_clears_old_assignment,
331+
test_cycle_mode, test_pump_validation, test_relative_pumps, test_owner_rejection, test_status_codes_are_distinct,
332+
test_settings_form_is_one_batch, test_settings_form_rejects_malformed_numbers, test_factory_reset_restarts_only_when_applied,
310333
test_sensor_mapping_is_a_command_batch, test_adapter_does_not_mutate_nodes};
311334
for (auto test : tests) {
312335
if (test() == 0) {

0 commit comments

Comments
 (0)