-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.cpp
662 lines (564 loc) · 17.6 KB
/
main.cpp
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
#include <Arduino.h>
#include <WiFiManager.h>
#include <LittleFS.h>
#include <ArduinoJson.h>
#include <HTTPClient.h>
#include <ESPmDNS.h>
#include <ESP32Time.h>
#include "./utils/LedControl.h"
#include "./utils/MotorControl.h"
#include "FS.h"
#include "ESPAsyncWebServer.h"
/*
* *************************************************************************************
* ********************************* CONFIGURABLES *************************************
* *************************************************************************************
*
* If you purchased the motor listed in the guide / Bill Of Materials, these default values are correct!
*
* durationInSecondsToCompleteOneRevolution = how long it takes the watch to complete one rotation on the winder.
* directionalPinA = this is the pin that's wired to IN1 on your L298N circuit board
* directionalPinB = this is the pin that's wired to IN2 on your L298N circuit board
* ledPin = by default this is set to the ESP32's onboard LED. If you've wired an external LED, change this value to the GPIO pin the LED is wired to.
* externalButton = OPTIONAL - If you want to use an external ON/OFF button, connect it to this pin 13. If you need to use another pin, change the value here.
*
* If you're using a NeoPixel equipped board, you'll need to change directionalPinA, directionalPinB and ledPin (pin 18 on most, I think) to appropriate GPIOs.
* Faiulre to set these pins on NeoPixel boards will result in kernel panics.
*/
int durationInSecondsToCompleteOneRevolution = 8;
int directionalPinA = 25;
int directionalPinB = 26;
int ledPin = 0;
int externalButton = 13;
/*
* *************************************************************************************
* ******************************* END CONFIGURABLES ***********************************
* *************************************************************************************
*/
/*
* DO NOT CHANGE THESE VARIABLES!
*/
String timeURL = "http://worldtimeapi.org/api/ip";
String settingsFile = "/settings.json";
unsigned long rtc_offset;
unsigned long rtc_epoch;
unsigned long estimatedRoutineFinishEpoch;
unsigned long previousEpoch;
unsigned long startTimeEpoch;
bool reset = false;
bool routineRunning = false;
struct RUNTIME_VARS
{
String status = "";
String rotationsPerDay = "";
String direction = "";
String hour = "00";
String minutes = "00";
String winderEnabled = "1";
String timerEnabled = "0";
};
/*
* DO NOT CHANGE THESE VARIABLES!
*/
RUNTIME_VARS userDefinedSettings;
LedControl LED(ledPin);
MotorControl motor(directionalPinA, directionalPinB);
WiFiManager wm;
AsyncWebServer server(80);
HTTPClient http;
WiFiClient client;
ESP32Time rtc;
/**
* Calclates the duration and estimated finish time of the winding routine
*
* @return epoch - estimated epoch when winding routine will finish
*/
unsigned long calculateWindingTime()
{
int tpd = atoi(userDefinedSettings.rotationsPerDay.c_str());
long totalSecondsSpentTurning = tpd * durationInSecondsToCompleteOneRevolution;
// We want to rest every 3 minutes for 15 seconds
long totalNumberOfRestingPeriods = totalSecondsSpentTurning / 180;
long totalRestDuration = totalNumberOfRestingPeriods * 180;
long finalRoutineDuration = totalRestDuration + totalSecondsSpentTurning;
Serial.print("[STATUS] - Total winding duration: ");
Serial.println(finalRoutineDuration);
unsigned long epoch = rtc.getEpoch();
unsigned long estimatedFinishTime = epoch + finalRoutineDuration;
return estimatedFinishTime;
}
/**
* Sets running conditions to TRUE & calculates winding time parameters
*/
void beginWindingRoutine()
{
startTimeEpoch = rtc.getEpoch();
previousEpoch = startTimeEpoch;
routineRunning = true;
userDefinedSettings.status = "Winding";
Serial.println("[STATUS] - Begin winding routine");
unsigned long finishTime = calculateWindingTime();
estimatedRoutineFinishEpoch = finishTime;
Serial.print("[STATUS] - Current time: ");
Serial.println(rtc.getEpoch());
Serial.print("[STATUS] - Estimated finish time: ");
Serial.println(finishTime);
}
/**
* Calls external time API & updates ESP32's onboard real time clock
*/
void getTime()
{
http.begin(client, timeURL);
int httpCode = http.GET();
if (httpCode > 0)
{
JsonDocument json;
deserializeJson(json, http.getStream());
const unsigned long epoch = json["unixtime"];
const unsigned long offset = json["raw_offset"];
rtc.offset = offset;
rtc.setTime(epoch);
}
http.end();
}
/**
* Loads user defined settings from data file
*
* @param file_name fully qualified name of file to load
* @return contents of file as a single string
*/
void loadConfigVarsFromFile(String file_name)
{
String result = "";
File this_file = LittleFS.open(file_name, "r");
JsonDocument json;
DeserializationError error = deserializeJson(json, this_file);
if (!this_file || error)
{
Serial.println("[STATUS] - Failed to open configuration file, returning empty result");
}
while (this_file.available())
{
result += (char)this_file.read();
}
userDefinedSettings.status = json["savedStatus"].as<String>(); // Winding || Stopped = 7char
userDefinedSettings.rotationsPerDay = json["savedTPD"].as<String>(); // min = 100 || max = 960
userDefinedSettings.hour = json["savedHour"].as<String>(); // 00
userDefinedSettings.minutes = json["savedMinutes"].as<String>(); // 00
userDefinedSettings.timerEnabled = json["savedTimerState"].as<String>(); // 0 || 1
userDefinedSettings.direction = json["savedDirection"].as<String>(); // CW || CCW || BOTH
this_file.close();
}
/**
* Saves user defined settings to data file
*
* @param file_name fully qualified name of file to save data to
* @param contents entire contents to write to file
* @return true if successfully wrote to file; else false
*/
bool writeConfigVarsToFile(String file_name, const RUNTIME_VARS& userDefinedSettings)
{
File this_file = LittleFS.open(file_name, "w");
JsonDocument json;
if (!this_file)
{
Serial.println("[STATUS] - Failed to open configuration file");
return false;
}
json["savedStatus"] = userDefinedSettings.status;
json["savedTPD"] = userDefinedSettings.rotationsPerDay;
json["savedHour"] = userDefinedSettings.hour;
json["savedMinutes"] = userDefinedSettings.minutes;
json["savedTimerState"] = userDefinedSettings.timerEnabled;
json["savedDirection"] = userDefinedSettings.direction;
if (serializeJson(json, this_file) == 0)
{
Serial.println("[STATUS] - Failed to write to configuration file");
return false;
}
this_file.close();
return true;
}
/**
* 404 handler for webserver
*/
void notFound(AsyncWebServerRequest *request)
{
// Handle HTTP_OPTIONS requests
if (request->method() == 64)
{
AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", "Ok");
request->send(response);
}
else
{
request->send(404, "text/plain", "Winderoo\n\n404 - Resource Not found");
}
}
/**
* API for front end
*/
void startWebserver()
{
server.on("/api/status", HTTP_GET, [](AsyncWebServerRequest *request)
{
AsyncResponseStream *response = request->beginResponseStream("application/json");
JsonDocument json;
json["status"] = userDefinedSettings.status;
json["rotationsPerDay"] = userDefinedSettings.rotationsPerDay;
json["direction"] = userDefinedSettings.direction;
json["hour"] = userDefinedSettings.hour;
json["minutes"] = userDefinedSettings.minutes;
json["durationInSecondsToCompleteOneRevolution"] = durationInSecondsToCompleteOneRevolution;
json["startTimeEpoch"] = startTimeEpoch;
json["currentTimeEpoch"] = rtc.getEpoch();
json["estimatedRoutineFinishEpoch"] = estimatedRoutineFinishEpoch;
json["winderEnabled"] = userDefinedSettings.winderEnabled;
json["timerEnabled"] = userDefinedSettings.timerEnabled;
json["db"] = WiFi.RSSI();
serializeJson(json, *response);
request->send(response);
// Update RTC time ref
getTime();
});
server.on("/api/timer", HTTP_POST, [](AsyncWebServerRequest *request)
{
int params = request->params();
for ( int i = 0; i < params; i++ )
{
AsyncWebParameter* p = request->getParam(i);
if( strcmp(p->name().c_str(), "timerEnabled") == 0 )
{
userDefinedSettings.timerEnabled = p->value().c_str();
}
}
bool writeSuccess = writeConfigVarsToFile(settingsFile, userDefinedSettings);
if ( !writeSuccess )
{
Serial.println("[ERROR] - Failed to write [timer] endpoint data to file");
request->send(500, "text/plain", "Failed to write new configuration to file");
}
request->send(204);
});
server.onRequestBody([](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total)
{
if (request->url() == "/api/power")
{
JsonDocument json;
DeserializationError error = deserializeJson(json, data);
if (error)
{
Serial.println("[ERROR] - Failed to deserialize [power] request body");
request->send(500, "text/plain", "Failed to deserialize request body");
return;
}
if (!json.containsKey("winderEnabled"))
{
request->send(400, "text/plain", "Missing required field: 'winderEnabled'");
}
userDefinedSettings.winderEnabled = json["winderEnabled"].as<String>();
if (userDefinedSettings.winderEnabled == "0")
{
Serial.println("[STATUS] - Switched off!");
userDefinedSettings.status = "Stopped";
routineRunning = false;
motor.stop();
}
request->send(204);
}
if (request->url() == "/api/update")
{
JsonDocument json;
DeserializationError error = deserializeJson(json, data);
int arraySize = 6;
String requiredKeys[arraySize] = {"rotationDirection", "tpd", "action", "hour", "minutes", "timerEnabled"};
if (error)
{
Serial.println("[ERROR] - Failed to deserialize [update] request body");
request->send(500, "text/plain", "Failed to deserialize request body");
return;
}
// validate request body
for (int i = 0; i < arraySize; i++)
{
if(!json.containsKey(requiredKeys[i]))
{
request->send(400, "text/plain", "Missing required field: '" + requiredKeys[i] +"'");
}
}
// These values can be mutated / saved directly
userDefinedSettings.hour = json["hour"].as<String>();
userDefinedSettings.minutes = json["minutes"].as<String>();
userDefinedSettings.timerEnabled = json["timerEnabled"].as<String>();
// These values need to be compared to the current settings / running state
String requestRotationDirection = json["rotationDirection"].as<String>();
String requestTPD = json["tpd"].as<String>();
String requestAction = json["action"].as<String>();
// Update motor direction
if (strcmp(requestRotationDirection.c_str(), userDefinedSettings.direction.c_str()) != 0)
{
userDefinedSettings.direction = requestRotationDirection;
motor.stop();
delay(250);
// Update motor direction
if (userDefinedSettings.direction == "CW" )
{
motor.setMotorDirection(1);
}
else if (userDefinedSettings.direction == "CCW")
{
motor.setMotorDirection(0);
}
Serial.println("[STATUS] - direction set: " + userDefinedSettings.direction);
}
else
{
userDefinedSettings.direction = requestRotationDirection;
}
// Update (turns) rotations per day
if (strcmp(requestTPD.c_str(), userDefinedSettings.rotationsPerDay .c_str()) != 0)
{
userDefinedSettings.rotationsPerDay = requestTPD;
unsigned long finishTime = calculateWindingTime();
estimatedRoutineFinishEpoch = finishTime;
}
// Update action (START/STOP)
if ( strcmp(requestAction.c_str(), "START") == 0 )
{
if (!routineRunning)
{
userDefinedSettings.status = "Winding";
beginWindingRoutine();
}
}
else
{
motor.stop();
routineRunning = false;
userDefinedSettings.status = "Stopped";
}
// Write new parameters to file
bool writeSuccess = writeConfigVarsToFile(settingsFile, userDefinedSettings);
if ( !writeSuccess )
{
Serial.println("[ERROR] - Failed to write [update] endpoint data to file");
request->send(500, "text/plain", "Failed to write new configuration to file");
}
request->send(204);
}
});
server.on("/api/reset", HTTP_GET, [](AsyncWebServerRequest *request)
{
Serial.println("[STATUS] - Received reset command");
AsyncResponseStream *response = request->beginResponseStream("application/json");
JsonDocument json;
json["status"] = "Resetting";
serializeJson(json, *response);
request->send(response);
reset = true;
});
server.serveStatic("/css/", LittleFS, "/css/").setCacheControl("max-age=31536000");
server.serveStatic("/js/", LittleFS, "/js/").setCacheControl("max-age=31536000");
server.serveStatic("/", LittleFS, "/").setDefaultFile("index.html");
server.onNotFound(notFound);
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*");
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
server.begin();
}
/**
* Initialize File System
*/
void initFS()
{
if (!LittleFS.begin(true))
{
Serial.println("[STATUS] - An error has occurred while mounting LittleFS");
}
Serial.println("[STATUS] - LittleFS mounted");
}
/**
* Change LED's state
*
* @param blinkState 1 = slow blink, 2 = fast blink, 3 = snooze state
*/
void triggerLEDCondition(int blinkState)
{
// remove any previous LED state (aka turn LED off)
LED.off();
delay(50);
switch (blinkState)
{
case 1:
LED.slowBlink();
break;
case 2:
LED.fastBlink();
break;
case 3:
LED.pwm();
break;
default:
Serial.println("[WARN] - blinkState not recognized");
break;
}
}
/**
* This is a non-block button listener function.
* Credit to github OSWW ontribution from user @danagarcia
*
* @param pauseInSeconds the amount of time to pause and listen
*/
void awaitWhileListening(int pauseInSeconds)
{
// While waiting for the 1 second to pass, actively monitor/listen for button press.
int delayEnd = millis() + (1000 * pauseInSeconds);
while (millis() < delayEnd) {
// get physical button state
int buttonState = digitalRead(externalButton);
if (buttonState == HIGH)
{
if (userDefinedSettings.winderEnabled == "0")
{
Serial.println("[STATUS] - Switched off!");
userDefinedSettings.status = "Stopped";
routineRunning = false;
motor.stop();
}
}
else
{
userDefinedSettings.winderEnabled == "1";
}
}
}
/**
* Callback triggered from WifiManager when successfully connected to new WiFi network
*/
void saveWifiCallback()
{
// slow blink to confirm connection success
triggerLEDCondition(1);
ESP.restart();
delay(2000);
}
void setup()
{
WiFi.mode(WIFI_STA);
Serial.begin(115200);
setCpuFrequencyMhz(80);
// Prepare pins
pinMode(directionalPinA, OUTPUT);
pinMode(directionalPinB, OUTPUT);
pinMode(externalButton, INPUT);
ledcSetup(LED.getChannel(), LED.getFrequency(), LED.getResolution());
ledcAttachPin(LED_BUILTIN, LED.getChannel());
// WiFi Manager config
wm.setConfigPortalTimeout(3600);
wm.setDarkMode(true);
wm.setConfigPortalBlocking(false);
wm.setHostname("Winderoo");
wm.setSaveConfigCallback(saveWifiCallback);
userDefinedSettings.winderEnabled = true;
// Connect using saved credentials, if they exist
// If connection fails, start setup Access Point
if (wm.autoConnect("Winderoo Setup"))
{
initFS();
Serial.println("[STATUS] - connected to saved network");
// retrieve & read saved settings
loadConfigVarsFromFile(settingsFile);
if (!MDNS.begin("winderoo"))
{
Serial.println("[STATUS] - Failed to start mDNS");
}
MDNS.addService("_winderoo", "_tcp", 80);
Serial.println("[STATUS] - mDNS started");
getTime();
startWebserver();
if (strcmp(userDefinedSettings.status.c_str(), "Winding") == 0)
{
beginWindingRoutine();
}
}
else
{
Serial.println("[STATUS] - WiFi Config Portal running");
ledcWrite(LED.getChannel(), 255);
};
}
void loop()
{
if (reset)
{
// fast blink
triggerLEDCondition(2);
Serial.println("[STATUS] - Stopping webserver");
server.end();
delay(600);
Serial.println("[STATUS] - Stopping File System");
LittleFS.end();
delay(200);
Serial.println("[STATUS] - Resetting Wifi Manager settings");
wm.resetSettings();
delay(200);
Serial.println("[STATUS] - Restart device...");
ESP.restart();
delay(2000);
}
if (userDefinedSettings.timerEnabled == "1")
{
if (rtc.getHour(true) == userDefinedSettings.hour.toInt() &&
rtc.getMinute() == userDefinedSettings.minutes.toInt() &&
!routineRunning &&
userDefinedSettings.winderEnabled == "1")
{
beginWindingRoutine();
}
}
if (routineRunning)
{
unsigned long currentTime = rtc.getEpoch();
if (rtc.getEpoch() < estimatedRoutineFinishEpoch)
{
// turn motor in direction
motor.determineMotorDirectionAndBegin();
int r = rand() % 100;
if (r <= 25)
{
if ((strcmp(userDefinedSettings.direction.c_str(), "BOTH") == 0) && (currentTime - previousEpoch) > 180)
{
motor.stop();
delay(3000);
previousEpoch = currentTime;
int currentDirection = motor.getMotorDirection();
motor.setMotorDirection(!currentDirection);
Serial.println("[STATUS] - Motor changing direction, mode: " + userDefinedSettings.direction);
motor.determineMotorDirectionAndBegin();
}
if ((currentTime - previousEpoch) > 180)
{
Serial.println("[STATUS] - Pause");
previousEpoch = currentTime;
motor.stop();
delay(3000);
}
}
}
else
{
// Routine has finished
userDefinedSettings.status = "Stopped";
routineRunning = false;
motor.stop();
}
}
// non-blocking button listener
awaitWhileListening(1); // 1 second
if (userDefinedSettings.winderEnabled == "0")
{
triggerLEDCondition(3);
}
wm.process();
}