-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathESP32_relay_door.ino
More file actions
93 lines (76 loc) · 1.89 KB
/
ESP32_relay_door.ino
File metadata and controls
93 lines (76 loc) · 1.89 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <WiFi.h>
#include <WebServer.h>
#include "ArduinoJson.h"
// Replace with your network credentials
const char *ssid = "TP-Link_DE83";
const char *password = "46193346";
// Create a web server on port 80
WebServer server(80);
// Assign output variables to GPIO pins
const int output16 = 16;
void handleOpenDoor()
{
digitalWrite(output16, HIGH);
}
void handleCloseDoor()
{
digitalWrite(output16, LOW);
}
void handleRequest()
{
if (server.hasArg("plain") == false)
{
server.send(400, "application/json", "{\n\t\"status\":\"error\",\n\t\"message\":\"Bad Request - No Data Received\"\n}\n");
return;
}
DynamicJsonDocument doc(1024);
deserializeJson(doc, server.arg("plain"));
String action = doc["action"];
if (action == "openDoor")
{
handleOpenDoor();
server.send(200, "application/json");
delay(1000);
}
else if (action == "closeDoor")
{
handleCloseDoor();
server.send(200, "application/json");
delay(1000);
}
else {
server.send(400, "application/json", "{\n\t\"status\":\"error\",\n\t\"data\":{\n\t\t\"message\":\"Invalid Action\"\n\t}\n}\n");
}
}
void setup()
{
Serial.begin(115200);
// Initialize the output variables as outputs
pinMode(output16, OUTPUT);
// Set outputs to LOW
digitalWrite(output16, LOW);
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
Serial.println("Connected to WiFi");
// Define endpoint and corresponding handler function
server.on("/request", HTTP_POST, handleRequest);
// Start the server
server.begin();
Serial.println("Server started");
}
void loop()
{
// Handle client requests
server.handleClient();
}