// OTA
#include <WiFi.h>
#include <WiFiAP.h>
#include <WebServer.h>
#include <ESP2SOTA.h>
// SI4713
#include <Wire.h>
#include <Adafruit_Si4713.h>

#define _BV(n) (1 << n)
#define RESET_PIN 13
#define FM_STATION 10230      // 10230 == 102.30 MHz

Adafruit_Si4713 radio = Adafruit_Si4713(RESET_PIN);

const char* ssid = "SLAUDIOADAPTER";
const char* password = "123456789";

int startup_period = 600000; //10mins
unsigned long lastTriggerTime = 0;
int loop_time = 1000; //1s
unsigned long startup_time = 0;

WebServer server(80);

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

  WiFi.mode(WIFI_AP);  
  WiFi.softAP(ssid, password);
  delay(1000);
  IPAddress IP = IPAddress (192, 168, 10, 1);
  IPAddress NMask = IPAddress (255, 255, 255, 0);
  WiFi.softAPConfig(IP, IP, NMask);
  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);

  server.on("/", HTTP_GET, []() {
    server.sendHeader("Connection", "close");
    server.send(200, "text/plain", "Hello there!");
  });

  /* INITIALIZE ESP2SOTA LIBRARY */
  ESP2SOTA.begin(&server);
  server.begin();
  startup_time = millis();

  delay(1000);
   
  // RADIO CONFIG
  if (!radio.begin()) {  // begin with address 0x63 (CS high default)
    Serial.println("Couldn't find SI4713");
    while (1);
  }
  Serial.println("Found SI4713");
  
  radio.setTXpower(115);  // dBuV, 88-115 max
  radio.tuneFM(FM_STATION);
  
  // begin the RDS/RDBS transmission
  radio.beginRDS();
  radio.setRDSstation("SL Bluetooth");
  radio.setRDSbuffer("");
}

void loop() {
  while(millis() <= startup_time + startup_period){
    if(millis() - lastTriggerTime >= loop_time){
      Serial.println("Update still possible for the next " + String((startup_period - millis())/1000) + "s");
      lastTriggerTime += loop_time;
    }
    server.handleClient();
  }

  radio.readASQ();
  Serial.print("\tCurr ASQ: 0x"); 
  Serial.println(radio.currASQ, HEX);
  Serial.print("\tCurr InLevel:"); 
  Serial.println(radio.currInLevel);
}
