-
Notifications
You must be signed in to change notification settings - Fork 0
/
ESP32_IoT_Shield_Dashboard.ino
340 lines (315 loc) · 13.4 KB
/
ESP32_IoT_Shield_Dashboard.ino
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
/*********
Rui Santos
Complete project details at https://RandomNerdTutorials.com/esp32-iot-shield-pcb-dashboard/
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*********/
// Import required libraries
#include "WiFi.h"
#include "ESPAsyncWebServer.h"
#include <Adafruit_BME280.h>
#include <Adafruit_Sensor.h>
// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
// Web Server HTTP Authentication credentials
const char* http_username = "admin";
const char* http_password = "admin";
Adafruit_BME280 bme; // BME280 connect to ESP32 I2C (GPIO 21 = SDA, GPIO 22 = SCL)
const int buttonPin = 18; // Pushbutton
const int ledPin = 19; // Status LED
const int output = 32; // Output socket
const int ldr = 33; // LDR (Light Dependent Resistor)
const int motionSensor = 27; // PIR Motion Sensor
int ledState = LOW; // current state of the output pin
int buttonState; // current reading from the input pin
int lastButtonState = LOW; // previous reading from the input pin
bool motionDetected = false; // flag variable to send motion alert message
bool clearMotionAlert = true; // clear last motion alert message from web page
unsigned long lastDebounceTime = 0; // the last time the output pin was toggled
unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
AsyncEventSource events("/events");
const char* PARAM_INPUT_1 = "state";
// Checks if motion was detected
void IRAM_ATTR detectsMovement() {
//Serial.println("MOTION DETECTED!!!");
motionDetected = true;
clearMotionAlert = false;
}
// Main HTML web page in root url /
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
<title>ESP IOT DASHBOARD</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="data:,">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<style>
html {font-family: Arial; display: inline-block; text-align: center;}
h3 {font-size: 1.8rem; color: white;}
h4 { font-size: 1.2rem;}
p { font-size: 1.4rem;}
body { margin: 0;}
.switch {position: relative; display: inline-block; width: 120px; height: 68px; margin-bottom: 20px;}
.switch input {display: none;}
.slider {position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; border-radius: 68px; opacity: 0.8; cursor: pointer;}
.slider:before {position: absolute; content: ""; height: 52px; width: 52px; left: 8px; bottom: 8px; background-color: #fff; -webkit-transition: .4s; transition: .4s; border-radius: 68px}
input:checked+.slider {background-color: #1b78e2}
input:checked+.slider:before {-webkit-transform: translateX(52px); -ms-transform: translateX(52px); transform: translateX(52px)}
.topnav { overflow: hidden; background-color: #1b78e2;}
.content { padding: 20px;}
.card { background-color: white; box-shadow: 2px 2px 12px 1px rgba(140,140,140,.5);}
.cards { max-width: 700px; margin: 0 auto; display: grid; grid-gap: 2rem; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));}
.slider2 { -webkit-appearance: none; margin: 14px; height: 20px; background: #ccc; outline: none; opacity: 0.8; -webkit-transition: .2s; transition: opacity .2s; margin-bottom: 40px; }
.slider:hover, .slider2:hover { opacity: 1; }
.slider2::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 40px; height: 40px; background: #008B74; cursor: pointer; }
.slider2::-moz-range-thumb { width: 40px; height: 40px; background: #008B74; cursor: pointer;}
.reading { font-size: 2.6rem;}
.card-switch {color: #50a2ff; }
.card-light{ color: #008B74;}
.card-bme{ color: #572dfb;}
.card-motion{ color: #3b3b3b; cursor: pointer;}
.icon-pointer{ cursor: pointer;}
</style>
</head>
<body>
<div class="topnav">
<h3>ESP IOT DASHBOARD <span style="text-align:right;"> <i class="fas fa-user-slash icon-pointer" onclick="logoutButton()"></i></span></h3>
</div>
<div class="content">
<div class="cards">
%BUTTONPLACEHOLDER%
<div class="card card-bme">
<h4><i class="fas fa-chart-bar"></i> TEMPERATURE</h4><div><p class="reading"><span id="temp"></span>°C</p></div>
</div>
<div class="card card-bme">
<h4><i class="fas fa-chart-bar"></i> HUMIDITY</h4><div><p class="reading"><span id="humi"></span>%</p></div>
</div>
<div class="card card-light">
<h4><i class="fas fa-sun"></i> LIGHT</h4><div><p class="reading"><span id="light"></span></p></div>
</div>
<div class="card card-motion" onClick="clearMotionAlert()">
<h4><i class="fas fa-running"></i> MOTION SENSOR</h4><div><p class="reading"><span id="motion">%MOTIONMESSAGE%</span></p></div>
</div>
</div>
<script>
function logoutButton() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "/logout", true);
xhr.send();
setTimeout(function(){ window.open("/logged-out","_self"); }, 1000);
}
function controlOutput(element) {
var xhr = new XMLHttpRequest();
if(element.checked){ xhr.open("GET", "/output?state=1", true); }
else { xhr.open("GET", "/output?state=0", true); }
xhr.send();
}
function toggleLed(element) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "/toggle", true);
xhr.send();
}
function clearMotionAlert() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "/clear-motion", true);
xhr.send();
setTimeout(function(){
document.getElementById("motion").innerHTML = "No motion";
document.getElementById("motion").style.color = "#3b3b3b";
}, 1000);
}
if (!!window.EventSource) {
var source = new EventSource('/events');
source.addEventListener('open', function(e) {
console.log("Events Connected");
}, false);
source.addEventListener('error', function(e) {
if (e.target.readyState != EventSource.OPEN) {
console.log("Events Disconnected");
}
}, false);
source.addEventListener('message', function(e) {
console.log("message", e.data);
}, false);
source.addEventListener('led_state', function(e) {
console.log("led_state", e.data);
var inputChecked;
if( e.data == 1){ inputChecked = true; }
else { inputChecked = false; }
document.getElementById("led").checked = inputChecked;
}, false);
source.addEventListener('motion', function(e) {
console.log("motion", e.data);
document.getElementById("motion").innerHTML = e.data;
document.getElementById("motion").style.color = "#b30000";
}, false);
source.addEventListener('temperature', function(e) {
console.log("temperature", e.data);
document.getElementById("temp").innerHTML = e.data;
}, false);
source.addEventListener('humidity', function(e) {
console.log("humidity", e.data);
document.getElementById("humi").innerHTML = e.data;
}, false);
source.addEventListener('light', function(e) {
console.log("light", e.data);
document.getElementById("light").innerHTML = e.data;
}, false);
}</script>
</body>
</html>)rawliteral";
String outputState(int gpio){
if(digitalRead(gpio)){
return "checked";
}
else {
return "";
}
}
String processor(const String& var){
//Serial.println(var);
if(var == "BUTTONPLACEHOLDER"){
String buttons;
String outputStateValue = outputState(32);
buttons+="<div class=\"card card-switch\"><h4><i class=\"fas fa-lightbulb\"></i> OUTPUT</h4><label class=\"switch\"><input type=\"checkbox\" onchange=\"controlOutput(this)\" id=\"output\" " + outputStateValue + "><span class=\"slider\"></span></label></div>";
outputStateValue = outputState(19);
buttons+="<div class=\"card card-switch\"><h4><i class=\"fas fa-lightbulb\"></i> STATUS LED</h4><label class=\"switch\"><input type=\"checkbox\" onchange=\"toggleLed(this)\" id=\"led\" " + outputStateValue + "><span class=\"slider\"></span></label></div>";
return buttons;
}
else if(var == "MOTIONMESSAGE"){
if(!clearMotionAlert) {
return String("<span style=\"color:#b30000;\">MOTION DETECTED!</span>");
}
else {
return String("No motion");
}
}
return String();
}
// Logged out web page
const char logout_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<p>Logged out or <a href="/">return to homepage</a>.</p>
<p><strong>Note:</strong> close all web browser tabs to complete the logout process.</p>
</body>
</html>
)rawliteral";
void setup(){
// Serial port for debugging purposes
Serial.begin(115200);
if (!bme.begin(0x76)) {
Serial.println("Could not find a valid BME280 sensor, check wiring!");
while (1);
}
// initialize the pushbutton pin as an input
pinMode(buttonPin, INPUT);
// initialize the LED pin as an output
pinMode(ledPin, OUTPUT);
// initialize the LED pin as an output
pinMode(output, OUTPUT);
// PIR Motion Sensor mode INPUT_PULLUP
pinMode(motionSensor, INPUT_PULLUP);
// Set motionSensor pin as interrupt, assign interrupt function and set RISING mode
attachInterrupt(digitalPinToInterrupt(motionSensor), detectsMovement, RISING);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
// Print ESP32 Local IP Address
Serial.println(WiFi.localIP());
// Route for root / web page
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
if(!request->authenticate(http_username, http_password))
return request->requestAuthentication();
request->send_P(200, "text/html", index_html, processor);
});
server.on("/logged-out", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", logout_html, processor);
});
server.on("/logout", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(401);
});
// Send a GET request to control output socket <ESP_IP>/output?state=<inputMessage>
server.on("/output", HTTP_GET, [] (AsyncWebServerRequest *request) {
if(!request->authenticate(http_username, http_password))
return request->requestAuthentication();
String inputMessage;
// GET gpio and state value
if (request->hasParam(PARAM_INPUT_1)) {
inputMessage = request->getParam(PARAM_INPUT_1)->value();
digitalWrite(output, inputMessage.toInt());
request->send(200, "text/plain", "OK");
}
request->send(200, "text/plain", "Failed");
});
// Send a GET request to control on board status LED <ESP_IP>/toggle
server.on("/toggle", HTTP_GET, [] (AsyncWebServerRequest *request) {
if(!request->authenticate(http_username, http_password))
return request->requestAuthentication();
ledState = !ledState;
digitalWrite(ledPin, ledState);
request->send(200, "text/plain", "OK");
});
// Send a GET request to clear the "Motion Detected" message <ESP_IP>/clear-motion
server.on("/clear-motion", HTTP_GET, [] (AsyncWebServerRequest *request) {
if(!request->authenticate(http_username, http_password))
return request->requestAuthentication();
clearMotionAlert = true;
request->send(200, "text/plain", "OK");
});
events.onConnect([](AsyncEventSourceClient *client){
if(client->lastId()){
Serial.printf("Client reconnected! Last message ID that it got is: %u\n", client->lastId());
}
// send event with message "hello!", id current millis and set reconnect delay to 1 second
client->send("hello!",NULL,millis(),1000);
});
server.addHandler(&events);
// Start server
server.begin();
}
void loop(){
static unsigned long lastEventTime = millis();
static const unsigned long EVENT_INTERVAL_MS = 10000;
// read the state of the switch into a local variable
int reading = digitalRead(buttonPin);
// If the switch changed
if (reading != lastButtonState) {
// reset the debouncing timer
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
// if the button state has changed:
if (reading != buttonState) {
buttonState = reading;
// only toggle the LED if the new button state is HIGH
if (buttonState == HIGH) {
ledState = !ledState;
digitalWrite(ledPin, ledState);
events.send(String(digitalRead(ledPin)).c_str(),"led_state",millis());
}
}
}
if ((millis() - lastEventTime) > EVENT_INTERVAL_MS) {
events.send("ping",NULL,millis());
events.send(String(bme.readTemperature()).c_str(),"temperature",millis());
events.send(String(bme.readHumidity()).c_str(),"humidity",millis());
events.send(String(analogRead(ldr)).c_str(),"light",millis());
lastEventTime = millis();
}
if(motionDetected & !clearMotionAlert){
events.send(String("MOTION DETECTED!").c_str(),"motion",millis());
motionDetected = false;
}
// save the reading. Next time through the loop, it'll be the lastButtonState:
lastButtonState = reading;
}