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
#![doc = include_str!("../README.md")]
#![no_std]
use embedded_io::{ErrorType, Read, ReadReady, Write};
use heapless::String;
use miniconf::{
json, postcard, Path, Traversal, TreeDeserializeOwned, TreeKey,
TreeSerialize,
};
mod interface;
pub use interface::BestEffortInterface;
/// Specifies the API required for objects that are used as settings with the serial terminal
/// interface.
pub trait Settings:
TreeKey + TreeSerialize + TreeDeserializeOwned + Clone
{
/// Reset the settings to their default values.
fn reset(&mut self) {}
}
/// Platform support for serial settings.
///
/// Covers platform-specific commands, persistent key-value storage and the
/// Read/Write interface for interaction.
///
/// Assuming there are no unit fields in the `Settings`, the empty value can be
/// used to mark the "cleared" state.
pub trait Platform {
/// This type specifies the interface to the user, for example, a USB CDC-ACM serial port.
type Interface: embedded_io::Read
+ embedded_io::ReadReady
+ embedded_io::Write;
type Error: core::fmt::Debug;
type Settings: Settings;
/// Fetch a value from persisten storage
fn fetch<'a>(
&mut self,
buf: &'a mut [u8],
key: &[u8],
) -> Result<Option<&'a [u8]>, Self::Error>;
/// Store a value to persistent storage
fn store(
&mut self,
buf: &mut [u8],
key: &[u8],
value: &[u8],
) -> Result<(), Self::Error>;
/// Remove a key from storage.
fn clear(&mut self, buf: &mut [u8], key: &[u8]) -> Result<(), Self::Error>;
/// Execute a platform specific command.
fn cmd(&mut self, cmd: &str);
/// Return a mutable reference to the `Interface`.
fn interface_mut(&mut self) -> &mut Self::Interface;
}
struct Interface<'a, P, const Y: usize> {
platform: P,
buffer: &'a mut [u8],
updated: bool,
}
impl<'a, P: Platform, const Y: usize> Interface<'a, P, Y> {
fn handle_platform(
_menu: &menu::Menu<Self, P::Settings>,
item: &menu::Item<Self, P::Settings>,
args: &[&str],
interface: &mut Self,
_settings: &mut P::Settings,
) {
let key = menu::argument_finder(item, args, "cmd").unwrap().unwrap();
interface.platform.cmd(key)
}
fn iter_root<F>(
key: Option<&str>,
interface: &mut Self,
settings: &mut P::Settings,
mut func: F,
) where
F: FnMut(
Path<&str, '/'>,
&mut Self,
&mut P::Settings,
&mut P::Settings,
),
{
let mut iter = P::Settings::nodes::<Path<String<128>, '/'>, Y>();
if let Some(key) = key {
match iter.root(Path::<_, '/'>::from(key)) {
Ok(it) => iter = it,
Err(e) => {
writeln!(interface, "Failed to locate `{key}`: {e}")
.unwrap();
return;
}
};
}
let mut defaults = settings.clone();
defaults.reset();
for key in iter {
match key {
Ok((key, node)) => {
debug_assert!(node.is_leaf());
func(
key.as_str().into(),
interface,
settings,
&mut defaults,
)
}
Err(depth) => {
writeln!(
interface,
"Failed to build path: no space at depth {depth}"
)
.unwrap();
}
}
}
}
fn handle_get(
_menu: &menu::Menu<Self, P::Settings>,
item: &menu::Item<Self, P::Settings>,
args: &[&str],
interface: &mut Self,
settings: &mut P::Settings,
) {
let key = menu::argument_finder(item, args, "path").unwrap();
Self::iter_root(
key,
interface,
settings,
|key, interface, settings, defaults| {
// Get current
let check =
match json::get_by_key(settings, key, interface.buffer) {
Err(miniconf::Error::Traversal(Traversal::Absent(
_,
))) => {
return;
}
Err(e) => {
writeln!(
interface,
"Failed to get `{}`: {e}",
*key
)
.unwrap();
return;
}
Ok(len) => {
write!(
interface.platform.interface_mut(),
"{}: {}",
*key,
core::str::from_utf8(&interface.buffer[..len])
.unwrap()
)
.unwrap();
yafnv::fnv1a::<u32>(&interface.buffer[..len])
}
};
// Get default and compare
match json::get_by_key(defaults, key, interface.buffer) {
Err(miniconf::Error::Traversal(Traversal::Absent(_))) => {
write!(interface, " [default: absent]")
}
Err(e) => {
write!(interface, " [default serialization error: {e}]")
}
Ok(len) => {
if yafnv::fnv1a::<u32>(&interface.buffer[..len])
!= check
{
write!(
interface.platform.interface_mut(),
" [default: {}]",
core::str::from_utf8(&interface.buffer[..len])
.unwrap()
)
} else {
write!(interface, " [default]")
}
}
}
.unwrap();
// Get stored and compare
match interface.platform.fetch(interface.buffer, key.as_bytes())
{
Err(e) => write!(
interface,
" [fetch error: {e:?}]"
),
Ok(None) =>
write!(interface, " [not stored]"),
Ok(Some(stored)) => {
let slic = ::postcard::de_flavors::Slice::new(stored);
// Use defaults as scratch space for postcard->json conversion
match postcard::set_by_key(defaults, key, slic) {
Err(e) => write!(
interface,
" [stored deserialize error: {e}]"
),
Ok(_rest) =>
match json::get_by_key(defaults, key, interface.buffer) {
Err(e) => write!(
interface,
" [stored serialization error: {e}]"
),
Ok(len) => {
if yafnv::fnv1a::<u32>(&interface.buffer[..len]) != check {
write!(
interface.platform.interface_mut(),
" [stored: {}]",
core::str::from_utf8(&interface.buffer[..len]).unwrap())
} else {
write!(
interface,
" [stored]"
)
}
},
}
}
}
}.unwrap();
writeln!(interface).unwrap();
},
);
}
fn handle_clear(
_menu: &menu::Menu<Self, P::Settings>,
item: &menu::Item<Self, P::Settings>,
args: &[&str],
interface: &mut Self,
settings: &mut P::Settings,
) {
let key = menu::argument_finder(item, args, "path").unwrap();
Self::iter_root(
key,
interface,
settings,
|key, interface, settings, defaults| {
// Get current value checksum
let slic =
::postcard::ser_flavors::Slice::new(interface.buffer);
let check = match postcard::get_by_key(settings, key, slic) {
Err(miniconf::Error::Traversal(Traversal::Absent(_))) => {
return;
}
Err(e) => {
writeln!(interface, "Failed to get {}: {e:?}", *key)
.unwrap();
return;
}
Ok(slic) => yafnv::fnv1a::<u32>(slic),
};
// Get default if different
let slic =
::postcard::ser_flavors::Slice::new(interface.buffer);
let slic = match postcard::get_by_key(defaults, key, slic) {
Err(miniconf::Error::Traversal(Traversal::Absent(_))) => {
log::warn!(
"Can't clear. Default is absent: `{}`",
*key
);
None
}
Err(e) => {
writeln!(
interface,
"Failed to get default `{}`: {e}",
*key
)
.unwrap();
return;
}
Ok(slic) => {
if yafnv::fnv1a::<u32>(slic) != check {
Some(slic)
} else {
None
}
}
};
// Set default
if let Some(slic) = slic {
let slic = ::postcard::de_flavors::Slice::new(slic);
match postcard::set_by_key(settings, key, slic) {
Err(miniconf::Error::Traversal(Traversal::Absent(
_,
))) => {
return;
}
Err(e) => {
writeln!(
interface,
"Failed to set {}: {e:?}",
*key
)
.unwrap();
return;
}
Ok(_rest) => {
interface.updated = true;
writeln!(interface, "Cleared current `{}`", *key)
.unwrap()
}
}
}
// Check for stored
match interface.platform.fetch(interface.buffer, key.as_bytes())
{
Err(e) => {
writeln!(
interface,
"Failed to fetch `{}`: {e:?}",
*key
)
.unwrap();
}
Ok(None) => {}
// Clear stored
Ok(Some(_stored)) => match interface
.platform
.clear(interface.buffer, key.as_bytes())
{
Ok(()) => {
writeln!(interface, "Clear stored `{}`", *key)
}
Err(e) => {
writeln!(
interface,
"Failed to clear `{}` from storage: {e:?}",
*key
)
}
}
.unwrap(),
}
},
);
interface.updated = true;
writeln!(interface, "Some values may require reboot to become active")
.unwrap();
}
fn handle_store(
_menu: &menu::Menu<Self, P::Settings>,
item: &menu::Item<Self, P::Settings>,
args: &[&str],
interface: &mut Self,
settings: &mut P::Settings,
) {
let key = menu::argument_finder(item, args, "path").unwrap();
let force = menu::argument_finder(item, args, "force")
.unwrap()
.is_some();
Self::iter_root(
key,
interface,
settings,
|key, interface, settings, defaults| {
// Get default value checksum
let slic =
::postcard::ser_flavors::Slice::new(interface.buffer);
let mut check = match postcard::get_by_key(defaults, key, slic)
{
// Could also serialize directly into the hasher for all these checksum calcs
Ok(slic) => yafnv::fnv1a::<u32>(slic),
Err(miniconf::Error::Traversal(Traversal::Absent(
_depth,
))) => {
log::warn!("Default absent: `{}`", *key);
return;
}
Err(e) => {
writeln!(
interface,
"Failed to get `{}` default: {e:?}",
*key
)
.unwrap();
return;
}
};
// Get stored value checksum
match interface.platform.fetch(interface.buffer, key.as_bytes())
{
Ok(None) => {}
Ok(Some(stored)) => {
let stored = yafnv::fnv1a::<u32>(stored);
if stored != check {
log::debug!(
"Stored differs from default: `{}`",
*key
);
} else {
log::debug!("Stored matches default: `{}`", *key);
}
check = stored;
}
Err(e) => {
writeln!(
interface,
"Failed to fetch `{}`: {e:?}",
*key
)
.unwrap();
}
}
// Get value
let slic =
::postcard::ser_flavors::Slice::new(interface.buffer);
let value = match postcard::get_by_key(settings, key, slic) {
Ok(value) => value,
Err(miniconf::Error::Traversal(Traversal::Absent(
_depth,
))) => {
return;
}
Err(e) => {
writeln!(interface, "Could not get `{}`: {e}", *key)
.unwrap();
return;
}
};
// Check for mismatch
if yafnv::fnv1a::<u32>(value) == check && !force {
log::debug!(
"Not saving matching default/stored `{}`",
*key
);
return;
}
let len = value.len();
let (value, rest) = interface.buffer.split_at_mut(len);
// Store
match interface.platform.store(rest, key.as_bytes(), value) {
Ok(_) => writeln!(interface, "`{}` stored", *key),
Err(e) => {
writeln!(interface, "Failed to store `{}`: {e:?}", *key)
}
}
.unwrap();
},
);
writeln!(interface, "Some values may require reboot to become active")
.unwrap();
}
fn handle_set(
_menu: &menu::Menu<Self, P::Settings>,
item: &menu::Item<Self, P::Settings>,
args: &[&str],
interface: &mut Self,
settings: &mut P::Settings,
) {
let key = menu::argument_finder(item, args, "path").unwrap().unwrap();
let value =
menu::argument_finder(item, args, "value").unwrap().unwrap();
// Now, write the new value into memory.
match json::set(settings, key, value.as_bytes()) {
Ok(_) => {
interface.updated = true;
writeln!(
interface,
"Set but not stored. May require store and reboot to activate."
)
}
Err(e) => {
writeln!(interface, "Failed to set `{key}`: {e:?}")
}
}
.unwrap();
}
fn menu() -> menu::Menu<'a, Self, P::Settings> {
menu::Menu {
label: "settings",
items: &[
&menu::Item {
command: "get",
help: Some("List paths and read current, default, and stored values"),
item_type: menu::ItemType::Callback {
function: Self::handle_get,
parameters: &[menu::Parameter::Optional {
parameter_name: "path",
help: Some("The path of the value or subtree to list/read."),
}]
},
},
&menu::Item {
command: "set",
help: Some("Update a value"),
item_type: menu::ItemType::Callback {
function: Self::handle_set,
parameters: &[
menu::Parameter::Mandatory {
parameter_name: "path",
help: Some("The path to set"),
},
menu::Parameter::Mandatory {
parameter_name: "value",
help: Some("The value to be written, JSON-encoded"),
},
]
},
},
&menu::Item {
command: "store",
help: Some("Store values that differ from defaults"),
item_type: menu::ItemType::Callback {
function: Self::handle_store,
parameters: &[
menu::Parameter::Named {
parameter_name: "force",
help: Some("Also store values that match defaults"),
},
menu::Parameter::Optional {
parameter_name: "path",
help: Some("The path of the value or subtree to store."),
},
]
},
},
&menu::Item {
command: "clear",
help: Some("Clear active to defaults and remove all stored values"),
item_type: menu::ItemType::Callback {
function: Self::handle_clear,
parameters: &[
menu::Parameter::Optional {
parameter_name: "path",
help: Some("The path of the value or subtree to clear"),
},
]
},
},
&menu::Item {
command: "platform",
help: Some("Platform specific commands"),
item_type: menu::ItemType::Callback {
function: Self::handle_platform,
parameters: &[menu::Parameter::Mandatory {
parameter_name: "cmd",
help: Some("The name of the command (e.g. `reboot`, `service`, `dfu`)."),
}]
},
},
],
entry: None,
exit: None,
}
}
}
impl<'a, P: Platform, const Y: usize> core::fmt::Write for Interface<'a, P, Y> {
fn write_str(&mut self, s: &str) -> core::fmt::Result {
self.platform
.interface_mut()
.write_all(s.as_bytes())
.or(Err(core::fmt::Error))
}
}
impl<'a, P: Platform, const Y: usize> ErrorType for Interface<'a, P, Y> {
type Error = <P::Interface as ErrorType>::Error;
}
impl<'a, P: Platform, const Y: usize> Write for Interface<'a, P, Y> {
fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
self.platform.interface_mut().write(buf)
}
fn flush(&mut self) -> Result<(), Self::Error> {
self.platform.interface_mut().flush()
}
}
// The Menu runner
pub struct Runner<'a, P: Platform, const Y: usize>(
menu::Runner<'a, Interface<'a, P, Y>, P::Settings, [u8]>,
);
impl<'a, P: Platform, const Y: usize> Runner<'a, P, Y> {
/// Constructor
///
/// # Args
/// * `platform` - The platform associated with the serial settings, providing the necessary
/// context and API to manage device settings.
///
/// * `line_buf` - A buffer used for maintaining the serial menu input line. It should be at
/// least as long as the longest user input.
///
/// * `serialize_buf` - A buffer used for serializing and deserializing settings. This buffer
/// needs to be at least as big as twice the biggest serialized setting plus its path.
pub fn new(
platform: P,
line_buf: &'a mut [u8],
serialize_buf: &'a mut [u8],
settings: &mut P::Settings,
) -> Result<Self, P::Error> {
Ok(Self(menu::Runner::new(
Interface::menu(),
line_buf,
Interface {
platform,
buffer: serialize_buf,
updated: false,
},
settings,
)))
}
/// Get the device communication interface
pub fn interface_mut(&mut self) -> &mut P::Interface {
self.0.interface.platform.interface_mut()
}
pub fn platform_mut(&mut self) -> &mut P {
&mut self.0.interface.platform
}
pub fn platform(&mut self) -> &P {
&self.0.interface.platform
}
/// Must be called periodically to process user input.
///
/// # Returns
/// A boolean indicating true if the settings were modified.
pub fn poll(
&mut self,
settings: &mut P::Settings,
) -> Result<bool, <P::Interface as embedded_io::ErrorType>::Error> {
self.0.interface.updated = false;
while self.interface_mut().read_ready()? {
let mut buffer = [0u8; 64];
let count = self.interface_mut().read(&mut buffer)?;
for &value in &buffer[..count] {
self.0.input_byte(value, settings);
}
}
Ok(self.0.interface.updated)
}
}