#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <TM1637Display.h>

#define CLK 32
#define DIO 33

const uint8_t CELSIUS[] = {SEG_A | SEG_D | SEG_E | SEG_F};
const uint8_t MINUS[] = {SEG_G};
const uint8_t HUMIDITY[] = {SEG_B | SEG_C | SEG_G | SEG_E | SEG_F};
uint8_t data[] = { 0x00, 0x00, 0x00, 0x00 };

const char* ssid = "aBcAdfh";//inserire nome rete WiFi
const char* password =  "wyZ23tX";//inserire password rete WiFi

const String endpoint = "http://api.openweathermap.org/data/2.5/weather?q=nova ponente,it&units=metric&APPID=";
const String key = "d5g8d4c3380283728b5d22f5d5df8bd9";//inserire codice API OWM

TM1637Display display(CLK, DIO);
 
void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to WiFi network");
  display.setBrightness(0x0f);
  display.setSegments(data);
}
 
void loop() {
  if ((WiFi.status() == WL_CONNECTED)) { 
    HTTPClient http;
    DynamicJsonDocument doc(1024);
 
    http.begin(endpoint + key); 
    int httpCode = http.GET();  

    String payload;
    if (httpCode > 0) { 
      String payload = http.getString();
      Serial.println(httpCode);
      Serial.println(payload);
      DeserializationError error = deserializeJson(doc, payload);
      if (error) {
        Serial.print(F("deserializeJson() failed: "));
        Serial.println(error.c_str());
        delay(120000);
      return;
    }
    // Get the root object in the document
    JsonObject root = doc.as<JsonObject>();

    float temperature = root["main"]["temp"];
    int humidity = root["main"]["humidity"];
    int pressure = root["main"]["pressure"];
        
    display.setSegments(data);
    display.showNumberDec(round(humidity),3,2);
    display.setSegments(HUMIDITY,1,3);
    Serial.println(humidity);
    delay(2000);
       
    display.setSegments(data);
    display.showNumberDec(pressure);
    Serial.println(pressure);
    delay(2000);
    
    display.setSegments(data);

    temperature = round(temperature);
    int len = 1; int pos = 2;

    if(temperature < 0){
      display.setSegments(MINUS,1,0);
      temperature = abs(temperature);
    }
    
    if(temperature >= 10) {
      len = 2;
      pos = 1;
    }
    
    display.showNumberDec(round(temperature),false,len,pos);
    display.setSegments(CELSIUS,1,3);
    Serial.println(temperature);    
    delay(30000);
    } else {
      Serial.println("Error on HTTP request");
      delay(30000);
    }
    http.end(); 
  }  
}
