bool simpleAuth::changePasswordHandler( Session &session,ESP8266WebServer *s,String &p){ DynamicJsonBuffer jsonBuffer; JsonObject& r = jsonBuffer.createObject(); r["exitcode"]="0"; r["exitmsg"]="OK password changed"; r["time"]=millis(); String callback=s->arg("callback"); if (s->arg("newpassword")==s->arg("newpassword2")){ String oldpass(s->arg("oldpassword")); String newpass(s->arg("newpassword")); bool chpass=this->changeUserPassword(session.user,oldpass,newpass); if (!chpass){ r["exitcode"]="20"; r["exitmsg"]="password change failed"; } } else{ r["exitcode"]="10"; r["exitmsg"]="new password repeat is not identical"; } String dstr; r.prettyPrintTo(dstr); s->send(200, "application/javascript",callback+"("+dstr+");"); return(true); }
//Load config from Json file in SPIFFS boolean loadJsonParam(const char *service) { File configFile = SPIFFS.open("/config/config.json", "r"); if (!configFile) { Serial.println("ERROR: Failed to open config file (loadJsonParam)"); return (boolean) false; } size_t size = configFile.size(); if (size > 1024) { Serial.println("ERROR: Config file size is too large (loadJsonParam)"); return (boolean) false; } std::unique_ptr<char[]> buf(new char[size]); configFile.readBytes(buf.get(), size); DynamicJsonBuffer jsonBuffer; JsonObject &json = jsonBuffer.parseObject(buf.get()); if (!json.success()) { Serial.println("ERROR: Failed to parse config file (loadJsonParam)"); return (boolean) false; } boolean config = json[service]["enabled"]; if (config) { return (boolean) true; } return (boolean) false; }
void BootConfig::_generateNetworksJson() { DynamicJsonBuffer generatedJsonBuffer = DynamicJsonBuffer(JSON_OBJECT_SIZE(1) + JSON_ARRAY_SIZE(_ssidCount) + (_ssidCount * JSON_OBJECT_SIZE(3))); // 1 at root, 3 in childrend JsonObject& json = generatedJsonBuffer.createObject(); JsonArray& networks = json.createNestedArray("networks"); for (int network = 0; network < _ssidCount; network++) { JsonObject& jsonNetwork = generatedJsonBuffer.createObject(); jsonNetwork["ssid"] = WiFi.SSID(network); jsonNetwork["rssi"] = WiFi.RSSI(network); switch (WiFi.encryptionType(network)) { case ENC_TYPE_WEP: jsonNetwork["encryption"] = "wep"; break; case ENC_TYPE_TKIP: jsonNetwork["encryption"] = "wpa"; break; case ENC_TYPE_CCMP: jsonNetwork["encryption"] = "wpa2"; break; case ENC_TYPE_NONE: jsonNetwork["encryption"] = "none"; break; case ENC_TYPE_AUTO: jsonNetwork["encryption"] = "auto"; break; } networks.add(jsonNetwork); } delete[] _jsonWifiNetworks; size_t jsonBufferLength = json.measureLength() + 1; _jsonWifiNetworks = new char[jsonBufferLength]; json.printTo(_jsonWifiNetworks, jsonBufferLength); }
MeteoConfig loadConfig() { DynamicJsonBuffer jsonBuffer; MeteoConfig cfg; if (fileExist(METEO_CONFIG_FILE)) { int size = fileGetSize(METEO_CONFIG_FILE); char* jsonString = new char[size + 1]; fileGetContent(METEO_CONFIG_FILE, jsonString, size + 1); JsonObject& root = jsonBuffer.parseObject(jsonString); JsonObject& network = root["network"]; cfg.NetworkSSID = String((const char*)network["ssid"]); cfg.NetworkPassword = String((const char*)network["password"]); JsonObject& correction = root["correction"]; cfg.AddT1 = correction["T1"]; cfg.AddT2 = correction["T2"]; cfg.AddTZ = correction["TZ"]; JsonObject& trigger = root["trigger"]; cfg.Trigger = (TriggerType)(int)trigger["type"]; cfg.RangeMin = trigger["min"]; cfg.RangeMax = trigger["max"]; delete[] jsonString; } else { cfg.NetworkSSID = WIFI_SSID; cfg.NetworkPassword = WIFI_PWD; } return cfg; }
boolean saveJsonConfig(const char *service, const char *param, boolean status) { File configFile = SPIFFS.open("/config/config.json", "r"); if (!configFile) { Serial.println("ERROR: Failed to open config file (saveJsonConfig)"); return (boolean) false; } size_t size = configFile.size(); if (size > 1024) { Serial.println("ERROR: Config file size is too large (saveJsonConfig)"); return (boolean) false; } std::unique_ptr<char[]> buf(new char[size]); configFile.readBytes(buf.get(), size); DynamicJsonBuffer jsonBuffer; JsonObject &json = jsonBuffer.parseObject(buf.get()); if (!json.success()) { Serial.println("ERROR: Failed to parse config file (saveJsonConfig)"); return (boolean) false; } configFile.close(); JsonObject &nested = json[service]; nested.set(param, status); configFile = SPIFFS.open("/config/config.json", "w+"); json.prettyPrintTo(configFile); return (boolean) true; }
/******************************************************************** parse the websocket json and look for a message type ********************************************************************/ void ArduinoSlackBot::parseResponse(char *payload) { DynamicJsonBuffer jsonBuffer; JsonObject& root = jsonBuffer.parseObject(payload); if (root.success()) { if (root.containsKey("type")) { slackMsg.type = root["type"]; PRINTLN(slackMsg.type); PRINT("free heap size:"); PRINTLN(ESP.getFreeHeap()); if (strcasecmp(slackMsg.type, "message") == 0) { slackMsg.channel = root["channel"]; slackMsg.user = root["user"]; slackMsg.text = root["text"]; slackMsg.timestamp = root["ts"]; slackMsg.team = root["team"]; PRINTLN("parseCommands"); parseCmds(); } } } else { PRINTLN("parse fail"); } }
void BootConfig::_onDeviceInfoRequest() { Logger.logln("Received device info request"); DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.createObject(); json["device_id"] = Helpers.getDeviceId(); json["homie_version"] = VERSION; JsonObject& firmware = json.createNestedObject("firmware"); firmware["name"] = this->_shared_interface->fwname; firmware["version"] = this->_shared_interface->fwversion; JsonArray& nodes = json.createNestedArray("nodes"); for (int i = 0; i < this->_shared_interface->nodes.size(); i++) { HomieNode node = this->_shared_interface->nodes[i]; JsonObject& json_node = jsonBuffer.createObject(); json_node["id"] = node.id; json_node["type"] = node.type; nodes.add(json_node); } // 110 bytes for {"homie_version":"11.10.0","firmware":{"name":"awesome-light-great-top","version":"11.10.0-beta"},"nodes":[]} // 60 bytes for {"id":"lightifydefoulooooo","type":"lightifydefouloooo"}, (-1 for leading ","), +1 for terminator String jsonString; jsonString.reserve(110 + (60 * this->_shared_interface->nodes.size()) - 1 + 1); json.printTo(jsonString); this->_http.send(200, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), jsonString); }
//---------------------------------------------------------------------------- // //---------------------------------------------------------------------------- void CApplication::confSave() { DynamicJsonBuffer jsonBuffer; JsonObject& root = jsonBuffer.createObject(); root["cpuBoost"] = m_cpuBoost; root["otaBaseUrl"] = m_otaBaseUrl.c_str(); root["emul"] = m_gpiodEmul; root["mode"] = m_gpiodMode; root["lock"] = m_gpiodLock; root["disable"] = m_gpiodDisable; root["in0Debounce"] = m_gpiodInDebounce[0]; root["in1Debounce"] = m_gpiodInDebounce[1]; root["in2Debounce"] = m_gpiodInDebounce[2]; root["in3Debounce"] = m_gpiodInDebounce[3]; root["out0DefRun"] = m_gpiodOutDefRun[0]; root["out1DefRun"] = m_gpiodOutDefRun[1]; root["out2DefRun"] = m_gpiodOutDefRun[2]; root["out3DefRun"] = m_gpiodOutDefRun[3]; root["udm0DefRun"] = m_gpiodUdmDefRun[0]; root["udm1DefRun"] = m_gpiodUdmDefRun[1]; // write to file String strRoot; root.printTo(strRoot); fileSetContent(CAPP_CONF_FILE, strRoot); } // confSave
void saveConfig(MeteoConfig& cfg) { ActiveConfig = cfg; DynamicJsonBuffer jsonBuffer; JsonObject& root = jsonBuffer.createObject(); JsonObject& network = jsonBuffer.createObject(); root["network"] = network; network["ssid"] = cfg.NetworkSSID.c_str(); network["password"] = cfg.NetworkPassword.c_str(); JsonObject& correction = jsonBuffer.createObject(); root["correction"] = correction; correction["T1"] = cfg.AddT1; correction["T2"] = cfg.AddT2; correction["TZ"] = cfg.AddTZ; JsonObject& trigger = jsonBuffer.createObject(); root["trigger"] = trigger; trigger["type"] = (int)cfg.Trigger; trigger["min"] = cfg.RangeMin; trigger["max"] = cfg.RangeMax; char buf[3048]; root.prettyPrintTo(buf, sizeof(buf)); fileSetContent(METEO_CONFIG_FILE, buf); }
void handleRequest(AsyncWebServerRequest *request) { DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.createObject(); int res = 400; // JSON error // GET - get sensor value if (request->method() == HTTP_GET && request->params() == 0) { float val = _plugin->getValue(_sensor); if (isnan(val)) json["value"] = JSON_NULL; else { json["value"] = val; res = 200; } } // POST - set sensor UUID else if ((request->method() == HTTP_POST || request->method() == HTTP_GET) && request->params() == 1 && request->hasParam("uuid")) { String uuid = request->getParam(0)->value(); if (_plugin->setUuid(uuid.c_str(), _sensor)) { _plugin->getSensorJson(&json, _sensor); res = 200; } } jsonResponse(request, res, json); }
void BootConfig::_onDeviceInfoRequest() { Logger.logln(F("Received device info request")); DynamicJsonBuffer jsonBuffer = DynamicJsonBuffer(JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(2) + JSON_ARRAY_SIZE(this->_interface->registeredNodesCount) + (this->_interface->registeredNodesCount * JSON_OBJECT_SIZE(2))); int jsonLength = 82; // {"device_id":"","homie_version":"","firmware":{"name":"","version":""},"nodes":[]} JsonObject& json = jsonBuffer.createObject(); jsonLength += strlen(Helpers::getDeviceId()); json["device_id"] = Helpers::getDeviceId(); jsonLength += strlen(VERSION); json["homie_version"] = VERSION; JsonObject& firmware = json.createNestedObject("firmware"); jsonLength += strlen(this->_interface->firmware.name); firmware["name"] = this->_interface->firmware.name; jsonLength += strlen(this->_interface->firmware.version); firmware["version"] = this->_interface->firmware.version; JsonArray& nodes = json.createNestedArray("nodes"); for (int i = 0; i < this->_interface->registeredNodesCount; i++) { jsonLength += 20; // {"id":"","type":""}, const HomieNode* node = this->_interface->registeredNodes[i]; JsonObject& jsonNode = jsonBuffer.createObject(); jsonLength += strlen(node->getId()); jsonNode["id"] = node->getId(); jsonLength += strlen(node->getType()); jsonNode["type"] = node->getType(); nodes.add(jsonNode); } jsonLength++; // \0 std::unique_ptr<char[]> jsonString(new char[jsonLength]); json.printTo(jsonString.get(), jsonLength); this->_http.send(200, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), jsonString.get()); }
void Esp8266Configuration::write(){ DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.createObject(); json["wifi_ap_ssid"] = wifi_ap_ssid; json["wifi_ap_password"] = wifi_ap_password; json["wifi_ap_enabled"] = wifi_ap_enabled; json["wifi_station_ssid"] = wifi_station_ssid; json["wifi_station_password"] = wifi_station_password; json["wifi_station_enabled"] = wifi_station_enabled; json["mqtt_enabled"] = mqtt_enabled; json["mqtt_host"] = mqtt_host; json["mqtt_port"] = mqtt_port; json["mqtt_user"] = mqtt_user; json["mqtt_password"] = mqtt_password; // File configFile = SPIFFS.open("/configuration.json", "w"); if (!configFile) { Serial.println("failed to open config file for writing"); } // json.printTo(Serial); json.printTo(configFile); configFile.close(); }
void ThingSpeakClass::begin() //loads settings from json file.... { String values = ""; File f = SPIFFS.open("/cloudgen.json", "r"); if (!f) { DebugPrintln("thingspeak config not found"); } else { //file exists; values = f.readStringUntil('\n'); //read json f.close(); DynamicJsonBuffer jsonBuffer; JsonObject& root = jsonBuffer.parseObject(values); //parse weburl if (!root.success()) { DebugPrintln("parseObject() thingspeak failed"); return; } if (root["spkurl"].asString() != "") { //verify good json info thingSpeakURL = root["spkurl"].asString(); thingWriteKey = root["spkwkey"].asString(); thingInterval = String(root["spkint"].asString()).toInt(); TalkBackID = root["tkbid"].asString(); TalkBackKey = root["tkbkey"].asString(); talkBackInterval = String(root["tkbint"].asString()).toInt(); if (String(root["status"].asString()).toInt() == 1) ThingEnabled = true; else ThingEnabled = false; if (String(root["tbstatus"].asString()).toInt() == 1) TalkBackEnabled = true; else TalkBackEnabled = false; DebugPrintln("ThingSpeak Starting...."); } } //file exists; }
void GlobalsClass::SendProbesToHM(String fname) { //sends Probes info to HM String values = ""; String hmsg; File f = SPIFFS.open(fname, "r"); if (f) { // we could open the file values = f.readStringUntil('\n'); //read json f.close(); //WRITE CONFIG TO HeaterMeter DynamicJsonBuffer jsonBuffer; JsonObject& root = jsonBuffer.parseObject(values); //parse json data if (!root.success()) { DebugPrintln("parseObject() failed"); return; } //const char* sensor = root["sensor"]; //long time = root["time"]; //double latitude = root["data"][0]; //double longitude = root["data"][1]; } qCon.println(String("/set?pn0=") + root["p0name"].asString()); delay(comdelay); qCon.println(String("/set?pn1=") + root["p1name"].asString()); delay(comdelay); qCon.println(String("/set?pn2=") + root["p2name"].asString()); delay(comdelay); qCon.println(String("/set?pn3=") + root["p3name"].asString()); delay(comdelay); //Set offsets hmsg = String("/set?po=") + root["p0off"].asString() + "," + root["p1off"].asString() + "," + root["p2off"].asString() + "," + root["p3off"].asString(); qCon.println(hmsg); delay(comdelay); DebugPrintln(hmsg); //Set Probe coeff. hmsg = String("/set?pc0=") + root["p0a"].asString() + "," + root["p0b"].asString() + "," + root["p0c"].asString() + "," + root["p0r"].asString() + "," + root["p0trm"].asString(); qCon.println(hmsg); delay(comdelay); DebugPrintln(hmsg); hmsg = String("/set?pc1=") + root["p1a"].asString() + "," + root["p1b"].asString() + "," + root["p1c"].asString() + "," + root["p1r"].asString() + "," + root["p1trm"].asString(); qCon.println(hmsg); delay(comdelay); DebugPrintln(hmsg); hmsg = String("/set?pc2=") + root["p2a"].asString() + "," + root["p2b"].asString() + "," + root["p2c"].asString() + "," + root["p2r"].asString() + "," + root["p2trm"].asString(); qCon.println(hmsg); delay(comdelay); DebugPrintln(hmsg); hmsg = String("/set?pc3=") + root["p3a"].asString() + "," + root["p3b"].asString() + "," + root["p3c"].asString() + "," + root["p3r"].asString() + "," + root["p3trm"].asString(); qCon.println(hmsg); delay(comdelay); DebugPrintln(hmsg); //Set Alarm offsets hmsg = String("/set?al=") + root["p0all"].asString() + "," + root["p0alh"].asString() + "," + root["p1all"].asString() + "," + root["p1alh"].asString() + "," + root["p2all"].asString() + "," + root["p2alh"].asString() + "," + root["p3all"].asString() + "," + root["p3alh"].asString(); qCon.println(hmsg); delay(comdelay); DebugPrintln(hmsg); qCon.println("/set?tt=Web Settings,Updated!!"); delay(comdelay); qCon.println("/save?"); delay(comdelay); } //open file success }
TEST(JsonVariant_As_Tests, ObjectAsJsonObject) { DynamicJsonBuffer buffer; JsonObject& arr = buffer.createObject(); JsonVariant variant = arr; ASSERT_EQ(&arr, &variant.as<JsonObject&>()); ASSERT_EQ(&arr, &variant.as<JsonObject>()); // <- shorthand }
TEST(JsonVariant_As_Tests, ArrayAsJsonArray) { DynamicJsonBuffer buffer; JsonArray& arr = buffer.createArray(); JsonVariant variant = arr; ASSERT_EQ(&arr, &variant.as<JsonArray&>()); ASSERT_EQ(&arr, &variant.as<JsonArray>()); // <- shorthand }
JsonObject& Record<T>::toJson() { DynamicJsonBuffer jsonBuffer; JsonObject& root = jsonBuffer.createObject(); root.set<long>("t", timestamp); root.set<T>("v", value); return root; }
TEST(StdStream, JsonArraySubscript) { std::ostringstream os; DynamicJsonBuffer jsonBuffer; JsonArray& array = jsonBuffer.createArray(); array.add("value"); os << array[0]; ASSERT_EQ("\"value\"", os.str()); }
TEST(StdStream, JsonObjectSubscript) { std::ostringstream os; DynamicJsonBuffer jsonBuffer; JsonObject& object = jsonBuffer.createObject(); object["key"] = "value"; os << object["key"]; ASSERT_EQ("\"value\"", os.str()); }
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { DynamicJsonBuffer jsonBuffer; memstream json(data, size); JsonVariant variant = jsonBuffer.parse(json); if (variant.success()) { variant.as<std::string>(); // <- serialize to JSON } return 0; }
TEST(JsonVariant_As_Tests, ObjectAsString) { DynamicJsonBuffer buffer; JsonObject& obj = buffer.createObject(); obj["key"] = "value"; JsonVariant variant = obj; ASSERT_EQ(String("{\"key\":\"value\"}"), variant.as<String>()); }
/******************************************************************** sendPing keeps the websocket connection alive by pinging slack ********************************************************************/ void ArduinoSlackBot::sendPing() { DynamicJsonBuffer jsonBuffer; JsonObject& root = jsonBuffer.createObject(); root["type"] = "ping"; root["id"] = nextCmdId++; String json; root.printTo(json); webSocket.sendTXT(json); }
TEST(JsonVariant_As_Tests, ArrayAsString) { DynamicJsonBuffer buffer; JsonArray& arr = buffer.createArray(); arr.add(4); arr.add(2); JsonVariant variant = arr; ASSERT_EQ(String("[4,2]"), variant.as<String>()); }
TEST(DynamicJsonBuffer_Array_Tests, CanAdd1000Values) { DynamicJsonBuffer jsonBuffer; JsonArray &array = jsonBuffer.createArray(); for (int i = 1; i <= 1000; i++) { array.add("hello"); ASSERT_EQ(array.size(), i); } }
/******************************************************************** sendMsg sends a message back to slack on a specific channel ********************************************************************/ void ArduinoSlackBot::sendMsg(const char *channel,const char *msg) { DynamicJsonBuffer jsonBuffer; JsonObject& root = jsonBuffer.createObject(); root["type"] = "message"; root["id"] = nextCmdId++; root["text"] = msg; root["channel"] = channel; String json; root.printTo(json); webSocket.sendTXT(json); }
TEST(DynamicJsonBuffer_Array_Tests, GrowsWithArray) { DynamicJsonBuffer jsonBuffer; JsonArray &array = jsonBuffer.createArray(); ASSERT_EQ(JSON_ARRAY_SIZE(0), jsonBuffer.size()); array.add("hello"); ASSERT_EQ(JSON_ARRAY_SIZE(1), jsonBuffer.size()); array.add("world"); ASSERT_EQ(JSON_ARRAY_SIZE(2), jsonBuffer.size()); }
TEST(JsonArray_CopyFrom_Tests, TwoDimensions) { DynamicJsonBuffer jsonBuffer; JsonArray& array = jsonBuffer.createArray(); char json[32]; int source[][3] = {{1, 2, 3}, {4, 5, 6}}; bool ok = array.copyFrom(source); ASSERT_TRUE(ok); array.printTo(json, sizeof(json)); ASSERT_STREQ("[[1,2,3],[4,5,6]]", json); }
TEST(JsonArray_CopyFrom_Tests, OneDimension) { DynamicJsonBuffer jsonBuffer; JsonArray& array = jsonBuffer.createArray(); char json[32]; int source[] = {1, 2, 3}; bool ok = array.copyFrom(source); ASSERT_TRUE(ok); array.printTo(json, sizeof(json)); ASSERT_STREQ("[1,2,3]", json); }
void Esp8266Configuration::writeConfiguration(const char* configuration){ DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.parseObject(configuration); json.printTo(Serial); File configFile = SPIFFS.open("/configuration.json", "w"); if (!configFile) { Serial.println("failed to open config file for writing"); } // json.printTo(configFile); configFile.close(); }
const FirebaseError FirebaseCloudMessaging::SendMessageToUser( const std::string& registration_id, const FirebaseCloudMessage& message) { DynamicJsonBuffer buffer; JsonObject& root = buffer.createObject(); root["to"] = registration_id.c_str(); AddToJson(message, root); char payload[root.measureLength() + 1]; root.printTo(payload, sizeof(payload)); return SendPayload(payload); }