-
Notifications
You must be signed in to change notification settings - Fork 0
/
esp32Nuno.ino
585 lines (453 loc) · 13.4 KB
/
esp32Nuno.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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
#include <WiFi.h>
#include <HTTPClient.h>
#include <Arduino_JSON.h>
#include <base64.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
//#include "mbedtls/base64.h"
#include "esp_camera.h"
//#include <ESP32Servo.h>
#define MAX_SENSORS 20
// Pin definition for CAMERA_MODEL_AI_THINKER
#define PWDN_GPIO_NUM 32
#define RESET_GPIO_NUM -1
#define XCLK_GPIO_NUM 0
#define SIOD_GPIO_NUM 26
#define SIOC_GPIO_NUM 27
#define Y9_GPIO_NUM 35
#define Y8_GPIO_NUM 34
#define Y7_GPIO_NUM 39
#define Y6_GPIO_NUM 36
#define Y5_GPIO_NUM 21
#define Y4_GPIO_NUM 19
#define Y3_GPIO_NUM 18
#define Y2_GPIO_NUM 5
#define VSYNC_GPIO_NUM 25
#define HREF_GPIO_NUM 23
#define PCLK_GPIO_NUM 22
int pictureNumber = 0;
camera_fb_t * fb = NULL;
class Sensor {
private:
int id;
String name;
int gpio;
double value;
String type;
int state;
double lastValue;
//Servo servo;
public:
Sensor(int id, String name, int gpio, double value, String type) {
this->id = id;
this->name = name;
this->gpio = gpio;
this->value = value;
this->type = type;
this->state = LOW;
this->lastValue = value;
init();
}
Sensor() {
}
void init() {
if (type.equals("led")) {
pinMode(gpio, OUTPUT);
}
if (type.equals("plug")) {
pinMode(gpio, OUTPUT);
}
if (type.equals("motion")) {
Serial.println("Init.");
pinMode(gpio, INPUT);
}
/* if (type.equals("servo")) {
this->servo = servo;
Serial.println(gpio);
ESP32PWM::allocateTimer(60);
ESP32PWM::allocateTimer(61);
ESP32PWM::allocateTimer(62);
ESP32PWM::allocateTimer(63);
ESP32PWM::allocateTimer(64);
servo.attach(gpio,500,2400);
servo.setPeriodHertz(50);
}*/
//falta meter aqui para ligar caso ja venha on
}
void on() {
digitalWrite(gpio, HIGH);
}
void off() {
digitalWrite(gpio, LOW);
}
/* void openServo(){
Serial.println("OPENSERVO");
this->value = HIGH;
servo.write(90);
}
void closeServo(){
this->value = LOW;
servo.write(0);
}*/
void read() {
}
int getGpio() {
return this->gpio;
}
String getType() {
return this->type;
}
String getName() {
return this->name;
}
String getId() {
return String(this->id);
}
void setValue(double val) {
this->value = val;
}
double getValue() {
return this->value;
}
void setLastValue(double val) {
this->lastValue = val;
}
double getLastValue() {
return this->lastValue;
}
void setState(int val) {
this->state = val;
}
int getState() {
return this->state;
}
};
//class Room ...
#define USE_SERIAL Serial
const char* ssid = "****";
const char* password = "****";
//const char* ssid = "Lord Voldmodem";
//const char* password = "deadlyshallows@69";
const char* mqtt_server = "161.35.8.148";
int mqtt_port = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;
String authUsername = "esp32";
String authPassword = "*****";
String auth = base64::encode(authUsername + ":" + authPassword);
int roomID = 9 ;
Sensor sensors[MAX_SENSORS];
String getCountStr = "http://161.35.8.148/api/countSensorsByRoom/?room=";
String sensorsStr = "http://161.35.8.148/api/sensors/";
String sensorsOfRoom = "http://161.35.8.148/api/sensorsofroom/?room=";
String countReadings;
String sensorReadings;
int countSensors;
const unsigned long eventInterval = 500;
const unsigned long eventIntervalToTakePicture = 500;
unsigned long previousTime = 0;
size_t capacity = 0;
String httpGETRequest(String serverName) {
HTTPClient http;
// Your IP address with path or Domain name with URL path
http.begin(serverName);
http.addHeader("Authorization", "Basic " + auth);
// Send HTTP POST request
int httpResponseCode = http.GET();
String payload = "{}";
if (httpResponseCode > 0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
payload = http.getString();
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
return payload;
}
void setup() {
Serial.begin(115200);
camera_config_t config;
config.ledc_channel = LEDC_CHANNEL_0;
config.ledc_timer = LEDC_TIMER_0;
config.pin_d0 = Y2_GPIO_NUM;
config.pin_d1 = Y3_GPIO_NUM;
config.pin_d2 = Y4_GPIO_NUM;
config.pin_d3 = Y5_GPIO_NUM;
config.pin_d4 = Y6_GPIO_NUM;
config.pin_d5 = Y7_GPIO_NUM;
config.pin_d6 = Y8_GPIO_NUM;
config.pin_d7 = Y9_GPIO_NUM;
config.pin_xclk = XCLK_GPIO_NUM;
config.pin_pclk = PCLK_GPIO_NUM;
config.pin_vsync = VSYNC_GPIO_NUM;
config.pin_href = HREF_GPIO_NUM;
config.pin_sscb_sda = SIOD_GPIO_NUM;
config.pin_sscb_scl = SIOC_GPIO_NUM;
config.pin_pwdn = PWDN_GPIO_NUM;
config.pin_reset = RESET_GPIO_NUM;
config.xclk_freq_hz = 20000000;
config.pixel_format = PIXFORMAT_JPEG;
if (psramFound()) {
config.frame_size = FRAMESIZE_CIF; // FRAMESIZE_ + QVGA|CIF|VGA|SVGA|XGA|SXGA|UXGA
config.jpeg_quality = 10;
config.fb_count = 2;
} else {
config.frame_size = FRAMESIZE_SVGA;
config.jpeg_quality = 12;
config.fb_count = 1;
}
WiFi.begin(ssid, password);
client.setBufferSize(1024);
Serial.print(auth);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("Connected to the WiFi network");
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
Serial.print("\nconnecting...");
while (!client.connect("esp32N", "smarthome", "smarthome")) {
Serial.print(".");
delay(1000);
}
client.subscribe("all");
// Init Camera
esp_err_t err = esp_camera_init(&config);
if (err != ESP_OK) {
Serial.printf("Camera init failed with error 0x%x", err);
return;
}
getCountStr.concat(roomID);
sensorsOfRoom.concat(roomID);
getAllSensors();
}
}
void getAllSensors(){
countReadings = httpGETRequest(getCountStr);
Serial.println(countReadings);
JSONVar myObject = JSON.parse(countReadings);
// JSON.typeof(jsonVar) can be used to get the type of the var
if (JSON.typeof(myObject) == "undefined") {
Serial.println("Parsing input failed!");
return;
}
Serial.print("JSON object = ");
Serial.println(myObject);
countSensors = myObject;
Serial.println(countSensors);
//malloc para os sensores
//countSensors++;
if (countSensors > 0) {
//sensors = (Sensor*)realloc(sensors ,10 * sizeof(Sensor));*/
sensorReadings = httpGETRequest(sensorsOfRoom);
JSONVar sensorsObject = JSON.parse(sensorReadings);
if (JSON.typeof(sensorsObject) == "undefined") {
Serial.println("Parsing input failed!");
return;
}
Serial.print("JSON object = ");
Serial.println(sensorsObject);
int idR;
String nameR;
int gpioR;
double valueR;
String sensortypeR;
for (int i = 0; i < countSensors; i++) {
idR = sensorsObject[i]["id"];
nameR = sensorsObject[i]["name"];
gpioR = sensorsObject[i]["gpio"];
valueR = sensorsObject[i]["value"];
sensortypeR = sensorsObject[i]["sensortype"];
sensors[i] = Sensor(idR, nameR, gpioR, valueR, sensortypeR);
String channel = "/" + String(idR);
client.subscribe(channel.c_str());
Serial.println("/" + String(idR));
}
Serial.print("Connected");
} else {
Serial.println("WiFi Disconnected");
}
}
/*char* jsonToSend(String to, String from, String message) {
}*/
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP32Nuno";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str(), "smarthome", "smarthome")) {
Serial.println("connected");
for (int i = 0; i < countSensors; i++) {
String channel = "/" + String(sensors[i].getId());
client.subscribe(channel.c_str());
}
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(1000);
}
}
}
void loop() {
/* Updates frequently */
unsigned long currentTime = millis();
while (!client.connected()) {
reconnect();
}
client.loop();
/* This is the event */
if (currentTime - previousTime >= eventInterval) {
handleSensors();
previousTime = currentTime;
}
}
void handleSensors() {
for (int i = 0; i < countSensors; i++) {
if (sensors[i].getType().equals("motion")) {
sensors[i].setValue(digitalRead(sensors[i].getGpio()));
Serial.println(digitalRead(sensors[i].getGpio()));
if (sensors[i].getValue() == HIGH) {
if (sensors[i].getState() == LOW) {
Serial.println("Motion detected!");
sensors[i].setState(HIGH);
}
} else {
if (sensors[i].getState() == HIGH) {
Serial.println("Motion ended!");
sensors[i].setState(LOW);
}
}
}
//if (sensors[i].getType().equals("motion") || sensors[i].getType().equals("led") || sensors[i].getType().equals("camera")){
if (sensors[i].getValue() != sensors[i].getLastValue()) {
sensors[i].setLastValue(sensors[i].getValue());
String channel = "/" + sensors[i].getId();
client.publish(channel.c_str(), createMessage("server", String(roomID), "sval", String(sensors[i].getValue())));
}
//}
}
}
const char* createMessage(String dest, String from, String action, String value) {
JSONVar myObject;
myObject["to"] = dest;
myObject["from"] = from;
myObject["action"] = action;
myObject["value"] = value;
String jsonString = JSON.stringify(myObject);
return jsonString.c_str();
}
String createMessagePhotoAux(String aux) {
JSONVar myObject;
myObject["photo"] = aux;
String jsonString = JSON.stringify(myObject);
//Serial.print(myObject["photo"]);
//Serial.print(jsonString);
return jsonString;
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
String top = String(topic);
String sensorId = top.substring(1);
String pay;
for (int i = 0; i < length; i++) {
pay += (char)payload[i];
}
JSONVar msgJson = JSON.parse(pay);
String dest;
String action;
String value;
dest = msgJson["to"];
action = msgJson["action"];
value = msgJson["value"];
if (dest.equals(String(roomID)) {
for (int i = 0; i < countSensors; i++) {
if (sensors[i].getId().equals(sensorId)) {
if (action.equals("turn")) {
if (sensors[i].getType().equals("led") || sensors[i].getType().equals("plug")) {
if (value.equals("on")) {
sensors[i].setLastValue(0.0);
sensors[i].setValue(1.0);
sensors[i].on();
}
if (value.equals("off")) {
sensors[i].setLastValue(1.0);
sensors[i].setValue(0.0);
sensors[i].off();
}
}
}
if (action.equals("photo") && value.equals("take") ) {
takePicture(top);
}
if (action.equals("photo") && value.equals("on") ) {
sensors[i].setLastValue(0.0);
sensors[i].setValue(1.0);
}
if (action.equals("photo") && value.equals("off") ) {
sensors[i].setLastValue(1.0);
sensors[i].setValue(0.0);
}
if (sensors[i].getType().equals("motion")) {
//client.publish("esp32/humidity", humString);
Serial.println("motion");
}
}
}
}
if ( dest.equals("all") && (action.equals("updateSensors") || action.equals("removeSensor") )) {
Serial.println("aqui");
getAllSensors();
}
}
void takePicture(String id) {
//uint8_t* rawData = getImage();
/*String h = httpGETRequest("http://161.35.8.148/static/photos/b66fdd23-fe5.jpg");
String h3 = base64::encode(h);
Serial.println(id);*/
// Take Picture with Camera
fb = esp_camera_fb_get();
if (!fb) {
Serial.println("Camera capture failed");
return;
} else {
//Serial.println("HI");
String aux = base64::encode(fb->buf, fb->len);
esp_camera_fb_return(fb);
String jsonString = createMessagePhotoAux(aux);
postImage(jsonString);
client.publish(id.c_str(), createMessage("server", String(roomID), "photo", "sent"));
}
//THIS WORKS DONT TOUCH
//String aux = createMessagePhotoAux(h3);
//postImage(aux);
}
void postImage(String rawdata) {
HTTPClient http;
// Your Domain name with URL path or IP address with path
http.begin("http://161.35.8.148/api/insertPhoto/");
http.addHeader("Content-Type", "application/json");
http.addHeader("Authorization", "Basic " + auth);
int httpResponseCode = http.POST(rawdata);
//Serial.println(http.getString());
Serial.print("HTTP Response code: ");
//Serial.println(httpResponseCode);
// Free resources
http.end();
}