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 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 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());
}
Beispiel #4
0
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);
}
Beispiel #5
0
  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 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();
}
Beispiel #7
0
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);
}
Beispiel #8
0
//----------------------------------------------------------------------------
//
//----------------------------------------------------------------------------
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
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
}
Beispiel #10
0
TEST(StdStream, JsonObjectSubscript) {
  std::ostringstream os;
  DynamicJsonBuffer jsonBuffer;
  JsonObject& object = jsonBuffer.createObject();
  object["key"] = "value";
  os << object["key"];
  ASSERT_EQ("\"value\"", os.str());
}
Beispiel #11
0
JsonObject& Record<T>::toJson()
{
  DynamicJsonBuffer jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();
  root.set<long>("t", timestamp);
  root.set<T>("v", value);
  return root;
}
/********************************************************************
  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, ObjectAsString) {
  DynamicJsonBuffer buffer;

  JsonObject& obj = buffer.createObject();
  obj["key"] = "value";

  JsonVariant variant = obj;
  ASSERT_EQ(String("{\"key\":\"value\"}"), variant.as<String>());
}
/********************************************************************
  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);
}
void BootConfig::_generateNetworksJson() {
  DynamicJsonBuffer generatedJsonBuffer = DynamicJsonBuffer(JSON_OBJECT_SIZE(1) + JSON_ARRAY_SIZE(this->_ssidCount) + (this->_ssidCount * JSON_OBJECT_SIZE(3))); // 1 at root, 3 in childrend
  JsonObject& json = generatedJsonBuffer.createObject();

  int jsonLength = 15; // {"networks":[]}
  JsonArray& networks = json.createNestedArray("networks");
  for (int network = 0; network < this->_ssidCount; network++) {
    jsonLength += 36; // {"ssid":"","rssi":,"encryption":""},
    JsonObject& jsonNetwork = generatedJsonBuffer.createObject();
    jsonLength += WiFi.SSID(network).length();
    jsonNetwork["ssid"] = WiFi.SSID(network);
    jsonLength += 4;
    jsonNetwork["rssi"] = WiFi.RSSI(network);
    jsonLength += 4;
    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);
  }

  jsonLength++; // \0

  delete[] this->_jsonWifiNetworks;
  this->_jsonWifiNetworks = new char[jsonLength];
  json.printTo(this->_jsonWifiNetworks, jsonLength);
}
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);
}
Beispiel #17
0
void udp_recieve(UdpConnection& connection, char *data, int size, IPAddress remoteIP, uint16_t remotePort) {
	debugf("UDP Sever callback from %s:%d, %d bytes", remoteIP.toString().c_str(), remotePort, size);
	debugf("UDP Data: %s", data);
	DynamicJsonBuffer jsonBuffer;
	JsonObject& root = jsonBuffer.createObject();
	if( !strcmp( data, "enum" ) ){
		root.addCopy("ip", WifiStation.getIP().toString());
		root.add("pos", driver_pos());
		udp.sendStringTo(remoteIP, remotePort, root.toJsonString().c_str());
		debugf("Sending to IP:%s:%d resp:%s", remoteIP.toString().c_str(), remotePort, root.toJsonString().c_str());
	} else {
		debugf("UDP Unknown packet : %s", data);
	}
}
String BootConfig::_generateNetworksJson() {
  DynamicJsonBuffer generatedJsonBuffer;
  JsonObject& json = generatedJsonBuffer.createObject();

  JsonArray& networks = json.createNestedArray("networks");
  for (int network = 0; network < this->_ssid_count; network++) {
    JsonObject& json_network = generatedJsonBuffer.createObject();
    json_network["ssid"] = WiFi.SSID(network);
    json_network["rssi"] = WiFi.RSSI(network);
    switch (WiFi.encryptionType(network)) {
      case ENC_TYPE_WEP:
        json_network["encryption"] = "wep";
        break;
      case ENC_TYPE_TKIP:
        json_network["encryption"] = "wpa";
        break;
      case ENC_TYPE_CCMP:
        json_network["encryption"] = "wpa2";
        break;
      case ENC_TYPE_NONE:
        json_network["encryption"] = "none";
        break;
      case ENC_TYPE_AUTO:
        json_network["encryption"] = "auto";
        break;
    }

    networks.add(json_network);
  }

  // 15 bytes: {"networks":[]}
  // 75 bytes: {"ssid":"thisisa32characterlongstringyes!","rssi":-99,"encryption":"none"}, (-1 for leading ","), +1 for terminator
  String json_string;
  json_string.reserve(15 + (75 * this->_ssid_count) - 1 + 1);
  json.printTo(json_string);
  return json_string;
}
const FirebaseError FirebaseCloudMessaging::SendMessageToTopic(
    const std::string& topic, const FirebaseCloudMessage& message) {
  std::string to("/topics/");
  to += topic;

  DynamicJsonBuffer buffer;
  JsonObject& root = buffer.createObject();
  root["to"] = to.c_str();

  AddToJson(message, root);

  char payload[root.measureLength() + 1];
  root.printTo(payload, sizeof(payload));
  return SendPayload(payload);
}
TEST_F(JsonVariant_Comparison_Tests, ObjectInVariant) {
  DynamicJsonBuffer jsonBuffer;
  JsonObject& obj1 = jsonBuffer.createObject();
  JsonObject& obj2 = jsonBuffer.createObject();

  JsonVariant variant1 = obj1;
  JsonVariant variant2 = obj1;
  JsonVariant variant3 = obj2;

  ASSERT_TRUE(variant1 == variant2);
  ASSERT_FALSE(variant1 != variant2);

  ASSERT_TRUE(variant1 != variant3);
  ASSERT_FALSE(variant1 == variant3);
}
const FirebaseError FirebaseCloudMessaging::SendMessageToUsers(
    const std::vector<std::string>& registration_ids,
    const FirebaseCloudMessage& message) {
  DynamicJsonBuffer buffer;
  JsonObject& root = buffer.createObject();
  JsonArray& ids = root.createNestedArray("registration_ids");
  for (const std::string& id : registration_ids) {
    ids.add(id.c_str());
  }

  AddToJson(message, root);

  char payload[root.measureLength() + 1];
  root.printTo(payload, sizeof(payload));
  return SendPayload(payload);
}
TEST_F(JsonVariant_Comparison_Tests, VariantsOfDifferentTypes) {
  DynamicJsonBuffer jsonBuffer;
  JsonVariant variants[] = {
      true,
      42,
      666.667,
      "hello",
      jsonBuffer.createArray(),
      jsonBuffer.createObject(),
  };
  size_t n = sizeof(variants) / sizeof(variants[0]);

  for (size_t i = 0; i < n; i++) {
    for (size_t j = i + 1; j < n; j++) {
      ASSERT_TRUE(variants[i] != variants[j]);
      ASSERT_FALSE(variants[i] == variants[j]);
    }
  }
}
Beispiel #23
0
bool IFTTTMaker::triggerEvent(String eventName , String value1, String value2, String value3){

  DynamicJsonBuffer jsonBuffer;
  JsonObject& payload = jsonBuffer.createObject();
  if(value1 != ""){
    payload["value1"] = value1;
  }
  if(value2 != ""){
    payload["value2"] = value2;
  }
  if(value3 != ""){
    payload["value3"] = value3;
  }

  String response = sendTriggerEventWithData(eventName, payload);
  if(checkForSucessResponse(response)){
    return true;
  }
  return false;
}
Beispiel #24
0
	void notify(String event, InstapushTrackers &trackersInfo)
	{
		debugf("preparing request");
		setRequestContentType("application/json");
		setRequestHeader("x-instapush-appid", app);
		setRequestHeader("x-instapush-appsecret", secret);

		DynamicJsonBuffer jsonBuffer;
		JsonObject& root = jsonBuffer.createObject();
		root["event"] = event.c_str();
		JsonObject& trackers = root.createNestedObject("trackers");
		for (int i = 0; i < trackersInfo.count(); i++)
		{
			debugf("%s: %s", trackersInfo.keyAt(i).c_str(), trackersInfo.valueAt(i).c_str());
			trackers.addCopy(trackersInfo.keyAt(i), trackersInfo[trackersInfo.keyAt(i)]);
		}

		setPostBody(root.toJsonString());
		downloadString(url, HttpClientCompletedCallback(&InstapushApplication::processed, this));
	}
Beispiel #25
0
// ArduinoJson - arduinojson.org
// Copyright Benoit Blanchon 2014-2018
// MIT License

#include <ArduinoJson.h>
#include <catch.hpp>

TEST_CASE("JsonObject basics") {
  DynamicJsonBuffer _jsonBuffer;
  JsonObject& _object = _jsonBuffer.createObject();

  SECTION("InitialSizeIsZero") {
    REQUIRE(0 == _object.size());
  }

  SECTION("SuccessIsTrue") {
    REQUIRE(_object.success());
  }
}
Beispiel #26
0
void parseTextMessage(AsyncWebSocketClient * client, uint8_t * data, size_t len)
{
  DynamicJsonBuffer jsonBuffer;
  
  // parse possible json files
  if( data[0] =='{' && data[len - 1] == '}' )
  {
     // let's parse the json file
     Serial.println("JSON STR RECEIVED!");

     char tmp[len + 1];
     memcpy(tmp, (char *)data, len);
     tmp[len] = '\0';
     JsonObject& root = jsonBuffer.parseObject(tmp);

     // ########################
     // Wifi configuration file
     // ########################
     if ( root.containsKey("mode") )
     {
  
       if ( strcmp((const char*)root["mode"], "ap") == 0 )
       {
         Serial.println("AP");
         storage.wifisett.setSSID((const char*)root["ssid"]);
         storage.wifisett.setPwd((const char*)root["pwd"]);

         storage.wifisett.enableSoftAP();
       }
       else if ( strcmp((const char*)root["mode"], "sta") == 0 )
       {
         Serial.println("STA");
         storage.wifisett.setClientSSID((const char*)root["ssid"]);
         storage.wifisett.setClientPwd((const char*)root["pwd"]);
  
         // set mode to STA
         storage.wifisett.enableClient();
       }
       
     }



     // #########################
     // Set Clock
     // #########################
     if (root.containsKey("setclock") )
     {
       JsonObject& rootsetclock = root.get("setclock");
      
       if ( rootsetclock.containsKey("type") && ( strcmp((const char*)rootsetclock["type"], "ntp") == 0 ) )
       {
         // get ntp time
         opaq_controller.syncClock();
       }
       else
       {
         // get values from json
         RtcDateTime tmp = RtcDateTime( rootsetclock["year"], rootsetclock["month"], rootsetclock["day"], rootsetclock["hour"], rootsetclock["minute"], rootsetclock["second"]);
         opaq_controller.getCom().setClock(tmp);
       }
     }

     // #########################
     // Get Clock
     // #########################
     if (root.containsKey("getclock") )
     {
       // let's send the clock values
       JsonObject& tmp_root = jsonBuffer.createObject();

       JsonObject& conf = tmp_root.createNestedObject("realtimeclock");

       RtcDateTime date;
       opaq_controller.getCom().getClock(date); // [TODO] this can fail
       
       conf["second"] = date.Second();
       conf["minute"] = date.Minute();
       conf["hour"]   = date.Hour();
       conf["day"]    = date.Day();
       conf["month"]  = date.Month();
       conf["year"]   = date.Year();

       String tmp = "";
       tmp_root.printTo(tmp);

       client->text(tmp);
     }


     
     // ################
     // Filename getter
     // ################
     if (root.containsKey("filename") )
     {
       String content = "";
       
       sendFile(SPIFFS, root["filename"], content);
       
       client->text(content);
     }

     // ################################
     // Light device full dimmer setter
     // ###############################
     if (root.containsKey("adimid") )
     {
       // let's write the file configuration
      
       storage.faqdim.save(root["adimid"], data, len);
      
       client->text("{\"success\":\"\"}");
     }

     // ################################
     // Light device full dimmer getter
     // ################################
     if (root.containsKey("adim") )
     {
       String content = "", dirname = "";
       
       // list devices and send it
       // {"adim":["filea.json","fileb.json"]}
       
       content += F("{\"adim\":[\"\"");

       storage.faqdim.getDir(dirname);
       
       // for each file in /sett/adim directory do
       Dir directory = SPIFFS.openDir(dirname.c_str());
       
       while ( directory.next() )
       {
         content += F(", \"");
         content += directory.fileName();
         content += F("\" ");
       }

       content += F(" ]}");
   
       client->text(content);
    }

    // ##################################
    // Light device full dimmer remover
    // #################################
    if (root.containsKey("adimremove") )
    {
      storage.faqdim.remove(root["adimremove"]);
     
      client->text("{\"success\":\"\"}");
    }

    // ################################
    // Light device full dimmer setter
    // ################################
    if (root.containsKey("adimadd") )
    {
      storage.faqdim.add();

      client->text("{\"success\":\"\"}");
          
    }

    // ####################################
    // Light device full dimmer bind state
    // ####################################
    if (root.containsKey("adimbind") )
    {
      //root["adimbind"]
    }




    // ################################
    // Power device getter
    // ################################
    if (root.containsKey("pdev") )
    {
      String content = "", dirname = "";
       
      // list devices and send it
      // {"pdev":["filea.json","fileb.json"]}
       
      content += F("{\"pdev\":[\"\"");

      storage.pwdevice.getDir(dirname);
       
      // for each file in /sett/pdev directory do
      Dir directory = SPIFFS.openDir(dirname.c_str());
       
      while ( directory.next() )
      {
        content += F(", \"");
        content += directory.fileName();
        content += F("\" ");
      }

      content += F(" ]}");
   
      client->text(content);
    }

    // ################################
    // Power device setter
    // ################################
    if (root.containsKey("pdevid") )
    {
      // let's write the file configuration
      
      storage.pwdevice.save(root["pdevid"], data, len);
      
      client->text("{\"success\":\"\"}");
    }

    // ################################
    // Power device add setter
    // ################################
    if (root.containsKey("pdevadd") )
    {
      storage.pwdevice.add();

      client->text("{\"success\":\"\"}");
          
    }

    // ##################################
    // Power device remover
    // #################################
    if (root.containsKey("pdevremove") )
    {
      storage.pwdevice.remove(root["pdevremove"]);
     
      client->text("{\"success\":\"\"}");
    }



    // ################################
    // Update filesystem
    // ###############################
    if (root.containsKey("updatefilesystem") )
    {
      // let's write the file configuration
      
      storage.setUpdate(true);
      
      client->text("{\"success\":\"\"}");
    }
     
  }
  else if( strcmp((char*)data, "GET_OPAQ_WIFISETTINGS") == 0 )
  {
    // let's send the wifisettings
    JsonObject& root = jsonBuffer.createObject();

    JsonObject& conf = root.createNestedObject("wifisettings");

    String wssid, wpwd, wclientssid, wclientpwd, wmode;
    storage.wifisett.getSSID(wssid);
    storage.wifisett.getPwd(wpwd);
    storage.wifisett.getClientSSID(wclientssid);
    storage.wifisett.getClientPwd(wclientpwd);
    storage.wifisett.getMode(wmode);
    
    conf["wssid"] = wssid.c_str();
    conf["wpwd"] = wpwd.c_str();
    conf["wchan"] = 6; // [TODO]
    
    conf["wssidsta"] = wclientssid.c_str();
    conf["wpwdsta"] = wclientpwd.c_str();
    conf["wmode"] = wmode.c_str();

    String tmp = "";
    root.printTo(tmp);

    client->text(tmp);
  }
  else if( strcmp((char*)data, "GET_OPAQ_SUMMARY") == 0 )
  {  
    String wssid;
    storage.wifisett.getSSID(wssid);
    
    JsonObject& root = jsonBuffer.createObject();
    root["version"] = OPAQ_VERSION;
    root["id"]      = ESP.getFlashChipId();
    root["status"]  = "Running without errors"; // [TODO]
    root["wstatus"] = "Radio is On"; // [TODO]
    root["wmode"]   = (storage.wifisett.getModeOperation())? "softAP" : "client";
    root["wssid"]   = wssid.c_str();
    root["wchan"]   = WiFi.channel();
    root["wdhcp"]   = "Enabled"; // [TODO]
    root["wmac"]    = WiFi.softAPmacAddress();
    root["wip"]     = (storage.wifisett.getModeOperation())? WiFi.softAPIP().toString() : WiFi.localIP().toString();

    String tmp = "";
    root.printTo(tmp);

    client->text(tmp);
  }
  else
  {
    client->text("{\"msg\":\"I got your text message\"}");
  }
  
}
Beispiel #27
0
void BootConfig::_onDeviceInfoRequest() {
  _interface->logger->logln(F("Received device info request"));
  auto numSettings = IHomieSetting::settings.size();
  auto numNodes = HomieNode::nodes.size();
  DynamicJsonBuffer jsonBuffer = DynamicJsonBuffer(JSON_OBJECT_SIZE(5) + JSON_OBJECT_SIZE(2) + JSON_ARRAY_SIZE(numNodes) + (numNodes * JSON_OBJECT_SIZE(2)) + JSON_ARRAY_SIZE(numSettings) + (numSettings * JSON_OBJECT_SIZE(5)));
  JsonObject& json = jsonBuffer.createObject();
  json["device_id"] = Helpers::getDeviceId();
  json["homie_esp8266_version"] = HOMIE_ESP8266_VERSION;
  JsonObject& firmware = json.createNestedObject("firmware");
  firmware["name"] = _interface->firmware.name;
  firmware["version"] = _interface->firmware.version;

  JsonArray& nodes = json.createNestedArray("nodes");
  for (HomieNode* iNode : HomieNode::nodes) {
    JsonObject& jsonNode = jsonBuffer.createObject();
    jsonNode["id"] = iNode->getId();
    jsonNode["type"] = iNode->getType();
    nodes.add(jsonNode);
  }

  JsonArray& settings = json.createNestedArray("settings");
  for (IHomieSetting* iSetting : IHomieSetting::settings) {
    JsonObject& jsonSetting = jsonBuffer.createObject();
    if (iSetting->isBool()) {
      HomieSetting<bool>* setting = static_cast<HomieSetting<bool>*>(iSetting);
      jsonSetting["name"] = setting->getName();
      jsonSetting["description"] = setting->getDescription();
      jsonSetting["type"] = "bool";
      jsonSetting["required"] = setting->isRequired();
      if (!setting->isRequired()) {
        jsonSetting["default"] = setting->get();
      }
    } else if (iSetting->isUnsignedLong()) {
      HomieSetting<unsigned long>* setting = static_cast<HomieSetting<unsigned long>*>(iSetting);
      jsonSetting["name"] = setting->getName();
      jsonSetting["description"] = setting->getDescription();
      jsonSetting["type"] = "ulong";
      jsonSetting["required"] = setting->isRequired();
      if (!setting->isRequired()) {
        jsonSetting["default"] = setting->get();
      }
    } else if (iSetting->isLong()) {
      HomieSetting<long>* setting = static_cast<HomieSetting<long>*>(iSetting);
      jsonSetting["name"] = setting->getName();
      jsonSetting["description"] = setting->getDescription();
      jsonSetting["type"] = "long";
      jsonSetting["required"] = setting->isRequired();
      if (!setting->isRequired()) {
        jsonSetting["default"] = setting->get();
      }
    } else if (iSetting->isDouble()) {
      HomieSetting<double>* setting = static_cast<HomieSetting<double>*>(iSetting);
      jsonSetting["name"] = setting->getName();
      jsonSetting["description"] = setting->getDescription();
      jsonSetting["type"] = "double";
      jsonSetting["required"] = setting->isRequired();
      if (!setting->isRequired()) {
        jsonSetting["default"] = setting->get();
      }
    } else if (iSetting->isConstChar()) {
      HomieSetting<const char*>* setting = static_cast<HomieSetting<const char*>*>(iSetting);
      jsonSetting["name"] = setting->getName();
      jsonSetting["description"] = setting->getDescription();
      jsonSetting["type"] = "string";
      jsonSetting["required"] = setting->isRequired();
      if (!setting->isRequired()) {
        jsonSetting["default"] = setting->get();
      }
    }

    settings.add(jsonSetting);
  }

  size_t jsonBufferLength = json.measureLength() + 1;
  std::unique_ptr<char[]> jsonString(new char[jsonBufferLength]);
  json.printTo(jsonString.get(), jsonBufferLength);
  _http.send(200, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), jsonString.get());
}
TEST(JsonVariant_Success_Tests, ReturnsTrue_WhenEmptyObject) {
    DynamicJsonBuffer jsonBuffer;

    JsonVariant variant = jsonBuffer.createObject();
    EXPECT_TRUE(variant.success());
}