#include "ESP8266WiFi.h"
#include "ESP8266WebServer.h"

// https://wiki.wemos.cc/products:d1:d1_mini
// https://techtutorialsx.com/2016/10/03/esp8266-setting-a-simple-http-webserver/
const char* SSID = "SSID";
const char* PASSWORD = "password";
ESP8266WebServer server(80);

const int remotePin = D1;
const int motorPin = D2;

const int remoteButton = D5;
const int motorButton = D6;

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

    server.on("/triggerRemote", handleTriggerRemote);
    server.on("/triggerMotor", handleTriggerMotor);
    server.on("/triggerAll", handleTriggerAll);
    server.begin();
    Serial.println("Server listening");
    
    pinMode(BUILTIN_LED, OUTPUT);
    pinMode(remotePin, OUTPUT);
    pinMode(remoteButton, INPUT);
    pinMode(motorPin, OUTPUT);
    pinMode(motorButton, INPUT);
}

void loop() {
    if ((WiFi.status() == WL_CONNECTED)) {
        server.handleClient();
    }
    else {
        Serial.println("WiFi not connected!");
        connectWifi();
    }
    
    if (digitalRead(remoteButton) == HIGH) {
        Serial.println("Remote button pressed");
        triggerRemote();
    }
    
    if (digitalRead(motorButton) == HIGH) {
        Serial.println("Motor button pressed");
        triggerMotor();
    }
}

void handleTriggerRemote() {
    Serial.println("handleTriggerRemote()");
    server.send(200, "text/plain", "Trigger remote");
    triggerRemote();
}

void handleTriggerMotor() {
    Serial.println("handleTriggerMotor()");
    server.send(200, "text/plain", "Trigger motor");
    triggerMotor();
}

void handleTriggerAll() {
    Serial.println("handleTriggerAll()");
    server.send(200, "text/plain", "Trigger all");
    triggerAll();
}

void triggerRemote() {
    digitalWrite(remotePin, HIGH);
    digitalWrite(BUILTIN_LED, LOW);
    delay(500);
    digitalWrite(remotePin, LOW);
    digitalWrite(BUILTIN_LED, HIGH);
}

void triggerMotor() {
    digitalWrite(motorPin, HIGH);
    digitalWrite(BUILTIN_LED, LOW);
    delay(500);
    digitalWrite(motorPin, LOW);
    digitalWrite(BUILTIN_LED, HIGH);
}

void triggerAll() {
    digitalWrite(remotePin, HIGH);
    digitalWrite(motorPin, HIGH);
    digitalWrite(BUILTIN_LED, LOW);
    delay(500);
    digitalWrite(remotePin, LOW);
    digitalWrite(motorPin, LOW);
    digitalWrite(BUILTIN_LED, HIGH);
}

void connectWifi() {
    Serial.print("Connecting to ");
    Serial.println(SSID);
    WiFi.begin(SSID, PASSWORD);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
}
