#include"pitch.h"
#include <Arduino.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <HTTPClient.h>

WiFiMulti wifiMulti;

const int relay = 13;

int resolution = 8; //Display sounds at 8 bit resolution
int channel = 0; //Set analog channel value to 0

int melody[]={  //Creates a variable for an array of notes defined in an H file as frequencies
  NOTE_D4, NOTE_G4, NOTE_FS4, NOTE_A4,
  NOTE_G4, NOTE_C5, NOTE_AS4, NOTE_A4,
  NOTE_FS4, NOTE_G4, NOTE_A4, NOTE_FS4, NOTE_DS4, NOTE_D4,
  NOTE_C4, NOTE_D4, END
};

void setup() {

  Serial.begin(115200); //Setup Serial to a Baud rate of 115200
  int thisNote = 0;
  ledcSetup(channel, melody[thisNote], resolution);
  ledcAttachPin(25, channel);
  wifiMulti.addAP("Owens","joerogan24"); //initializes wifi network
  Serial.println(melody[thisNote]);
}
int number = -1;

void loop() {
  Serial.println("Starting loop");
  if((wifiMulti.run()==WL_CONNECTED)){ //wait for WiFi connection
    HTTPClient http; //Creates an HTTPClient object to be used
    http.begin("https://web.engr.oregonstate.edu/~reynolow/sensorData.csv");
    int httpCode = http.GET();
    if(httpCode > 0){ //Did we get a valid response?
      if(httpCode == HTTP_CODE_OK){ //The POST happened correctly
        String payload = http.getString();
        Serial.println(payload);
        payload.trim();
        int number = payload.toInt();
        if(number == 1){
          for(int thisNote = 0; melody[thisNote]!=-1; thisNote++){ //Begin melody array at the first value in array and procceed to next value after
            ledcWriteTone(0, melody[thisNote]); // Using LED control (ledc), send melody array value frequency using channel 0
            delay(100); //wait 0.1 seconds
            }
            ledcWriteTone(0,0); //Stop the speaker from playing
            }
        else{
          int thisNote = 0;
          ledcWriteTone(0,0);
        }
      }
      else{
        Serial.printf("[HTTP}]GET...code:%d\n",httpCode);
      }
    }
    http.end(); //End this request
  }
  else{
    Serial.println("Not connected :("); //Print if wifi connection is unsuccessful
    } 
  delay(100); //wait 0.1 seconds
  }
 
