Advertisement
Guest User

Untitled

a guest
Oct 4th, 2018
279
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.27 KB | None | 0 0
  1. #include <ArduinoJson.h>
  2. #include <ESP8266WiFi.h>
  3. #include <ESP8266HTTPClient.h>
  4. #include <Timers.h>
  5.  
  6. const char *ssid = "DataJugling";
  7. const char *password = "jugle123";
  8. const char *url = "http://dataserver.local/";
  9.  
  10. Timer requestTimer;
  11.  
  12. DynamicJsonDocument doc;
  13. HTTPClient http;
  14.  
  15. void setup() {
  16.   Serial.begin(115200);
  17.   requestTimer.begin(500);
  18.  
  19.   pinMode(LED_BUILTIN, OUTPUT);
  20.   digitalWrite(LED_BUILTIN, LOW);
  21.  
  22.   WiFi.mode(WIFI_STA);
  23.   WiFi.begin(ssid, password);
  24.   while (WiFi.status() != WL_CONNECTED) delay(500);
  25.   digitalWrite(LED_BUILTIN, HIGH);
  26.  
  27.   //Generating URL from server IP which is client gateway.
  28.   //And URL have to look fine for HTTPClient
  29.   //url = "http://" + WiFi.gatewayIP().toString() + "/";
  30.   //url = "http://dataserver.local/";
  31. }
  32.  
  33. void loop() {
  34.   if(requestTimer.available()) {
  35.     http.begin(url);
  36.     int httpCode = http.GET();
  37.  
  38.     if (httpCode > 0) {
  39.       String data = http.getString();
  40.      
  41.       deserializeJson(doc, data);
  42.       JsonObject root = doc.as<JsonObject>();
  43.  
  44.       Serial.print("JSON decode: ");
  45.       Serial.println(root["state"].as<bool>());
  46.     } else {
  47.       Serial.printf("[HTTP] Error: %s\n", http.errorToString(httpCode).c_str());
  48.     }
  49.     http.end();
  50.     requestTimer.restart();
  51.   }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement