Using as state keeper
Created by: dvv
Hello, am looking for a way to keep a state "map" of a system. Initially empty, it is updated via incoming JSON key-value messages. I'd like to both keep the state and react to changes to the state. Below is a draft of what I mean.
// FIXME 1: global (https://arduinojson.org/faq/why-shouldnt-i-use-a-global-jsonbuffer?utm_source=github&utm_medium=issues)
// ^^^^^^^^^^^^
static StaticJsonBuffer<1024> stateBuffer;
static JsonObject& state = stateBuffer.createObject();
// updater
void onData(char *buf)
{
StaticJsonBuffer<256> jsonBuffer;
JsonObject& msg = jsonBuffer.parseObject(buf);
if (!msg.success()) return;
for (auto kv : msg) {
// FIXME 2: no comparison for JsonVariantBase vs JsonVariantBase
// ^^^^^^^^^^^^
if (kv.value != state[kv.key]) {
state[kv.key] = kv.value;
onChanged(kv.key, kv.value);
}
}
}
// reactor
void onChanged(char *key, JsonVariant& value)
{
// custom logic, may involve global state
}
Questions:
- on FIXME 1: is it legal to use global here as it is only updated, not used for parsing?
- on FIXME 2: is there a method to compare two variants (other than serializing them to JSON and comparing resulting strings which is inelegant and ineffective)?
- is there an alternate solution to the problem of maintaining the state?
TIA, --Vladimir