当前位置: 首页>>代码示例>>C++>>正文


C++ StaticJsonBuffer类代码示例

本文整理汇总了C++中StaticJsonBuffer的典型用法代码示例。如果您正苦于以下问题:C++ StaticJsonBuffer类的具体用法?C++ StaticJsonBuffer怎么用?C++ StaticJsonBuffer使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了StaticJsonBuffer类的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: saveConfig

bool JsonConf::saveConfig() {
  StaticJsonBuffer<1024> jsonBuffer;
#ifdef DEBUG_JSON_CONFIG
  Serial.print(F("saveConfig()"));  Serial.println();
#endif

  JsonObject& json = jsonBuffer.createObject();


  json["module_id"]                     = module_id                    ;                           
  json["sta_ssid"]                      = sta_ssid                     ;                         
  json["sta_pwd"]                       = sta_pwd                      ;                       
  json["static_ip_mode"]                = static_ip_mode               ;                                     
  json["static_ip"]                     = static_ip                    ;                           
  json["static_gateway"]                = static_gateway               ;                                     
  json["static_subnet"]                 = static_subnet                ;                                   
  json["ntp_server"]                    = ntp_server                   ;                             
  json["my_time_zone"]                  = my_time_zone                 ;                           
  json["mqtt_server"]                   = mqtt_server                  ;                               
  json["mqtt_port"]                     = mqtt_port                    ;                           
  json["mqtt_user"]                     = mqtt_user                    ;                           
  json["mqtt_pwd"]                      = mqtt_pwd                     ;                         
  json["mqtt_name"]                     = mqtt_name                    ;                           
  json["publish_topic"]                 = publish_topic                ;                                   
  json["subscribe_topic"]               = subscribe_topic              ;                                       
  json["command_pub_topic"]             = command_pub_topic            ;                                           
  json["light_pin"]                     = light_pin                    ;                           
  json["lightoff_delay"]                = lightoff_delay               ;                                     
  json["light_pin2"]                    = light_pin2                   ;                             
  json["light2off_delay"]               = light2off_delay              ;                                       
  json["motion_pin"]                    = motion_pin                   ;                             
  json["dht_pin"]                       = dht_pin                      ;                       
  json["get_data_delay"]                = get_data_delay               ;                                     
  json["publish_delay"]                 = publish_delay                ;                                   
  json["subscribe_delay"]               = subscribe_delay              ;                                       
  json["motion_read_delay"]             = motion_read_delay            ;                                           
  json["reboot_delay"]                  = reboot_delay                 ;                                 
  json["uart_delay_analog_pin0"]        = uart_delay_analog_pin0       ;                                                     
  json["uart_delay_analog_pin1"]        = uart_delay_analog_pin1       ;                                                     
  json["uart_delay_analog_pin2"]        = uart_delay_analog_pin2       ;                                                     
  json["uart_delay_analog_pin3"]        = uart_delay_analog_pin3       ;                                                     
  json["uart_delay_analog_pin4"]        = uart_delay_analog_pin4       ;                                                     
  json["uart_delay_analog_pin5"]        = uart_delay_analog_pin5       ;                                                     
  json["green_light_on"]                = green_light_on               ;                                     
  json["green_light_off"]               = green_light_off              ;                                       
  json["green_light_pin"]               = green_light_pin              ;                                       
  json["green_humidity_threshold_up"]   = green_humidity_threshold_up  ;                                                               
  json["green_humidity_threshold_down"] = green_humidity_threshold_down;                                                                   
  json["green_humidity_sensor_pin"]     = green_humidity_sensor_pin    ;                                                           
  json["green_pump_pin"]                = green_pump_pin               ;                                     


  File configFile = SPIFFS.open("/config.json", "w");
  if (!configFile) {
#ifdef DEBUG_JSON_CONFIG
    Serial.println(F("Failed to open config file for writing"));
#endif
    return false;
  }
#ifdef DEBUG_JSON_CONFIG
  Serial.println();
  json.printTo(Serial);
  Serial.println();
#endif
  json.printTo(configFile);
  configFile.close();
  return true;
}
开发者ID:semxx,项目名称:Wi-Fi-Sensor,代码行数:68,代码来源:json_config.cpp

