#include "Arduino.h" #include #include #include #include // WiFi Settings const char* WIFI_SSID = "-----";; const char* WIFI_PASSWORD = "-----"; // REST Endpoint const int REST_PORT = 80; const char* REST_SECRET = "-----"; // Map of the Relay PINs int RELAYS[] = { D5, D6, D1, D2 }; ESP8266WebServer server(80); void setup(void) { setupPins(); setupSerial(); setupWifi(); setupWebserver(); } void loop(void) { server.handleClient(); } void runRelay(int pin, int openFor = 2000, int cooldown = 500) { digitalWrite(pin, LOW); delay(openFor); digitalWrite(pin, HIGH); delay(cooldown); } void blinkNotify(int amount = 2, int duration = 500) { digitalWrite(LED_BUILTIN, HIGH); for (int i = 0; i < amount; i++) { delay(duration); digitalWrite(LED_BUILTIN, LOW); delay(duration); digitalWrite(LED_BUILTIN, HIGH); } } void setupPins(void) { for(int pin : RELAYS) { pinMode(pin, OUTPUT); digitalWrite(pin, HIGH); } pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, HIGH); } void setupSerial(void) { Serial.begin(115200); } void setupWifi(void) { WiFi.mode(WIFI_STA); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); // Clean the output before displaying info Serial.flush(); Serial.println(""); // Waiting animation Serial.print("Connecting "); while (WiFi.status() != WL_CONNECTED) { blinkNotify(1); Serial.print("."); } Serial.println(""); // Connection info Serial.print("IP address: "); Serial.print(WiFi.localIP()); Serial.print(":"); Serial.println(REST_PORT); // Broadcast .local domain MDNS.begin("relay-rest"); } void setupWebserver(void) { routing(); server.begin(); Serial.println("REST is now available!"); } void routing(void) { server.on(F("/relay"), HTTP_GET, action_relay); server.on(F("/heartbeat"), HTTP_GET, action_heartbeat); server.onNotFound(action_418); } void response(int code, String message) { server.send(code, F("text/plain"), message); } void action_418(void) { response(418, "418 - Don't bother me. I'm a peaceful teapot."); } void action_heartbeat(void) { response(200, "healthy"); } // Serving Relay // /relay?secret=&identifier=<1-4>&duration= void action_relay(void) { String secret = server.arg("secret"); if(0 != strcmp(secret.c_str(), REST_SECRET)) return action_418(); int duration = server.arg("duration").toInt(); if(duration < 500 || duration > 30000) return action_418(); int relay = server.arg("identifier").toInt() - 1; if(relay < 0 || relay > 3) return action_418(); response(200, "success"); runRelay(relay, duration); }