Files
sprocket-core/src/JsonStruct.h
2018-08-26 19:04:25 +02:00

93 lines
2.9 KiB
C++

#ifndef __JSON_STRUCT__
#define __JSON_STRUCT__
#include <ArduinoJson.h>
#include <FS.h>
struct JsonStruct {
SprocketConfig soricketConfig;
MeshConfig meshConfig;
int valid = 0;
// ------------------------------------------------------------------------------------------
virtual void mapJsonObject(JsonObject& json);
virtual void fromJsonObject(JsonObject& json);
virtual int verifyJsonObject(JsonObject& json){
return json.success();
//&& json.containsKey(JSON_DOMAIN)
};
String toJsonString(){
//StaticJsonBuffer<200> StringjsonBuffer;
DynamicJsonBuffer jsonBuffer(JSON_ARRAY_SIZE(300));
JsonObject& root = jsonBuffer.createObject();
mapJsonObject(root);
String jsonString;
root.printTo(jsonString);
return jsonString;
}
String getAttrFromJson(JsonObject& json, const char* attr, String defautValue = ""){
if(json.containsKey(String(attr))){
const char *value = json[attr];
return String(value);
}
return defautValue;
}
int getIntAttrFromJson(JsonObject& json, const char* attr, int defautValue = 0){
if(json.containsKey(attr)){
return json[attr];
}
return defautValue;
}
// Map a json object to this struct.
// Parse a json string and map parsed object
void fromJsonString(String& str){
//StaticJsonBuffer<200> jsonBuffer;
DynamicJsonBuffer jsonBuffer(JSON_ARRAY_SIZE(300));
JsonObject& json = jsonBuffer.parseObject(str);
valid = verifyJsonObject(json);
if(valid) {
fromJsonObject(json);
}
};
void fromFile(const char* path) {
Serial.println("read json");
File configFile = SPIFFS.open(path, "r");
String cfgFileStr = configFile.readString();
// Allocate a buffer to store contents of the file.
//size_t size = configFile.size();
//std::unique_ptr<char[]> buf(new char[size]);
//configFile.readBytes(buf.get(), size);
//StaticJsonBuffer<1024> jsonBuffer;
//JsonObject& json = jsonBuffer.parseObject(buf.get());
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.parseObject(cfgFileStr);
valid = verifyJsonObject(json);
if(configFile) {
Serial.println("map json object");
fromJsonObject(json);
}
if(!valid){
Serial.println("read json failed");
}
configFile.close();
}
void saveFile(const char* path) {
File configFile = SPIFFS.open(path, "w");
DynamicJsonBuffer jsonBuffer(JSON_ARRAY_SIZE(300));
JsonObject& json = jsonBuffer.createObject();
valid = configFile && verifyJsonObject(json);
if(valid){
mapJsonObject(json);
json.printTo(configFile);
}
}
};
#endif