示例2: mustFailWith

void mustFailWith(S source) {
  StaticJsonBuffer<N> jsonBuffer;
  ASSERT_FALSE(jsonBuffer.parseObject(source).success());
}
开发者ID:BOBRAPHTONE,项目名称:ArduinoJson,代码行数:4,代码来源:Issue104.cpp

示例3: saveConfig

bool JsonConfig::loadConfig()
{
    Serial.println("\r\nConfig: loading");

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

    size_t size = configFile.size();
    if (size > 2048)
    {
        Serial.println("Config: file size is too large");
        SPIFFS.remove("/config.json");
        saveConfig();
        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<1024> jsonBuffer;
    JsonObject& json = jsonBuffer.parseObject(buf.get());

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

    if (json.containsKey("module_id")) { const char* module_id_char = json["module_id"]; sprintf_P(module_id, ("%s"), module_id_char); }
    if (json.containsKey("module_name")) { const char* module_name_char = json["module_name"]; sprintf_P(module_name, ("%s"), module_name_char); }
    if (json.containsKey("sta_ssid")) { const char* sta_ssid_char = json["sta_ssid"]; sprintf_P(sta_ssid, ("%s"), sta_ssid_char); }
    if (json.containsKey("sta_pwd")) { const char* sta_pwd_char = json["sta_pwd"]; sprintf_P(sta_pwd, ("%s"), sta_pwd_char); }

    if (json.containsKey("static_ip_mode")) { const char* static_ip_mode_char = json["static_ip_mode"]; sprintf_P(static_ip_mode, ("%s"), static_ip_mode_char); }
    if (json.containsKey("static_ip")) { const char* static_ip_char = json["static_ip"]; sprintf_P(static_ip, ("%s"), static_ip_char); }
    if (json.containsKey("static_gateway")) { const char* static_gateway_char = json["static_gateway"]; sprintf_P(static_gateway, ("%s"), static_gateway_char); }
    if (json.containsKey("static_subnet")) { const char* static_subnet_char = json["static_subnet"]; sprintf_P(static_subnet, ("%s"), static_subnet_char); }

    if (json.containsKey("get_data_delay")) { const char* get_data_delay_char = json["get_data_delay"]; sprintf_P(get_data_delay, ("%s"), get_data_delay_char); }
    if (json.containsKey("reboot_delay")) { const char* reboot_delay_char = json["reboot_delay"]; sprintf_P(reboot_delay, ("%s"), reboot_delay_char); }

    if (json.containsKey("add_data_url")) { const char* add_data_url_char = json["add_data_url"]; sprintf_P(add_data_url, ("%s"), add_data_url_char); }

    if (json.containsKey("sensor_bmp180_on")) { const char* sensor_bmp180_on_char = json["sensor_bmp180_on"]; sprintf_P(sensor_bmp180_on, ("%s"), sensor_bmp180_on_char); }
    if (json.containsKey("sensor_dht22_on")) { const char* sensor_dht22_on_char = json["sensor_dht22_on"]; sprintf_P(sensor_dht22_on, ("%s"), sensor_dht22_on_char); }
    if (json.containsKey("sensor_sht21_on")) { const char* sensor_sht21_on_char = json["sensor_sht21_on"]; sprintf_P(sensor_sht21_on, ("%s"), sensor_sht21_on_char); }
    if (json.containsKey("sensor_bh1750_on")) { const char* sensor_bh1750_on_char = json["sensor_bh1750_on"]; sprintf_P(sensor_bh1750_on, ("%s"), sensor_bh1750_on_char); }

    if (json.containsKey("rtc_on")) { const char* rtc_on_char = json["rtc_on"]; sprintf_P(rtc_on, ("%s"), rtc_on_char); }
    if (json.containsKey("use_server_time")) { const char* use_server_time_char = json["use_server_time"]; sprintf_P(use_server_time, ("%s"), use_server_time_char); }
    if (json.containsKey("use_ntp_server")) { const char* use_ntp_server_char = json["use_ntp_server"]; sprintf_P(use_ntp_server, ("%s"), use_ntp_server_char); }
    if (json.containsKey("ntp_server")) { const char* ntp_server_char = json["ntp_server"]; sprintf_P(ntp_server, ("%s"), ntp_server_char); }
    if (json.containsKey("time_zone_offset")) { const char* time_zone_offset_char = json["time_zone_offset"]; sprintf_P(time_zone_offset, ("%s"), time_zone_offset_char); }

    configFile.close();

    Serial.println("Config: loaded");

    return true;
}
开发者ID:kogleron,项目名称:MeteoEsp,代码行数:71,代码来源:JsonConfig.cpp

示例4: load_config

boolean load_config() {
	File configFile = SPIFFS.open(CONFIG_FILE, "r");
	if (!configFile) {
#ifdef DEBUG
		DBG_OUTPUT_PORT.println("Failed to open config file");
#endif // DEBUG
		return false;
	}

	size_t size = configFile.size();
	if (size > 1024) {
#ifdef DEBUG
		DBG_OUTPUT_PORT.println("Config file size is too large");
#endif
		configFile.close();
		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);
	configFile.close();
#ifdef DEBUG
	DBG_OUTPUT_PORT.print("JSON file size: "); Serial.print(size); Serial.println(" bytes");
#endif

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

	if (!json.success()) {
#ifdef DEBUG
		DBG_OUTPUT_PORT.println("Failed to parse config file");
#endif // DEBUG
		return false;
	}
#ifdef DEBUG
	String temp;
	json.prettyPrintTo(temp);
	Serial.println(temp);
#endif
	//memset(config.ssid, 0, 28);
	//memset(config.pass, 0, 50);
	//String("Virus_Detected!!!").toCharArray(config.ssid, 28); // Assign WiFi SSID
	//String("[email protected]").toCharArray(config.pass, 50); // Assign WiFi PASS

	config.ssid = json["ssid"].asString();
	//String(ssid_str).toCharArray(config.ssid, 28);

	config.password = json["pass"].asString();
	
	config.IP[0] = json["ip"][0];
	config.IP[1] = json["ip"][1];
	config.IP[2] = json["ip"][2];
	config.IP[3] = json["ip"][3];

	config.Netmask[0] = json["netmask"][0];
	config.Netmask[1] = json["netmask"][1];
	config.Netmask[2] = json["netmask"][2];
	config.Netmask[3] = json["netmask"][3];

	config.Gateway[0] = json["gateway"][0];
	config.Gateway[1] = json["gateway"][1];
	config.Gateway[2] = json["gateway"][2];
	config.Gateway[3] = json["gateway"][3];

	config.DNS[0] = json["dns"][0];
	config.DNS[1] = json["dns"][1];
	config.DNS[2] = json["dns"][2];
	config.DNS[3] = json["dns"][3];

	config.dhcp = json["dhcp"];

	//String(pass_str).toCharArray(config.pass, 28);
	config.ntpServerName = json["ntp"].asString();
	config.Update_Time_Via_NTP_Every = json["NTPperiod"];
	config.timezone = json["timeZone"];
	config.daylight = json["daylight"];
	config.DeviceName = json["deviceName"].asString();

	//config.connectionLed = json["led"];

#ifdef DEBUG
	DBG_OUTPUT_PORT.println("Data initialized.");
	DBG_OUTPUT_PORT.print("SSID: "); Serial.println(config.ssid);
	DBG_OUTPUT_PORT.print("PASS: "); Serial.println(config.password);
	DBG_OUTPUT_PORT.print("NTP Server: "); Serial.println(config.ntpServerName);
	//DBG_OUTPUT_PORT.printf("Connection LED: %d\n", config.connectionLed);
	DBG_OUTPUT_PORT.println(__PRETTY_FUNCTION__);
#endif // DEBUG
	return true;
}
开发者ID:TopperBB,项目名称:FSBrowser,代码行数:95,代码来源:Config.cpp

示例5: mustSucceedWith

void mustSucceedWith(S source) {
  StaticJsonBuffer<N> jsonBuffer;
  ASSERT_TRUE(jsonBuffer.parseObject(source).success());
}
开发者ID:BOBRAPHTONE,项目名称:ArduinoJson,代码行数:4,代码来源:Issue104.cpp

示例6: save_config

boolean save_config() {
	//flag_config = false;
#ifdef DEBUG
	DBG_OUTPUT_PORT.println("Save config");
#endif
	StaticJsonBuffer<1024> jsonBuffer;
	JsonObject& json = jsonBuffer.createObject();
	json["ssid"] = config.ssid;
	json["pass"] = config.password;
	
	JsonArray& jsonip = json.createNestedArray("ip");
	jsonip.add(config.IP[0]);
	jsonip.add(config.IP[1]);
	jsonip.add(config.IP[2]);
	jsonip.add(config.IP[3]);
	
	JsonArray& jsonNM = json.createNestedArray("netmask");
	jsonNM.add(config.Netmask[0]);
	jsonNM.add(config.Netmask[1]);
	jsonNM.add(config.Netmask[2]);
	jsonNM.add(config.Netmask[3]);
	
	JsonArray& jsonGateway = json.createNestedArray("gateway");
	jsonGateway.add(config.Gateway[0]);
	jsonGateway.add(config.Gateway[1]);
	jsonGateway.add(config.Gateway[2]);
	jsonGateway.add(config.Gateway[3]);
	
	JsonArray& jsondns = json.createNestedArray("dns");
	jsondns.add(config.DNS[0]);
	jsondns.add(config.DNS[1]);
	jsondns.add(config.DNS[2]);
	jsondns.add(config.DNS[3]);
	
	json["dhcp"] = config.dhcp;
	json["ntp"] = config.ntpServerName;
	json["NTPperiod"] = config.Update_Time_Via_NTP_Every;
	json["timeZone"] = config.timezone;
	json["daylight"] = config.daylight;
	json["deviceName"] = config.DeviceName;

	//json["led"] = config.connectionLed;
			
	//TODO add AP data to html
	File configFile = SPIFFS.open(CONFIG_FILE, "w");
	if (!configFile) {
#ifdef DEBUG
		DBG_OUTPUT_PORT.println("Failed to open config file for writing");
#endif // DEBUG
		configFile.close();
		return false;
	}

#ifdef DEBUG
	String temp;
	json.prettyPrintTo(temp);
	Serial.println(temp);
#endif

	json.printTo(configFile);
	configFile.flush();
	configFile.close();
	return true;
}
开发者ID:TopperBB,项目名称:FSBrowser,代码行数:64,代码来源:Config.cpp

示例7: loadHTTPAuth

boolean loadHTTPAuth() {
	File configFile = SPIFFS.open(SECRET_FILE, "r");
	if (!configFile) {
#ifdef DEBUG
		DBG_OUTPUT_PORT.println("Failed to open secret file");
#endif // DEBUG
		httpAuth.auth = false;
		httpAuth.wwwUsername = "";
		httpAuth.wwwPassword = "";
		configFile.close();
		return false;
	}

	size_t size = configFile.size();
	if (size > 256) {
#ifdef DEBUG
		DBG_OUTPUT_PORT.println("Secret file size is too large");
#endif
		httpAuth.auth = false;
		configFile.close();
		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);
	configFile.close();
#ifdef DEBUG
	DBG_OUTPUT_PORT.printf("JSON secret file size: %d %s\n", size, "bytes");
#endif

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

	if (!json.success()) {
#ifdef DEBUG
		String temp;
		json.prettyPrintTo(temp);
		DBG_OUTPUT_PORT.println(temp);
		DBG_OUTPUT_PORT.println("Failed to parse secret file");
#endif // DEBUG
		httpAuth.auth = false;
		return false;
	}
#ifdef DEBUG
	String temp;
	json.prettyPrintTo(temp);
	DBG_OUTPUT_PORT.println(temp);
#endif
	//memset(config.ssid, 0, 28);
	//memset(config.pass, 0, 50);
	//String("Virus_Detected!!!").toCharArray(config.ssid, 28); // Assign WiFi SSID
	//String("[email protected]").toCharArray(config.pass, 50); // Assign WiFi PASS

	httpAuth.auth = json["auth"];
	httpAuth.wwwUsername = json["user"].asString();
	httpAuth.wwwPassword = json["pass"].asString();

#ifdef DEBUG
	DBG_OUTPUT_PORT.println("Secret initialized.");
	DBG_OUTPUT_PORT.print("User: "); DBG_OUTPUT_PORT.println(httpAuth.wwwUsername);
	DBG_OUTPUT_PORT.print("Pass: "); DBG_OUTPUT_PORT.println(httpAuth.wwwPassword);
	DBG_OUTPUT_PORT.println(__PRETTY_FUNCTION__);
#endif // DEBUG
	return true;
}
开发者ID:TopperBB,项目名称:FSBrowser,代码行数:70,代码来源:Config.cpp

示例8: load

bool ConfigClass::load() {
  if (!this->_spiffsBegin()) { return false; }

  this->_bootMode = BOOT_CONFIG;

  if (!SPIFFS.exists(CONFIG_FILE_PATH)) {
    Logger.log(F("✖ "));
    Logger.log(CONFIG_FILE_PATH);
    Logger.logln(F(" doesn't exist"));
    return false;
  }

  File configFile = SPIFFS.open(CONFIG_FILE_PATH, "r");
  if (!configFile) {
    Logger.logln(F("✖ Cannot open config file"));
    return false;
  }

  size_t configSize = configFile.size();

  if (configSize > MAX_JSON_CONFIG_FILE_BUFFER_SIZE) {
    Logger.logln(F("✖ Config file too big"));
    return false;
  }

  char buf[MAX_JSON_CONFIG_FILE_BUFFER_SIZE];
  configFile.readBytes(buf, configSize);
  configFile.close();

  StaticJsonBuffer<MAX_JSON_CONFIG_ARDUINOJSON_BUFFER_SIZE> jsonBuffer;
  JsonObject& parsedJson = jsonBuffer.parseObject(buf);
  if (!parsedJson.success()) {
    Logger.logln(F("✖ Invalid JSON in the config file"));
    return false;
  }

  if (!Helpers::validateConfig(parsedJson)) {
    Logger.logln(F("✖ Config file is not valid"));
    return false;
  }

  if (SPIFFS.exists(CONFIG_OTA_PATH)) {
    this->_bootMode = BOOT_OTA;

    File otaFile = SPIFFS.open(CONFIG_OTA_PATH, "r");
    if (otaFile) {
      size_t otaSize = otaFile.size();
      otaFile.readBytes(this->_otaVersion, otaSize);
      otaFile.close();
    } else {
      Logger.logln(F("✖ Cannot open OTA file"));
    }
  } else {
    this->_bootMode = BOOT_NORMAL;
  }

  const char* reqName = parsedJson["name"];
  const char* reqWifiSsid = parsedJson["wifi"]["ssid"];
  const char* reqWifiPassword = parsedJson["wifi"]["password"];
  bool reqMqttMdns = false;
  if (parsedJson["mqtt"].as<JsonObject&>().containsKey("mdns")) reqMqttMdns = true;
  bool reqOtaMdns = false;
  if (parsedJson["ota"].as<JsonObject&>().containsKey("mdns")) reqOtaMdns = true;

  const char* reqMqttHost = "";
  const char* reqMqttMdnsService = "";
  if (reqMqttMdns) {
    reqMqttMdnsService = parsedJson["mqtt"]["mdns"];
  } else {
    reqMqttHost = parsedJson["mqtt"]["host"];
  }
  const char* reqDeviceId = Helpers::getDeviceId();
  if (parsedJson.containsKey("device_id")) {
    reqDeviceId = parsedJson["device_id"];
  }
  unsigned int reqMqttPort = DEFAULT_MQTT_PORT;
  if (parsedJson["mqtt"].as<JsonObject&>().containsKey("port")) {
    reqMqttPort = parsedJson["mqtt"]["port"];
  }
  const char* reqMqttBaseTopic = DEFAULT_MQTT_BASE_TOPIC;
  if (parsedJson["mqtt"].as<JsonObject&>().containsKey("base_topic")) {
    reqMqttBaseTopic = parsedJson["mqtt"]["base_topic"];
  }
  bool reqMqttAuth = false;
  if (parsedJson["mqtt"].as<JsonObject&>().containsKey("auth")) {
    reqMqttAuth = parsedJson["mqtt"]["auth"];
  }
  const char* reqMqttUsername = "";
  if (parsedJson["mqtt"].as<JsonObject&>().containsKey("username")) {
    reqMqttUsername = parsedJson["mqtt"]["username"];
  }
  const char* reqMqttPassword = "";
  if (parsedJson["mqtt"].as<JsonObject&>().containsKey("password")) {
    reqMqttPassword = parsedJson["mqtt"]["password"];
  }
  bool reqMqttSsl = false;
  if (parsedJson["mqtt"].as<JsonObject&>().containsKey("ssl")) {
    reqMqttSsl = parsedJson["mqtt"]["ssl"];
  }
  const char* reqMqttFingerprint = "";
//.........这里部分代码省略.........
开发者ID:karlpilkington,项目名称:homie-esp8266,代码行数:101,代码来源:Config.cpp

示例9: isAligned

// ArduinoJson - arduinojson.org
// Copyright Benoit Blanchon 2014-2018
// MIT License

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

static bool isAligned(void *ptr) {
  const size_t mask = sizeof(void *) - 1;
  size_t addr = reinterpret_cast<size_t>(ptr);
  return (addr & mask) == 0;
}

TEST_CASE("StaticJsonBuffer::alloc()") {
  StaticJsonBuffer<64> buffer;

  SECTION("Returns different addresses") {
    void *p1 = buffer.alloc(1);
    void *p2 = buffer.alloc(1);
    REQUIRE(p1 != p2);
  }

  SECTION("Returns non-NULL when using full capacity") {
    void *p = buffer.alloc(64);
    REQUIRE(0 != p);
  }

  SECTION("Returns NULL when full") {
    buffer.alloc(64);
    void *p = buffer.alloc(1);
    REQUIRE(0 == p);
开发者ID:RitterRBC,项目名称:Arduino,代码行数:31,代码来源:alloc.cpp

示例10: getSensors

void getSensors() {
  StaticJsonBuffer<BUFFER_LENGTH + 1> jsonBuffer;
  JsonObject &json = jsonBuffer.createObject();
  json["ambient"] = ambient;
  sendResponse(200, json);
}
开发者ID:grappendorf,项目名称:signal-tower,代码行数:6,代码来源:main.cpp

示例11: resetReadyCheck

void ProtocolFSM::update() {
  if(state > RESET) {
    esp.process();
  }
     
  if(state > CONNECTING_WIFI && !wifi_connected) {
    // we're newly disconnected disconnected
    state = DISCONNECTED_WIFI;
  }
  
  if(state > CONNECTING_WIFI && readyCheckTime()) {
    Serial.println(F("PFSM: Checking readyness"));
    resetReadyCheck();
    if(!esp.ready()) {
      state = ENABLE;
      wifi_connected = false;
    }
  }
  
  if(state > CONNECTING_WIFI && isResetTime()) {
    // nothing conclusive has happened to convince us we still
    // have comms so it's time to reset
    Serial.println(F("PFSM: Forcing reset"));
    resetResetTime();
    state = STARTUP;
  }
  
  if(state == POWER_ON) {
    // ESP12 is fairly high current so we want to give it time to stabalize
    // and give the other electronics a chance to stabalize as well
    digitalWrite(RESET_PIN, LOW);
    delay_end = millis() + 1000;
    state = POWER_ON_RESET;
        
    // correct our swarm id in the endpoint string
    insertBase10(&command_endpoint[sizeof(command_endpoint) - 4], swarmID());
    Serial.println(command_endpoint);
  }
  
  if(state == POWER_ON_RESET && delayComplete()) {
    digitalWrite(RESET_PIN, HIGH);
    state = STARTUP;
  }
  
  if(state == STARTUP) {
    resetResetTime();
    esp.enable();
    delay_end = millis() + 500;
    state = ENABLE;
  }
  
  if(state == ENABLE && delayComplete()) {
    resetResetTime();
    esp.reset();
    delay_end = millis() + 500;
    state = RESET;
  }
  
  if(state == RESET && delayComplete() && esp.ready()) {
    resetResetTime();
    resetReadyCheck();
    state = DISCONNECTED_WIFI;
  }

  
  if(state == DISCONNECTED_WIFI) {
    esp.wifiCb.attach(this, &ProtocolFSM::wifiCallback);
    esp.wifiConnect(ssid, password);
    state = CONNECTING_WIFI;
  }
  
  if(state == CONNECTING_WIFI && wifi_connected) {
    state = DISCONNECTED_REST;
  }
  
  if(state == DISCONNECTED_REST) {
    if(rest.begin(server, port, false)) {
      state = IDLE;
    }
  }
  
  if(state == IDLE && !command_valid && commandCheck()) {
    state = FETCH_COMMAND;
  }
  
  if(state == IDLE && command_complete) {
    state = ACK_COMMAND;
  }
  
  if(state == IDLE && status_pending) {
    state = SENDING_STATUS;
    status_pending = false;
    
    StaticJsonBuffer<256> jsonBuffer;
    char buffer[256];
    
    JsonObject& obj = jsonBuffer.createObject();
    status.toJson(obj);
    obj.printTo(buffer, sizeof(buffer));
    rest.setContentType("application/json");
//.........这里部分代码省略.........
开发者ID:TEchlin,项目名称:swarm-mothership,代码行数:101,代码来源:pfsm.cpp

示例12: iothub_ping_run

void iothub_ping_run(void)
{
//    srand((unsigned int)time(NULL));
    int displayedMessageCounter = -1;
    
    IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle;

    iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, HTTP_Protocol);
    if (iotHubClientHandle == NULL)
    {
        LogInfo("Failed on IoTHubClient_CreateFromConnectionString\r\n");
    }
    else
    {
#ifdef MBED_BUILD_TIMESTAMP
        // For mbed add the certificate information
        if (IoTHubClient_LL_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK)
        { 
            LogInfo("failure to set option \"TrustedCerts\"\r\n");
        }
#endif // MBED_BUILD_TIMESTAMP

        /* Attach callback for received messages */
        if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, ReceiveMessageCallback, NULL) != IOTHUB_CLIENT_OK)
        {
            LogInfo("unable to IoTHubClient_SetMessageCallback\r\n");
        }
        else
        {
            /* Send the ping message to IoT Hub */
            JsonObject& root = jsonBuffer.createObject();
            root["deviceId"] = (char*)deviceId;
            root["message"] = (char*)pingMessage;
            
            char buffer[256];
            root.printTo(buffer, sizeof(buffer));
            
            LogInfo("Send ping to IoT Hub with message: %s\r\n", buffer);
            
            sendMessage(iotHubClientHandle, (unsigned char*)buffer, sizeof(buffer));

            /* Wait for the answer back from IoT Hub */
            while (!receivedMessageBack)
            {
              IoTHubClient_LL_DoWork(iotHubClientHandle);
              ThreadAPI_Sleep(300);
              if ( messageDelivered&& !receivedMessageBack )
              {
                if (displayedMessageCounter++ == -1)
                {
                  LogInfo("Waiting for response from IoT Hub.\r\n");
                } else
                {
                  LogInfo(".");
                  if (displayedMessageCounter++ >= 59)
                  {
                    LogInfo("\r\n");
                    displayedMessageCounter = 0;
                  }
                }
              }
            }
        }
        // Reset flags
        receivedMessageBack = false;
        messageDelivered = false;
        
      IoTHubClient_LL_Destroy(iotHubClientHandle);
    }
}
开发者ID:alinamstanciu,项目名称:iot-hub-node-ping,代码行数:70,代码来源:iothub_ping.cpp


注:本文中的StaticJsonBuffer类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。