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

#define S1 23
#define S2 22

const char* ssid = "Wokwi-GUEST";
const char* password = "";

String talk_back_id = "52716";
String command_id = "42735175";
String talk_back_api = "7L9VFP60H1JH20G0";// write API key
int field_no = 1;// temperature



void PUTupdateCommand (String command)
{
  if(WiFi.status()== WL_CONNECTED){   //Check WiFi connection status
 
     HTTPClient http;    //Declare object of class HTTPClient
     https://api.thingspeak.com/talkbacks/12345/commands/23456.json
     String url =  "http://api.thingspeak.com/talkbacks/";
            url += talk_back_id;
            url += "/commands/";
            url += command_id;
            url += ".json"; 
     Serial.println(url);
     http.begin(url);      //Specify request destination
     
     http.addHeader("Content-Type", "application/x-www-form-urlencoded");  //Specify content-type header
     //String postMessage = "api_key=LK7OXGEIVFTPDIJT&command_string=rahul\r\n\r\n";
     String putMessage  = "api_key=";
            putMessage += talk_back_api;
            putMessage += "&command_string=";
            putMessage += command;

     
     int httpCode = http.PUT(putMessage);   //Send the request//"{\"api_key:\"\"0E1160BEX9CSNU6V\"}"
     String payload = http.getString();                  //Get the response payload
   
     Serial.println(httpCode);   //Print HTTP return code
     if(payload.length()>0)
     {
     Serial.println(payload);//Print request response payload
     }
     else
     {
     Serial.println("HTTP ERROR");
     }
     http.end();
     delay(1500);
     }
 
 else{
     Serial.println("Error in WiFi connection"); 
     connectWifi(ssid, password);
       
 }  
}

void connectWifi (const char* ssid, const char* password)
{
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to WiFi");
}

void setup() {
  Serial.begin(115200);

  // Connect to Wi-Fi
  connectWifi(ssid, password);
  pinMode(S1, INPUT_PULLUP);// INPUT, PULLUP -> Defult Voltage at s1 becomes 3.3V (LOGIC HIGH) for ESP32
  pinMode(S2, INPUT_PULLUP);

}

void loop() {
  // Nothing to do here for this example
    if(digitalRead(S1)==LOW)
    {
       PUTupdateCommand("LEDON");
       delay(1000);
    }
    else if(digitalRead(S2)==LOW)
    {
       PUTupdateCommand("ANKITTOPNO");
       delay(1000);
    }    
    Serial.println("No Change");
    delay(1000);
}