-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSystemModule.h
More file actions
300 lines (266 loc) · 15.8 KB
/
Copy pathSystemModule.h
File metadata and controls
300 lines (266 loc) · 15.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
#pragma once
#include "core/MoonModule.h"
#include "core/Scheduler.h"
#include "core/build_info.h"
#include "core/FilesystemModule.h" // setDeviceModel() arms the debounced save (noteDirty)
#include "platform/platform.h"
#include <cstdio>
#include <cstring>
namespace mm {
class SystemModule : public MoonModule {
public:
void setScheduler(Scheduler* s) { scheduler_ = s; }
// Diagnostics keep ticking regardless — disabling System hides uptime/heap/fps
// from the UI for no good reason, and the user can't easily re-enable.
bool respectsEnabled() const override { return false; }
// Accepts user-added Peripheral children (sensors, actuators — bridges to
// hardware/network the user solders on or off). The same firmware runs with
// or without them, so the user adds/deletes them at runtime; the add/replace/
// delete + persistence machinery is the generic MoonModule path. (The deviceModel
// identity is a SystemModule control above, not a child module — SystemModule owns
// the device's identity, name + model, directly.)
const char* acceptsChildRoles() const override { return "peripheral"; }
void setup() override {
// Compute default deviceName from MAC: MM-XXXX. Skip if a persisted value was
// already overlaid by Scheduler phase 2 (deviceName_ non-empty). Sanitize first
// in case the persisted value is an invalid hostname (older firmware let any
// text through); coerce + MAC-fallback so deviceName_ is a valid, non-empty
// hostname from the very first read — every network name (mDNS/AP/DHCP) derives
// from it directly, so it must be valid before NetworkModule::setup() reads it.
sanitizeHostname(deviceName_);
if (deviceName_[0] == 0) {
uint8_t mac[6];
platform::getMacAddress(mac);
std::snprintf(deviceName_, sizeof(deviceName_), "MM-%02X%02X",
mac[4], mac[5]);
}
// Snprintf static display strings into the bound buffers. onBuildControls already
// bound these buffers by pointer; we fill them now and the UI picks up the content
// on the next WebSocket push.
std::snprintf(chipInfo_, sizeof(chipInfo_), "%s", platform::chipModel());
std::snprintf(sdkInfo_, sizeof(sdkInfo_), "%s", platform::sdkVersion());
// version = semver (what code) + release channel (which channel) when
// the build pipeline burned one in: "1.0.0-rc2 (latest)". kRelease is
// "" on local / dev builds, where we show the bare semver. See
// build_info.h for the MM_VERSION vs MM_RELEASE split.
if (kRelease[0] != 0) {
std::snprintf(versionStr_, sizeof(versionStr_), "%s (%s)", kVersion, kRelease);
} else {
std::snprintf(versionStr_, sizeof(versionStr_), "%s", kVersion);
}
std::snprintf(buildStr_, sizeof(buildStr_), "%s", kBuildDate);
std::snprintf(firmwareStr_, sizeof(firmwareStr_), "%s", kFirmwareName);
std::snprintf(bootReasonStr_, sizeof(bootReasonStr_), "%s", platform::resetReason());
if constexpr (platform::hasWifiCoprocessor) {
std::snprintf(coprocStr_, sizeof(coprocStr_), "%s", platform::coprocessorWifi());
}
if (chipFlashVal_ > 0) {
std::snprintf(flashStr_, sizeof(flashStr_), "%uMB",
static_cast<unsigned>(chipFlashVal_ / (1024 * 1024)));
}
// Chain to base so children (user-added Peripherals) get
// their setup() — a peripheral initialises its hardware here. Overriding
// setup() shadows the base default that would otherwise propagate.
MoonModule::setup();
}
void onBuildControls() override {
// Platform-derived totals queried here (idempotent, no I/O) so the conditionals that
// gate the Progress controls see real values rather than waiting on setup().
totalInternalVal_ = static_cast<uint32_t>(platform::totalInternalHeap());
totalHeapVal_ = static_cast<uint32_t>(platform::totalHeap());
firmwareSizeVal_ = static_cast<uint32_t>(platform::firmwareSize());
totalFlashVal_ = static_cast<uint32_t>(platform::firmwarePartition());
chipFlashVal_ = static_cast<uint32_t>(platform::flashChipSize());
totalFsVal_ = static_cast<uint32_t>(platform::filesystemTotal());
// Device name on top
controls_.addText("deviceName", deviceName_, sizeof(deviceName_));
// deviceModel — the physical-hardware identity (the catalog entry name, e.g.
// "Olimex ESP32-Gateway Rev G"). The device can't self-identify its hardware, so
// this is INJECTED by tooling: MoonDeck / the device UI's ?deviceModel= inject via
// HTTP /api/control, or the web installer via the Improv SET_DEVICE_MODEL RPC
// (which routes through setDeviceModel() below). Display-only in the UI (pushed,
// never user-typed at the device); bound as Text — not ReadOnly — because Text is
// auto-persisted by FilesystemModule, and the readonly flag is a UI-render hint
// that doesn't change persistence or HTTP-write semantics.
controls_.addText("deviceModel", deviceModel_, sizeof(deviceModel_));
controls_.setReadOnly(controls_.count() - 1, true);
// Dynamic (updated every second)
controls_.addReadOnly("uptime", uptimeStr_, sizeof(uptimeStr_));
controls_.addReadOnly("fps", fpsStr_, sizeof(fpsStr_));
controls_.addReadOnly("tickTimeUs", tickStr_, sizeof(tickStr_));
if (totalInternalVal_ > 0) {
controls_.addProgress("heap", heapUsedVal_, totalInternalVal_);
}
// PSRAM detection — derived, not flagged. ESP-IDF auto-detects the
// PSRAM chip at boot (`I (...) esp_psram: Found NMB PSRAM device`)
// and merges its pool into the heap allocator. After that
// `totalHeap()` reports internal + PSRAM combined while
// `totalInternalHeap()` reports internal only — so `totalHeap >
// totalInternal` IS the "PSRAM present" signal. No explicit flag,
// no per-platform code path; boards without PSRAM (or with PSRAM
// disabled in sdkconfig) skip this control naturally.
if (totalHeapVal_ > totalInternalVal_) {
controls_.addProgress("psram", psramUsedVal_, totalHeapVal_ - totalInternalVal_);
}
controls_.addReadOnly("maxBlock", maxBlockStr_, sizeof(maxBlockStr_));
// Flash/firmware/filesystem. The progress bar is named
// `firmwarePartition` (not `firmware`) to avoid colliding with the
// string `firmware` control bound a few lines below — both shared the
// name pre-board-injection, which made any consumer that did
// `controls.find(c => c.name === "firmware")` get whichever was bound
// first (the progress bar's integer value) and break on string-only
// operations like install-picker's isCompatible.
if (totalFlashVal_ > 0) {
controls_.addProgress("firmwarePartition", firmwareSizeVal_, totalFlashVal_);
}
if (chipFlashVal_ > 0) {
controls_.addReadOnly("flash", flashStr_, sizeof(flashStr_));
}
if (totalFsVal_ > 0) {
controls_.addProgress("filesystem", fsUsedVal_, totalFsVal_);
}
// Static info
controls_.addReadOnly("version", versionStr_, sizeof(versionStr_));
controls_.addReadOnly("build", buildStr_, sizeof(buildStr_));
controls_.addReadOnly("firmware", firmwareStr_, sizeof(firmwareStr_));
controls_.addReadOnly("chip", chipInfo_, sizeof(chipInfo_));
controls_.addReadOnly("sdk", sdkInfo_, sizeof(sdkInfo_));
controls_.addReadOnly("bootReason", bootReasonStr_, sizeof(bootReasonStr_));
// WiFi co-processor (P4 + on-board C6) firmware read-out. Gated at compile
// time on hasWifiCoprocessor, so the whole control — and the snprintf/query
// cost — vanishes on native-radio builds (classic/S3/desktop) and the
// eth-only P4. Its value proves the C6 slave-firmware state ("C6 fw 2.12.9"
// vs "not detected"). loop1s() refreshes it.
if constexpr (platform::hasWifiCoprocessor) {
std::snprintf(coprocStr_, sizeof(coprocStr_), "%s", platform::coprocessorWifi());
controls_.addReadOnly("wifiCoproc", coprocStr_, sizeof(coprocStr_));
}
// Chain into children (user-added Peripherals). Per the override-and-chain
// convention in architecture.md § Lifecycle propagation to children:
// `onBuildControls` cascades to children via MoonModule's base default;
// overriding the method shadows that default, so we must call it
// explicitly. Order doesn't matter here — SystemModule's own controls
// don't depend on children's controls.
MoonModule::onBuildControls();
}
void loop1s() override {
// deviceName is the single network identity (mDNS <name>.local, SoftAP SSID,
// DHCP hostname all derive from it), so it must stay a valid hostname whatever
// the user typed or persistence restored. Coerce it here each tick — idempotent
// on an already-valid name, and it runs before NetworkModule::loop1s() reads it,
// so a live rename ("My Room" → "My-Room") propagates everywhere within a tick.
sanitizeHostname(deviceName_);
if (deviceName_[0] == 0) { // user cleared it / all-invalid → MAC fallback
uint8_t mac[6];
platform::getMacAddress(mac);
std::snprintf(deviceName_, sizeof(deviceName_), "MM-%02X%02X", mac[4], mac[5]);
}
// Update dynamic values
uint32_t uptimeSec = scheduler_ ? scheduler_->elapsed() / 1000 : 0;
uint32_t hours = uptimeSec / 3600;
uint32_t mins = (uptimeSec % 3600) / 60;
uint32_t secs = uptimeSec % 60;
std::snprintf(uptimeStr_, sizeof(uptimeStr_), "%u:%02u:%02u",
static_cast<unsigned>(hours),
static_cast<unsigned>(mins),
static_cast<unsigned>(secs));
uint32_t fps = scheduler_ ? scheduler_->fps() : 0;
std::snprintf(fpsStr_, sizeof(fpsStr_), "%u", static_cast<unsigned>(fps));
uint32_t tickUs = scheduler_ ? scheduler_->tickTimeUs() : 0;
std::snprintf(tickStr_, sizeof(tickStr_), "%u", static_cast<unsigned>(tickUs));
uint32_t freeTotal = static_cast<uint32_t>(platform::freeHeap());
uint32_t freeInternal = static_cast<uint32_t>(platform::freeInternalHeap());
heapUsedVal_ = totalInternalVal_ > freeInternal ? totalInternalVal_ - freeInternal : 0;
uint32_t freePsram = freeTotal > freeInternal ? freeTotal - freeInternal : 0;
uint32_t totalPsram = totalHeapVal_ > totalInternalVal_ ? totalHeapVal_ - totalInternalVal_ : 0;
psramUsedVal_ = totalPsram > freePsram ? totalPsram - freePsram : 0;
fsUsedVal_ = static_cast<uint32_t>(platform::filesystemUsed());
// maxInternalAllocBlock — NOT maxAllocBlock. The internal-RAM block
// is the scarce-resource KPI; the all-memory variant reports ~8 MB
// on PSRAM-equipped boards (S3/S2) and tells the user nothing.
std::snprintf(maxBlockStr_, sizeof(maxBlockStr_), "%uKB",
static_cast<unsigned>(platform::maxInternalAllocBlock() / 1024));
// Refresh the WiFi co-processor status, so the displayed C6 firmware state
// stays current if the link comes up after boot or the C6 is reflashed
// without a host reboot. Compiled out where there's no co-processor.
if constexpr (platform::hasWifiCoprocessor) {
std::snprintf(coprocStr_, sizeof(coprocStr_), "%s", platform::coprocessorWifi());
}
// Chain to base so children get their loop1s() — a Peripheral formats
// its read-only display values here. Overriding loop1s() shadows the
// base default that would otherwise propagate. (setup/loop20ms/loop/
// teardown propagate too: setup is chained above, loop20ms/loop/teardown
// aren't overridden so the base default carries them.)
MoonModule::loop1s();
}
const char* deviceName() const { return deviceName_; }
const char* deviceModel() const { return deviceModel_; }
// External setter for transports that bypass /api/control (today: the web installer's
// Improv vendor RPC SET_DEVICE_MODEL, routed here by ImprovProvisioningModule).
// Validates: 1..31 chars, ASCII-printable (0x20–0x7E), no embedded NUL. The printable
// floor rejects control bytes / NULs that would corrupt downstream consumers — JSON
// serialization (control bytes need \u escaping at best, break naive emitters at
// worst), the device UI (rendered verbatim; a BEL/ESC would mangle the page), and
// C-string handling (no embedded NUL → strlen/strcpy round-trip cleanly). Printable
// ASCII still contains `"` and `\`, which serializers must escape normally — the
// floor isn't a license to skip escaping. Returns false on rejection so the Improv
// handler can map to ErrorState. On accept: copies into deviceModel_ and arms
// FilesystemModule's debounced save — same idiom as NetworkModule::setWifiCredentials.
//
// Known asymmetry: HTTP POST /api/control writes to `deviceModel` go through the
// generic Text-control write in applyControlValue() (Control.cpp), which does NO
// printable-ASCII check. A malicious LAN client could write control bytes / NUL via
// that path. Acceptable today because the HTTP-write callers (MoonDeck, the
// installer's HTTP inject) source the value from the device-model catalog, which the
// project controls; there is no end-user-typed input on this field. If the threat
// model grows, the right fix is a per-control validator hook on ControlDescriptor —
// not a one-off HTTP dispatch exception. Until then this validation lives only on the
// SET_DEVICE_MODEL-over-Improv path, the only path where wire-untrusted bytes arrive.
bool setDeviceModel(const char* value) {
if (!value) return false;
size_t n = std::strlen(value);
if (n == 0 || n >= sizeof(deviceModel_)) return false;
for (size_t i = 0; i < n; i++) {
unsigned char b = static_cast<unsigned char>(value[i]);
if (b < 0x20 || b > 0x7E) return false;
}
std::strncpy(deviceModel_, value, sizeof(deviceModel_) - 1);
deviceModel_[sizeof(deviceModel_) - 1] = 0;
markDirty();
FilesystemModule::noteDirty();
return true;
}
private:
Scheduler* scheduler_ = nullptr;
// Configurable
char deviceName_[24] = {};
// Physical-hardware identity (catalog entry name). 32-byte buffer fits the longest
// entry ("Olimex ESP32-Gateway Rev G" = 26) with headroom; the Improv RPC handler
// caps str_len against this size dynamically.
char deviceModel_[32] = {};
// Dynamic (updated in loop1s)
char uptimeStr_[16] = {};
char fpsStr_[8] = {};
char tickStr_[8] = {};
char maxBlockStr_[12] = {};
uint32_t heapUsedVal_ = 0;
uint32_t psramUsedVal_ = 0;
uint32_t fsUsedVal_ = 0;
// Static (set in setup)
char chipInfo_[16] = {};
char sdkInfo_[24] = {};
char versionStr_[32] = {}; // semver + " (channel)" — e.g. "1.0.0-rc2 (latest)"
char buildStr_[24] = {};
// 24 fits the longest current key ("desktop-macos-arm64" = 19) with headroom.
char firmwareStr_[24] = {};
char bootReasonStr_[16] = {};
char coprocStr_[24] = {}; // WiFi co-processor status, e.g. "C6 fw 2.12.9" / "not detected"
uint32_t totalInternalVal_ = 0;
uint32_t totalHeapVal_ = 0;
char flashStr_[12] = {};
uint32_t totalFlashVal_ = 0; // app partition size
uint32_t firmwareSizeVal_ = 0;
uint32_t chipFlashVal_ = 0; // total chip flash
uint32_t totalFsVal_ = 0;
};
} // namespace mm