# 1 "/Users/nico/Documents/GitHub/blinds-controller/blinds-controller.ino"
# 2 "/Users/nico/Documents/GitHub/blinds-controller/blinds-controller.ino" 2
# 3 "/Users/nico/Documents/GitHub/blinds-controller/blinds-controller.ino" 2
# 4 "/Users/nico/Documents/GitHub/blinds-controller/blinds-controller.ino" 2
# 5 "/Users/nico/Documents/GitHub/blinds-controller/blinds-controller.ino" 2

const char ssid[] = "DasWifi";
const char pass[] = "xsw2XSW@";
WiFiClient wifiClient; // Used for the TCP socket connection

Servo blind;

int position = 0;
int photoDiode = A0;
int pdValue = 0;

void setup()
{
    blind.attach(9);
    SerialUSB.begin(9600);
}

void openBlind()
{
    for (position = 0; position <= 180; position += 1)
    {
        blind.write(position);
        delay(15);
    }
    SerialUSB.print("Open Blind End Position: ");
    SerialUSB.print(position);
    SerialUSB.print("\n");
}

void closeBlind()
{
    for (position = 180; position >= 0; position -= 1)
    {
        blind.write(position);
        delay(15);
    }
    SerialUSB.print("Close Blind End Position: ");
    SerialUSB.print(position);
    SerialUSB.print("\n");
}

void loop()
{
    if (WiFi.status() != WL_CONNECTED)
    {
        connectWiFi();
    }
    pdValue = analogRead(photoDiode);
    SerialUSB.println(String(pdValue / 1024.0 * 100) + "%");
    delay(500);

    SerialUSB.println("Now from TimeLib module: " + String(hour()) + ":" + String(minute()) + " " + String(day()) + "/" + String(month()) + "/" + String(year()));
    SerialUSB.println("Now from the WiFi module: " + String(getTime()));
    if(getTime() > 0){
        setTime(getTime());
    }
    // if pdValue below 50% and inSchedule then open blind else close blind
    if (pdValue / 1024.0 < 0.5)
    {
        openBlind();
    }
    else
    {
        closeBlind();
    }
    delay(2000);
}

unsigned long getTime()
{
    // get the current time from the WiFi module
    return WiFi.getTime();
}

void connectWiFi()
{
    SerialUSB.print("Attempting to connect to SSID: ");
    SerialUSB.print(ssid);
    SerialUSB.print(" ");

    while (WiFi.begin(ssid, pass) != WL_CONNECTED)
    {
        // failed, retry
        SerialUSB.print(".");
        delay(5000);
    }
    SerialUSB.println();

    SerialUSB.println("You're connected to the network");
    getTime();
    //setTime(getTime());
    SerialUSB.println();
}
