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; }
void mustFailWith(S source) { StaticJsonBuffer<N> jsonBuffer; ASSERT_FALSE(jsonBuffer.parseObject(source).success()); }
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; }
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("LaJunglaSigloXX1@.").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: "******"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; }
void mustSucceedWith(S source) { StaticJsonBuffer<N> jsonBuffer; ASSERT_TRUE(jsonBuffer.parseObject(source).success()); }
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; }
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("LaJunglaSigloXX1@.").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: "******"Pass: "); DBG_OUTPUT_PORT.println(httpAuth.wwwPassword); DBG_OUTPUT_PORT.println(__PRETTY_FUNCTION__); #endif // DEBUG return true; }
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 = ""; if (parsedJson["mqtt"].as<JsonObject&>().containsKey("fingerprint")) { reqMqttFingerprint = parsedJson["mqtt"]["fingerprint"]; } bool reqOtaEnabled = false; if (parsedJson["ota"].as<JsonObject&>().containsKey("enabled")) { reqOtaEnabled = parsedJson["ota"]["enabled"]; } const char* reqOtaHost = reqMqttHost; const char* reqOtaMdnsService = ""; if (reqOtaMdns) { reqOtaMdnsService = parsedJson["ota"]["mdns"]; } else if (parsedJson["ota"].as<JsonObject&>().containsKey("host")) { reqOtaHost = parsedJson["ota"]["host"]; } unsigned int reqOtaPort = DEFAULT_OTA_PORT; if (parsedJson["ota"].as<JsonObject&>().containsKey("port")) { reqOtaPort = parsedJson["ota"]["port"]; } const char* reqOtaPath = DEFAULT_OTA_PATH; if (parsedJson["ota"].as<JsonObject&>().containsKey("path")) { reqOtaPath = parsedJson["ota"]["path"]; } bool reqOtaSsl = false; if (parsedJson["ota"].as<JsonObject&>().containsKey("ssl")) { reqOtaSsl = parsedJson["ota"]["ssl"]; } const char* reqOtaFingerprint = ""; if (parsedJson["ota"].as<JsonObject&>().containsKey("fingerprint")) { reqOtaFingerprint = parsedJson["ota"]["fingerprint"]; } strcpy(this->_configStruct.name, reqName); strcpy(this->_configStruct.wifi.ssid, reqWifiSsid); strcpy(this->_configStruct.wifi.password, reqWifiPassword); strcpy(this->_configStruct.deviceId, reqDeviceId); strcpy(this->_configStruct.mqtt.server.host, reqMqttHost); this->_configStruct.mqtt.server.port = reqMqttPort; this->_configStruct.mqtt.server.mdns.enabled = reqMqttMdns; strcpy(this->_configStruct.mqtt.server.mdns.service, reqMqttMdnsService); strcpy(this->_configStruct.mqtt.baseTopic, reqMqttBaseTopic); this->_configStruct.mqtt.auth = reqMqttAuth; strcpy(this->_configStruct.mqtt.username, reqMqttUsername); strcpy(this->_configStruct.mqtt.password, reqMqttPassword); this->_configStruct.mqtt.server.ssl.enabled = reqMqttSsl; strcpy(this->_configStruct.mqtt.server.ssl.fingerprint, reqMqttFingerprint); this->_configStruct.ota.enabled = reqOtaEnabled; strcpy(this->_configStruct.ota.server.host, reqOtaHost); this->_configStruct.ota.server.port = reqOtaPort; this->_configStruct.ota.server.mdns.enabled = reqOtaMdns; strcpy(this->_configStruct.ota.server.mdns.service, reqOtaMdnsService); strcpy(this->_configStruct.ota.path, reqOtaPath); this->_configStruct.ota.server.ssl.enabled = reqOtaSsl; strcpy(this->_configStruct.ota.server.ssl.fingerprint, reqOtaFingerprint); return true; }
// 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);
void getSensors() { StaticJsonBuffer<BUFFER_LENGTH + 1> jsonBuffer; JsonObject &json = jsonBuffer.createObject(); json["ambient"] = ambient; sendResponse(200, json); }
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"); rest.put("/status", buffer); // prepare for response rest.getResponse(NULL, 0, true); delay_end = millis() + 1000; state = SENDING_STATUS; } if(state == SENDING_STATUS) { char buffer[128]; int resp; if((resp = rest.getResponse(buffer, sizeof(buffer), false)) == HTTP_STATUS_OK) { Serial.println(F("PFSM: Status delivered")); resetResetTime(); resetReadyCheck(); state = IDLE; } else if(delayComplete()) { Serial.println(F("PFSM: Status timed out")); state = IDLE; } } if(state == FETCH_COMMAND) { rest.get(command_endpoint); // prepare for response rest.getResponse(NULL, 0, true); delay_end = millis() + 1000; state = AWAITING_COMMAND; } if(state == AWAITING_COMMAND) { StaticJsonBuffer<256> jsonBuffer; char buffer[256]; int resp; if((resp = rest.getResponse(buffer, sizeof(buffer), false)) == HTTP_STATUS_OK) { // parse the response resetResetTime(); resetReadyCheck(); char* ptr = buffer; // skip to the payload for(uint16_t ii = 0; ii < sizeof(buffer); ++ii) { if(buffer[ii] == '\n') { ptr = &buffer[ii+1]; break; } } JsonArray& root = jsonBuffer.parseArray(ptr); if(!root.success()) { Serial.print(F("PFSM: Failed to parse ")); Serial.println(ptr); command_check = millis() + 1000; state = IDLE; } else { if(root.size() == 0) { // nothing in our queue Serial.println(F("No commands waiting")); command_check = millis() + 1000; state = IDLE; } else { if(command.fromJson(root[0])) { command_valid = true; command_complete = false; state = IDLE; } else { Serial.print(F("PFSM: Message invalid ")); Serial.println(buffer); command_check = millis() + 1000; state = IDLE; } } } } else if(delayComplete()) { Serial.println(F("PFSM: Command request timed out")); command_check = millis() + 1000; state = IDLE; } } if(state == ACK_COMMAND) { StaticJsonBuffer<128> jsonBuffer; char buffer[128]; JsonObject& obj = jsonBuffer.createObject(); obj["pid"] = swarmID(); obj["cid"] = command.cid; obj["complete"] = true; obj.printTo(buffer, sizeof(buffer)); rest.put(command_endpoint, buffer); // prepare for response rest.getResponse(NULL, 0, true); delay_end = millis() + 1000; state = AWAITING_ACK; } if(state == AWAITING_ACK) { char buffer[128]; int resp; if((resp = rest.getResponse(buffer, sizeof(buffer), false)) == HTTP_STATUS_OK) { // assume we got goodness state = IDLE; command_valid = false; command_complete = false; } else if(delayComplete()) { // this is the one case we retry forever. It's important that the mothership know that // we did what we said we would do. Serial.println(F("PFSM: Ack timed out")); state = ACK_COMMAND; } } }
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); } }