-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconfig.hh
90 lines (74 loc) · 2.36 KB
/
config.hh
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
#pragma once
#include <variant>
#include <optional>
#include <ArduinoJson.h>
struct SetConfigResult {
public:
enum class ErrorType {
NONE,
NO_VALUES,
GENERIC,
};
public:
static SetConfigResult okay() {
return SetConfigResult { .type=ErrorType::NONE };
}
static SetConfigResult no_values_set() {
return SetConfigResult {.type=ErrorType::NO_VALUES, .message="No config values set"};
}
static SetConfigResult error(String message) {
return SetConfigResult { .type=ErrorType::GENERIC, .message=message };
}
bool is_okay() const { return type == ErrorType::NONE; }
template <typename T>
bool maybe_set(const JsonObject& obj, const char* name, T& out) {
auto field = obj[name];
if (field.isNull()) {
return false;
}
// If we haven't seen any values yet but the field is there, we're good now!
if (type == ErrorType::NO_VALUES) {
*this = okay();
}
out = field.as<T>();
return true;
}
template <typename T>
T value_or(const JsonObject& obj, const char* name, const T& fallback) {
auto field = obj[name];
if (field.isNull()) {
return fallback;
}
// If we haven't seen any values yet but the field is there, we're good now!
if (type == ErrorType::NO_VALUES) {
*this = okay();
}
return field.as<T>();
}
SetConfigResult& consider(const SetConfigResult& rhs, const String& name="") {
if (is_okay() && rhs.type == SetConfigResult::ErrorType::NO_VALUES) {
return *this;
}
if (rhs.is_okay()) {
// If there were no values, but the latest is okay we're okay too!
if (type == SetConfigResult::ErrorType::NO_VALUES) {
*this = rhs;
}
return *this;
}
if (type != rhs.type) {
// If the errors are different, just give a generic error back.
type = ErrorType::GENERIC;
}
if (type == ErrorType::GENERIC) {
if (!message.length() == 0) {
message += " " + name + ":";
}
message += " '" + rhs.message + "'";
}
return *this;
}
// Default to a good state
ErrorType type = ErrorType::NONE;
String message;
};