diff --git a/ground_station/platformio.ini b/ground_station/platformio.ini index d9b2cf05..a6ffa67b 100644 --- a/ground_station/platformio.ini +++ b/ground_station/platformio.ini @@ -28,7 +28,7 @@ lib_deps = build_flags = -fexceptions ; Required by the Nayuki C++ QR encoder - -DFIRMWARE_VERSION='"1.3.2"' ; Enter Firmware Version here + -DFIRMWARE_VERSION='"1.3.3"' ; Enter Firmware Version here -DUSB_MANUFACTURER='"CATS"' ; USB Manufacturer string -DUSB_PRODUCT='"CATS Ground Station"' ; USB Product String -D USB_SERIAL="0" ; Enter Device Serial Number here diff --git a/ground_station/simulator/COVERAGE.md b/ground_station/simulator/COVERAGE.md index 757dd123..e74d6e1a 100644 --- a/ground_station/simulator/COVERAGE.md +++ b/ground_station/simulator/COVERAGE.md @@ -33,7 +33,7 @@ browser and compares its framebuffer. | Equator or prime-meridian fix | `qr-zero-coordinate.json`, `zero-coordinate` fixture | `zero-coordinate-qr` | Golden | Fixture smoke | | More than 11 logs | `log-management.json`, `many` fixture | `log-management` | Deterministic | Fixture smoke | | Legacy CSV names | `legacy-log-names.json` | `legacy-log-names` | Deterministic | — | -| Recording independent of screen | `recording-independent.json` | `screen-independent-recording` | Deterministic | — | +| Recording only in Live; confirmed exit and re-entry | `recording-live-only.json` | `live-only-recording` | Deterministic | — | | Automatic and Never-mode finalization | `recording-modes.json`, `never` fixture | `recording-modes` | Deterministic | Fixture smoke | | Malformed or partial log | `demo` fixture | — | Deterministic fixture load | Fixture smoke | | Deletion failure | `delete-failure` fixture | — | Deterministic fixture load | Fixture smoke | @@ -44,3 +44,6 @@ browser and compares its framebuffer. The explicit gaps are intentional: they stay visible here until a scenario and framebuffer assertion are added, instead of being implied by unrelated tests. + +The UI simulator models recording. Production recorder, filesystem, flash-cache, +and exit/scan regression checks are separate: see [recorder host tests](../tests/recorder_host/README.md). diff --git a/ground_station/simulator/gs_sim.py b/ground_station/simulator/gs_sim.py index 53a0fcdf..273664d3 100644 --- a/ground_station/simulator/gs_sim.py +++ b/ground_station/simulator/gs_sim.py @@ -323,6 +323,7 @@ def __init__(self, initial: dict[str, Any] | None = None, ready: bool = True, ba self.participant_mask = 0 self.touchdown_mask = 0 self.recorder_armed = True + self.live_exit_state = "none" self.completed_participants = 0 self.rearm_mask = 0 self.keyboard_index = 0 @@ -625,11 +626,10 @@ def ingest_recording(self) -> None: if not telemetry.get("updated", False): continue telemetry["updated"] = False + if self.screen != "live": + continue source_bit = 1 << index state = int(telemetry.get("state", 0)) - if state > 2 and self.state["deviceStatus"].get("usbStorageState", "firmware") != "firmware": - self.state["deviceStatus"]["usbStorageState"] = "firmware" - self.emit("usb_storage_reclaimed_for_logging") if not self.recorder_armed: if state <= 2: self.rearm_mask |= source_bit @@ -641,8 +641,11 @@ def ingest_recording(self) -> None: self.completed_participants = 0 self.recorded_rows = 0 continue - if state <= 2: + if state <= 2 or (not self.active_filename and state >= 7): continue + if self.state["deviceStatus"].get("usbStorageState", "firmware") != "firmware": + self.state["deviceStatus"]["usbStorageState"] = "firmware" + self.emit("usb_storage_reclaimed_for_logging") if self.state["deviceStatus"].get("recorderWriteFailure", False): self.recorder_state = "fault" continue @@ -747,6 +750,12 @@ def menu_step(self, pressed: set[str]) -> None: self.emit("menu_selection", value=self.menu_selection) if "ok" in pressed or "center" in pressed: self.screen = MENU_SCREENS[self.menu_selection] + if self.screen == "live": + self.live_exit_state = "none" + self.recorder_armed = True + self.touchdown_mask = self.rearm_mask = self.completed_participants = 0 + self.participant_mask = self.recorded_rows = self.dropped_rows = 0 + self.recorder_state = "idle" if self.screen == "sensors": self.sensor_view = "readings" if self.screen == "data": @@ -762,12 +771,33 @@ def menu_step(self, pressed: set[str]) -> None: self.render_screen() def live_step(self, pressed: set[str]) -> None: + if self.live_exit_state == "stop_failed": + if "back" in pressed: + self.live_exit_state = "none" + return + if self.live_exit_state == "confirm": + if "back" in pressed: + self.live_exit_state = "none" + elif "ok" in pressed: + if self.active_filename and not self.finalize_recording(): + self.live_exit_state = "stop_failed" + else: + self.recorder_state = "idle" + self.automatic_usb_share_pending = bool(self.state["deviceStatus"].get("usb", False)) + self.to_menu() + return + if "back" in pressed: + if self.active_filename: + self.live_exit_state = "confirm" + else: + self.recorder_state = "idle" + self.automatic_usb_share_pending = bool(self.state["deviceStatus"].get("usb", False)) + self.to_menu() + return if "right" in pressed: self.emit("live_view", text="gnss") if "left" in pressed: self.emit("live_view", text="downrange") - if "back" in pressed: - self.to_menu() def recovery_step(self, pressed: set[str]) -> None: if self.config().get("dualReceiver", False): @@ -1289,6 +1319,7 @@ def snapshot(self) -> dict[str, Any]: "settingsSelection": self.settings_selection, "dataSelection": self.data_selection, "dataStatistics": self.data_statistics, + "liveExitState": self.live_exit_state, "currentDataSubview": self.data_subview, "logCount": len(logs), "logScrollOffset": self.log_scroll_offset, @@ -1539,7 +1570,7 @@ def deterministic_test(root: Path) -> int: for scenario_name in ("startup-intro.json", "startup-static.json", "menu.json", "live.json", "testing-timeout.json", "sensors.json", "sensors-orientation.json", "settings.json", "settings-versions.json", "bootloader.json", "replay.json", "qr-recovery.json", "qr-data.json", "qr-no-fix.json", "qr-zero-coordinate.json", - "recording-independent.json", "recording-modes.json", "log-management.json", + "recording-live-only.json", "recording-modes.json", "log-management.json", "legacy-log-names.json", "usb-storage.json", "radio-update.json"): scenario_path = scenario_dir / scenario_name if scenario_path.exists(): diff --git a/ground_station/simulator/hmi_controller.cpp b/ground_station/simulator/hmi_controller.cpp index 92305b88..4942c963 100644 --- a/ground_station/simulator/hmi_controller.cpp +++ b/ground_station/simulator/hmi_controller.cpp @@ -47,6 +47,7 @@ void HmiController::start() { recoveryLocations_ = {}; clearQr(); liveDownrange_ = true; + liveExitState_ = "none"; sensorOrientation_ = false; keyboardActive_ = false; keyboardSelection_ = 0; @@ -231,7 +232,10 @@ void HmiController::enter(Screen screen) { screen_ == Screen::RadioUpdate; screen_ = screen; clearQr(); - if (screen_ == Screen::Live) liveDownrange_ = true; + if (screen_ == Screen::Live) { + liveDownrange_ = true; + liveExitState_ = logs_.startLiveRecording() ? "none" : "start_failed"; + } if (screen_ == Screen::Testing) { testingState_ = TestingState::Disclaimer; testingSelection_ = 0; @@ -292,6 +296,43 @@ void HmiController::menuStep(uint64_t nowMs) { } void HmiController::liveStep(uint64_t nowMs) { + if (liveExitState_ == "start_failed" || liveExitState_ == "stop_failed") { + if (pressed(HmiButton::Back)) { + if (liveExitState_ == "start_failed") { + if (logs_.stopLiveRecording()) enter(Screen::Menu); + } else { + liveExitState_ = "none"; + liveDownrange_ = true; + } + } + return; + } + if (liveExitState_ == "confirm") { + if (pressed(HmiButton::Back)) { + liveExitState_ = "none"; + liveDownrange_ = true; + } else if (pressed(HmiButton::Ok)) { + if (!logs_.stopLiveRecording()) { + liveExitState_ = "stop_failed"; + } else { + automaticUsbSharePending_ = device_.snapshot().usb; + enter(Screen::Menu); + } + } + return; + } + if (pressed(HmiButton::Back)) { + bool needsConfirmation = false; + if (logs_.stopLiveRecording(true, &needsConfirmation)) { + automaticUsbSharePending_ = device_.snapshot().usb; + enter(Screen::Menu); + } else if (needsConfirmation) { + liveExitState_ = "confirm"; + } else { + liveExitState_ = "stop_failed"; + } + return; + } if (pressed(HmiButton::Right)) { liveDownrange_ = false; emit("live_view", 0, 0, "gnss"); @@ -300,9 +341,6 @@ void HmiController::liveStep(uint64_t nowMs) { liveDownrange_ = true; emit("live_view", 0, 0, "downrange"); } - if (pressed(HmiButton::Back)) { - enter(Screen::Menu); - } (void)nowMs; } @@ -311,17 +349,21 @@ void HmiController::ingestTelemetry() { const auto first = link1_.snapshot(); const auto second = link2_.snapshot(); if (first.telemetry.updated) { - if (first.telemetry.state > 2 && device_.snapshot().usbStorageState != "firmware") { + if (screen_ == Screen::Live && first.telemetry.state > 2 && + (first.telemetry.state < 7 || !logs_.recorderStatus().activeFilename.empty()) && + device_.snapshot().usbStorageState != "firmware") { device_.requestFirmwareStorage(); } - logs_.record(first.telemetry, 1); + if (screen_ == Screen::Live) logs_.record(first.telemetry, 1); link1_.clearUpdates(); } if (second.telemetry.updated) { - if (second.telemetry.state > 2 && device_.snapshot().usbStorageState != "firmware") { + if (screen_ == Screen::Live && second.telemetry.state > 2 && + (second.telemetry.state < 7 || !logs_.recorderStatus().activeFilename.empty()) && + device_.snapshot().usbStorageState != "firmware") { device_.requestFirmwareStorage(); } - logs_.record(second.telemetry, 2); + if (screen_ == Screen::Live) logs_.record(second.telemetry, 2); link2_.clearUpdates(); } } @@ -889,6 +931,7 @@ HmiSnapshot HmiController::snapshot() const { result.settingsVersions = settingsVersions_; result.inputState = "idle"; result.liveView = liveDownrange_ ? "downrange" : "gnss"; + result.liveExitState = liveExitState_; result.sensorView = sensorOrientation_ ? "orientation" : "readings"; for (const bool held : input_.held) { if (held) { diff --git a/ground_station/simulator/hmi_controller.hpp b/ground_station/simulator/hmi_controller.hpp index aa0a8443..738db820 100644 --- a/ground_station/simulator/hmi_controller.hpp +++ b/ground_station/simulator/hmi_controller.hpp @@ -199,6 +199,8 @@ class ILogStore { virtual void configure(bool dual, bool neverStop) = 0; virtual void record(const TelemetrySample& sample, uint8_t link) = 0; virtual bool finalize() = 0; + virtual bool startLiveRecording() = 0; + virtual bool stopLiveRecording(bool onlyIfIdle = false, bool* needsConfirmation = nullptr) = 0; virtual bool remove(const std::string& name) = 0; }; @@ -227,6 +229,7 @@ struct HmiSnapshot { std::array settingsVersions{}; std::string inputState = "idle"; std::string liveView = "downrange"; + std::string liveExitState = "none"; std::string sensorView = "readings"; int16_t menuSelection = 0; int16_t testingSelection = 0; @@ -375,6 +378,7 @@ class HmiController { std::array recoveryLocations_{}; int8_t selectedRecoveryLink_ = 0; bool liveDownrange_ = true; + std::string liveExitState_ = "none"; bool sensorOrientation_ = false; bool keyboardActive_ = false; uint64_t versionLastRequest_ = 0; diff --git a/ground_station/simulator/scenarios/recording-independent.json b/ground_station/simulator/scenarios/recording-independent.json deleted file mode 100644 index 975de30e..00000000 --- a/ground_station/simulator/scenarios/recording-independent.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "initial": {"ready": true, "configuration": {"dualReceiver": true, "neverStopLogging": false}}, - "steps": [ - {"set": {"link1.telemetry.state": 3, "link1.telemetry.timestampDs": 10, "link1.telemetry.latitude": 33.7363, "link1.telemetry.longitude": 132.4829}}, - {"advance": 0}, - {"press": "right"}, - {"press": "ok"}, - {"assert": {"activeScreen": "recovery", "recorderState": "recording", "recordedRowCount": 1}}, - {"set": {"link2.telemetry.state": 3, "link2.telemetry.timestampDs": 11, "link2.telemetry.latitude": 33.7358, "link2.telemetry.longitude": 132.4762}}, - {"advance": 0}, - {"assert": {"activeScreen": "recovery", "recordedRowCount": 2}}, - {"set": {"link1.telemetry.state": 7, "link1.telemetry.timestampDs": 50}}, - {"advance": 0}, - {"assert": {"recorderState": "recording", "recordedRowCount": 3}}, - {"set": {"link2.telemetry.state": 7, "link2.telemetry.timestampDs": 51}}, - {"advance": 0}, - {"assert": {"recorderState": "idle", "recordedRowCount": 4, "logCount": 1}}, - {"set": {"link1.telemetry.state": 7, "link1.telemetry.timestampDs": 52}}, - {"advance": 0}, - {"assert": {"recorderState": "idle", "recordedRowCount": 4, "logCount": 1}}, - {"set": {"link1.telemetry.state": 2, "link2.telemetry.state": 2}}, - {"advance": 0}, - {"set": {"link1.telemetry.state": 3, "link1.telemetry.timestampDs": 1}}, - {"advance": 0}, - {"assert": {"recorderState": "recording", "recordedRowCount": 1, "logCount": 2}}, - {"snapshot": "screen-independent-recording"} - ] -} diff --git a/ground_station/simulator/scenarios/recording-live-only.json b/ground_station/simulator/scenarios/recording-live-only.json new file mode 100644 index 00000000..6bb66533 --- /dev/null +++ b/ground_station/simulator/scenarios/recording-live-only.json @@ -0,0 +1,61 @@ +{ + "initial":{"ready":true,"configuration":{"dualReceiver":true,"neverStopLogging":true},"logs":[{"name":"log_000.csv","csv":""}]}, + "steps":[ + {"set":{"link1.telemetry.state":3,"link1.telemetry.timestampDs":1}}, {"advance":0}, + {"assert":{"activeScreen":"menu","recorderState":"idle","logCount":1}}, + {"press":"right"}, {"press":"ok"}, + {"set":{"link2.telemetry.state":3,"link2.telemetry.timestampDs":1}}, {"advance":0}, + {"assert":{"activeScreen":"recovery","recorderState":"idle","logCount":1}}, + {"press":"back"}, {"press":"left"}, {"press":"ok"}, + {"set":{"link1.telemetry.timestampDs":2}}, {"advance":0}, + {"set":{"link2.telemetry.timestampDs":2}}, {"advance":0}, + {"assert":{"activeScreen":"live","recorderState":"recording","recordedRowCount":2,"logCount":2}}, + {"press":"back"}, + {"assert":{"activeScreen":"live","liveExitState":"confirm"}}, + {"set":{"link1.telemetry.timestampDs":3}}, {"advance":0}, + {"assert":{"recordedRowCount":3}}, + {"press":"back"}, {"assert":{"liveExitState":"none","recorderState":"recording"}}, + {"press":"back"}, {"press":"right"}, {"press":"left"}, {"press":"back"}, + {"assert":{"liveExitState":"none","recorderState":"recording"}}, + {"press":"back"}, + {"set":{"device.finalizeFailure":true}}, {"press":"ok"}, + {"assert":{"activeScreen":"live","liveExitState":"stop_failed","recorderState":"fault"}}, + {"press":"back"}, {"set":{"device.finalizeFailure":false}}, + {"press":"back"}, {"press":"ok"}, + {"assert":{"activeScreen":"menu","recorderState":"idle","logCount":2}}, + {"press":"down"}, {"press":"ok"}, {"press":"ok"}, + {"set":{"link1.telemetry.timestampDs":4}}, {"advance":0}, + {"assert":{"activeScreen":"data","currentDataSubview":"details","recorderState":"idle","recordedRowCount":3,"logCount":2}}, + {"press":"back"}, {"press":"back"}, {"press":"up"}, {"press":"ok"}, + {"set":{"link1.telemetry.timestampDs":5}}, {"advance":0}, + {"assert":{"activeScreen":"live","recorderState":"recording","recordedRowCount":1,"logCount":3,"activeFilename":"log_002.csv"}}, + {"press":"back"}, {"press":"ok"}, + {"press":"right"}, {"press":"right"}, {"press":"down"}, {"press":"ok"}, + {"set":{"link1.telemetry.timestampDs":6}}, {"advance":0}, + {"assert":{"activeScreen":"settings","recorderState":"idle","logCount":3}}, + {"press":"back"}, {"press":"left"}, {"press":"left"}, {"press":"up"}, {"press":"ok"}, + {"press":"back"}, + {"assert":{"activeScreen":"menu","recorderState":"idle","logCount":3}}, + {"press":"ok"}, + {"set":{"link1.telemetry.timestampDs":7}}, {"press":"back"}, + {"assert":{"activeScreen":"live","liveExitState":"confirm","recorderState":"recording","logCount":4}}, + {"press":"ok"}, + {"assert":{"activeScreen":"menu","recorderState":"idle","logCount":4}}, + {"set":{"config.neverStopLogging":false}}, {"press":"ok"}, + {"set":{"link1.telemetry.state":3,"link1.telemetry.timestampDs":8}}, {"advance":0}, + {"set":{"link1.telemetry.state":7,"link1.telemetry.timestampDs":9}}, {"advance":0}, + {"assert":{"recorderState":"idle","logCount":5}}, + {"press":"back"}, + {"assert":{"activeScreen":"menu","recorderState":"idle","logCount":5}}, + {"press":"ok"}, + {"set":{"link1.telemetry.state":7,"link1.telemetry.timestampDs":10}}, {"advance":0}, + {"set":{"link2.telemetry.state":7,"link2.telemetry.timestampDs":10}}, {"advance":0}, + {"assert":{"recorderState":"idle","logCount":5}}, + {"press":"back"}, {"assert":{"activeScreen":"menu","liveExitState":"none","logCount":5}}, + {"set":{"config.neverStopLogging":true}}, {"press":"ok"}, + {"set":{"link1.telemetry.timestampDs":11}}, {"advance":0}, + {"assert":{"recorderState":"idle","logCount":5}}, + {"press":"back"}, {"assert":{"activeScreen":"menu","liveExitState":"none","logCount":5}}, + {"snapshot":"live-only-recording"} + ] +} diff --git a/ground_station/simulator/scenarios/recording-modes.json b/ground_station/simulator/scenarios/recording-modes.json index f7077c88..b182e337 100644 --- a/ground_station/simulator/scenarios/recording-modes.json +++ b/ground_station/simulator/scenarios/recording-modes.json @@ -1,6 +1,7 @@ { "initial":{"ready":true,"configuration":{"dualReceiver":false,"neverStopLogging":false}}, "steps":[ + {"press":"ok"}, {"set":{"link1.telemetry.state":3,"link1.telemetry.timestampDs":1}}, {"advance":0}, {"set":{"link1.telemetry.state":7,"link1.telemetry.timestampDs":2}}, @@ -20,10 +21,10 @@ {"set":{"link1.telemetry.state":7,"link1.telemetry.timestampDs":2}}, {"advance":0}, {"assert":{"recorderState":"recording","recordedRowCount":2,"logCount":3}}, - {"press":"down"},{"press":"ok"},{"press":"ok"},{"press":"down"},{"press":"ok"}, - {"assert":{"currentDataSubview":"confirm_finalize","recorderState":"recording"}}, + {"press":"back"}, + {"assert":{"activeScreen":"live","liveExitState":"confirm","recorderState":"recording"}}, {"press":"ok"}, - {"assert":{"currentDataSubview":"list","recorderState":"idle","logCount":3}}, + {"assert":{"activeScreen":"menu","recorderState":"idle","logCount":3}}, {"snapshot":"recording-modes"} ] } diff --git a/ground_station/simulator/scenarios/usb-storage.json b/ground_station/simulator/scenarios/usb-storage.json index 3f21dfff..d3e78b7b 100644 --- a/ground_station/simulator/scenarios/usb-storage.json +++ b/ground_station/simulator/scenarios/usb-storage.json @@ -26,14 +26,14 @@ {"advance":0}, {"set":{"link1.telemetry.state":3,"link1.telemetry.timestampDs":12}}, {"advance":0}, - {"assert":{"recorderState":"recording","recordedRowCount":1,"usbStorageState":"firmware"}}, - {"press":"ok"}, - {"assert":{"activeScreen":"usb_storage","usbStorageState":"firmware","usbStorageMessage":"Finalize the active log first."}}, - {"press":"back"}, - {"assert":{"activeScreen":"settings","settingsPage":2,"settingsSelection":1}}, - {"set":{"link1.telemetry.state":7,"link1.telemetry.timestampDs":20}}, - {"advance":0}, + {"assert":{"recorderState":"idle","recordedRowCount":0,"usbStorageState":"firmware"}}, + {"press":"back"},{"press":"back"},{"press":"left"},{"press":"left"},{"press":"up"},{"press":"ok"}, + {"set":{"link1.telemetry.timestampDs":13}},{"advance":0}, + {"assert":{"activeScreen":"live","recorderState":"recording","recordedRowCount":1,"usbStorageState":"firmware"}}, + {"set":{"link1.telemetry.state":7,"link1.telemetry.timestampDs":20}},{"advance":0}, {"assert":{"recorderState":"idle","recordedRowCount":2,"usbStorageState":"host"}}, + {"press":"back"}, + {"assert":{"activeScreen":"menu","usbStorageState":"host"}}, {"snapshot":"usb-storage-handoff"} ] } diff --git a/ground_station/simulator/wasm_api.cpp b/ground_station/simulator/wasm_api.cpp index 4a9526f9..7c09416a 100644 --- a/ground_station/simulator/wasm_api.cpp +++ b/ground_station/simulator/wasm_api.cpp @@ -87,7 +87,7 @@ class Logs final : public ILogStore { } return; } - if (sample.state <= 2) return; + if (sample.state <= 2 || (activeIndex < 0 && sample.state >= 7)) return; if (failWrite) { status.state = "fault"; status.lastError = "Injected write failure"; @@ -132,6 +132,20 @@ class Logs final : public ILogStore { return true; } + bool startLiveRecording() override { + if (activeIndex >= 0) return false; + armed = true; + touchdownMask = rearmMask = completedParticipants = 0; + status = RecorderSnapshot{}; + return true; + } + bool stopLiveRecording(bool onlyIfIdle = false, bool* needsConfirmation = nullptr) override { + if (needsConfirmation != nullptr) *needsConfirmation = onlyIfIdle && activeIndex >= 0; + if (activeIndex >= 0) return !onlyIfIdle && finalize(); + status.state = "idle"; + return true; + } + bool remove(const std::string& name) override { if (failDelete) return false; const auto found = std::find_if(value.begin(), value.end(), [&](const FlightLogSnapshot& log) { @@ -506,6 +520,7 @@ void rebuildSnapshot() { return output; }() + "]" + ",\"liveView\":" + quote(state.liveView) + + ",\"liveExitState\":" + quote(state.liveExitState) + ",\"sensorView\":" + quote(state.sensorView) + ",\"testingState\":" + quote(state.testingState) + ",\"testingSelection\":" + std::to_string(state.testingSelection) + diff --git a/ground_station/simulator/web/browser-golden.json b/ground_station/simulator/web/browser-golden.json index 138c0192..58e16a58 100644 --- a/ground_station/simulator/web/browser-golden.json +++ b/ground_station/simulator/web/browser-golden.json @@ -13,7 +13,7 @@ "phoneHeading270": "54e15a0c450e58330c5f8b652772f2ddf55c3af6046051049cce274b89256e11", "phoneHeading315": "818b61f055e87eb5ebbd68a0bd01c8c96c953417af739a0d028f2ed8f58c2f18", "usbStorage": "cd4a76e556b38614ce3194c15fb40de92c012ab78f128d9624d4c3043047c089", - "recorderFault": "29c8f06ba5aa1cdb16e2e27044f6ccda914f19481d7dd05a3f4a7c847af052b3", + "recorderFault": "d23dd5aafd5a25f3f7ed5dcaa4fa2ff749b056eb1225397563c200614c8e3a2f", "liveNorthEast": "4d3632e0acd225a76dfc286f7380cd75cf760bcb5b09b5cd893a1ad9d6fce4be", "liveSouthWest": "289dd9e3c844104a384c6c8db1f3b0fa4bff7e9f04a3727c574ac69ec03afbad", "descentFourDigits": "e37a51b54fed98847534c5b39f2efe895ee0d3dd76986285acdc830e1a7931dd" diff --git a/ground_station/simulator/web/browser-tests.js b/ground_station/simulator/web/browser-tests.js index 969534c7..9eae289b 100644 --- a/ground_station/simulator/web/browser-tests.js +++ b/ground_station/simulator/web/browser-tests.js @@ -260,6 +260,16 @@ async function run() { assert(typeof state.activeScreen === 'string', `${fixture.id}: missing activeScreen`); assert(state.framebufferRevision > 0, `${fixture.id}: framebuffer was not rendered`); assert(bytes.length === 12000 && bytes.some(byte => byte !== 0), `${fixture.id}: invalid framebuffer`); + if (fixture.id === 'never' || fixture.id === 'finalize-failure') { + assert(state.activeScreen === 'live' && state.recorderState === 'recording' && state.activeFilename && state.recordedRowCount === 4, + `${fixture.id}: expected an active log including both touchdown samples`); + if (fixture.id === 'finalize-failure') { + tap(wasm, 'back'); tap(wasm, 'ok'); + const failed = snapshot(wasm); + assert(failed.activeScreen === 'live' && failed.liveExitState === 'stop_failed' && failed.activeFilename === state.activeFilename, + 'finalize-failure: failed close must retain the active log in Live'); + } + } } }); @@ -279,6 +289,90 @@ async function run() { captureSelfTest('Recorder fault status bar'); }); + await test('Live-only recording: confirmed exit, failure, and mid-flight re-entry', async () => { + const setLink = (index, value) => wasm.ccall('gs_set_link_json', null, ['string', 'string'], [String(index), JSON.stringify(value)]); + const setDevice = value => wasm.ccall('gs_set_device_status_json', null, ['string'], [JSON.stringify(value)]); + wasm.ccall('gs_reset', null, [], []); + wasm.ccall('gs_set_logs_json', null, ['string'], ['[]']); + wasm.ccall('gs_set_configuration_json', null, ['string'], ['{"dualReceiver":true,"neverStopLogging":true}']); + setDevice({usb: true}); + setLink(1, {state: 3, timestampDs: 10}); + assert(snapshot(wasm).recorderState === 'idle' && snapshot(wasm).logCount === 0, 'Menu does not record'); + assert(snapshot(wasm).usbStorageState === 'host', 'telemetry outside Live does not reclaim USB'); + tap(wasm, 'right'); tap(wasm, 'ok'); + setLink(2, {state: 3, timestampDs: 10}); + assert(snapshot(wasm).activeScreen === 'recovery' && snapshot(wasm).logCount === 0, 'Recovery does not record'); + tap(wasm, 'back'); tap(wasm, 'left'); tap(wasm, 'ok'); + setLink(1, {state: 3, timestampDs: 11, altitudeM: 100, velocityMps: 40, connected: true}); + setLink(2, {state: 3, timestampDs: 11, altitudeM: 110, velocityMps: 42, connected: true}); + let state = snapshot(wasm); + assert(state.recorderState === 'recording' && state.recordedRowCount === 2 && state.logCount === 1, 'Live records both links'); + assert(state.usbStorageState === 'firmware', 'recording reclaims USB'); + tap(wasm, 'back'); + state = snapshot(wasm); + assert(state.activeScreen === 'live' && state.liveExitState === 'confirm', 'Back asks only while recording'); + captureSelfTest('Leave Live - direct A and B actions'); + setLink(1, {state: 4, timestampDs: 12}); + assert(snapshot(wasm).recordedRowCount === 3, 'recording continues while confirmation is open'); + tap(wasm, 'left'); tap(wasm, 'right'); + assert(snapshot(wasm).liveExitState === 'confirm' && snapshot(wasm).recorderState === 'recording', 'direction buttons do not stop recording'); + tap(wasm, 'back'); + assert(snapshot(wasm).liveExitState === 'none' && snapshot(wasm).recorderState === 'recording', 'B returns to Live and keeps recording'); + captureSelfTest('Live after cancelling exit'); + assert(snapshot(wasm).logCount === 1, 'B does not restart the log'); + tap(wasm, 'back'); + setDevice({finalizeFailure: true}); tap(wasm, 'ok'); + assert(snapshot(wasm).activeScreen === 'live' && snapshot(wasm).liveExitState === 'stop_failed', 'failed stop stays in Live'); + captureSelfTest('Leave Live - stop failed'); + tap(wasm, 'back'); setDevice({finalizeFailure: false}); + tap(wasm, 'back'); tap(wasm, 'ok'); + assert(snapshot(wasm).activeScreen === 'menu' && snapshot(wasm).recorderState === 'idle', 'successful close leaves Live'); + tap(wasm, 'down'); tap(wasm, 'ok'); tap(wasm, 'ok'); + setLink(1, {state: 4, timestampDs: 13}); + assert(snapshot(wasm).currentDataSubview === 'details' && snapshot(wasm).recordedRowCount === 3, 'Data opens directly and does not record'); + tap(wasm, 'back'); tap(wasm, 'back'); tap(wasm, 'up'); tap(wasm, 'ok'); + setLink(1, {state: 4, timestampDs: 14}); + state = snapshot(wasm); + assert(state.recorderState === 'recording' && state.activeFilename === 'log_001.csv' && state.logCount === 2 && state.recordedRowCount === 1, + 'mid-flight re-entry creates a new segment without READY'); + tap(wasm, 'back'); tap(wasm, 'ok'); + tap(wasm, 'right'); tap(wasm, 'right'); tap(wasm, 'down'); tap(wasm, 'ok'); + setLink(1, {state: 4, timestampDs: 15}); + assert(snapshot(wasm).activeScreen === 'settings' && snapshot(wasm).logCount === 2 && snapshot(wasm).recorderState === 'idle', 'Settings does not record'); + + wasm.ccall('gs_reset', null, [], []); + wasm.ccall('gs_set_logs_json', null, ['string'], ['[]']); + tap(wasm, 'ok'); tap(wasm, 'back'); + assert(snapshot(wasm).activeScreen === 'menu' && snapshot(wasm).recorderState === 'idle' && snapshot(wasm).logCount === 0, + 'Back leaves immediately before recording starts'); + tap(wasm, 'ok'); + setLink(1, {state: 3, timestampDs: 20}); + setLink(1, {state: 7, timestampDs: 21}); + assert(snapshot(wasm).recorderState === 'idle', 'touchdown closes the log'); + tap(wasm, 'back'); + assert(snapshot(wasm).activeScreen === 'menu' && snapshot(wasm).logCount === 1, 'Back leaves immediately after recording finishes'); + + tap(wasm, 'ok'); + setLink(1, {state: 3, timestampDs: 22}); tap(wasm, 'back'); + setLink(1, {state: 7, timestampDs: 23}); tap(wasm, 'ok'); + assert(snapshot(wasm).activeScreen === 'menu' && snapshot(wasm).logCount === 2, 'A leaves if touchdown finishes recording while the prompt is open'); + for (const dualReceiver of [false, true]) { + for (const neverStopLogging of [false, true]) { + wasm.ccall('gs_reset', null, [], []); + wasm.ccall('gs_set_logs_json', null, ['string'], ['[]']); + wasm.ccall('gs_set_configuration_json', null, ['string'], [JSON.stringify({dualReceiver, neverStopLogging})]); + setDevice({usb: true}); + tap(wasm, 'ok'); + setLink(1, {state: 7, timestampDs: 30}); + setLink(2, {state: 7, timestampDs: 30}); + assert(snapshot(wasm).recorderState === 'idle' && snapshot(wasm).logCount === 0, 'DOWN re-entry never starts a log'); + assert(snapshot(wasm).usbStorageState === 'host', 'DOWN alone does not reclaim USB storage'); + tap(wasm, 'back'); + assert(snapshot(wasm).activeScreen === 'menu' && snapshot(wasm).liveExitState === 'none', 'B leaves DOWN without a prompt'); + } + } + }); + await test('framebuffer goldens', async () => { for (const [name, actual] of Object.entries(actualHashes)) { assert(goldens[name], `missing browser golden for ${name}`); @@ -1031,7 +1125,7 @@ async function run() { sample(1, 12); check(0, drogue, 'telemetry recovery retains the established phase and restarts confirmation'); advance(1900); sample(1, 12); check(0, drogue, 'stale time cannot count toward confirmation'); advance(100); sample(1, 12); check(0, main, 'fresh recovery samples can confirm Main'); - reset(38); sample(1, 12); tap(wasm, 'back'); advance(6000); sample(1, 12); tap(wasm, 'ok'); + reset(38); sample(1, 12); tap(wasm, 'back'); tap(wasm, 'ok'); advance(6000); sample(1, 12); tap(wasm, 'ok'); check(0, drogue, 'a telemetry gap cancels pending confirmation even while outside Live'); reset(10, 80); sample(1, 14); advance(1000); sample(2, 57); advance(1000); sample(1, 14); @@ -1053,7 +1147,7 @@ async function run() { sample(1, 14, {timestampDs: 32760}); advance(2000); sample(1, 14, {timestampDs: 12}); check(0, drogue, 'confirmation handles the 15-bit timestamp wrap'); - reset(10); tap(wasm, 'back'); advance(60000); + reset(10); tap(wasm, 'back'); tap(wasm, 'ok'); advance(60000); sample(1, 38, {timestampDs: 500}); tap(wasm, 'ok'); check(0, drogue, 'a restarted source timestamp after an outage initializes the new flight'); confirm(63, fast, 'confirmation continues on the restarted source timeline'); diff --git a/ground_station/simulator/web/coverage.json b/ground_station/simulator/web/coverage.json index 06503d10..59b8fd80 100644 --- a/ground_station/simulator/web/coverage.json +++ b/ground_station/simulator/web/coverage.json @@ -28,7 +28,7 @@ {"path": "Equator or prime-meridian fix", "scenario": "qr-zero-coordinate.json; zero-coordinate fixture", "snapshot": "zero-coordinate-qr", "framebuffer": "Golden", "browser": "Fixture smoke"}, {"path": "More than 11 logs", "scenario": "log-management.json; many fixture", "snapshot": "log-management", "framebuffer": "Deterministic", "browser": "Fixture smoke"}, {"path": "Legacy CSV names", "scenario": "legacy-log-names.json", "snapshot": "legacy-log-names", "framebuffer": "Deterministic", "browser": "—"}, - {"path": "Recording independent of screen", "scenario": "recording-independent.json", "snapshot": "screen-independent-recording", "framebuffer": "Deterministic", "browser": "—"}, + {"path": "Recording only in Live; confirmed exit and re-entry", "scenario": "recording-live-only.json", "snapshot": "live-only-recording", "framebuffer": "Deterministic", "browser": "—"}, {"path": "Automatic and Never-mode finalization", "scenario": "recording-modes.json; never fixture", "snapshot": "recording-modes", "framebuffer": "Deterministic", "browser": "Fixture smoke"}, {"path": "Malformed or partial log", "scenario": "demo fixture", "snapshot": "—", "framebuffer": "Deterministic fixture load", "browser": "Fixture smoke"}, {"path": "Deletion failure", "scenario": "delete-failure fixture", "snapshot": "—", "framebuffer": "Deterministic fixture load", "browser": "Fixture smoke"}, diff --git a/ground_station/simulator/web/fixtures.json b/ground_station/simulator/web/fixtures.json index 2bddf324..32773f45 100644 --- a/ground_station/simulator/web/fixtures.json +++ b/ground_station/simulator/web/fixtures.json @@ -76,6 +76,7 @@ {"logs": []}, {"configuration": {"dualReceiver": true, "neverStopLogging": false}}, {"navigation": {"homeLatitude": 33.6838649, "homeLongitude": 132.6331541, "northRad": 0.35}}, + {"tap": "ok"}, {"link": {"index": 1, "value": {"state": 3, "timestampDs": 10, "latitude": 33.7365, "longitude": 132.4881, "altitudeM": 120, "velocityMps": 42, "voltage": 4.1, "pyroContinuity": 3, "connected": true}}}, {"link": {"index": 2, "value": {"state": 3, "timestampDs": 10, "latitude": 33.7369, "longitude": 132.4874, "altitudeM": 110, "velocityMps": 39, "voltage": 4.1, "pyroContinuity": 3, "connected": true}}}, {"link": {"index": 1, "value": {"state": 5, "timestampDs": 20, "latitude": 33.7365, "longitude": 132.4881, "altitudeM": 1000, "velocityMps": 0, "voltage": 4.0, "pyroContinuity": 3, "connected": true}}}, @@ -83,7 +84,8 @@ {"link": {"index": 1, "value": {"state": 6, "timestampDs": 30, "latitude": 33.7365, "longitude": 132.4881, "altitudeM": 400, "velocityMps": -25, "voltage": 4.0, "pyroContinuity": 3, "connected": true}}}, {"link": {"index": 2, "value": {"state": 6, "timestampDs": 30, "latitude": 33.7369, "longitude": 132.4874, "altitudeM": 400, "velocityMps": -25, "voltage": 4.0, "pyroContinuity": 3, "connected": true}}}, {"link": {"index": 1, "value": {"state": 7, "timestampDs": 50, "latitude": 33.7365, "longitude": 132.4881, "altitudeM": 5, "velocityMps": 0, "voltage": 4.0, "pyroContinuity": 3, "connected": true}}}, - {"link": {"index": 2, "value": {"state": 7, "timestampDs": 50, "latitude": 33.7369, "longitude": 132.4874, "altitudeM": 5, "velocityMps": 0, "voltage": 4.0, "pyroContinuity": 3, "connected": true}}} + {"link": {"index": 2, "value": {"state": 7, "timestampDs": 50, "latitude": 33.7369, "longitude": 132.4874, "altitudeM": 5, "velocityMps": 0, "voltage": 4.0, "pyroContinuity": 3, "connected": true}}}, + {"tap": "back"} ] }, { @@ -102,6 +104,7 @@ {"logs": []}, {"configuration": {"dualReceiver": true, "neverStopLogging": false}}, {"navigation": {"homeLatitude": 33.6838649, "homeLongitude": 132.6331541, "northRad": 0.35}}, + {"tap": "ok"}, {"link": {"index": 1, "value": {"state": 3, "timestampDs": 10, "latitude": 33.7365, "longitude": 132.4881, "altitudeM": 120, "velocityMps": 42, "voltage": 4.1, "pyroContinuity": 3, "connected": true}}}, {"link": {"index": 2, "value": {"state": 2, "timestampDs": 10, "latitude": 0, "longitude": 0, "altitudeM": 110, "velocityMps": 39, "voltage": 4.1, "pyroContinuity": 3, "connected": true}}}, {"link": {"index": 1, "value": {"state": 5, "timestampDs": 20, "latitude": 33.7365, "longitude": 132.4881, "altitudeM": 1000, "velocityMps": 0, "voltage": 4.0, "pyroContinuity": 3, "connected": true}}}, @@ -109,7 +112,8 @@ {"link": {"index": 1, "value": {"state": 6, "timestampDs": 30, "latitude": 33.7365, "longitude": 132.4881, "altitudeM": 400, "velocityMps": -25, "voltage": 4.0, "pyroContinuity": 3, "connected": true}}}, {"link": {"index": 2, "value": {"state": 2, "timestampDs": 30, "latitude": 0, "longitude": 0, "altitudeM": 400, "velocityMps": -25, "voltage": 4.0, "pyroContinuity": 3, "connected": true}}}, {"link": {"index": 1, "value": {"state": 7, "timestampDs": 50, "latitude": 33.7365, "longitude": 132.4881, "altitudeM": 5, "velocityMps": 0, "voltage": 4.0, "pyroContinuity": 3, "connected": true}}}, - {"link": {"index": 2, "value": {"state": 2, "timestampDs": 50, "latitude": 0, "longitude": 0, "altitudeM": 5, "velocityMps": 0, "voltage": 4.0, "pyroContinuity": 3, "connected": true}}} + {"link": {"index": 2, "value": {"state": 2, "timestampDs": 50, "latitude": 0, "longitude": 0, "altitudeM": 5, "velocityMps": 0, "voltage": 4.0, "pyroContinuity": 3, "connected": true}}}, + {"tap": "back"} ] }, { @@ -124,10 +128,13 @@ { "id": "never", "label": "Active Never recording", - "description": "Creates an active dual-link log with Stop Logging set to Never. Recording remains active after touchdown until Finalize Log is confirmed.", + "description": "Creates an active dual-link log with Stop Logging set to Never. Recording remains active after touchdown until leaving Live is confirmed.", "operations": [ {"logs": []}, {"configuration": {"dualReceiver": true, "neverStopLogging": true}}, + {"tap": "ok"}, + {"link": {"index": 1, "value": {"state": 3, "timestampDs": 10, "connected": true}}}, + {"link": {"index": 2, "value": {"state": 3, "timestampDs": 10, "connected": true}}}, {"link": {"index": 1, "value": {"state": 7, "timestampDs": 50, "latitude": 33.7365, "longitude": 132.4881, "connected": true}}}, {"link": {"index": 2, "value": {"state": 7, "timestampDs": 50, "latitude": 33.7369, "longitude": 132.4874, "connected": true}}} ] @@ -167,6 +174,9 @@ "operations": [ {"logs": []}, {"configuration": {"dualReceiver": true, "neverStopLogging": true}}, + {"tap": "ok"}, + {"link": {"index": 1, "value": {"state": 3, "timestampDs": 10, "connected": true}}}, + {"link": {"index": 2, "value": {"state": 3, "timestampDs": 10, "connected": true}}}, {"link": {"index": 1, "value": {"state": 7, "timestampDs": 50, "latitude": 33.7365, "longitude": 132.4881, "connected": true}}}, {"link": {"index": 2, "value": {"state": 7, "timestampDs": 50, "latitude": 33.7369, "longitude": 132.4874, "connected": true}}}, {"deviceStatus": {"finalizeFailure": true}} @@ -178,6 +188,7 @@ "description": "Injects a storage write failure as recording starts. Use it to check the recorder fault state and crossed logging indicator.", "operations": [ {"logs": []}, + {"tap": "ok"}, {"deviceStatus": {"recorderWriteFailure": true}}, {"link": {"index": 1, "value": {"state": 3, "timestampDs": 10, "latitude": 33.7365, "longitude": 132.4881, "connected": true}}} ] diff --git a/ground_station/simulator/window_hmi_renderer.cpp b/ground_station/simulator/window_hmi_renderer.cpp index 46c6dd54..ebf1824b 100644 --- a/ground_station/simulator/window_hmi_renderer.cpp +++ b/ground_station/simulator/window_hmi_renderer.cpp @@ -111,6 +111,13 @@ void WindowHmiRenderer::render(const HmiSnapshot& state) { } } window_.updateLiveNavigation(telemetry_[0], telemetry_[1], &navigation_); + if (state.liveExitState == "confirm") { + window_.initLiveConfirmExit(); + } else if (state.liveExitState == "stop_failed") { + window_.initDataMessage("Stop Failed", "Unable to close recording"); + } else if (state.liveExitState == "start_failed") { + window_.initDataMessage("Log Error", "Unable to enable recording"); + } } else if (state.screen == "recovery") { if (state.qrView == "recovery_link_1") { window_.showLocationQr( diff --git a/ground_station/src/hmi/hmi.cpp b/ground_station/src/hmi/hmi.cpp index 23b84081..c56c0f27 100644 --- a/ground_station/src/hmi/hmi.cpp +++ b/ground_station/src/hmi/hmi.cpp @@ -36,7 +36,6 @@ void Hmi::begin() { recorder.begin(); recorder.configure(systemConfig.config.receiverMode, systemConfig.config.neverStopLogging); - recorder.enable(); link1.setPacketSink(&recorder, 1); link2.setPacketSink(&recorder, 2); static RadioUpdate::RadioFirmwareUpdater updater(recorder, link1, link2); @@ -136,7 +135,12 @@ void Hmi::menu() { if (okButton.wasPressed() || centerButton.wasPressed()) { state = static_cast(menuIndex + 1); if (state == LIVE) { - initLive(); + if (recorder.startLiveRecording()) { + initLive(); + } else { + liveExitState = LiveExitState::StartFailed; + window.initDataMessage("Log Error", "Unable to enable recording"); + } } else if (state == RECOVERY) { initRecovery(); } else if (state == TESTING) { @@ -154,7 +158,11 @@ void Hmi::menu() { /* LIVE */ void Hmi::initLive() { + liveExitState = LiveExitState::None; window.initLive(); + window.updateLive(&link1.data, &navigation, &link1.info, 0); + window.updateLive(&link2.data, &navigation, &link2.info, 1); + window.refresh(); lastLiveRefresh = millis(); } @@ -165,10 +173,48 @@ bool Hmi::liveButtonPending() const { } void Hmi::live() { + if (liveExitState == LiveExitState::StartFailed || liveExitState == LiveExitState::StopFailed) { + if (backButton.wasPressed()) { + if (liveExitState == LiveExitState::StartFailed) { + // Also cancel a start command whose acknowledgement may have timed out. + if (!recorder.stopLiveRecording()) return; + state = MENU; + window.initMenu(menuIndex); + } else { + initLive(); + } + } + return; + } + if (liveExitState == LiveExitState::Confirm) { + if (backButton.wasPressed()) { + initLive(); + } else if (okButton.wasPressed()) { + if (!recorder.stopLiveRecording()) { + liveExitState = LiveExitState::StopFailed; + window.initDataMessage("Stop Failed", "Unable to close recording"); + return; + } + state = MENU; + automaticUsbSharePending = Utils::isConnected(); + window.initMenu(menuIndex); + } + return; + } // Honour navigation before a full LCD transfer can delay button polling. if (backButton.wasPressed()) { - state = MENU; - window.initMenu(menuIndex); + bool needsConfirmation = false; + if (recorder.stopLiveRecording(true, &needsConfirmation)) { + state = MENU; + automaticUsbSharePending = Utils::isConnected(); + window.initMenu(menuIndex); + } else if (needsConfirmation) { + liveExitState = LiveExitState::Confirm; + window.initLiveConfirmExit(); + } else { + liveExitState = LiveExitState::StopFailed; + window.initDataMessage("Stop Failed", "Unable to close recording"); + } return; } if (rightButton.wasPressed()) { @@ -1298,7 +1344,8 @@ void Hmi::update(void *pvParameter) { if (ref->state != SELF_TEST && millis() - barUpdate >= 1000 && (ref->state != LIVE || !ref->liveButtonPending())) { barUpdate = millis(); const float voltage = static_cast(analogRead(18)) * 0.00062F; // 0.00059154929F; - if (!ref->isLogging && Utils::isFilesystemAvailable()) { + // Live can start/finalize recording after the status snapshot. Do not scan its shared FAT cache here. + if (ref->state != LIVE && !ref->isLogging && Utils::isFilesystemAvailable()) { ref->flashFreeMemory = Utils::getFlashMemoryUsage(); } if (link2.time.isUpdated()) { diff --git a/ground_station/src/hmi/hmi.hpp b/ground_station/src/hmi/hmi.hpp index e305e6b3..316a0862 100644 --- a/ground_station/src/hmi/hmi.hpp +++ b/ground_station/src/hmi/hmi.hpp @@ -85,6 +85,8 @@ class Hmi { SensorView sensorView = SensorView::Readings; uint32_t lastSensorRefresh = 0; uint32_t lastLiveRefresh = 0; + enum class LiveExitState : uint8_t { None, Confirm, StartFailed, StopFailed }; + LiveExitState liveExitState{LiveExitState::None}; Recorder recorder; RadioUpdate::RadioFirmwareUpdater* radioUpdater{nullptr}; diff --git a/ground_station/src/hmi/hmi_self_test.cpp b/ground_station/src/hmi/hmi_self_test.cpp index d41fa80a..66a9c847 100644 --- a/ground_station/src/hmi/hmi_self_test.cpp +++ b/ground_station/src/hmi/hmi_self_test.cpp @@ -45,9 +45,7 @@ void Hmi::startSelfTest() { return; } // The queue barrier drains any in-flight packet before touching storage. - recorder.disable(); if (!recorder.sync() || recorder.getStatus().state != RecorderState::Idle) { - recorder.enable(); window.initDataMessage("Self-test unavailable", "Recorder is busy. Try again."); return; } @@ -112,7 +110,6 @@ bool Hmi::testStorage() { void Hmi::leaveSelfTest() { navigation.enableSelfTestSampling(false); - recorder.enable(); automaticUsbSharePending = Utils::isConnected(); state = SETTINGS; window.initBar(); diff --git a/ground_station/src/hmi/window.cpp b/ground_station/src/hmi/window.cpp index ae82fdd9..a08ded2d 100644 --- a/ground_station/src/hmi/window.cpp +++ b/ground_station/src/hmi/window.cpp @@ -1156,6 +1156,20 @@ void Window::drawRecoveryHint(bool showHint) { display.print("last locations"); } +void Window::initLiveConfirmExit() { + display.fillRect(40, 50, 320, 150, WHITE); + display.drawRect(40, 50, 320, 150, BLACK); + display.setTextSize(1); + display.setTextColor(BLACK); + display.setFont(&FreeSans12pt7b); + drawCentreString("Recording in progress", 200, 82); + display.setFont(&FreeSans9pt7b); + drawCentreString("Main menu will stop recording.", 200, 111); + drawCentreString("B: Back to Live", 200, 151); + drawCentreString("A: Main menu", 200, 180); + surface.present(); +} + void Window::initBox(const char *text) { display.fillRect(60, 60, 280, 120, WHITE); display.drawRect(60, 60, 280, 120, BLACK); diff --git a/ground_station/src/hmi/window.hpp b/ground_station/src/hmi/window.hpp index fe2ec19b..c160522f 100644 --- a/ground_station/src/hmi/window.hpp +++ b/ground_station/src/hmi/window.hpp @@ -102,6 +102,7 @@ class Window { void drawSettingsTriangles(int16_t submenuIdx, int16_t color); void initBox(const char *text); + void initLiveConfirmExit(); void initKeyboard(char *text, uint32_t maxLength = 0); void drawKeyboard(char *text, int32_t keyHighlight, bool uppercase, uint32_t maxLength = 0); diff --git a/ground_station/src/logging/recorder.cpp b/ground_station/src/logging/recorder.cpp index 8bc215a8..d7d4e7b5 100644 --- a/ground_station/src/logging/recorder.cpp +++ b/ground_station/src/logging/recorder.cpp @@ -182,7 +182,7 @@ bool Recorder::finalizeFile(FinalizeReason reason [[maybe_unused]]) { return false; } const auto synced = file.sync(); - file.close(); + if (synced) file.close(); xSemaphoreGive(fsMutex); if (!synced) { setFault("Could not finalize log"); @@ -215,7 +215,8 @@ bool Recorder::deleteFile(const char* name) { return result; } -bool Recorder::submitAndWait(Command& command) { +bool Recorder::submitAndWait(Command& command, bool* needsConfirmation) { + if (needsConfirmation != nullptr) *needsConfirmation = false; if (!initialized) { return false; } @@ -231,12 +232,27 @@ bool Recorder::submitAndWait(Command& command) { return false; } if (response.requestId == command.requestId) { + if (needsConfirmation != nullptr) *needsConfirmation = response.needsConfirmation; return response.result; } } return false; } +bool Recorder::startLiveRecording() { + Command command{}; + command.type = CommandType::StartLive; + return submitAndWait(command); +} + +bool Recorder::stopLiveRecording(bool onlyIfIdle, bool* needsConfirmation) { + if (needsConfirmation != nullptr) *needsConfirmation = false; + if (!initialized) return true; + Command command{}; + command.type = onlyIfIdle ? CommandType::StopLiveIfIdle : CommandType::StopLive; + return submitAndWait(command, needsConfirmation); +} + bool Recorder::finalize(FinalizeReason reason) { Command command{}; command.type = CommandType::Finalize; @@ -293,6 +309,7 @@ void Recorder::recordTask(void* pvParameter) { continue; } bool result = true; + bool needsConfirmation = false; if (command.type == CommandType::Sample) { if (!ref->enabled || ref->radioUpdatePaused) { continue; @@ -313,7 +330,7 @@ void Recorder::recordTask(void* pvParameter) { portEXIT_CRITICAL(&ref->statusMux); } } - } else if (command.data.state > kReadyState) { + } else if (command.data.state > kReadyState && (ref->fileCreated || command.data.state < kTouchdownState)) { if (!Utils::isFilesystemAvailable() && !Utils::claimFirmwareStorage()) { ref->setFault("Storage unavailable for logging"); result = false; @@ -339,6 +356,29 @@ void Recorder::recordTask(void* pvParameter) { portEXIT_CRITICAL(&ref->statusMux); } else if (ref->radioUpdatePaused) { result = false; + } else if (command.type == CommandType::StartLive) { + result = !ref->fileCreated; + if (result) { + ref->armed = true; + ref->touchdownMask = ref->rearmMask = ref->completedParticipantMask = 0; + portENTER_CRITICAL(&ref->statusMux); + ref->status = RecorderStatus{}; + portEXIT_CRITICAL(&ref->statusMux); + ref->enabled = true; + } + } else if (command.type == CommandType::StopLive || command.type == CommandType::StopLiveIfIdle) { + // Process earlier samples before closing; later samples are ignored once + // this succeeds. A failed close leaves recording enabled in Live. + // Check idle here, after queued samples, so a new flight still gets a prompt. + needsConfirmation = command.type == CommandType::StopLiveIfIdle && ref->fileCreated; + result = !ref->fileCreated || + (command.type == CommandType::StopLive && ref->finalizeFile(FinalizeReason::UserRequested)); + if (result) { + ref->enabled = false; + portENTER_CRITICAL(&ref->statusMux); + ref->status.state = RecorderState::Idle; + portEXIT_CRITICAL(&ref->statusMux); + } } else if (command.type == CommandType::Finalize) { result = ref->finalizeFile(command.reason); } else if (command.type == CommandType::Sync) { @@ -369,7 +409,7 @@ void Recorder::recordTask(void* pvParameter) { } } if (command.requestId != 0U) { - const Response response{command.requestId, result}; + const Response response{command.requestId, result, needsConfirmation}; (void)xQueueSend(ref->responseQueue, &response, 0); } } diff --git a/ground_station/src/logging/recorder.hpp b/ground_station/src/logging/recorder.hpp index aaa72c23..311351bd 100644 --- a/ground_station/src/logging/recorder.hpp +++ b/ground_station/src/logging/recorder.hpp @@ -37,8 +37,8 @@ class Recorder : public ITelemetryPacketSink { explicit Recorder(const char* directory) : directory(directory) {} bool begin(); - void enable() { enabled = true; } - void disable() { enabled = false; } + bool startLiveRecording(); + bool stopLiveRecording(bool onlyIfIdle = false, bool* needsConfirmation = nullptr); void configure(ReceiverTelemetryMode_e mode, bool neverStop) { receiverMode = mode; neverStopLogging = neverStop; @@ -59,6 +59,9 @@ class Recorder : public ITelemetryPacketSink { private: enum class CommandType : uint8_t { Sample, + StartLive, + StopLive, + StopLiveIfIdle, Finalize, Sync, CatalogRefresh, @@ -77,6 +80,7 @@ class Recorder : public ITelemetryPacketSink { struct Response { uint32_t requestId{0}; bool result{false}; + bool needsConfirmation{false}; }; bool initialized{false}; @@ -111,7 +115,7 @@ class Recorder : public ITelemetryPacketSink { bool deleteFile(const char* name); bool scanCatalog(std::vector& entries); void setFault(const char* message); - bool submitAndWait(Command& command); + bool submitAndWait(Command& command, bool* needsConfirmation = nullptr); static bool isCsvLog(const char* name); static int32_t logNumber(const char* name); static void recordTask(void* pvParameter); diff --git a/ground_station/tests/recorder_host/Arduino.h b/ground_station/tests/recorder_host/Arduino.h new file mode 100644 index 00000000..d1d89a7c --- /dev/null +++ b/ground_station/tests/recorder_host/Arduino.h @@ -0,0 +1,83 @@ +// Copyright (C) 2026 Control and Telemetry Systems GmbH +// SPDX-License-Identifier: GPL-3.0-or-later + +// Host adapters only: the recorder and SdFat sources are compiled unchanged. +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +constexpr double PI = 3.141592653589793; +constexpr int LOW = 0; +constexpr int SS = 10; +using TickType_t = uint32_t; +constexpr int pdPASS = 1, pdTRUE = 1; +constexpr TickType_t portMAX_DELAY = UINT32_MAX; +inline TickType_t pdMS_TO_TICKS(uint32_t value) { return value; } +using portMUX_TYPE = std::mutex; +#define portMUX_INITIALIZER_UNLOCKED {} +inline void portENTER_CRITICAL(std::mutex* mutex) { mutex->lock(); } +inline void portEXIT_CRITICAL(std::mutex* mutex) { mutex->unlock(); } +struct HostQueue { + size_t capacity, itemSize; + std::mutex mutex; + std::condition_variable changed; + std::deque> items; + bool stopped = false; +}; +using QueueHandle_t = HostQueue*; +using SemaphoreHandle_t = std::timed_mutex*; +QueueHandle_t xQueueCreate(size_t capacity, size_t itemSize); +int xQueueSend(QueueHandle_t queue, const void* item, TickType_t timeout); +int xQueueReceive(QueueHandle_t queue, void* item, TickType_t timeout); +SemaphoreHandle_t xSemaphoreCreateMutex(); +int xSemaphoreTake(SemaphoreHandle_t mutex, TickType_t timeout); +void xSemaphoreGive(SemaphoreHandle_t mutex); +void xTaskCreate(void (*task)(void*), const char*, size_t, void* argument, int, void*); +inline void vTaskDelete(void*) {} +TickType_t xTaskGetTickCount(); +uint32_t millis(); +inline void vTaskDelay(TickType_t) {} +inline void vTaskDelayUntil(TickType_t*, TickType_t) {} +inline int digitalRead(int) { return 1; } +inline int analogRead(int) { return 4000; } +inline void setTime(int, int, int, int, int, int) {} +inline void adjustTime(long) {} + +namespace host { +extern std::function beforeReplyDelivery; +extern std::atomic clockOffset; +extern unsigned scans; +extern bool failSend; +void shutdown(); +} + +// Replace only the physical flash transport under the pinned FlashCache.cpp. +// Its 4 KiB erase/rewrite/cache logic is the actual library implementation. +#define ADAFRUIT_SPIFLASHBASE_H_ +#define SFLASH_SECTOR_SIZE 4096 +using std::min; +class Adafruit_SPIFlashBase { + public: + std::vector bytes; + uint32_t readBuffer(uint32_t address, uint8_t* buffer, uint32_t size) { + std::memcpy(buffer, bytes.data() + address, size); + return size; + } + uint32_t writeBuffer(uint32_t address, const uint8_t* buffer, uint32_t size) { + for (uint32_t i = 0; i < size; ++i) bytes.at(address + i) &= buffer[i]; + return size; + } + bool eraseSector(uint32_t sector) { + std::fill_n(bytes.begin() + sector * 4096, 4096, 0xff); + return true; + } +}; diff --git a/ground_station/tests/recorder_host/README.md b/ground_station/tests/recorder_host/README.md new file mode 100644 index 00000000..9473fd42 --- /dev/null +++ b/ground_station/tests/recorder_host/README.md @@ -0,0 +1,35 @@ + + + +# Recorder and filesystem regression test + +Run after PlatformIO has installed the pinned Ground Station dependencies: + +```sh +python3 ground_station/tests/recorder_host/run.py +``` + +Requires Linux (or WSL), Python 3, GCC/G++, and AddressSanitizer/UndefinedBehaviorSanitizer. +Generated files and results belong under `ground_station/.pio/recorder-host/`. + +This compiles the production `src/logging/recorder.cpp`, its real packet and configuration +headers, pinned SdFat sources, and pinned `Adafruit_FlashCache.cpp`. The recorder runs on +a worker thread with host queue/semaphore adapters. Flash erase/program operations use +an in-memory 960 KiB FAT12 volume formatted by the project's FatFs implementation. + +The runner also compiles the production `Hmi::live`, `Hmi::initLive`, `Hmi::update`, and +`Utils::getFlashMemoryUsage` function bodies, extracted verbatim on every run. Display, +buttons, timing, and unrelated HMI work use stand-ins. This checks the actual exit and +free-space guards without introducing test hooks into firmware. + +Coverage includes DOWN-only entry in both receiver modes and stop settings, mid-flight +segmentation, terminal samples, queued liftoff before exit, touchdown before exit-reply +delivery, cancellation, failed flush/retry, queue failure, and suppression outside Live. +Four existing logs and every generated log are checked by exact filename and complete +contents through fresh filesystem and flash-cache instances after each closed segment. +Three negative controls independently restore the old DOWN, exit, and free-space behavior; +each must fail its corresponding assertion. + +This does not emulate ESP32 FreeRTOS scheduling, physical flash failures, LCD/GPIO timing, +or Windows USB MSC. USB handoff/reclaim is a synchronous adapter that flushes, unmounts, +and remounts the actual filesystem. Physical qualification remains necessary. diff --git a/ground_station/tests/recorder_host/console.hpp b/ground_station/tests/recorder_host/console.hpp new file mode 100644 index 00000000..0d4da199 --- /dev/null +++ b/ground_station/tests/recorder_host/console.hpp @@ -0,0 +1,11 @@ +// Copyright (C) 2026 Control and Telemetry Systems GmbH +// SPDX-License-Identifier: GPL-3.0-or-later + +#pragma once +struct HostConsole { + struct Output { + void print(const char*) {} + void println(const char*) {} + } warning; +}; +inline HostConsole console; diff --git a/ground_station/tests/recorder_host/hmi_host.hpp b/ground_station/tests/recorder_host/hmi_host.hpp new file mode 100644 index 00000000..c960603e --- /dev/null +++ b/ground_station/tests/recorder_host/hmi_host.hpp @@ -0,0 +1,64 @@ +// Copyright (C) 2026 Control and Telemetry Systems GmbH +// SPDX-License-Identifier: GPL-3.0-or-later + +// Hardware stand-ins for compiling the real Hmi::live/initLive/update bodies. +// The test runner extracts those bodies verbatim; no navigation logic is copied. +#pragma once +#include "logging/recorder.hpp" +#include + +struct HostButton { + bool pressed = false; + bool wasPressed() { bool result = pressed; pressed = false; return result; } + void read() {} +}; +struct HostLink { + struct Datum { + bool isUpdated() { return false; } + bool isValid() { return false; } + int hour() { return 0; } + int minute() { return 0; } + int second() { return 0; } + } data, info, time, location; +}; +inline HostLink link1, link2; +inline int navigation; +struct Window { + enum class LiveState { kShowGnss, kShowDownRange }; + std::string message; + void initDataMessage(const char* title, const char*) { message = title; } + void initLiveConfirmExit() { message = "confirm"; } + void initLive() { message = "live"; } + void initMenu(int) { message = "menu"; } + void refresh() {} + template void updateLive(T...) {} + template bool updateLiveNavigation(T...) { return false; } + template void UpdateLiveState(T...) {} + template void updateBar(T...) {} + void initBar() {} + void logo() {} + void drawStartupIntroFrame(uint32_t) {} +}; +namespace StartupIntro { +constexpr uint32_t kDurationMs = 0, kFrameIntervalMs = 0, kStaticLogoDurationMs = 0; +} +constexpr uint32_t kLiveRefreshIntervalMs = 200; +struct Hmi { + enum State { MENU, LIVE, SELF_TEST }; + enum class LiveExitState { None, Confirm, StartFailed, StopFailed }; + explicit Hmi(Recorder& recorder) : recorder(recorder) {} + Recorder& recorder; + Window window; + State state = LIVE; + LiveExitState liveExitState = LiveExitState::None; + HostButton upButton, downButton, leftButton, rightButton, centerButton, okButton, backButton; + bool automaticUsbSharePending = false, initialized = true, isLogging = false; + int menuIndex = 0, flashFreeMemory = 0; + uint32_t lastLiveRefresh = 0; + bool liveButtonPending() const { return false; } + void initMenu() {} // Preserve the test's chosen screen for the update-loop probe. + void fsm() { host::clockOffset += 1000; initialized = false; } + void initLive(); + void live(); + static void update(void*); +}; diff --git a/ground_station/tests/recorder_host/run.py b/ground_station/tests/recorder_host/run.py new file mode 100644 index 00000000..7b8de2db --- /dev/null +++ b/ground_station/tests/recorder_host/run.py @@ -0,0 +1,105 @@ +# Copyright (C) 2026 Control and Telemetry Systems GmbH +# SPDX-License-Identifier: GPL-3.0-or-later + +"""Run production recorder/SdFat/FlashCache and selected production HMI bodies on Linux. + +Usage from the repo: python3 ground_station/tests/recorder_host/run.py +Only generated files under ground_station/.pio/recorder-host are written. +""" +from pathlib import Path +import subprocess +import sys + +ROOT = Path(__file__).resolve().parents[2] +HERE = Path(__file__).resolve().parent +OUT = ROOT / '.pio' / 'recorder-host' +SD = ROOT / '.pio/libdeps/ground_station/SdFat - Adafruit Fork/src' +FLASH = ROOT / '.pio/libdeps/ground_station/Adafruit SPIFlash/src' + + +def run(args, **kwargs): + subprocess.run([str(arg) for arg in args], check=True, timeout=180, **kwargs) + + +def body(source, signature): + start = source.index(signature) + opening = source.index('{', start) + depth = 1 + end = opening + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + '\n' + + +OUT.mkdir(parents=True, exist_ok=True) +# Same FatFs formatter as the compatibility test, with the GS's 960 KiB volume. +formatter = (ROOT / 'tests/fatfs_compatibility.c').read_text().replace( + '#define TEST_SECTOR_COUNT 512U', '#define TEST_SECTOR_COUNT 1920U') +(OUT / 'format.c').write_text(formatter) +fat = ROOT / 'lib/FatFs' +run(['gcc', OUT / 'format.c', fat / 'ff.c', fat / 'ffunicode.c', '-I' + str(fat), '-o', OUT / 'format']) +run([OUT / 'format', 'create', OUT / 'blank.img']) + +hmi = (ROOT / 'src/hmi/hmi.cpp').read_text() +utils = (ROOT / 'src/utils.cpp').read_text() +extracted = '#include "hmi_host.hpp"\n#include \nextern SemaphoreHandle_t storageAccessMutex;\n' +for signature in ('void Hmi::initLive()', 'void Hmi::live()', 'void Hmi::update(void *pvParameter)'): + extracted += body(hmi, signature) +extracted += body(utils, 'int32_t Utils::getFlashMemoryUsage()') +(OUT / 'hmi.cpp').write_text(extracted) + +flags = ['-std=c++17', '-O1', '-g', '-pthread', '-fsanitize=address,undefined', '-fno-omit-frame-pointer', + '-DENABLE_ARDUINO_FEATURES=0', '-DENABLE_ARDUINO_SERIAL=0', '-DENABLE_ARDUINO_STRING=0', + '-DSPI_DRIVER_SELECT=3', '-D__FlashStringHelper=void', '-include', str(HERE / 'Arduino.h'), + '-I' + str(HERE), '-I' + str(ROOT / 'src'), '-I' + str(ROOT / 'src/logging'), + '-I' + str(SD), '-I' + str(FLASH)] + + +def compile_one(source, name): + target = OUT / (name + '.o') + run(['g++', *flags, '-c', source, '-o', target]) + return target + + +libraries = [compile_one(source, 'lib-' + source.stem) + for folder in (SD / 'FatLib', SD / 'common') for source in sorted(folder.glob('*.cpp'))] +libraries += [compile_one(FLASH / 'Adafruit_FlashCache.cpp', 'flash-cache'), + compile_one(HERE / 'test.cpp', 'test')] +recorder_source = (ROOT / 'src/logging/recorder.cpp').read_text() +recorder = compile_one(ROOT / 'src/logging/recorder.cpp', 'recorder') +hmi_object = compile_one(OUT / 'hmi.cpp', 'hmi') + + +def link(name, recorder_object, hmi_part): + binary = OUT / name + run(['g++', *flags, *libraries, recorder_object, hmi_part, '-o', binary]) + return binary + + +binary = link('recorder-test', recorder, hmi_object) +run([binary, OUT / 'blank.img', 'all']) + +# Negative controls: each regression test must reject the corresponding old code. +mutations = [ + ('down', 'recorder', recorder_source.replace( + '(ref->fileCreated || command.data.state < kTouchdownState)', 'true')), + ('exit', 'hmi', extracted.replace('else if (needsConfirmation)', + "else if (recorder.getStatus().activeFilename[0] != '\\0')")), + ('scan', 'hmi', extracted.replace('ref->state != LIVE && !ref->isLogging', '!ref->isLogging')), +] +for name, part, source in mutations: + original = recorder_source if part == 'recorder' else extracted + assert source != original, f'{name}: mutation no longer matches production source' + path = OUT / (name + '-old.cpp') + path.write_text(source) + obj = compile_one(path, name + '-old') + mutant = link(name + '-old', obj if part == 'recorder' else recorder, + obj if part == 'hmi' else hmi_object) + result = subprocess.run([str(mutant), str(OUT / 'blank.img'), name], timeout=30, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + (OUT / (name + '-old.log')).write_text(result.stdout) + if result.returncode == 0 or 'FAIL:' not in result.stdout: + sys.exit(f'Negative control {name} did not fail its assertion: {result.stdout}') + print(f'PASS: negative control {name} rejected the old behavior', flush=True) +print('PASS: production recorder/filesystem tests and all three negative controls', flush=True) diff --git a/ground_station/tests/recorder_host/test.cpp b/ground_station/tests/recorder_host/test.cpp new file mode 100644 index 00000000..3dbf0b09 --- /dev/null +++ b/ground_station/tests/recorder_host/test.cpp @@ -0,0 +1,320 @@ +// Copyright (C) 2026 Control and Telemetry Systems GmbH +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "hmi_host.hpp" +#include "Adafruit_FlashCache.h" +#include +#include +#include +#include +#include +#include + +static void check(bool ok, const char* message) { + if (!ok) throw std::runtime_error(message); +} +namespace host { +std::function beforeReplyDelivery; +std::atomic clockOffset{0}; +unsigned scans = 0; +bool failSend = false; +std::vector queues; +std::vector mutexes; +std::thread worker; +struct Stop {}; +void shutdown() { + for (auto* queue : queues) { + std::lock_guard lock(queue->mutex); + queue->stopped = true; + queue->changed.notify_all(); + } + if (worker.joinable()) worker.join(); + for (auto* queue : queues) delete queue; + for (auto* mutex : mutexes) delete mutex; +} +} +SemaphoreHandle_t storageAccessMutex = nullptr; +QueueHandle_t xQueueCreate(size_t capacity, size_t itemSize) { + auto* queue = new HostQueue{capacity, itemSize}; + host::queues.push_back(queue); + return queue; +} +int xQueueSend(QueueHandle_t queue, const void* item, TickType_t timeout) { + if (timeout && host::failSend) return 0; + std::unique_lock lock(queue->mutex); + if (!queue->changed.wait_for(lock, std::chrono::milliseconds(timeout), + [&] { return queue->items.size() < queue->capacity; })) return 0; + const auto* bytes = static_cast(item); + queue->items.emplace_back(bytes, bytes + queue->itemSize); + queue->changed.notify_all(); + return pdPASS; +} +int xQueueReceive(QueueHandle_t queue, void* item, TickType_t timeout) { + std::unique_lock lock(queue->mutex); + const auto ready = [&] { return queue->stopped || !queue->items.empty(); }; + if (timeout == portMAX_DELAY) queue->changed.wait(lock, ready); + else if (!queue->changed.wait_for(lock, std::chrono::milliseconds(timeout), ready)) return 0; + if (queue->stopped) throw host::Stop{}; + std::memcpy(item, queue->items.front().data(), queue->itemSize); + queue->items.pop_front(); + queue->changed.notify_all(); + lock.unlock(); + // Delay delivery, not worker processing: the recorder can close the log before + // the UI receives the earlier reply. This forces the identified race window. + if (queue == host::queues.at(1) && host::beforeReplyDelivery) { + auto hook = std::move(host::beforeReplyDelivery); + host::beforeReplyDelivery = nullptr; + hook(); + } + return pdPASS; +} +SemaphoreHandle_t xSemaphoreCreateMutex() { + auto* mutex = new std::timed_mutex; + host::mutexes.push_back(mutex); + return mutex; +} +int xSemaphoreTake(SemaphoreHandle_t mutex, TickType_t timeout) { + if (mutex == storageAccessMutex) ++host::scans; + if (timeout == portMAX_DELAY) { mutex->lock(); return pdTRUE; } + return mutex->try_lock_for(std::chrono::milliseconds(timeout)) ? pdTRUE : 0; +} +void xSemaphoreGive(SemaphoreHandle_t mutex) { mutex->unlock(); } +void xTaskCreate(void (*task)(void*), const char*, size_t, void* argument, int, void*) { + host::worker = std::thread([=] { try { task(argument); } catch (host::Stop&) {} }); +} +TickType_t xTaskGetTickCount() { + static const auto start = std::chrono::steady_clock::now(); + return std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count(); +} +uint32_t millis() { return xTaskGetTickCount() + host::clockOffset.load(); } + +class Flash : public FsBlockDeviceInterface { + public: + Adafruit_SPIFlashBase raw; + Adafruit_FlashCache cache; + bool failSync = false; + bool isBusy() override { return false; } + Sector_t sectorCount() override { return raw.bytes.size() / 512; } + bool readSector(Sector_t sector, uint8_t* dst) override { return readSectors(sector, dst, 1); } + bool readSectors(Sector_t sector, uint8_t* dst, size_t count) override { + check((sector + count) * 512 <= raw.bytes.size(), "read beyond flash"); + return cache.read(&raw, sector * 512, dst, count * 512); + } + bool writeSector(Sector_t sector, const uint8_t* src) override { return writeSectors(sector, src, 1); } + bool writeSectors(Sector_t sector, const uint8_t* src, size_t count) override { + check((sector + count) * 512 <= raw.bytes.size(), "write beyond flash"); + return cache.write(&raw, sector * 512, src, count * 512); + } + bool syncDevice() override { return !failSync && cache.sync(&raw); } +} flash; +FatFileSystem fatfs; +Config systemConfig; +static bool hostOwned = false; +bool Utils::isConnected() { return true; } +bool Utils::isFilesystemAvailable() { return !hostOwned; } +bool Utils::requestMassStorage() { + check(fatfs.end() != nullptr && flash.syncDevice(), "USB handoff flush"); + hostOwned = true; + return true; +} +bool Utils::claimFirmwareStorage(uint32_t) { + if (hostOwned) check(fatfs.begin(&flash), "USB reclaim remount"); + hostOwned = false; + return true; +} + +static std::map expected; +static const std::string header = "link,ts[deciseconds],state,errors,lat[deg/10000],lon[deg/10000],altitude[m],velocity[m/s],battery[decivolts],pyro1,pyro2\r\n"; +static packedRXMessage packet(uint8_t state, unsigned timestamp) { + packedRXMessage data{}; + data.state = state; data.timestamp = timestamp; + data.lat = 470000; data.lon = 80000; data.altitude = 123; data.velocity = 42; data.voltage = 80; + return data; +} +static std::string row(uint8_t state, unsigned timestamp, uint8_t source) { + return std::to_string(source) + ',' + std::to_string(timestamp) + ',' + std::to_string(state) + + ",0,470000,80000,123,42,80,0,0\r\n"; +} +static void send(Recorder& recorder, uint8_t state, unsigned timestamp, uint8_t source = 1) { + recorder.onTelemetryPacket(packet(state, timestamp), source); + check(recorder.sync(), "drain queued telemetry"); +} +static std::string beginSegment(Recorder& recorder, uint8_t state = 3, unsigned timestamp = 1) { + check(recorder.startLiveRecording(), "enter Live"); + send(recorder, state, timestamp); + const auto status = recorder.getStatus(); + check(status.state == RecorderState::Recording, "mid-flight entry starts recording"); + std::string name = status.activeFilename; + check(!expected.count(name), "new segment must not reuse an old filename"); + expected[name] = header + row(state, timestamp, 1); + return name; +} +static void verifyDisk() { + // Fresh filesystem AND flash cache: only persisted bytes count. + Flash fresh; + fresh.raw.bytes = flash.raw.bytes; + FatVolume mounted; + check(mounted.begin(&fresh), "persisted filesystem mounts"); + check(mounted.fatType() == 12, "test uses GS FAT12 geometry"); + auto directory = mounted.open("/logs"); + check(bool(directory), "persisted /logs exists"); + std::set names; + for (auto file = directory.openNextFile(); file; file = directory.openNextFile()) { + char name[64]{}; + file.getName(name, sizeof(name)); + check(expected.count(name) != 0, "unexpected/corrupt directory entry"); + std::string bytes(file.size(), '\0'); + check(file.read(bytes.data(), bytes.size()) == static_cast(bytes.size()), "read full persisted log"); + check(bytes == expected.at(name), "persisted log contents changed or samples lost"); + names.insert(name); + file.close(); + } + check(names.size() == expected.size(), "one or more logs disappeared"); + directory.close(); + mounted.end(); +} +static void testDown(Recorder& recorder) { + for (bool dual : {false, true}) for (bool never : {false, true}) { + recorder.configure(dual ? DUAL : SINGLE, never); + check(recorder.shareWithMassStorage(), "idle USB sharing"); + check(recorder.startLiveRecording(), "re-enter Live at DOWN"); + for (unsigned i = 0; i < 100; ++i) send(recorder, 7, i, i % 2 + 1); + check(recorder.getStatus().state == RecorderState::Idle, "DOWN must not create a new log"); + check(hostOwned, "DOWN alone must not reclaim USB for recording"); + Hmi hmi(recorder); hmi.backButton.pressed = true; hmi.live(); + check(hmi.state == Hmi::MENU && hmi.liveExitState == Hmi::LiveExitState::None, + "B must leave DOWN immediately without confirmation"); + verifyDisk(); + Utils::claimFirmwareStorage(); + } + std::cout << "PASS: DOWN re-entry, both receiver modes and stop settings, no new files\n"; +} +static void testExit(Recorder& recorder) { + recorder.configure(SINGLE, false); + const auto name = beginSegment(recorder); + Hmi hmi(recorder); + host::beforeReplyDelivery = [&] { + send(recorder, 7, 2); + expected[name] += row(7, 2, 1); + check(recorder.getStatus().activeFilename[0] == '\0', "touchdown happens before reply delivery"); + }; + hmi.backButton.pressed = true; hmi.live(); + check(hmi.liveExitState == Hmi::LiveExitState::Confirm, "exit must use its reply, never show false Stop Failed"); + hmi.okButton.pressed = true; hmi.live(); + check(hmi.state == Hmi::MENU, "confirm after touchdown leaves Live"); + verifyDisk(); + + check(recorder.startLiveRecording(), "enter before queued liftoff"); + recorder.onTelemetryPacket(packet(3, 3), 1); + bool prompt = false; + check(!recorder.stopLiveRecording(true, &prompt) && prompt, "queued liftoff must require confirmation"); + const std::string queuedName = recorder.getStatus().activeFilename; + expected[queuedName] = header + row(3, 3, 1); + check(recorder.stopLiveRecording(), "confirmed stop drains preceding samples"); + recorder.onTelemetryPacket(packet(4, 4), 1); + check(recorder.sync(), "drain after leaving"); + prompt = true; host::failSend = true; + check(!recorder.stopLiveRecording(true, &prompt) && !prompt, "queue failure is not a confirmation request"); + host::failSend = false; + verifyDisk(); + std::cout << "PASS: real queued exit/landing interleaving, pending liftoff, disabled samples and failure reply\n"; +} +static void testScan(Recorder& recorder) { + recorder.configure(SINGLE, true); + beginSegment(recorder); + for (int phase = 0; phase < 3; ++phase) { + if (phase == 1) { + flash.failSync = true; + check(!recorder.sync(), "injected sync failure"); + flash.failSync = false; + check(recorder.getStatus().state == RecorderState::Fault, "real recorder fault state"); + } + if (phase == 2) check(recorder.stopLiveRecording(), "close after fault"); + Hmi hmi(recorder); + hmi.isLogging = false; // Stale Idle snapshot, Fault, then genuinely Idle. + const auto scans = host::scans; + Hmi::update(&hmi); + check(host::scans == scans, "Live must never run the free-space filesystem scan"); + } + Hmi menu(recorder); menu.state = Hmi::MENU; + const auto scans = host::scans; + Hmi::update(&menu); + check(host::scans == scans + 1, "Menu still updates free space using actual SdFat scan"); + verifyDisk(); + std::cout << "PASS: production HMI scan guard for stale Idle, Fault and Idle; Menu scan still works\n"; +} +static void testSegments(Recorder& recorder) { + for (bool dual : {false, true}) for (bool never : {false, true}) { + recorder.configure(dual ? DUAL : SINGLE, never); + for (unsigned segment = 0; segment < 16; ++segment) { + check(recorder.shareWithMassStorage(), "share before mid-flight entry"); + const auto name = beginSegment(recorder, 3 + segment % 4); + check(!hostOwned, "first flight sample reclaims storage"); + for (unsigned i = 2; i <= 30; ++i) { + const uint8_t source = dual ? i % 2 + 1 : 1; + send(recorder, 4, i, source); + expected[name] += row(4, i, source); + } + send(recorder, 7, 31, 1); expected[name] += row(7, 31, 1); + if (dual) { + check(recorder.getStatus().state == RecorderState::Recording, "other participant still flying"); + send(recorder, 7, 32, 2); expected[name] += row(7, 32, 2); + } + check(recorder.getStatus().state == (never ? RecorderState::Recording : RecorderState::Idle), + "touchdown honors stop setting and retains final sample"); + if (never && segment == 0) { + Hmi hmi(recorder); hmi.backButton.pressed = true; hmi.live(); + check(hmi.liveExitState == Hmi::LiveExitState::Confirm, "active log asks confirmation"); + hmi.backButton.pressed = true; hmi.live(); + check(hmi.state == Hmi::LIVE && recorder.getStatus().state == RecorderState::Recording, + "B cancels without closing log"); + hmi.backButton.pressed = true; hmi.live(); + flash.failSync = true; + hmi.okButton.pressed = true; hmi.live(); + check(hmi.state == Hmi::LIVE && hmi.liveExitState == Hmi::LiveExitState::StopFailed, + "failed sync must retain Live and the open log"); + flash.failSync = false; + hmi.backButton.pressed = true; hmi.live(); + hmi.backButton.pressed = true; hmi.live(); + hmi.okButton.pressed = true; hmi.live(); + check(hmi.state == Hmi::MENU, "retry closes and leaves Live"); + } else check(recorder.stopLiveRecording(), "stop segment"); + verifyDisk(); + } + } + std::cout << "PASS: 64 flight segments, dual/single + Never/landing, USB remounts, cancellation/failure/retry\n"; +} +int main(int argc, char** argv) { + int result = 0; + try { + check(argc == 3, "usage: test image all|down|exit|scan"); + std::ifstream input(argv[1], std::ios::binary); + flash.raw.bytes.assign(std::istreambuf_iterator(input), {}); + check(flash.raw.bytes.size() == 960 * 1024, "GS volume size"); + check(fatfs.begin(&flash), "initial mount"); + check(fatfs.mkdir("/logs"), "seed log directory"); + for (const char* name : {"log_000.csv", "log_001.csv", "log_002.csv", "cats1_legacy.csv"}) { + expected[name] = std::string("Existing flight ") + name + '\n' + std::string(1800, 'x'); + auto file = fatfs.open((std::string("/logs/") + name).c_str(), FILE_WRITE); + check(file.write(expected[name].data(), expected[name].size()) == expected[name].size() && file.close(), "seed old log"); + } + storageAccessMutex = xSemaphoreCreateMutex(); + Recorder recorder("/logs"); + check(recorder.begin(), "start production recorder task"); + const std::string mode = argv[2]; + if (mode == "all" || mode == "down") testDown(recorder); + if (mode == "all" || mode == "exit") testExit(recorder); + if (mode == "all" || mode == "scan") testScan(recorder); + if (mode == "all") testSegments(recorder); + check(recorder.stopLiveRecording(), "final stop"); + verifyDisk(); + check(fatfs.end() != nullptr, "final unmount"); + host::shutdown(); // Join before recorder/status mutex lifetime ends. + std::cout << "PASS: all " << expected.size() << " log names and complete contents survived fresh mounts\n"; + } catch (const std::exception& error) { + std::cerr << "FAIL: " << error.what() << '\n'; + host::shutdown(); + result = 1; + } + return result; +}