Arduinojson传递变量范围

时间:2017-06-10 16:16:50

标签: c++ json arduino arduino-esp8266

我遇到以下代码的问题。我正在编写ESP8266 wifi模块,以便它自动注册到MQTT服务器。为了便于配置,我建立了一个门户,您可以在第一次连接设备时访问该门户。您可以在此处输入API密钥和设备的IOT路径名称。我想从json.config文件加载和存储这些配置。这有效,我希望我似乎无法将变量传递给void设置范围。代码完全是我最后的努力。

有关如何解决此问题的任何指示?

#include <ArduinoJson.h>
#include <ESP8266WebServer.h>
#include "FS.h"

ESP8266WebServer server ( 80 );

char* ssid;
char* password;
char* apikey;
char* iotpath;

void setup() {

    const char* values = loadConfig();
    Serial.println(values);

  // declare ssid and password
 //char* ssid = "xxxxxxx";
 //char* password = "xxxxxxxx";

  // start serial connection and SPIFFS
  Serial.begin (115200);
  SPIFFS.begin();

   Serial.println(ssid);
   Serial.println(password);
   Serial.println(apikey);
   Serial.println(iotpath);

  // WiFi connection sequence
  WiFi.begin ( ssid, password );
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 ); Serial.print ( "." );
  }

  // WiFi success print
  Serial.println ( "" );
  Serial.print ( "Connected to " ); Serial.println ( ssid );
  Serial.print ( "IP address: " ); Serial.println ( WiFi.localIP() );

  // Check if SPIFSS is started
  if (!SPIFFS.begin())
  {
    Serial.println("SPIFFS Mount failed");
  } else {
    Serial.println("SPIFFS Mount succesfull");
  }

  // check if config file was loaded
  /*
   if (!loadConfig()) {
    Serial.println("Failed to load config");
  } else {
    Serial.println("Config loaded");
  }*/

  // Server root handling
  server.serveStatic("/img", SPIFFS, "/img");
  server.serveStatic("/", SPIFFS, "/index.html");
  server.serveStatic("/css", SPIFFS, "/css");

  server.begin();
  Serial.println ( "HTTP server started" );

}

void loop() {
  // put your main code here, to run repeatedly:
  server.handleClient();
  delay(100);
  //Serial.println(".");
}

const char* loadConfig() {

  File configFile = SPIFFS.open("/config.json", "r");
  if (!configFile) {
    Serial.println("Failed to open config file");
    //return false;
  }

  size_t size = configFile.size();
  if (size > 1024) {
    Serial.println("Config file size is too large");
    //return false;
  }

  // Allocate a buffer to store contents of the file.
  std::unique_ptr<char[]> buf(new char[size]);

  // We don't use String here because ArduinoJson library requires the input
  // buffer to be mutable. If you don't use ArduinoJson, you may as well
  // use configFile.readString instead.
  configFile.readBytes(buf.get(), size);

  StaticJsonBuffer<200> jsonBuffer;
  JsonObject& json = jsonBuffer.parseObject(buf.get());

  if (!json.success()) {
    Serial.println("Failed to parse config file");
    //return false;
  }

  const char* ssid = json["ssid"];
  const char* password= json["password"];
  const char* apikey = json["apikey"];
  const char* iotpath = json["iotpath"];
  //String ssid_string = String(ssid);
  //return ssid;
}

0 个答案:

没有答案