So you're a Noob? Post your questions here until you graduate! Don't be shy.

User avatar
By johweb
#76488 Hello,
I'm having issues with my project. I'm trying to connect to different websites to get json results. First connection (getInfo("crypto")) goes well, but esp8266 hangs on second connection (getInfo("weather_today")).
If I put "weather_today" in first position, it runs well and hangs on second connection too...
Thanks for any help !

Code: Select all//Notes
  //we need to tie the RST pin to GPIO 16 (D0)
  //The fix is to remove the D0 - RST link while uploading, and the comms errors went away.
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
#include <WiFiClientSecure.h>
#include <NTPClient.h>
#include <TimeLib.h>
#include <Timezone.h>
#include <WifiUDP.h>
#include <SPI.h>
#include <GxEPD.h>
#include <GxGDEW042T2/GxGDEW042T2.cpp>
#include <Fonts/FreeSans9pt7b.h>
#include <GxIO/GxIO_SPI/GxIO_SPI.cpp>
#include <GxIO/GxIO.cpp>
#include <pgmspace.h>

const int nbWifis = 2;
char* myWifis[nbWifis][3] = { { "Home", "NEUF_JOH", "yoctashlalcenwapoic3" }, { "Work", "Applidev' Wifi", "Applidev.72" } };
int locationWifi = -1;

#define NTP_OFFSET   60 * 60      // In seconds
#define NTP_INTERVAL 60 * 1000    // In miliseconds
#define NTP_ADDRESS  "fr.pool.ntp.org"  // change this to whatever pool is closest (see ntp.org)
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, NTP_ADDRESS, NTP_OFFSET, NTP_INTERVAL);
String date;
const char * days[] = {"dimanche", "lundi", "mardi", "mMercredi", "jeudi", "vendredi", "samedi"} ;
const char * months[] = {"janvier", "fevrier", "mars", "avril", "mai", "juin", "juillet", "aout", "septembre", "octobre", "novembre", "decembre"} ;

//static const uint8_t SS    = D8;
//static const uint8_t MOSI  = D7;
//static const uint8_t MISO  = ;
//static const uint8_t SCK   = D5;
// GxIO_SPI(SPIClass& spi, int8_t cs, int8_t dc, int8_t rst = -1, int8_t bl = -1);
GxIO_Class io(SPI, /*CS=D1*/ 5, /*DC=D3*/ 0, /*RST=D4*/ 2); // arbitrary selection of D3(=0), D4(=2), selected for default of GxEPD_Class
GxEPD_Class display(io /*RST=D4*/ /*BUSY=D2*/); // default selection of D4(=2), D2(=4)

#include "imglib/gridicons_align_right.h"

void setup() {
  Serial.begin(74880);
  display.init();
  display.fillScreen(GxEPD_WHITE);
  display.setTextColor(GxEPD_BLACK);
  display.setFont(&FreeSans9pt7b);
  display.setRotation(0);
  Serial.println("\n\nWake up.");
  if (wifiConnect())
  {
    getTime();
    getInfo("crypto");
    getInfo("weather_today");
    getInfo("weather_tomorrow");   
    getVoltage();
    display.update();
    WiFi.disconnect();
    delay(100);
  } 
  Serial.println("Back to sleep.\n\n");
  //ESP.deepSleep(sleepMinutes * 60000000);
}

void loop() {
}

void getTime() {
  Serial.println("#Get time");
 
  date = "";
  timeClient.update();
  unsigned long epochTime =  timeClient.getEpochTime();

  time_t local, utc;
  utc = epochTime;

  TimeChangeRule usEDT = {"EDT", Second, Sun, Mar, 2, 60};  //UTC +1 hours - change this as needed
  TimeChangeRule usEST = {"EST", First, Sun, Nov, 2, 120};   //UTC +2 hours - change this as needed
  Timezone usEastern(usEDT, usEST);
  local = usEastern.toLocal(utc);
 
  date += days[weekday(local)-1];
  date += " ";
  date += day(local);
  date += " ";
  date += months[month(local)-1];
  date += " ";
  date += year(local);
  date += " - ";
  date += hour(local);
  date += ":";
  if(minute(local) < 10)
  {
    date += "0";
  }
  date += minute(local);
  Serial.println("OK");
  display.setCursor(5,290);
  display.println("maj  : " + date);
}

