Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <ArduinoJson.h>
- #include <ESP8266WiFi.h>
- #include <ESP8266HTTPClient.h>
- #include "Esp.h"
- const char* ssid = "unoffice";
- const char* password = "15eb9a233199";
- const char* host = "energymonitor.xyz";
- String lineX="";
- //*Inicialização de vars para conexão
- HTTPClient http;
- WiFiClient client;
- void setup() {
- Serial.begin(115200);
- Serial.println();
- Serial.print("Connecting to ");
- Serial.println(ssid);
- WiFi.mode(WIFI_STA);
- if(WiFi.status() != WL_CONNECTED) {
- connectWiFi();
- }
- Serial.println("");
- Serial.println("WiFi connected");
- Serial.println("IP address: ");
- Serial.println(WiFi.localIP());
- }
- void loop() {
- if(WiFi.status() != WL_CONNECTED) {
- connectWiFi();
- }
- if(WiFi.status() == WL_CONNECTED) {
- httpget();
- delay(3000);
- Serial.println(lineX);
- //JSON
- delay(3000);
- //WORKING: parseJson("{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}");
- //NOT WORKING (below):
- parseJson(lineX);
- }
- }
- /*
- * connectWifi: Connect to WiFi and counterPanic
- */
- void connectWiFi(void){
- int counterPanic = 0;
- while (WiFi.status() != WL_CONNECTED) {
- WiFi.begin(ssid, password);
- delay(3000);
- counterPanic++;
- Serial.println("Counter Panic:");
- Serial.println(counterPanic);
- if(counterPanic>8){
- ESP.restart();
- }
- }
- }
- /*
- * httpget
- */
- void httpget(){
- int lineNo=0;
- const int httpPort = 80;
- //String url = "/feedback-esp3/fbdata3.json";
- String url = "/feedback-esp/fbdataino.json";
- if(WiFi.status() != WL_CONNECTED) {
- connectWiFi();
- }
- Serial.println("WiFi connected");
- // Use WiFiClient class to create TCP connections
- if (!client.connect(host, httpPort)) {
- Serial.println("Connection to HTTP: FAILED!");
- client.stop();
- delay(1000);
- ESP.restart();
- }else{
- client.print(String("GET ") + url + " HTTP/1.1\r\n" +
- "Host: " + host + "\r\n" +
- "Connection: close\r\n\r\n");
- delay(1000);
- Serial.println("Connection to HTTP: OK!");
- }
- // Read all the lines of the reply from server and print them to Serial
- while(client.available()){
- //lines[lineNo] = client.readStringUntil('\r');
- //lineNo=lineNo+1;
- lineX = client.readStringUntil('\n');
- //Serial.println(line);
- }
- Serial.println();
- Serial.println("closing connection");
- client.stop();
- }
- void parseJson(String lineX2){
- StaticJsonBuffer<500> jsonBuffer;
- JsonObject& root = jsonBuffer.parseObject(lineX2);
- if (!root.success()) {
- Serial.println("parseObject() failed");
- //return;
- }
- const char* sensor = root["sensor"];
- long time = root["time"];
- double latitude = root["data"][0];
- double longitude = root["data"][1];
- Serial.println(sensor);
- Serial.println(time);
- Serial.println(latitude, 6);
- Serial.println(longitude, 6);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement