-
Notifications
You must be signed in to change notification settings - Fork 6
/
DeepSleepScheduler.h
705 lines (629 loc) · 22.1 KB
/
DeepSleepScheduler.h
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
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
/*
Copyright 2016-2016 Peter Rosenberg
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
This file is part of the DeepSleepScheduler library for Arduino.
Definition and code are in the header file in order to allow the user to configure the library by using defines.
The following options are available:
- #define LIBCALL_DEEP_SLEEP_SCHEDULER: This h file can only be included once within a project as it also contains the implementation.
To use it in multiple files, define LIBCALL_DEEP_SLEEP_SCHEDULER before all include statements except one.
All following options are to be set before the include where no LIBCALL_DEEP_SLEEP_SCHEDULER is defined.
- #define SLEEP_DELAY: Prevent the CPU from entering sleep for the specified amount of milli seconds after finishing the previous task.
- #define SUPERVISION_CALLBACK: Allows to specify a callback Runnable to be called when a task runs too long. When
the callback returns, the CPU is restarted after 15 ms by the watchdog. The callback method is called directly
from the watchdog interrupt. This means that e.g. delay() does not work.
- #define SUPERVISION_CALLBACK_TIMEOUT: Specify the timeout of the callback on AVR until the watchdog resets the CPU. Defaults to WDTO_1S.
- #define AWAKE_INDICATION_PIN: Show on a LED if the CPU is active or in sleep mode. HIGH = active, LOW = sleeping.
*/
#ifndef DEEP_SLEEP_SCHEDULER_H
#define DEEP_SLEEP_SCHEDULER_H
// -------------------------------------------------------------------------------------------------
// Definition (usually in H file)
// -------------------------------------------------------------------------------------------------
#include <Arduino.h>
#if defined(ESP32) || defined(ESP8266)
#include "DeepSleepScheduler_esp_includes.h"
#endif
#define BUFFER_TIME 2
#define NOT_USED 255
enum TaskTimeout {
TIMEOUT_15Ms,
TIMEOUT_30MS,
TIMEOUT_60MS,
TIMEOUT_120MS,
TIMEOUT_250MS,
TIMEOUT_500MS,
TIMEOUT_1S,
TIMEOUT_2S,
TIMEOUT_4S,
TIMEOUT_8S,
NO_SUPERVISION
};
/**
Extend from Runnable in order to have the run() method run by the scheduler.
*/
class Runnable {
public:
virtual void run() = 0;
};
class Scheduler {
public:
/**
Schedule the callback method as soon as possible but after other tasks
that are to be scheduled immediately and are in the queue already.
@param callback: the method to be called on the main thread
*/
void schedule(void (*callback)());
/**
Schedule the Runnable as soon as possible but after other tasks
that are to be scheduled immediately and are in the queue already.
@param runnable: the Runnable on which the run() method will be called on the main thread
*/
void schedule(Runnable *runnable);
/**
Schedule the callback method as soon as possible and remove all other
tasks with the same callback. This is useful if you call it
from an interrupt and want one execution only even if the interrupt triggers
multiple times.
@param callback: the method to be called on the main thread
*/
void scheduleOnce(void (*callback)());
/**
Schedule the Runnable as soon as possible and remove all other
tasks with the same Runnable. This is useful if you call it
from an interrupt and want one execution only even if the interrupt triggers
multiple times.
@param runnable: the Runnable on which the run() method will be called on the main thread
*/
void scheduleOnce(Runnable *runnable);
/**
Schedule the callback after delayMillis milliseconds.
@param callback: the method to be called on the main thread
@param delayMillis: the time to wait in milliseconds until the callback shall be made
*/
void scheduleDelayed(void (*callback)(), unsigned long delayMillis);
/**
Schedule the callback after delayMillis milliseconds.
@param runnable: the Runnable on which the run() method will be called on the main thread
@param delayMillis: the time to wait in milliseconds until the callback shall be made
*/
void scheduleDelayed(Runnable *runnable, unsigned long delayMillis);
/**
Schedule the callback uptimeMillis milliseconds after the device was started.
Please be aware that uptimeMillis is stopped when no task is pending. In this case,
the CPU may only wake up on an external interrupt.
@param callback: the method to be called on the main thread
@param uptimeMillis: the time in milliseconds since the device was started
to schedule the callback.
*/
void scheduleAt(void (*callback)(), unsigned long uptimeMillis);
/**
Schedule the callback uptimeMillis milliseconds after the device was started.
Please be aware that uptimeMillis is stopped when no task is pending. In this case,
the CPU may only wake up on an external interrupt.
@param runnable: the Runnable on which the run() method will be called on the main thread
@param uptimeMillis: the time in milliseconds since the device was started
to schedule the callback.
*/
void scheduleAt(Runnable *runnable, unsigned long uptimeMillis);
/**
Schedule the callback method as next task even if other tasks are in the queue already.
@param callback: the method to be called on the main thread
*/
void scheduleAtFrontOfQueue(void (*callback)());
/**
Schedule the callback method as next task even if other tasks are in the queue already.
@param runnable: the Runnable on which the run() method will be called on the main thread
*/
void scheduleAtFrontOfQueue(Runnable *runnable);
/**
Check if this callback is scheduled at least once already.
This method can be called in an interrupt but bear in mind, that it loops through
the run queue until it finds it or reaches the end.
@param callback: callback to check
*/
bool isScheduled(void (*callback)()) const;
/**
Check if this runnable is scheduled at least once already.
This method can be called in an interrupt but bear in mind, that it loops through
the run queue until it finds it or reaches the end.
@param runnable: Runnable to check
*/
bool isScheduled(Runnable *runnable) const;
/**
Returns the scheduled time of the task that is currently running.
If no task is currently running, 0 is returned.
*/
unsigned long getScheduleTimeOfCurrentTask() const;
/**
Cancel all schedules that were scheduled for this callback.
@param callback: method of which all schedules shall be removed
*/
void removeCallbacks(void (*callback)());
/**
Cancel all schedules that were scheduled for this runnable.
@param runnable: instance of Runnable of which all schedules shall be removed
*/
void removeCallbacks(Runnable *runnable);
/**
Acquire a lock to prevent the CPU from entering sleep.
acquireNoSleepLock() supports up to 255 locks.
You need to call releaseNoSleepLock() the same amount of times
to allow the CPU to enter sleep again.
*/
void acquireNoSleepLock();
/**
Release the lock acquired by acquireNoSleepLock(). Please make sure you
call releaseNoSleepLock() the same amount of times as acquireNoSleepLock(),
otherwise the CPU is not allowed to enter sleep.
*/
void releaseNoSleepLock();
/**
return: true if the CPU is currently allowed to enter sleep, false otherwise.
*/
inline bool doesSleep() const;
/**
Configure the supervision of future tasks. Can be deactivated with NO_SUPERVISION.
Default: TIMEOUT_8S
@param taskTimeout: The task timeout to be used
*/
void setTaskTimeout(TaskTimeout taskTimeout);
/**
Resets the task watchdog. After this call returns, the currently running
Task can run up to the configured TaskTimeout set by setTaskTimeout().
*/
void taskWdtReset();
/**
return: The milliseconds since startup of the device where the sleep time was added.
This value does not consider the time when the CPU is in infinite deep sleep
while nothing is in the queue.
*/
unsigned long getMillis() const;
#ifdef SUPERVISION_CALLBACK
#ifdef ESP8266
#error "SUPERVISION_CALLBACK not supported for ESP8266"
#endif
/**
Sets the runnable to be called when the task supervision detects a task that runs too long.
The run() method will be called from the watchdog interrupt what means, that
e.g. the method delay() does not work.
On AVR, when run() returns, the CPU will be restarted after 15ms.
On ESP32, the interrupt service routine as a whole has a time limit and calls
abort() when returning from this method.
See description of SUPERVISION_CALLBACK and SUPERVISION_CALLBACK_TIMEOUT.
@param runnable: instance of Runnable where the run() method is called
*/
void setSupervisionCallback(Runnable *runnable) {
supervisionCallbackRunnable = runnable;
}
#endif
/**
This method needs to be called from your loop() method and does not return.
*/
void execute();
/**
Constructor of the scheduler. Do not all this method as there is only one instance of Scheduler supported.
*/
Scheduler();
private:
class Task {
public:
Task(const unsigned long scheduledUptimeMillis, const bool isCallbackTask)
: scheduledUptimeMillis(scheduledUptimeMillis), isCallbackTask(isCallbackTask), next(NULL) {
}
void execute() {
// do in base class to prevent virtual method
if (isCallbackTask) {
((CallbackTask*)this)->callback();
} else {
((RunnableTask*)this)->runnable->run();
}
}
bool equalCallback(Task *task) {
// do in base class to prevent virtual method
if (isCallbackTask) {
return task->isCallbackTask && ((CallbackTask*)task)->callback == ((CallbackTask*)this)->callback;
} else {
return !task->isCallbackTask && ((RunnableTask*)task)->runnable == ((RunnableTask*)this)->runnable;
}
}
const unsigned long scheduledUptimeMillis;
// dynamic_cast is not supported by default as it compiles with -fno-rtti
// Therefore, we use this variable to detect which Task type it is.
const bool isCallbackTask;
Task *next;
};
class CallbackTask: public Task {
public:
CallbackTask(void (*callback)(), const unsigned long scheduledUptimeMillis)
: Task(scheduledUptimeMillis, true), callback(callback) {
}
void (* const callback)();
};
class RunnableTask: public Task {
public:
RunnableTask(Runnable *runnable, const unsigned long scheduledUptimeMillis)
: Task(scheduledUptimeMillis, false), runnable(runnable) {
}
Runnable * const runnable;
};
/**
controls if sleep is done, 0 does sleep
*/
byte noSleepLocksCount;
void insertTask(Task *task);
void insertTaskAndRemoveExisting(Task *newTask);
void deleteTask(Task *taskToDelete, Task *previousTask);
private:
enum SleepMode {
NO_SLEEP,
IDLE,
SLEEP
};
#ifdef SUPERVISION_CALLBACK
static Runnable *supervisionCallbackRunnable;
#endif
/**
currently set task timeout
*/
TaskTimeout taskTimeout;
/**
first element in the run queue
*/
Task *first;
/*
the task currently running or null if none running
*/
Task *current;
#ifdef SLEEP_DELAY
/**
The time in millis since start up when the last task finished.
Used to delay deep sleep.
*/
unsigned long lastTaskFinishedMillis;
#endif
inline void setupTaskTimeoutIfConfigured();
inline bool executeNextIfTime();
inline void reactivateTaskTimeoutIfRequired();
// These methods MUST be defined by the definition include
// void taskWdtEnable(const uint8_t value);
// void taskWdtReset();
// void taskWdtDisable();
// void sleepIfRequired();
//
// // only used by AVR as the watchdog timer is used
// bool isWakeupByOtherInterrupt();
//
// // only used for AVR
// void wdtEnableInterrupt();
#if defined(ESP32) || defined(ESP8266)
#include "DeepSleepScheduler_esp_definition.h"
#else
#include "DeepSleepScheduler_avr_definition.h"
#endif
};
extern Scheduler scheduler;
#ifndef LIBCALL_DEEP_SLEEP_SCHEDULER
// -------------------------------------------------------------------------------------------------
// Implementation (usuallly in CPP file)
// -------------------------------------------------------------------------------------------------
/**
the one and only instance of Scheduler
*/
Scheduler scheduler;
#ifdef SUPERVISION_CALLBACK
Runnable *Scheduler::supervisionCallbackRunnable;
#endif
Scheduler::Scheduler() {
#ifdef AWAKE_INDICATION_PIN
pinMode(AWAKE_INDICATION_PIN, OUTPUT);
#endif
taskTimeout = TIMEOUT_8S;
first = NULL;
current = NULL;
noSleepLocksCount = 0;
init();
}
void Scheduler::schedule(void (*callback)()) {
Task *newTask = new CallbackTask(callback, getMillis());
insertTask(newTask);
}
void Scheduler::schedule(Runnable *runnable) {
Task *newTask = new RunnableTask(runnable, getMillis());
insertTask(newTask);
}
void Scheduler::scheduleOnce(void (*callback)()) {
Task *newTask = new CallbackTask(callback, getMillis());
insertTaskAndRemoveExisting(newTask);
}
void Scheduler::scheduleOnce(Runnable *runnable) {
Task *newTask = new RunnableTask(runnable, getMillis());
insertTaskAndRemoveExisting(newTask);
}
void Scheduler::scheduleDelayed(void (*callback)(), unsigned long delayMillis) {
Task *newTask = new CallbackTask(callback, getMillis() + delayMillis);
insertTask(newTask);
}
void Scheduler::scheduleDelayed(Runnable *runnable, unsigned long delayMillis) {
Task *newTask = new RunnableTask(runnable, getMillis() + delayMillis);
insertTask(newTask);
}
void Scheduler::scheduleAt(void (*callback)(), unsigned long uptimeMillis) {
Task *newTask = new CallbackTask(callback, uptimeMillis);
insertTask(newTask);
}
void Scheduler::scheduleAt(Runnable *runnable, unsigned long uptimeMillis) {
Task *newTask = new RunnableTask(runnable, uptimeMillis);
insertTask(newTask);
}
void Scheduler::scheduleAtFrontOfQueue(void (*callback)()) {
Task *newTask = new CallbackTask(callback, getMillis());
noInterrupts();
newTask->next = first;
first = newTask;
interrupts();
}
void Scheduler::scheduleAtFrontOfQueue(Runnable *runnable) {
Task *newTask = new RunnableTask(runnable, getMillis());
noInterrupts();
newTask->next = first;
first = newTask;
interrupts();
}
bool Scheduler::isScheduled(void (*callback)()) const {
bool scheduled = false;
noInterrupts();
Task *currentTask = first;
while (currentTask != NULL) {
if (currentTask->isCallbackTask && ((CallbackTask*)currentTask)->callback == callback) {
scheduled = true;
break;
}
currentTask = currentTask->next;
}
interrupts();
return scheduled;
}
bool Scheduler::isScheduled(Runnable *runnable) const {
bool scheduled = false;
noInterrupts();
Task *currentTask = first;
while (currentTask != NULL) {
if (!currentTask->isCallbackTask && ((RunnableTask*)currentTask)->runnable == runnable) {
scheduled = true;
break;
}
currentTask = currentTask->next;
}
interrupts();
return scheduled;
}
unsigned long Scheduler::getScheduleTimeOfCurrentTask() const {
noInterrupts();
if (current != NULL) {
return current->scheduledUptimeMillis;
}
interrupts();
return 0;
}
void Scheduler::removeCallbacks(void (*callback)()) {
noInterrupts();
if (first != NULL) {
Task *previousTask = NULL;
Task *currentTask = first;
while (currentTask != NULL) {
if (currentTask->isCallbackTask && ((CallbackTask*)currentTask)->callback == callback) {
Task *taskToDelete = currentTask;
if (previousTask == NULL) {
// remove the first task
first = taskToDelete->next;
} else {
previousTask->next = taskToDelete->next;
}
currentTask = taskToDelete->next;
delete taskToDelete;
} else {
previousTask = currentTask;
currentTask = currentTask->next;
}
}
}
interrupts();
}
void Scheduler::removeCallbacks(Runnable *runnable) {
noInterrupts();
if (first != NULL) {
Task *previousTask = NULL;
Task *currentTask = first;
while (currentTask != NULL) {
if (!currentTask->isCallbackTask && ((RunnableTask*)currentTask)->runnable == runnable) {
Task *taskToDelete = currentTask;
if (previousTask == NULL) {
// remove the first task
first = taskToDelete->next;
} else {
previousTask->next = taskToDelete->next;
}
currentTask = taskToDelete->next;
delete taskToDelete;
} else {
previousTask = currentTask;
currentTask = currentTask->next;
}
}
}
interrupts();
}
void Scheduler::acquireNoSleepLock() {
noSleepLocksCount++;
}
void Scheduler::releaseNoSleepLock() {
if (noSleepLocksCount != 0) {
noSleepLocksCount--;
}
}
bool Scheduler::doesSleep() const {
return noSleepLocksCount == 0;
}
void Scheduler::setTaskTimeout(TaskTimeout taskTimeout) {
noInterrupts();
this->taskTimeout = taskTimeout;
interrupts();
}
// Inserts a new task in the ordered lists of tasks.
void Scheduler::insertTask(Task *newTask) {
noInterrupts();
if (first == NULL) {
first = newTask;
} else {
if (first->scheduledUptimeMillis > newTask->scheduledUptimeMillis) {
// insert before first
newTask->next = first;
first = newTask;
} else {
Task *previousTask = first;
while (previousTask->next != NULL
&& previousTask->next->scheduledUptimeMillis <= newTask->scheduledUptimeMillis) {
previousTask = previousTask->next;
}
// insert after previousTask
newTask->next = previousTask->next;
previousTask->next = newTask;
}
}
interrupts();
}
// Inserts a new task in the ordered lists of tasks and remove all existing tasks with the same callback
void Scheduler::insertTaskAndRemoveExisting(Task *newTask) {
noInterrupts();
// remove first if it has the same callback as we insert
while (first != NULL && first->equalCallback(newTask)) {
deleteTask(first, NULL);
}
// here first is not equal to the one we insert
if (first == NULL) {
first = newTask;
} else {
if (first->scheduledUptimeMillis > newTask->scheduledUptimeMillis) {
// insert before first
newTask->next = first;
first = newTask;
} else {
Task *previousTask = first;
while (previousTask->next != NULL
&& previousTask->next->scheduledUptimeMillis <= newTask->scheduledUptimeMillis) {
if (previousTask->next->equalCallback(newTask)) {
deleteTask(previousTask->next, previousTask);
// previousTask->next was deleted so we keep previousTask
// and will check the next previousTask->next on next loop
} else {
previousTask = previousTask->next;
}
}
// insert after previousTask
newTask->next = previousTask->next;
previousTask->next = newTask;
}
// delete all existing tasks after the insert one
Task *previousTask = newTask;
while (previousTask->next != NULL) {
if (previousTask->next->equalCallback(newTask)) {
deleteTask(previousTask->next, previousTask);
} else {
previousTask = previousTask->next;
}
}
}
interrupts();
}
void Scheduler::deleteTask(Task *taskToDelete, Task *previousTask) {
if (previousTask == NULL) {
// remove the first task
first = taskToDelete->next;
} else {
previousTask->next = taskToDelete->next;
}
delete taskToDelete;
}
void Scheduler::setupTaskTimeoutIfConfigured() {
noInterrupts();
if (taskTimeout != NO_SUPERVISION) {
taskWdtEnable(taskTimeout);
#ifdef SUPERVISION_CALLBACK
wdtEnableInterrupt();
#endif
}
interrupts();
}
bool Scheduler::executeNextIfTime() {
noInterrupts();
if (first != NULL && first->scheduledUptimeMillis <= getMillis()) {
current = first;
first = current->next;
}
interrupts();
if (current != NULL) {
taskWdtReset();
current->execute();
taskWdtReset();
#ifdef SLEEP_DELAY
// use millis() instead of getMillis() because getMillis() may be manipulated by our WTD interrupt.
lastTaskFinishedMillis = millis();
#endif
delete current;
noInterrupts();
current = NULL;
interrupts();
return true;
} else {
return false;
}
}
void Scheduler::reactivateTaskTimeoutIfRequired() {
if (!isWakeupByOtherInterrupt()) {
// woken up due to WDT interrupt in case of AVR
// always executed for esp
noInterrupts();
const TaskTimeout taskTimeoutLocal = taskTimeout;
interrupts();
if (taskTimeoutLocal != NO_SUPERVISION) {
// change back to taskTimeout
taskWdtReset();
taskWdtEnable(taskTimeoutLocal);
#ifdef SUPERVISION_CALLBACK
wdtEnableInterrupt();
#endif
} else {
// tasks are not supervised, deactivate WDT
taskWdtDisable();
}
} // else the wd is still running in case of AVR
}
void Scheduler::execute() {
setupTaskTimeoutIfConfigured();
while (true) {
bool hasExecuted = executeNextIfTime();
while (hasExecuted) {
hasExecuted = executeNextIfTime();
}
sleepIfRequired();
reactivateTaskTimeoutIfRequired();
}
// never executed so no need to deactivate the WDT
}
#endif // #ifndef LIBCALL_DEEP_SLEEP_SCHEDULER
#if defined(ESP32) || defined(ESP8266)
#include "DeepSleepScheduler_esp_implementation.h"
#else
#include "DeepSleepScheduler_avr_implementation.h"
#endif
#endif // #ifndef DEEP_SLEEP_SCHEDULER_H