-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemPoolExpoMenu.ino
More file actions
915 lines (769 loc) · 32.4 KB
/
Copy pathMemPoolExpoMenu.ino
File metadata and controls
915 lines (769 loc) · 32.4 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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
/**
* Interactive MemPool expo demo.
*
* Open the Arduino Serial Monitor at 115200 baud and send one menu character
* at a time. This sketch avoids RTC, SD, and radio hardware dependencies so it
* is safe to run as a table demo.
*/
#include <Arduino.h>
#include <ArduinoJson.h>
#include <MemoryFree.h>
#include <MemPool.hpp>
#include <MemPoolJson.hpp>
MemPool pool;
MemPool::Lease staticConfig;
MemPool::Lease staticCalibration;
MemPool::Lease staticSensorMap;
static const unsigned long STARTUP_INPUT_IGNORE_MS = 1000UL;
static const uint8_t TERMINAL_SPACER_LINES = 16;
unsigned long ignoreInputUntilMs = 0;
void drainSerialInput() {
while (Serial.available() > 0) {
(void)Serial.read();
}
}
bool isPrintableCommandByte(char input) {
uint8_t value = (uint8_t)input;
return value > 32 && value <= 126;
}
bool isDemoCommand(char input) {
return (input >= '0' && input <= '9') || input == 'l' || input == 'L' ||
input == 'r' || input == 'R';
}
void pushTerminalViewDown() {
for (uint8_t i = 0; i < TERMINAL_SPACER_LINES; i++) {
Serial.println();
}
Serial.println(F("------------------------------------------------------------"));
}
void dumpPoolLine(const char *line, void *ctx) {
(void)ctx;
Serial.print(F(" "));
Serial.println(line);
}
void dumpLeaseLine(const char *line, void *ctx) {
(void)ctx;
Serial.print(F(" lease: "));
Serial.println(line);
}
void printPoolStats(const __FlashStringHelper *label) {
Serial.println();
Serial.print(F("["));
Serial.print(label);
Serial.println(F("]"));
pool.dumpStats(dumpPoolLine, nullptr);
}
void printActiveLeases() {
size_t active = pool.dumpActiveLeases(dumpLeaseLine, nullptr);
if (active == 0) {
Serial.println(F(" no active leases"));
}
}
void printMemorySummary(const __FlashStringHelper *label) {
MemPool::Stats stats = pool.stats();
Serial.println();
Serial.print(F("[Memory summary: "));
Serial.print(label);
Serial.println(F("]"));
Serial.print(F(" active buffers: "));
Serial.println((unsigned int)stats.activeLeases);
Serial.print(F(" pool used/free: "));
Serial.print((unsigned int)stats.bytesUsed);
Serial.print(F(" / "));
Serial.print((unsigned int)stats.bytesFree);
Serial.println(F(" bytes"));
Serial.print(F(" largest single buffer available: "));
Serial.print((unsigned long)pool.maxAllocBytes());
Serial.println(F(" bytes"));
Serial.print(F(" high-water memory used: "));
Serial.print((unsigned long)stats.highWaterBlocks * MEMPOOL_BLOCK_SIZE);
Serial.println(F(" bytes"));
Serial.print(F(" failed allocations: "));
Serial.println((unsigned int)stats.failedAllocs);
}
void printTechnicalSnapshot(const __FlashStringHelper *label) {
Serial.println();
Serial.print(F("[Technical details: "));
Serial.print(label);
Serial.println(F("]"));
Serial.println(F("Active lease table:"));
printActiveLeases();
printPoolStats(label);
}
void printFailureReason() {
MemPool::Stats stats = pool.stats();
Serial.print(F(" last failure reason: "));
switch (stats.lastAllocFailureReason) {
case MemPool::ALLOC_FAIL_TOO_LARGE:
Serial.println(F("request larger than entire pool"));
break;
case MemPool::ALLOC_FAIL_NO_CONTIGUOUS_RUN:
Serial.println(F("no contiguous free run large enough"));
break;
case MemPool::ALLOC_FAIL_NO_LEASE_SLOT:
Serial.println(F("no lease metadata slot available"));
break;
case MemPool::ALLOC_FAIL_NONE:
default:
Serial.println(F("none"));
break;
}
}
void printLeaseSummary(const __FlashStringHelper *label, const MemPool::Lease &lease) {
Serial.print(F(" "));
Serial.print(label);
Serial.print(F(": "));
if (!lease) {
Serial.println(F("not active"));
return;
}
MemPool::Handle handle = lease.handle();
const char *tag = pool.tag(handle);
Serial.print(F("slot="));
Serial.print((unsigned int)handle.slot);
Serial.print(F(" gen="));
Serial.print((unsigned int)handle.generation);
Serial.print(F(" size="));
Serial.print((unsigned long)lease.size());
Serial.print(F(" capacity="));
Serial.print((unsigned long)lease.capacity());
Serial.print(F(" tag="));
Serial.println(tag != nullptr ? tag : "-");
}
void printFixedX10(const __FlashStringHelper *label, int valueX10,
const __FlashStringHelper *unit) {
int whole = valueX10 / 10;
int tenths = valueX10 % 10;
if (tenths < 0) {
tenths = -tenths;
}
Serial.print(F(" "));
Serial.print(label);
Serial.print(F(": "));
Serial.print(whole);
Serial.print('.');
Serial.print(tenths);
Serial.println(unit);
}
void printByteBudget(const __FlashStringHelper *label, size_t used, size_t total) {
const uint8_t barWidth = 20;
unsigned long percent = total > 0 ? ((unsigned long)used * 100UL + (total / 2)) / total : 0;
uint8_t filled = total > 0 ? (uint8_t)(((unsigned long)used * barWidth + (total / 2)) / total) : 0;
if (filled > barWidth) {
filled = barWidth;
}
Serial.print(F(" "));
Serial.print(label);
Serial.print(F(": "));
Serial.print((unsigned long)used);
Serial.print(F(" / "));
Serial.print((unsigned long)total);
Serial.print(F(" bytes ("));
Serial.print(percent);
Serial.println(F("% full)"));
Serial.print(F(" ["));
for (uint8_t i = 0; i < barWidth; i++) {
Serial.print(i < filled ? '#' : '.');
}
Serial.println(F("]"));
Serial.print(F(" headroom: "));
Serial.print((unsigned long)(total > used ? total - used : 0));
Serial.println(F(" bytes"));
}
bool persistentLeasesActive() {
return staticConfig && staticCalibration && staticSensorMap;
}
void fillPersistentLeaseData() {
snprintf(staticConfig.chars(), staticConfig.size(),
"site=expo_canopy interval_s=60 radio=LoRa");
snprintf(staticCalibration.chars(), staticCalibration.size(),
"temp_offset_x10=-2 rh_offset_x10=5 co2_offset_ppm=18");
snprintf(staticSensorMap.chars(), staticSensorMap.size(),
"SHT31=temp/rh; SCD30=co2; ADS1115=battery");
}
void releasePersistentLeases() {
staticConfig.release();
staticCalibration.release();
staticSensorMap.release();
}
void resetDemoPool() {
releasePersistentLeases();
pool.init();
Serial.println(F("\n--- Reset pool ---"));
Serial.println(F("All demo buffers were returned. Counters and high-water marks were reset."));
printMemorySummary(F("after reset"));
printTechnicalSnapshot(F("after reset"));
}
void showMenu() {
Serial.println();
Serial.println(F("=== Loom MemPool Expo Menu ==="));
Serial.println(F("0: Pool status dashboard"));
Serial.println(F("1: Keep config/calibration in memory"));
Serial.println(F("2: Release saved config/calibration"));
Serial.println(F("3: One temporary sensor reading"));
Serial.println(F("4: Build and release a JSON message"));
Serial.println(F("5: Grow a message buffer"));
Serial.println(F("6: Fragmentation and recovery"));
Serial.println(F("7: Out-of-memory safety"));
Serial.println(F("8: Environmental sensing pipeline"));
Serial.println(F("9: Load config from a mock SD file"));
Serial.println(F("l: Pack a reading for LoRa"));
Serial.println(F("r: Reset pool"));
Serial.println(F("h: Print this menu"));
Serial.println(F("Send one character to run a demo."));
}
void runStatsDemo() {
Serial.println(F("\n--- Pool status dashboard ---"));
Serial.println(F("This is the quick health check: how much pool memory is in use,"));
Serial.println(F("what buffers are active, and whether anything has failed."));
printMemorySummary(F("current pool state"));
printTechnicalSnapshot(F("current pool state"));
}
void runLongTermLeaseDemo() {
Serial.println(F("\n--- Long-term static lease demo ---"));
Serial.println(F("Story: some embedded data should live for a long time, such as"));
Serial.println(F("site settings, calibration values, and a sensor map."));
if (persistentLeasesActive()) {
Serial.println(F("\nThese long-term leases already exist."));
Serial.println(F("No new allocation was made, so the slot/generation values stay stable."));
} else {
Serial.println(F("\nAllocating three named long-term buffers."));
releasePersistentLeases();
staticConfig = pool.allocLease(256, "cfg_static");
staticCalibration = pool.allocLease(384, "cal_static");
staticSensorMap = pool.allocLease(512, "sensor_map");
if (!staticConfig || !staticCalibration || !staticSensorMap) {
Serial.println(F("Failed to allocate one or more long-term leases."));
printFailureReason();
return;
}
fillPersistentLeaseData();
}
Serial.println(F("\nVisitor view: data kept available across the menu."));
Serial.print(F(" config: "));
Serial.println(staticConfig.chars());
Serial.print(F(" calibration: "));
Serial.println(staticCalibration.chars());
Serial.print(F(" sensor map: "));
Serial.println(staticSensorMap.chars());
Serial.println(F("\nTechnical view: stable named leases."));
printLeaseSummary(F("config"), staticConfig);
printLeaseSummary(F("calibration"), staticCalibration);
printLeaseSummary(F("sensor map"), staticSensorMap);
printMemorySummary(F("long-term leases active"));
printTechnicalSnapshot(F("long-term leases active"));
}
void runReleaseLongTermDemo() {
Serial.println(F("\n--- Release long-term static leases ---"));
Serial.println(F("Story: when a deployment no longer needs stored configuration data,"));
Serial.println(F("those named buffers can be returned to the pool."));
if (!persistentLeasesActive()) {
Serial.println(F("\nNo complete long-term lease set is currently active."));
}
releasePersistentLeases();
printMemorySummary(F("after releasing static leases"));
printTechnicalSnapshot(F("after releasing static leases"));
}
void runShortTermLeaseDemo() {
Serial.println(F("\n--- Short-term dynamic sensor lease demo ---"));
Serial.println(F("Story: a sensor reading needs temporary scratch space, then that"));
Serial.println(F("space should immediately become available for the next task."));
printMemorySummary(F("before dynamic lease"));
{
MemPool::Lease reading = pool.allocLease(192, "temp_sense");
if (!reading) {
Serial.println(F("Failed to allocate temporary sensor payload."));
printFailureReason();
return;
}
unsigned long sample = millis() / 1000UL;
int tempX10 = 215 + (int)(sample % 20UL);
int rhX10 = 480 + (int)((sample * 3UL) % 80UL);
unsigned int co2 = 410U + (unsigned int)((sample * 7UL) % 90UL);
snprintf(reading.chars(), reading.size(),
"sample=%lu temp_c_x10=%d rh_x10=%d co2_ppm=%u",
sample, tempX10, rhX10, co2);
Serial.println(F("\nVisitor view: one environmental sample."));
printFixedX10(F("temperature"), tempX10, F(" C"));
printFixedX10(F("relative humidity"), rhX10, F(" %"));
Serial.print(F(" CO2: "));
Serial.print(co2);
Serial.println(F(" ppm"));
Serial.print(F(" compact payload text: "));
Serial.println(reading.chars());
Serial.println(F("\nTechnical view: the temporary buffer is active only now."));
printLeaseSummary(F("sensor payload"), reading);
printActiveLeases();
printMemorySummary(F("inside dynamic lease scope"));
}
Serial.println(F("\nThe sample buffer went out of scope and returned itself to the pool."));
printMemorySummary(F("after dynamic lease"));
printTechnicalSnapshot(F("after dynamic lease"));
}
void runJsonLifecycleDemo() {
Serial.println(F("\n--- JSON document lifecycle demo ---"));
Serial.println(F("Story: Loom often builds JSON messages. Here ArduinoJson gets its"));
Serial.println(F("document memory from MemPool instead of the general heap."));
printMemorySummary(F("before JSON document"));
{
LoomJsonDocument doc(512, MemPoolJsonAllocator(&pool));
if (doc.capacity() == 0) {
Serial.println(F("Failed to allocate MemPool-backed JSON document."));
printFailureReason();
return;
}
doc["type"] = "mempool-json";
doc["site"] = "expo";
doc["sample"] = millis() / 1000UL;
JsonArray readings = doc.createNestedArray("readings");
JsonObject temp = readings.createNestedObject();
temp["sensor"] = "SHT31";
temp["temp_c_x10"] = 223;
temp["rh_x10"] = 512;
JsonObject co2 = readings.createNestedObject();
co2["sensor"] = "SCD30";
co2["co2_ppm"] = 438;
Serial.println(F("\nVisitor view: a structured sensor message."));
Serial.print(F(" serialized JSON: "));
serializeJson(doc, Serial);
Serial.println();
Serial.println(F("\nTechnical view: ArduinoJson is using a tagged pool lease."));
Serial.print(F(" JSON document capacity: "));
Serial.println((unsigned long)doc.capacity());
Serial.print(F(" JSON memory currently used: "));
Serial.println((unsigned long)doc.memoryUsage());
printActiveLeases();
printMemorySummary(F("inside JSON scope"));
}
Serial.println(F("\nThe JSON document went out of scope; its pool lease was released."));
printMemorySummary(F("after JSON document"));
printTechnicalSnapshot(F("after JSON document"));
}
void runReallocationDemo() {
Serial.println(F("\n--- Reallocation and resize demo ---"));
Serial.println(F("Story: messages sometimes grow as more fields are added. MemPool can"));
Serial.println(F("grow inside reserved space, and only move when more capacity is needed."));
printMemorySummary(F("before reallocation demo"));
{
MemPool::Lease raw = pool.allocLease(80, "resize_raw");
if (!raw) {
Serial.println(F("Failed to allocate raw resize lease."));
printFailureReason();
return;
}
Serial.println(F("\nStep 1: reserve a small message buffer."));
printLeaseSummary(F("raw before resize"), raw);
bool resizeWithinCapacity = pool.resize(raw.handle(), 120);
Serial.print(F(" grow from 80 to 120 bytes inside existing 128-byte reservation: "));
Serial.println(resizeWithinCapacity ? F("ok") : F("failed"));
printLeaseSummary(F("raw after resize"), raw);
bool resizePastCapacity = pool.resize(raw.handle(), 129);
Serial.print(F(" try to grow to 129 bytes without a bigger reservation: "));
Serial.println(resizePastCapacity ? F("unexpected ok") : F("blocked"));
}
Serial.println(F("\nStep 2: show allocator-style growth used by ArduinoJson."));
MemPoolJsonAllocator allocator(&pool);
void *current = allocator.allocate(80);
if (current == nullptr) {
Serial.println(F("Allocator allocate(80) failed."));
printFailureReason();
return;
}
MemPool::Handle handle = pool.handleFromPointer(current);
size_t capacity = pool.capacity(handle);
Serial.print(F(" initial allocator reservation: "));
Serial.println((unsigned long)capacity);
void *inPlace = allocator.reallocate(current, capacity);
Serial.print(F(" grow up to existing capacity, same memory block: "));
Serial.println(inPlace == current ? F("yes") : F("no"));
if (inPlace != nullptr) {
current = inPlace;
}
handle = pool.handleFromPointer(current);
capacity = pool.capacity(handle);
void *grown = allocator.reallocate(current, capacity + MEMPOOL_BLOCK_SIZE);
Serial.print(F(" grow past capacity, moved into a larger block: "));
Serial.println(grown != nullptr && grown != current ? F("yes") : F("no"));
if (grown != nullptr) {
current = grown;
}
Serial.println(F("\nTechnical view: allocator lease before cleanup."));
printActiveLeases();
printMemorySummary(F("before allocator cleanup"));
allocator.deallocate(current);
Serial.println(F("\nAllocator memory was returned to the pool."));
printMemorySummary(F("after reallocation demo"));
printTechnicalSnapshot(F("after reallocation demo"));
}
void runFragmentationDemo() {
Serial.println(F("\n--- Fragmentation and recovery demo ---"));
Serial.println(F("Story: memory is like a row of parking spaces. A large buffer needs"));
Serial.println(F("neighboring spaces, not just enough spaces scattered around."));
Serial.println(F("This demo resets the pool so the pattern is easy to see."));
releasePersistentLeases();
pool.init();
printMemorySummary(F("after reset for fragmentation"));
static const size_t chunkCount = 8;
static const size_t chunkBytes = 1024;
MemPool::Lease chunks[chunkCount];
Serial.println(F("\nStep 1: fill the 8 KB pool with eight 1 KB buffers."));
for (size_t i = 0; i < chunkCount; i++) {
char tag[MEMPOOL_TAG_MAX_LEN];
snprintf(tag, sizeof(tag), "frag%u", (unsigned int)i);
chunks[i] = pool.allocLease(chunkBytes, tag);
if (!chunks[i]) {
Serial.println(F("Failed while filling the pool for fragmentation demo."));
printFailureReason();
return;
}
}
printMemorySummary(F("after filling pool with 8 x 1024-byte buffers"));
Serial.println(F("\nStep 2: release every other buffer, creating holes."));
for (size_t i = 1; i < chunkCount; i += 2) {
chunks[i].release();
}
Serial.println(F("There is plenty of total free memory, but each open run is only 1 KB."));
printMemorySummary(F("after punching holes"));
Serial.println(F("\nTechnical view: active buffers are separated by holes."));
printActiveLeases();
Serial.println(F("\nStep 3: request one 2 KB buffer."));
MemPool::Lease large = pool.allocLease(2048, "frag_big");
if (!large) {
Serial.println(F("Expected result: it fails because no 2 KB contiguous run exists."));
printFailureReason();
} else {
Serial.println(F("Unexpected result: 2048-byte allocation succeeded."));
large.release();
}
Serial.println(F("\nStep 4: release the remaining buffers to make one open run again."));
for (size_t i = 0; i < chunkCount; i++) {
chunks[i].release();
}
large = pool.allocLease(2048, "frag_big");
Serial.print(F(" retry 2 KB allocation after recovery: "));
Serial.println(large ? F("ok") : F("failed"));
large.release();
printMemorySummary(F("after fragmentation recovery"));
printTechnicalSnapshot(F("after fragmentation recovery"));
}
void runFailureDemo() {
Serial.println(F("\n--- Clean allocation failure demo ---"));
Serial.println(F("Story: in embedded systems, running out of memory should be a handled"));
Serial.println(F("event, not a mystery crash or silent data corruption."));
size_t tooLarge = ((size_t)MEMPOOL_BLOCK_SIZE * (size_t)MEMPOOL_BLOCK_COUNT) + 1;
printMemorySummary(F("before clean failure"));
Serial.println(F("\nStep 1: deliberately ask for one byte more than the whole pool."));
Serial.print(F("Requesting "));
Serial.print((unsigned long)tooLarge);
Serial.print(F(" bytes from a "));
Serial.print((unsigned long)((size_t)MEMPOOL_BLOCK_SIZE * (size_t)MEMPOOL_BLOCK_COUNT));
Serial.println(F("-byte arena."));
MemPool::Lease impossible = pool.allocLease(tooLarge, "too_large");
if (!impossible) {
Serial.println(F("\nVisitor view: the allocation was refused, and the board keeps running."));
printFailureReason();
} else {
Serial.println(F(" unexpected allocation success"));
impossible.release();
}
Serial.println(F("\nTechnical view: the failure counter records why it failed."));
printMemorySummary(F("after clean failure"));
printTechnicalSnapshot(F("after clean failure"));
}
void runEnvironmentalPipelineDemo() {
Serial.println(F("\n--- Environmental sensing pipeline demo ---"));
Serial.println(F("Story: one field sample may need multiple formats: a readable sensor"));
Serial.println(F("record, a CSV row for SD logging, and a JSON message for sending."));
printMemorySummary(F("before pipeline"));
{
LoomJsonDocument payload(768, MemPoolJsonAllocator(&pool));
MemPool::Lease sdRow = pool.allocLease(256, "sd_row");
MemPool::Lease radioMessage = pool.allocLease(512, "lora_msg");
if (payload.capacity() == 0 || !sdRow || !radioMessage) {
Serial.println(F("Failed to allocate one or more pipeline buffers."));
printFailureReason();
return;
}
unsigned long sample = millis() / 1000UL;
int tempX10 = 220 + (int)(sample % 15UL);
int rhX10 = 500 + (int)((sample * 2UL) % 60UL);
unsigned int co2 = 420U + (unsigned int)((sample * 5UL) % 120UL);
unsigned int batteryMv = 4100U - (unsigned int)(sample % 120UL);
payload["site"] = "expo_canopy";
payload["sample"] = sample;
payload["temp_c_x10"] = tempX10;
payload["rh_x10"] = rhX10;
payload["co2_ppm"] = co2;
payload["battery_mv"] = batteryMv;
Serial.println(F("\nStep 1: collect one environmental reading."));
Serial.println(F(" site: expo_canopy"));
printFixedX10(F("temperature"), tempX10, F(" C"));
printFixedX10(F("relative humidity"), rhX10, F(" %"));
Serial.print(F(" CO2: "));
Serial.print(co2);
Serial.println(F(" ppm"));
Serial.print(F(" battery: "));
Serial.print(batteryMv);
Serial.println(F(" mV"));
Serial.println(F("\nStep 2: format the same reading for different outputs."));
snprintf(sdRow.chars(), sdRow.size(), "%lu,%d,%d,%u,%u",
sample, tempX10, rhX10, co2, batteryMv);
size_t jsonBytes = measureJson(payload);
if (jsonBytes + 1 > radioMessage.size()) {
Serial.println(F("Serialized payload does not fit radio lease."));
return;
}
serializeJson(payload, radioMessage.chars(), radioMessage.size());
radioMessage.chars()[jsonBytes] = '\0';
pool.resize(radioMessage.handle(), jsonBytes + 1);
Serial.print(F(" CSV row for SD: "));
Serial.println(sdRow.chars());
Serial.print(F(" JSON message for radio/MQTT: "));
Serial.println(radioMessage.chars());
printByteBudget(F("JSON message buffer"), jsonBytes + 1, radioMessage.capacity());
Serial.println(F("\nTechnical view: three temporary pipeline buffers are active."));
printLeaseSummary(F("SD row"), sdRow);
printLeaseSummary(F("radio message"), radioMessage);
printActiveLeases();
printMemorySummary(F("inside pipeline"));
}
Serial.println(F("\nPipeline scope ended; SD row, JSON doc, and radio buffer returned."));
printMemorySummary(F("after pipeline"));
printTechnicalSnapshot(F("after pipeline"));
}
void runMockSdConfigDemo() {
Serial.println(F("\n--- Mock SD config file lease demo ---"));
Serial.println(F("Story: many Loom deployments load settings from an SD card. This demo"));
Serial.println(F("uses a fake file string so no SD card is needed at the expo table."));
printMemorySummary(F("before mock SD config"));
{
const char configJson[] =
"{\"site\":\"expo_canopy\",\"interval_s\":60,\"sensors\":[\"SHT31\",\"SCD30\",\"battery\"]}";
Serial.println(F("\nStep 1: copy the file contents into a pool lease."));
MemPool::Lease fileLease = pool.allocLease(sizeof(configJson), "sd_file");
if (!fileLease) {
Serial.println(F("Failed to allocate mock SD file lease."));
printFailureReason();
return;
}
if (!pool.write(fileLease.handle(), 0, configJson, sizeof(configJson))) {
Serial.println(F("Failed to copy mock file contents into lease."));
return;
}
Serial.print(F(" mock file text: "));
Serial.println(fileLease.chars());
printLeaseSummary(F("file buffer"), fileLease);
Serial.println(F("\nStep 2: parse the config into a MemPool-backed JSON document."));
LoomJsonDocument configDoc(512, MemPoolJsonAllocator(&pool));
if (configDoc.capacity() == 0) {
Serial.println(F("Failed to allocate config JSON document."));
printFailureReason();
return;
}
DeserializationError err = deserializeJson(configDoc, fileLease.chars());
if (err != DeserializationError::Ok) {
Serial.print(F("deserializeJson failed: "));
Serial.println(err.c_str());
return;
}
Serial.println(F("\nVisitor view: settings loaded from the file."));
Serial.print(F(" parsed site: "));
Serial.println(configDoc["site"] | "(missing)");
Serial.print(F(" parsed interval_s: "));
Serial.println((int)(configDoc["interval_s"] | -1));
Serial.print(F(" parsed sensors: "));
Serial.print(configDoc["sensors"][0] | "?");
Serial.print(F(", "));
Serial.print(configDoc["sensors"][1] | "?");
Serial.print(F(", "));
Serial.println(configDoc["sensors"][2] | "?");
Serial.println(F("\nTechnical view: file text and parsed JSON are separate leases."));
printActiveLeases();
printMemorySummary(F("inside mock SD config"));
}
Serial.println(F("\nMock SD config scope ended; file and parsed config leases returned."));
printMemorySummary(F("after mock SD config"));
printTechnicalSnapshot(F("after mock SD config"));
}
void runLoraNoRadioDemo() {
Serial.println(F("\n--- LoRa no-radio packet simulation ---"));
Serial.println(F("Story: Loom collects an environmental reading, packs it into one small"));
Serial.println(F("LoRa radio message, receives it, and returns all temporary memory."));
printMemorySummary(F("before LoRa simulation"));
{
static const size_t LORA_FRAME_BYTES = 251;
MemPool::Lease rawPacket = pool.allocLease(LORA_FRAME_BYTES, "lora_raw");
if (!rawPacket) {
Serial.println(F("Failed to allocate LoRa raw packet lease."));
printFailureReason();
return;
}
Serial.println(F("\nStep 1: reserve one radio frame from the pool."));
printLeaseSummary(F("raw frame"), rawPacket);
{
LoomJsonDocument outbound(512, MemPoolJsonAllocator(&pool));
if (outbound.capacity() == 0) {
Serial.println(F("Failed to allocate outbound JSON document."));
printFailureReason();
return;
}
int tempX10 = 224;
int rhX10 = 509;
unsigned int co2 = 437;
outbound["type"] = "data";
outbound["node"] = "expo_node";
outbound["packet"] = 1;
outbound["temp_c_x10"] = tempX10;
outbound["rh_x10"] = rhX10;
outbound["co2_ppm"] = co2;
Serial.println(F("\nStep 2: make a human-readable environmental reading."));
Serial.println(F(" node: expo_node"));
printFixedX10(F("temperature"), tempX10, F(" C"));
printFixedX10(F("relative humidity"), rhX10, F(" %"));
Serial.print(F(" CO2: "));
Serial.print(co2);
Serial.println(F(" ppm"));
Serial.print(F(" outbound JSON: "));
serializeJson(outbound, Serial);
Serial.println();
size_t packetBytes = measureMsgPack(outbound);
size_t jsonBytes = measureJson(outbound);
Serial.println(F("\nStep 3: compare plain JSON to the packed radio message."));
printByteBudget(F("plain JSON text"), jsonBytes, LORA_FRAME_BYTES);
printByteBudget(F("packed radio message"), packetBytes, LORA_FRAME_BYTES);
if (packetBytes == 0 || packetBytes > LORA_FRAME_BYTES) {
Serial.println(F("Outbound packet does not fit in one LoRa frame."));
return;
}
Serial.println(F("\nStep 4: write the packed message into the raw frame lease."));
size_t written = serializeMsgPack(outbound, rawPacket.bytes(), LORA_FRAME_BYTES);
pool.resize(rawPacket.handle(), written);
printByteBudget(F("actual radio frame used"), written, LORA_FRAME_BYTES);
printLeaseSummary(F("raw frame after resize"), rawPacket);
Serial.println(F("\nActive leases during transmit stage:"));
printActiveLeases();
printMemorySummary(F("transmit stage"));
}
Serial.println(F("\nStep 5: the transmit JSON document is gone."));
Serial.println(F("Only the compact radio frame stays alive for the receive step."));
printActiveLeases();
{
LoomJsonDocument inbound(768, MemPoolJsonAllocator(&pool));
if (inbound.capacity() == 0) {
Serial.println(F("Failed to allocate inbound JSON document."));
printFailureReason();
return;
}
Serial.println(F("\nStep 6: receive side decodes the compact frame back to values."));
DeserializationError err =
deserializeMsgPack(inbound, rawPacket.bytes(), rawPacket.size());
if (err != DeserializationError::Ok) {
Serial.print(F("deserializeMsgPack failed: "));
Serial.println(err.c_str());
return;
}
Serial.print(F(" decoded packet: "));
serializeJson(inbound, Serial);
Serial.println();
Serial.print(F(" decoded node: "));
Serial.println(inbound["node"] | "(missing)");
printFixedX10(F("decoded temperature"), (int)(inbound["temp_c_x10"] | -999),
F(" C"));
printFixedX10(F("decoded humidity"), (int)(inbound["rh_x10"] | -999), F(" %"));
Serial.print(F(" decoded CO2: "));
Serial.print((int)(inbound["co2_ppm"] | -1));
Serial.println(F(" ppm"));
Serial.println(F("\nActive leases while raw packet and inbound doc are in scope:"));
printActiveLeases();
printMemorySummary(F("receive stage"));
}
}
Serial.println(F("\nLoRa simulation scope ended; packet and documents returned to pool."));
printMemorySummary(F("after LoRa no-radio simulation"));
printTechnicalSnapshot(F("after LoRa no-radio simulation"));
}
void handleMenuInput(char input) {
if (isDemoCommand(input)) {
pushTerminalViewDown();
}
switch (input) {
case '0':
runStatsDemo();
break;
case '1':
runLongTermLeaseDemo();
break;
case '2':
runReleaseLongTermDemo();
break;
case '3':
runShortTermLeaseDemo();
break;
case '4':
runJsonLifecycleDemo();
break;
case '5':
runReallocationDemo();
break;
case '6':
runFragmentationDemo();
break;
case '7':
runFailureDemo();
break;
case '8':
runEnvironmentalPipelineDemo();
break;
case '9':
runMockSdConfigDemo();
break;
case 'l':
case 'L':
runLoraNoRadioDemo();
break;
case 'r':
case 'R':
resetDemoPool();
break;
case 'h':
case 'H':
case '?':
break;
default:
Serial.print(F("\nUnknown menu input: "));
Serial.println(input);
break;
}
showMenu();
Serial.println(F("\nReady for next menu input."));
}
void setup() {
Serial.begin(115200);
unsigned long start = millis();
while (!Serial && (millis() - start < 15000UL)) {
delay(10);
}
pool.setFreeRamProvider(freeMemory);
pool.init();
delay(250);
drainSerialInput();
ignoreInputUntilMs = millis() + STARTUP_INPUT_IGNORE_MS;
Serial.println(F("\nLoom MemPool expo menu ready."));
Serial.println(F("No RTC, SD card, or radio hardware is required for this sketch."));
printMemorySummary(F("initial pool state"));
showMenu();
}
void loop() {
if (ignoreInputUntilMs != 0 && millis() < ignoreInputUntilMs) {
drainSerialInput();
return;
}
ignoreInputUntilMs = 0;
while (Serial.available() > 0) {
char input = (char)Serial.read();
if (!isPrintableCommandByte(input)) {
continue;
}
handleMenuInput(input);
}
}