void getInfo(String type){
  Serial.println("#Get " + type);
  WiFiClientSecure client;
 
  char* host;
  const int port=443;
  String url;

  if (type=="weather_today")
  {
    host = "api.openweathermap.org";
    url = "/data/2.5/weather?id=2991207&units=metric&APPID=daebba2c7550ea9c94177ddb86cb8870";
  }
  else if (type=="weather_tomorrow")
  {
    host = "api.openweathermap.org";
    url = "/data/2.5/weather?id=2991207&units=metric&APPID=daebba2c7550ea9c94177ddb86cb8870";
  }
  else
  {
    host = "api.bitfinex.com";
    url = "/v1/pubticker/iotusd";
  }
  Serial.println(host);
  if (!client.connect(host, port))
  {
      Serial.println("connection failed");
      return;
  }
 
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
      "Host: " + host + "\r\n" +
      "User-Agent: User-Agent: ESP8266 v1.0\r\n" +
      "Accept: */*\r\n" +
      "Connection: close\r\n\r\n");
 
  while (client.connected())
  {
      String line = client.readStringUntil('\n');
      if (line == "\r") {
          break;
      }
  }
  // read body
  String body = client.readString();
  Serial.println(body);
  client.close();
  if (type=="weather_today")
  {
    const size_t bufferSize = JSON_ARRAY_SIZE(1) + JSON_OBJECT_SIZE(1) + 2*JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(5) + JSON_OBJECT_SIZE(6) + JSON_OBJECT_SIZE(12) + 400;
    DynamicJsonBuffer jsonBuffer(bufferSize);
    JsonObject& root = jsonBuffer.parseObject(body);
   
    JsonObject& weather0 = root["weather"][0];
    String Icon0 = weather0["main"]; // "Clouds"
    String Conditions0 = weather0["description"]; // "broken clouds"

    JsonObject& main = root["main"];
    String Averagehumidity0 = main["humidity"]; // 55
    String Low0 = main["temp_min"];
    String High0 = main["temp_max"];

    display.setCursor(0,12);
    DisplayWXicon(60,80, Icon0);  DisplayWXicon(107,0, "thermo");;
    display.setCursor(232,15);  display.println("Xdimanche");
    display.setCursor(227,30);  display.println(Conditions0);
    display.setCursor(92,40);   display.println(High0 + "/" + Low0);
    display.setCursor(147,40);  display.println(Averagehumidity0 + "%");
    display.setCursor(92,55);   display.println(F("--------------------------"));
  }
  else if (type="weather_tomorrow")
  {
    const size_t bufferSize = 40*JSON_ARRAY_SIZE(1) + JSON_ARRAY_SIZE(40) + 37*JSON_OBJECT_SIZE(0) + 83*JSON_OBJECT_SIZE(1) + 41*JSON_OBJECT_SIZE(2) + 41*JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(5) + 80*JSON_OBJECT_SIZE(8) + 12450;
    DynamicJsonBuffer jsonBuffer(bufferSize);
    JsonObject& root = jsonBuffer.parseObject(body);

    JsonArray& list = root["list"];
   
    JsonObject& list0 = list[0];
    JsonObject& list0_main = list0["main"];
    String Low1 = list0_main["temp_min"]; // 17.92
    String High1 = list0_main["temp_max"]; // 20.68
    String Averagehumidity1 = list0_main["humidity"]; // 90
   
    JsonObject& list0_weather0 = list0["weather"][0];
    String Icon1 = list0_weather0["main"]; // "Clouds"
    String Conditions1 = list0_weather0["description"]; // "few clouds"
   
    DisplayWXicon(60,180, Icon1); DisplayWXicon(107,60, "thermo");;
    display.setCursor(232,75);  display.println("Xlundi");
    display.setCursor(227,90);  display.println(Conditions1);
    display.setCursor(92,100);  display.println(High1 + "/" + Low1);
    display.setCursor(147,100); display.println(Averagehumidity1 + "%");
    display.setCursor(92,115);  display.println(F("-------------------------"));
  }
  else
  {
    const size_t bufferSize = JSON_OBJECT_SIZE(8) + 140;
    DynamicJsonBuffer jsonBuffer(bufferSize);
    JsonObject& root = jsonBuffer.parseObject(body);
 
    const String last_price = root["last_price"];
 
    display.setCursor(40,260);
    display.println("IOTA : " + last_price + " $");
  }
  Serial.println("OK");
}

