-
Notifications
You must be signed in to change notification settings - Fork 1
/
Project.ino
377 lines (315 loc) · 9.77 KB
/
Project.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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
/****Includes****/
#include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino
#include <WiFiClient.h>
#include <DNSServer.h> //Local DNS Server used for redirecting all requests to the &onfiguration portal
#include <ESP8266WebServer.h> //Local WebServer used to serve the configuration portal
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager WiFi Configuration Magic
#include <ESP8266mDNS.h> //Allow custom URL
#include "Gsender.h" //Library to sendMail (Gmail)
/*****Initialization*****/
ESP8266WebServer server(80);
const char *ssid = "Riot_intro_ini";
const int alertLEDpin = D1; // This LED return the state of alarm (active/inactive)
const int processLEDpin = D3; // This LED return the state of server (active/inactive)
const int debugLEDpin = D4; // This LED return the state of alarm (armed/disable)
const int buzzer = D6; // Sortie Buzzer
const int movementSensorPin = D7; // Movement sensor
const int photocellSensorPin = A0; // the cell and 10K pulldown are connected to a0
bool isActive = false; // the state of alarm (active/inactive)
bool inProcess = false; // the state of server (active/inactive)
bool inAlarm = false; // the state of server (active/inactive)
bool mailSend = false; // limit the number send mail
int sensor; // Variable to store analog value (0-1023)
int photocellReading; // the analog reading from the analog resistor divider
/******__AUTHENTICATE__********/
String www_username = "admin"; // username for authenticate
String www_password = "admin"; // password for authenticate
/******____MAILING_____********/
String email = "admin@admin.ad";
/*******__PAGES__CODE__********/
const int PAGE_ROOT = 0; // Main page
const int PAGE_TOGGLE = 1; // Alarm setting page
/*******__HTML_PAGE__**********/
String page_struct = "<!doctype html> <html> <head> <title> IoT into </title> </head><style>{%CSS%}</style><body><div class='container'>{%CONTENT%}</div></body></html>";
String page_root = "\
<p>{%CURRENT_STATE%}</p>\
<p><a href='/alarm'>Settings</a></p>\
<p><a href='/log'>Logs</a></p>\
<p><a href='/logout'>Logout</a></p>\
\
";
String page_toggleAlarm = "\
<p>{%CURRENT_STATE%}</p>\
<form method='get' action='/set'>\
<button type='submit' name='toggle' value='alarm'>{%STATUS%}</button>\
</form>\
<a href='\/'>return</>\
";
/*******__CSS___***************/
String main_css = ".container{padding: 9px 14px;margin-bottom: 14px;background-color: #f7f7f9;border: 1px solid #e1e1e8;border-radius: 4px;}";
/*******__MESSAGES__***********/
String active = "Active";
String desactive = "Desactive";
String toggle_activation = "Activation";
String toggle_desactivation = "Desactivation";
/**
ARDUINO SYSTEM
*/
void setup() {
email = "gamelinfabien@gmail.com";
pinMode(debugLEDpin, OUTPUT);
pinMode(alertLEDpin, OUTPUT);
pinMode(processLEDpin, OUTPUT);
pinMode(movementSensorPin, INPUT_PULLUP);
Serial.begin(115200);
Serial.println("Starting WiFi.");
setupWifi();
setupServer();
setupMDNS();
Serial.println("Setup OK.");
}
void loop() {
server.handleClient();
runLED();
runAlarm();
delay(1);
}
/***************______SETUP_____**********************/
void setupWifi() {
WiFiManager wifiManager;
// wifiManager.resetSettings();
wifiManager.autoConnect(ssid);
Serial.println("local ip");
Serial.println(WiFi.localIP());
}
void setupMDNS() {
// Add service to MDNS-SD to access the ESP with the URL http://<ssid>.local
if (MDNS.begin(ssid)) {
Serial.print("MDNS responder started as http://");
Serial.print(ssid);
Serial.println(".local");
}
MDNS.addService("http", "tcp", 8080);
}
void setupServer() {
server.on("/", handleRoot);
server.on("/alarm", handleAlarm);
server.on("/login", handleLogin);
server.on("/logout", handleLogout);
server.on("/set", handleAlarmSetting);
server.on("/log", handleRoot);
server.onNotFound(handleError);
const char *headerkeys[] = {"User-Agent", "Cookie"};
size_t headerkeyssize = sizeof(headerkeys) / sizeof(char *);
//ask server to track these headers
server.collectHeaders(headerkeys, headerkeyssize);
server.begin();
inProcess = true; // server ready
runLED();
Serial.println("HTTP server started");
}
/**
RUN System (in loop)
*/
bool runLED() {
digitalWrite(processLEDpin, inProcess ? HIGH : LOW);
digitalWrite(debugLEDpin, isActive ? HIGH : LOW);
digitalWrite(alertLEDpin, isActive && inAlarm ? HIGH : LOW);
}
bool runAlarm() {
if (isActive && inAlarm) {
tone(buzzer, 500);
if (!mailSend) {
sendMail();
mailSend = true;
Serial.println("Mail envoyé ! ");
}
} else if (isActive) {
inAlarm = sensorOnAlert();
} else {
toggleInAlarm();
toggleMailSend();
noTone(buzzer);
}
}
/**
Template Engine
*/
String getHTML(int page) {
Serial.println("Call getHTML.");
digitalWrite(debugLEDpin, LOW); // (inverted logic)
String html = "";
if (page == PAGE_ROOT) {
html = html + page_root;
} else if (page == PAGE_TOGGLE) {
html = html + page_toggleAlarm;
html.replace("{%STATUS%}", getLabelToggleButton());
}
html.replace("{%CURRENT_STATE%}", getLabelCurrentState());
String html_struct = "" + page_struct;
html_struct.replace("{%CONTENT%}", html);
html_struct.replace("{%CSS%}", main_css);
return html_struct;
}
/**
Security
*/
void _authenticate() {
server.sendHeader("Location", "/login");
server.sendHeader("Cache-Control", "no-cache");
server.send(301);
return;
}
/**
CONTROLLER (Handle_)
*/
void handleRoot() {
if (!is_authentified()) {
_authenticate();
return;
}
Serial.println("Call handleRoot.");
server.send(200, "text/html", getHTML(PAGE_ROOT));
}
/** Alarm form Settings Controller **/
void handleAlarm() {
if (!is_authentified()) {
_authenticate();
return;
}
Serial.print("Call handleAlarm ...");
Serial.println("Alam Form .");
server.send(200, "text/html", getHTML(PAGE_TOGGLE));
}
/** Alarm Alter Settings Controller **/
void handleAlarmSetting() {
if (!is_authentified()) {
_authenticate();
return;
}
Serial.print("Call handleAlarmSetting ...");
if (server.hasArg("toggle")) {
Serial.print("toggleAlarm ...");
toggleAlarm();
} else {
Serial.println("Bad URL.");
server.send(404, "text/plain", "Bad URL.");
return;
}
Serial.println("success .");
handleAlarm();
}
/** Error Page Controller**/
void handleError() {
server.send(404, "text/plain", "Bad URL.");
}
/** Login Controller **/
void handleLogin() {
String msg = "";
if (server.hasHeader("Cookie")) {
Serial.print("Found cookie: ");
String cookie = server.header("Cookie");
Serial.println(cookie);
}
if (server.hasArg("USERNAME") && server.hasArg("PASSWORD")) {
if (server.arg("USERNAME") == www_username && server.arg("PASSWORD") == www_password) {
server.sendHeader("Location", "/");
server.sendHeader("Cache-Control", "no-cache");
server.sendHeader("Set-Cookie", "ESPSESSIONID=1");
server.send(301);
Serial.println("Log in Successful");
return;
}
msg = "Wrong username/password! try again.";
Serial.println("Log in Failed");
}
String content = "<html><body><form action='/login' method='POST'>To log in, please use : admin/admin<br>";
content += "User:<input type='text' name='USERNAME' placeholder='user name'><br>";
content += "Password:<input type='password' name='PASSWORD' placeholder='password'><br>";
content += "<input type='submit' name='SUBMIT' value='Submit'></form>" + msg + "<br>";
content += "</body></html>";
server.send(200, "text/html", content);
}
/** LogOut Controller **/
void handleLogout() {
Serial.println("Disconnection");
server.sendHeader("Location", "/login");
server.sendHeader("Cache-Control", "no-cache");
server.sendHeader("Set-Cookie", "ESPSESSIONID=0");
server.send(301);
return;
}
/**
Mailings system
*/
void sendMail() {
Gsender *gsender = Gsender::Instance(); // Getting pointer to class instance
String subject = "Box Security - WARNING : BOITE THREATENED";
if (gsender->Subject(subject)->Send(email, "WARNING : Your box is threatened !")) {
Serial.println("Message send.");
} else {
Serial.print("Error sending message: ");
Serial.println(gsender->getError());
}
}
/**
Sensor Reader
*/
bool sensorOnAlert() {
return movementSensorOnAlert() || lightSensorOnAlert();
}
bool movementSensorOnAlert() {
sensor = digitalRead(movementSensorPin);
// While sensor is not moving, pin receive
//In Analog => 1023~1024 value
//In Digit => 0 value (LOW)
Serial.print("sensor :");
Serial.println(sensor);
Serial.print("sensor :");
Serial.println(sensor == LOW ? "LOW" : "HIGH");
return sensor == HIGH;
}
bool lightSensorOnAlert() {
photocellReading = analogRead(photocellSensorPin);
Serial.print("photocellReading : ");
Serial.println(photocellReading);
return photocellReading > 500;
}
/**
Tools function
*/
bool is_authentified() {
Serial.println("Enter is_authentified");
if (server.hasHeader("Cookie")) {
Serial.print("Found cookie: ");
String cookie = server.header("Cookie");
Serial.println(cookie);
if (cookie.indexOf("ESPSESSIONID=1") != -1) {
Serial.println("Authentification Successful");
return true;
}
}
Serial.println("Authentification Failed");
return false;
}
bool toggleAlarm() {
return isActive = !isActive;
}
bool toggleInAlarm() {
if (!isActive) {
return inAlarm = false;
}
return inAlarm = !inAlarm;
}
bool toggleMailSend() {
if (!isActive) {
return mailSend = false;
}
return mailSend = !mailSend;
}
String getLabelCurrentState() {
return isActive ? active : desactive;
}
String getLabelToggleButton() {
return isActive ? toggle_desactivation : toggle_activation;
}