1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| #include <ESP8266WebServer.h> #include <ESP8266HTTPClient.h>
const char* SSID = "********"; const char* PASSWORD = "********";
HTTPClient http; ESP8266WebServer server(80);
const int relay = 0;
String getStatusJSON() { String json = "{ \"status\": 0, \"data\": { \"status\": "; json += digitalRead(relay); json += " } }"; return json; }
void connectWiFi(const char *ssid, const char *password) { WiFi.begin(ssid, password); Serial.printf("connecting to %s\n", SSID); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.printf("\nconnected to %s\n", ssid); Serial.print("ip address is: "); Serial.println(WiFi.localIP()); }
void setup(void){ Serial.begin(115200);
pinMode(relay, OUTPUT); digitalWrite(relay, 1);
WiFi.mode(WIFI_STA); connectWiFi(SSID, PASSWORD);
server.on("/on", []() { digitalWrite(relay, LOW); server.send(200, "text/json", getStatusJSON()); });
server.on("/off", []() { digitalWrite(relay, HIGH); server.send(200, "text/json", getStatusJSON()); });
server.on("/status", []() { server.send(200, "text/json", getStatusJSON()); });
server.onNotFound([]() { server.send(404, "text/plain", "Not Found"); });
server.begin(); Serial.println("HTTP server started"); }
void loop(void){ while (WiFi.status() == WL_CONNECT_FAILED || WiFi.status() == WL_CONNECTION_LOST || WiFi.status() == WL_DISCONNECTED) { Serial.printf("reconnect to %s\n", SSID); connectWiFi(SSID, PASSWORD); } server.handleClient(); }
|