void getVoltage(){
  Serial.println("#Get voltage");
  display.setCursor(240,260);
  display.println("Batterie : 3,14 V");
  Serial.println("OK");
}

void DisplayWXicon(int x, int y, String IconName){
  int scale = 10; // Adjust size as necessary
  if      (IconName == "rain"            || IconName == "nt_rain")             Rain(x,y, scale);
  else if (IconName == "chancerain"      || IconName == "nt_chancerain")       ExpectRain(x,y,scale);
  else if (IconName == "snow"            || IconName == "nt_snow"         ||
           IconName == "flurries"        || IconName == "nt_flurries"     ||
           IconName == "chancesnow"      || IconName == "nt_chancesnow"   ||
           IconName == "chanceflurries"  || IconName == "nt_chanceflurries")   Snow(x,y,scale);
  else if (IconName == "sleet"           || IconName == "nt_sleet"        ||
           IconName == "chancesleet"     || IconName == "nt_chancesleet")      Snow(x,y,scale);
  else if (IconName == "sunny"           || IconName == "nt_sunny"        ||
           IconName == "clear"           || IconName == "nt_clear")            Sunny(x,y,scale);
  else if (IconName == "partlysunny"     || IconName == "nt_partlysunny"  ||
           IconName == "mostlysunny"     || IconName == "nt_mostlysunny")      MostlySunny(x,y,scale);
  else if (IconName == "cloudy"          || IconName == "nt_cloudy"       ||
           IconName == "mostlycloudy"    || IconName == "nt_mostlycloudy" ||
           IconName == "partlycloudy"    || IconName == "nt_partlycloudy")     Cloudy(x,y,scale);           
  else if (IconName == "tstorms"         || IconName == "nt_tstorms"      ||
           IconName == "chancetstorms"   || IconName == "nt_chancetstorms")    Tstorms(x,y,scale);
  else if (IconName == "fog"             || IconName == "nt_fog"          ||
           IconName == "hazy"            || IconName == "nt_hazy")             Fog(x,y,scale);
  else if (IconName == "thermo")
           display.drawBitmap(x,y, thermo_icon,64,24, GxEPD_BLACK);
  else if (IconName == "probrain")
           display.drawBitmap(x,y, probrain_icon,32,24, GxEPD_BLACK);
  else     Nodata(x,y,scale);
}

bool wifiConnect() {
  Serial.println("# Connecting Wifi");

  bool connection = false;

  WiFi.persistent(false);
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);

  int n = WiFi.scanNetworks();
  if (n == 0)
  {
    Serial.println(" _ no network found");
  }
  else
  {
    Serial.print(" _ ");
    Serial.print(n);
    Serial.println(" network(s) found");

    for (int i = 0; i < n; ++i)
    {
      for ( int j = 0; j < nbWifis; ++j ) {
        if (WiFi.SSID(i) == myWifis[j][1])
        {
          locationWifi = j;
        }
      }
    }

    if (locationWifi == -1) {
      Serial.println(" _ unknown networks");
    }
    else
    {
      int counter = 0;
      Serial.print(" _ connecting ");
      Serial.print(myWifis[locationWifi][0]);
      Serial.print(" : ");
      WiFi.begin(myWifis[locationWifi][1], myWifis[locationWifi][2]);
      while ((!connection) && (counter<10))
      { 
        Serial.print(" .");
        if (WiFi.status() == WL_CONNECTED)
        {
          connection = true;
        }
        delay(1000);
        counter++;
      }
      if (connection)
      {
        Serial.println(" connected.");
      }
      else
      {
        Serial.println(" error !");
      }
    }
  }
  Serial.println("OK");
 
  return connection;
}