TaskScheduler.h 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  1. // Cooperative multitasking library for Arduino
  2. // Copyright (c) 2015-2017 Anatoli Arkhipenko
  3. //
  4. // Changelog:
  5. // v1.0.0:
  6. // 2015-02-24 - Initial release
  7. // 2015-02-28 - added delay() and disableOnLastIteration() methods
  8. // 2015-03-25 - changed scheduler execute() method for a more precise delay calculation:
  9. // 1. Do not delay if any of the tasks ran (making request for immediate execution redundant)
  10. // 2. Delay is invoked only if none of the tasks ran
  11. // 3. Delay is based on the min anticipated wait until next task _AND_ the runtime of execute method itself.
  12. // 2015-05-11 - added restart() and restartDelayed() methods to restart tasks which are on hold after running all iterations
  13. // 2015-05-19 - completely removed delay from the scheduler since there are no power saving there. using 1 ms sleep instead
  14. //
  15. // v1.4.1:
  16. // 2015-09-15 - more careful placement of AVR-specific includes for sleep method (compatibility with DUE)
  17. // sleep on idle run is no longer a default and should be explicitly compiled with
  18. // _TASK_SLEEP_ON_IDLE_RUN defined
  19. //
  20. // v1.5.0:
  21. // 2015-09-20 - access to currently executing task (for callback methods)
  22. // 2015-09-20 - pass scheduler as a parameter to the task constructor to append the task to the end of the chain
  23. // 2015-09-20 - option to create a task already enabled
  24. //
  25. // v1.5.1:
  26. // 2015-09-21 - bug fix: incorrect handling of active tasks via set() and setIterations().
  27. // Thanks to Hannes Morgenstern for catching this one
  28. //
  29. // v1.6.0:
  30. // 2015-09-22 - revert back to having all tasks disable on last iteration.
  31. // 2015-09-22 - deprecated disableOnLastIteration method as a result
  32. // 2015-09-22 - created a separate branch 'disable-on-last-iteration' for this
  33. // 2015-10-01 - made version numbers semver compliant (documentation only)
  34. //
  35. // v1.7.0:
  36. // 2015-10-08 - introduced callback run counter - callback methods can branch on the iteration number.
  37. // 2015-10-11 - enableIfNot() - enable a task only if it is not already enabled. Returns true if was already enabled,
  38. // false if was disabled.
  39. // 2015-10-11 - disable() returns previous enable state (true if was enabled, false if was already disabled)
  40. // 2015-10-11 - introduced callback methods "on enable" and "on disable". On enable runs every time enable is called,
  41. // on disable runs only if task was enabled
  42. // 2015-10-12 - new Task method: forceNextIteration() - makes next iteration happen immediately during the next pass
  43. // regardless how much time is left
  44. //
  45. // v1.8.0:
  46. // 2015-10-13 - support for status request objects allowing tasks waiting on requests
  47. // 2015-10-13 - moved to a single header file to allow compilation control via #defines from the main sketch
  48. //
  49. // v1.8.1:
  50. // 2015-10-22 - implement Task id and control points to support identification of failure points for watchdog timer logging
  51. //
  52. // v1.8.2:
  53. // 2015-10-27 - implement Local Task Storage Pointer (allow use of same callback code for different tasks)
  54. // 2015-10-27 - bug: currentTask() method returns incorrect Task reference if called within OnEnable and OnDisable methods
  55. // 2015-10-27 - protection against infinite loop in OnEnable (if enable() methods are called within OnEnable)
  56. // 2015-10-29 - new currentLts() method in the scheduler class returns current task's LTS pointer in one call
  57. //
  58. // v1.8.3:
  59. // 2015-11-05 - support for task activation on a status request with arbitrary interval and number of iterations
  60. // (0 and 1 are still default values)
  61. // 2015-11-05 - implement waitForDelayed() method to allow task activation on the status request completion
  62. // delayed for one current interval
  63. // 2015-11-09 - added callback methods prototypes to all examples for Arduino IDE 1.6.6 compatibility
  64. // 2015-11-14 - added several constants to be used as task parameters for readability (e.g, TASK_FOREVER, TASK_SECOND, etc.)
  65. // 2015-11-14 - significant optimization of the scheduler's execute loop, including millis() rollover fix option
  66. //
  67. // v1.8.4:
  68. // 2015-11-15 - bug fix: Task alignment with millis() for scheduling purposes should be done after OnEnable, not before.
  69. // Especially since OnEnable method can change the interval
  70. // 2015-11-16 - further optimizations of the task scheduler execute loop
  71. //
  72. // v1.8.5:
  73. // 2015-11-23 - bug fix: incorrect calculation of next task invocation in case callback changed the interval
  74. // 2015-11-23 - bug fix: Task::set() method calls setInterval() explicitly, therefore delaying the task in the same manner
  75. //
  76. // v1.9.0:
  77. // 2015-11-24 - packed three byte-long status variables into bit array structure data type - saving 2 bytes per each task instance
  78. //
  79. // v1.9.2:
  80. // 2015-11-28 - _TASK_ROLLOVER_FIX is deprecated (not necessary)
  81. // 2015-12-16 - bug fixes: automatic millis rollover support for delay methods
  82. // 2015-12-17 - new method for _TASK_TIMECRITICAL option: getStartDelay()
  83. //
  84. // v2.0.0:
  85. // 2015-12-22 - _TASK_PRIORITY - support for layered task prioritization
  86. //
  87. // v2.0.1:
  88. // 2016-01-02 - bug fix: issue#11 Xtensa compiler (esp8266): Declaration of constructor does not match implementation
  89. //
  90. // v2.0.2:
  91. // 2016-01-05 - bug fix: time constants wrapped inside compile option
  92. // 2016-01-05 - support for ESP8266 wifi power saving mode for _TASK_SLEEP_ON_IDLE_RUN compile option
  93. //
  94. // v2.1.0:
  95. // 2016-02-01 - support for microsecond resolution
  96. // 2016-02-02 - added Scheduler baseline start time reset method: startNow()
  97. //
  98. // v2.2.0:
  99. // 2016-11-17 - all methods made 'inline' to support inclusion of TaskSchedule.h file into other header files
  100. //
  101. // v2.2.1:
  102. // 2016-11-30 - inlined constructors. Added "yield()" and "yieldOnce()" functions to easily break down and chain
  103. // back together long running callback methods
  104. // 2016-12-16 - added "getCount()" to StatusRequest objects, made every task StatusRequest enabled.
  105. // Internal StatusRequest objects are accessible via "getInternalStatusRequest()" method.
  106. //
  107. // v2.3.0:
  108. // 2017-02-24 - new timeUntilNextIteration() method within Scheduler class - inquire when a particlar task is
  109. // scheduled to run next time
  110. //
  111. // v2.4.0:
  112. // 2017-04-27 - added destructor to the Task class to ensure tasks are disables and taken off the execution chain
  113. // upon destruction. (Contributed by Edwin van Leeuwen [BlackEdder - https://github.com/BlackEdder)
  114. //
  115. // v2.5.0:
  116. // 2017-04-27 - ESP8266 ONLY: added optional support for std::functions via _TASK_STD_FUNCTION compilation option
  117. // (Contributed by Edwin van Leeuwen [BlackEdder - https://github.com/BlackEdder)
  118. // 2017-08-30 - add _TASK_DEBUG making all methods and variables public FOR DEBUGGING PURPOSES ONLY!
  119. // Use at your own risk!
  120. // 2017-08-30 - bug fix: Scheduler::addTask() checks if task is already part of an execution chain (github issue #37)
  121. // 2017-08-30 - support for multi-tab sketches (Contributed by Adam Ryczkowski - https://github.com/adamryczkowski)
  122. //
  123. // v2.5.1:
  124. // 2018-01-06 - support for IDLE sleep on Teensy boards (tested on Teensy 3.5)
  125. //
  126. // v2.5.2:
  127. // 2018-01-09 - _TASK_INLINE compilation directive making all methods declared "inline" (issue #42)
  128. //
  129. // v2.6.0:
  130. // 2018-01-30 - _TASK_TIMEOUT compilation directive: Task overall timeout functionality
  131. // 2018-01-30 - ESP32 support (experimental)
  132. // (Contributed by Marco Tombesi: https://github.com/baggior)
  133. #include <Arduino.h>
  134. #include "TaskSchedulerDeclarations.h"
  135. #ifndef _TASKSCHEDULER_H_
  136. #define _TASKSCHEDULER_H_
  137. // ----------------------------------------
  138. // The following "defines" control library functionality at compile time,
  139. // and should be used in the main sketch depending on the functionality required
  140. //
  141. // #define _TASK_TIMECRITICAL // Enable monitoring scheduling overruns
  142. // #define _TASK_SLEEP_ON_IDLE_RUN // Enable 1 ms SLEEP_IDLE powerdowns between tasks if no callback methods were invoked during the pass
  143. // #define _TASK_STATUS_REQUEST // Compile with support for StatusRequest functionality - triggering tasks on status change events in addition to time only
  144. // #define _TASK_WDT_IDS // Compile with support for wdt control points and task ids
  145. // #define _TASK_LTS_POINTER // Compile with support for local task storage pointer
  146. // #define _TASK_PRIORITY // Support for layered scheduling priority
  147. // #define _TASK_MICRO_RES // Support for microsecond resolution
  148. // #define _TASK_STD_FUNCTION // Support for std::function (ESP8266 ONLY)
  149. // #define _TASK_DEBUG // Make all methods and variables public for debug purposes
  150. // #define _TASK_INLINE // Make all methods "inline" - needed to support some multi-tab, multi-file implementations
  151. // #define _TASK_TIMEOUT // Support for overall task timeout
  152. #ifdef _TASK_MICRO_RES
  153. #undef _TASK_SLEEP_ON_IDLE_RUN // SLEEP_ON_IDLE has only millisecond resolution
  154. #define _TASK_TIME_FUNCTION() micros()
  155. #else
  156. #define _TASK_TIME_FUNCTION() millis()
  157. #endif // _TASK_MICRO_RES
  158. #ifdef _TASK_SLEEP_ON_IDLE_RUN
  159. #ifdef ARDUINO_ARCH_AVR
  160. #include <avr/sleep.h>
  161. #include <avr/power.h>
  162. #endif // ARDUINO_ARCH_AVR
  163. #ifdef ARDUINO_ARCH_ESP8266
  164. extern "C" {
  165. #include "user_interface.h"
  166. }
  167. #define _TASK_ESP8266_DLY_THRESHOLD 200L
  168. #endif // ARDUINO_ARCH_ESP8266
  169. #ifdef ARDUINO_ARCH_ESP32
  170. //#warning _TASK_SLEEP_ON_IDLE_RUN is not tested for ESP32.. going in light sleep for 1 ms
  171. #endif // ARDUINO_ARCH_ESP8266 ESP32
  172. #endif // _TASK_SLEEP_ON_IDLE_RUN
  173. #if !defined (ARDUINO_ARCH_ESP8266) && !defined (ARDUINO_ARCH_ESP32)
  174. #ifdef _TASK_STD_FUNCTION
  175. #error Support for std::function only for ESP8266 architecture
  176. #undef _TASK_STD_FUNCTION
  177. #endif // _TASK_STD_FUNCTION
  178. #endif // ARDUINO_ARCH_ESP8266
  179. #ifdef _TASK_WDT_IDS
  180. static unsigned int __task_id_counter = 0; // global task ID counter for assiging task IDs automatically.
  181. #endif // _TASK_WDT_IDS
  182. #ifdef _TASK_PRIORITY
  183. Scheduler* iCurrentScheduler;
  184. #endif // _TASK_PRIORITY
  185. // ------------------ TaskScheduler implementation --------------------
  186. /** Constructor, uses default values for the parameters
  187. * so could be called with no parameters.
  188. */
  189. Task::Task( unsigned long aInterval, long aIterations, TaskCallback aCallback, Scheduler* aScheduler, bool aEnable, TaskOnEnable aOnEnable, TaskOnDisable aOnDisable ) {
  190. reset();
  191. set(aInterval, aIterations, aCallback, aOnEnable, aOnDisable);
  192. if (aScheduler) aScheduler->addTask(*this);
  193. #ifdef _TASK_WDT_IDS
  194. iTaskID = ++__task_id_counter;
  195. #endif // _TASK_WDT_IDS
  196. if (aEnable) enable();
  197. }
  198. /** Destructor.
  199. * Makes sure the task disabled and deleted out of the chain
  200. * prior to being deleted.
  201. */
  202. Task::~Task() {
  203. disable();
  204. if (iScheduler)
  205. iScheduler->deleteTask(*this);
  206. }
  207. #ifdef _TASK_STATUS_REQUEST
  208. /** Constructor with reduced parameter list for tasks created for
  209. * StatusRequest only triggering (always immediate and only 1 iteration)
  210. */
  211. Task::Task( TaskCallback aCallback, Scheduler* aScheduler, TaskOnEnable aOnEnable, TaskOnDisable aOnDisable ) {
  212. reset();
  213. set(TASK_IMMEDIATE, TASK_ONCE, aCallback, aOnEnable, aOnDisable);
  214. if (aScheduler) aScheduler->addTask(*this);
  215. #ifdef _TASK_WDT_IDS
  216. iTaskID = ++__task_id_counter;
  217. #endif // _TASK_WDT_IDS
  218. }
  219. StatusRequest::StatusRequest()
  220. {
  221. iCount = 0;
  222. iStatus = 0;
  223. }
  224. void StatusRequest::setWaiting(unsigned int aCount) { iCount = aCount; iStatus = 0; }
  225. bool StatusRequest::pending() { return (iCount != 0); }
  226. bool StatusRequest::completed() { return (iCount == 0); }
  227. int StatusRequest::getStatus() { return iStatus; }
  228. int StatusRequest::getCount() { return iCount; }
  229. StatusRequest* Task::getStatusRequest() { return iStatusRequest; }
  230. StatusRequest* Task::getInternalStatusRequest() { return &iMyStatusRequest; }
  231. /** Signals completion of the StatusRequest by one of the participating events
  232. * @param: aStatus - if provided, sets the return code of the StatusRequest: negative = error, 0 (default) = OK, positive = OK with a specific status code
  233. * Negative status will complete Status Request fully (since an error occured).
  234. * @return: true, if StatusRequest is complete, false otherwise (still waiting for other events)
  235. */
  236. bool StatusRequest::signal(int aStatus) {
  237. if ( iCount) { // do not update the status request if it was already completed
  238. if (iCount > 0) --iCount;
  239. if ( (iStatus = aStatus) < 0 ) iCount = 0; // if an error is reported, the status is requested to be completed immediately
  240. }
  241. return (iCount == 0);
  242. }
  243. void StatusRequest::signalComplete(int aStatus) {
  244. if (iCount) { // do not update the status request if it was already completed
  245. iCount = 0;
  246. iStatus = aStatus;
  247. }
  248. }
  249. /** Sets a Task to wait until a particular event completes
  250. * @param: aStatusRequest - a pointer for the StatusRequest to wait for.
  251. * If aStatusRequest is NULL, request for waiting is ignored, and the waiting task is not enabled.
  252. */
  253. void Task::waitFor(StatusRequest* aStatusRequest, unsigned long aInterval, long aIterations) {
  254. if ( ( iStatusRequest = aStatusRequest) ) { // assign internal StatusRequest var and check if it is not NULL
  255. setIterations(aIterations);
  256. setInterval(aInterval);
  257. iStatus.waiting = _TASK_SR_NODELAY; // no delay
  258. enable();
  259. }
  260. }
  261. void Task::waitForDelayed(StatusRequest* aStatusRequest, unsigned long aInterval, long aIterations) {
  262. if ( ( iStatusRequest = aStatusRequest) ) { // assign internal StatusRequest var and check if it is not NULL
  263. setIterations(aIterations);
  264. if ( aInterval ) setInterval(aInterval); // For the dealyed version only set the interval if it was not a zero
  265. iStatus.waiting = _TASK_SR_DELAY; // with delay equal to the current interval
  266. enable();
  267. }
  268. }
  269. #endif // _TASK_STATUS_REQUEST
  270. bool Task::isEnabled() { return iStatus.enabled; }
  271. unsigned long Task::getInterval() { return iInterval; }
  272. long Task::getIterations() { return iIterations; }
  273. unsigned long Task::getRunCounter() { return iRunCounter; }
  274. void Task::setCallback(TaskCallback aCallback) { iCallback = aCallback; }
  275. void Task::setOnEnable(TaskOnEnable aCallback) { iOnEnable = aCallback; }
  276. void Task::setOnDisable(TaskOnDisable aCallback) { iOnDisable = aCallback; }
  277. /** Resets (initializes) the task/
  278. * Task is not enabled and is taken out
  279. * out of the execution chain as a result
  280. */
  281. void Task::reset() {
  282. iStatus.enabled = false;
  283. iStatus.inonenable = false;
  284. iPreviousMillis = 0;
  285. iInterval = iDelay = 0;
  286. iPrev = NULL;
  287. iNext = NULL;
  288. iScheduler = NULL;
  289. iRunCounter = 0;
  290. #ifdef _TASK_TIMECRITICAL
  291. iOverrun = 0;
  292. iStartDelay = 0;
  293. #endif // _TASK_TIMECRITICAL
  294. #ifdef _TASK_WDT_IDS
  295. iControlPoint = 0;
  296. #endif // _TASK_WDT_IDS
  297. #ifdef _TASK_LTS_POINTER
  298. iLTS = NULL;
  299. #endif // _TASK_LTS_POINTER
  300. #ifdef _TASK_STATUS_REQUEST
  301. iStatusRequest = NULL;
  302. iStatus.waiting = 0;
  303. iMyStatusRequest.signalComplete();
  304. #endif // _TASK_STATUS_REQUEST
  305. #ifdef _TASK_TIMEOUT
  306. iTimeout = 0;
  307. iStarttime = 0;
  308. iStatus.timeout = false;
  309. #endif // _TASK_TIMEOUT
  310. }
  311. /** Explicitly set Task execution parameters
  312. * @param aInterval - execution interval in ms
  313. * @param aIterations - number of iterations, use -1 for no limit
  314. * @param aCallback - pointer to the callback method which executes the task actions
  315. * @param aOnEnable - pointer to the callback method which is called on enable()
  316. * @param aOnDisable - pointer to the callback method which is called on disable()
  317. */
  318. void Task::set(unsigned long aInterval, long aIterations, TaskCallback aCallback, TaskOnEnable aOnEnable, TaskOnDisable aOnDisable) {
  319. setInterval(aInterval);
  320. iSetIterations = iIterations = aIterations;
  321. iCallback = aCallback;
  322. iOnEnable = aOnEnable;
  323. iOnDisable = aOnDisable;
  324. }
  325. /** Sets number of iterations for the task
  326. * if task is enabled, schedule for immediate execution
  327. * @param aIterations - number of iterations, use -1 for no limit
  328. */
  329. void Task::setIterations(long aIterations) {
  330. iSetIterations = iIterations = aIterations;
  331. }
  332. /** Prepare task for next step iteration following yielding of control to the scheduler
  333. * @param aCallback - pointer to the callback method for the next step
  334. */
  335. void Task::yield (TaskCallback aCallback) {
  336. iCallback = aCallback;
  337. forceNextIteration();
  338. // The next 2 lines adjust runcounter and number of iterations
  339. // as if it is the same run of the callback, just split between
  340. // a series of callback methods
  341. iRunCounter--;
  342. if ( iIterations >= 0 ) iIterations++;
  343. }
  344. /** Prepare task for next step iteration following yielding of control to the scheduler
  345. * @param aCallback - pointer to the callback method for the next step
  346. */
  347. void Task::yieldOnce (TaskCallback aCallback) {
  348. yield(aCallback);
  349. iIterations = 1;
  350. }
  351. /** Enables the task
  352. * schedules it for execution as soon as possible,
  353. * and resets the RunCounter back to zero
  354. */
  355. void Task::enable() {
  356. if (iScheduler) { // activation without active scheduler does not make sense
  357. iRunCounter = 0;
  358. if ( iOnEnable && !iStatus.inonenable ) {
  359. Task *current = iScheduler->iCurrent;
  360. iScheduler->iCurrent = this;
  361. iStatus.inonenable = true; // Protection against potential infinite loop
  362. iStatus.enabled = iOnEnable();
  363. iStatus.inonenable = false; // Protection against potential infinite loop
  364. iScheduler->iCurrent = current;
  365. }
  366. else {
  367. iStatus.enabled = true;
  368. }
  369. iPreviousMillis = _TASK_TIME_FUNCTION() - (iDelay = iInterval);
  370. #ifdef _TASK_TIMEOUT
  371. resetTimeout();
  372. #endif // _TASK_TIMEOUT
  373. #ifdef _TASK_STATUS_REQUEST
  374. if ( iStatus.enabled ) {
  375. iMyStatusRequest.setWaiting();
  376. }
  377. #endif // _TASK_STATUS_REQUEST
  378. }
  379. }
  380. /** Enables the task only if it was not enabled already
  381. * Returns previous state (true if was already enabled, false if was not)
  382. */
  383. bool Task::enableIfNot() {
  384. bool previousEnabled = iStatus.enabled;
  385. if ( !previousEnabled ) enable();
  386. return (previousEnabled);
  387. }
  388. /** Enables the task
  389. * and schedules it for execution after a delay = aInterval
  390. */
  391. void Task::enableDelayed(unsigned long aDelay) {
  392. enable();
  393. delay(aDelay);
  394. }
  395. #ifdef _TASK_TIMEOUT
  396. void Task::setTimeout(unsigned long aTimeout, bool aReset) {
  397. iTimeout = aTimeout;
  398. if (aReset) resetTimeout();
  399. }
  400. void Task::resetTimeout() {
  401. iStarttime = _TASK_TIME_FUNCTION();
  402. iStatus.timeout = false;
  403. }
  404. unsigned long Task::getTimeout() {
  405. return iTimeout;
  406. }
  407. long Task::untilTimeout() {
  408. if ( iTimeout ) {
  409. return ( (long) (iStarttime + iTimeout) - (long) _TASK_TIME_FUNCTION() );
  410. }
  411. return -1;
  412. }
  413. bool Task::timedOut() {
  414. return iStatus.timeout;
  415. }
  416. #endif // _TASK_TIMEOUT
  417. /** Delays Task for execution after a delay = aInterval (if task is enabled).
  418. * leaves task enabled or disabled
  419. * if aDelay is zero, delays for the original scheduling interval from now
  420. */
  421. void Task::delay(unsigned long aDelay) {
  422. // if (!aDelay) aDelay = iInterval;
  423. iDelay = aDelay ? aDelay : iInterval;
  424. iPreviousMillis = _TASK_TIME_FUNCTION(); // - iInterval + aDelay;
  425. }
  426. /** Schedules next iteration of Task for execution immediately (if enabled)
  427. * leaves task enabled or disabled
  428. * Task's original schedule is shifted, and all subsequent iterations will continue from this point in time
  429. */
  430. void Task::forceNextIteration() {
  431. iPreviousMillis = _TASK_TIME_FUNCTION() - (iDelay = iInterval);
  432. }
  433. /** Sets the execution interval.
  434. * Task execution is delayed for aInterval
  435. * Use enable() to schedule execution ASAP
  436. * @param aInterval - new execution interval
  437. */
  438. void Task::setInterval (unsigned long aInterval) {
  439. iInterval = aInterval;
  440. delay(); // iDelay will be updated by the delay() function
  441. }
  442. /** Disables task
  443. * Task will no longer be executed by the scheduler
  444. * Returns status of the task before disable was called (i.e., if the task was already disabled)
  445. */
  446. bool Task::disable() {
  447. bool previousEnabled = iStatus.enabled;
  448. iStatus.enabled = false;
  449. iStatus.inonenable = false;
  450. if (previousEnabled && iOnDisable) {
  451. Task *current = iScheduler->iCurrent;
  452. iScheduler->iCurrent = this;
  453. iOnDisable();
  454. iScheduler->iCurrent = current;
  455. }
  456. #ifdef _TASK_STATUS_REQUEST
  457. iMyStatusRequest.signalComplete();
  458. #endif
  459. return (previousEnabled);
  460. }
  461. /** Restarts task
  462. * Task will run number of iterations again
  463. */
  464. void Task::restart() {
  465. enable();
  466. iIterations = iSetIterations;
  467. }
  468. /** Restarts task delayed
  469. * Task will run number of iterations again
  470. */
  471. void Task::restartDelayed(unsigned long aDelay) {
  472. enableDelayed(aDelay);
  473. iIterations = iSetIterations;
  474. }
  475. bool Task::isFirstIteration() { return (iRunCounter <= 1); }
  476. bool Task::isLastIteration() { return (iIterations == 0); }
  477. #ifdef _TASK_TIMECRITICAL
  478. long Task::getOverrun() { return iOverrun; }
  479. long Task::getStartDelay() { return iStartDelay; }
  480. #endif // _TASK_TIMECRITICAL
  481. #ifdef _TASK_WDT_IDS
  482. void Task::setId(unsigned int aID) { iTaskID = aID; }
  483. unsigned int Task::getId() { return iTaskID; }
  484. void Task::setControlPoint(unsigned int aPoint) { iControlPoint = aPoint; }
  485. unsigned int Task::getControlPoint() { return iControlPoint; }
  486. #endif // _TASK_WDT_IDS
  487. #ifdef _TASK_LTS_POINTER
  488. void Task::setLtsPointer(void *aPtr) { iLTS = aPtr; }
  489. void* Task::getLtsPointer() { return iLTS; }
  490. #endif // _TASK_LTS_POINTER
  491. // ------------------ Scheduler implementation --------------------
  492. /** Default constructor.
  493. * Creates a scheduler with an empty execution chain.
  494. */
  495. Scheduler::Scheduler() {
  496. init();
  497. }
  498. /*
  499. Scheduler::~Scheduler() {
  500. #ifdef _TASK_SLEEP_ON_IDLE_RUN
  501. #endif // _TASK_SLEEP_ON_IDLE_RUN
  502. }
  503. */
  504. /** Initializes all internal varaibles
  505. */
  506. void Scheduler::init() {
  507. iFirst = NULL;
  508. iLast = NULL;
  509. iCurrent = NULL;
  510. #ifdef _TASK_PRIORITY
  511. iHighPriority = NULL;
  512. #endif // _TASK_PRIORITY
  513. #ifdef _TASK_SLEEP_ON_IDLE_RUN
  514. allowSleep(true);
  515. #endif // _TASK_SLEEP_ON_IDLE_RUN
  516. }
  517. /** Appends task aTask to the tail of the execution chain.
  518. * @param &aTask - reference to the Task to be appended.
  519. * @note Task can only be part of the chain once.
  520. */
  521. void Scheduler::addTask(Task& aTask) {
  522. // Avoid adding task twice to the same scheduler
  523. if (aTask.iScheduler == this)
  524. return;
  525. aTask.iScheduler = this;
  526. // First task situation:
  527. if (iFirst == NULL) {
  528. iFirst = &aTask;
  529. aTask.iPrev = NULL;
  530. }
  531. else {
  532. // This task gets linked back to the previous last one
  533. aTask.iPrev = iLast;
  534. iLast->iNext = &aTask;
  535. }
  536. // "Previous" last task gets linked to this one - as this one becomes the last one
  537. aTask.iNext = NULL;
  538. iLast = &aTask;
  539. }
  540. /** Deletes specific Task from the execution chain
  541. * @param &aTask - reference to the task to be deleted from the chain
  542. */
  543. void Scheduler::deleteTask(Task& aTask) {
  544. if (aTask.iPrev == NULL) {
  545. if (aTask.iNext == NULL) {
  546. iFirst = NULL;
  547. iLast = NULL;
  548. return;
  549. }
  550. else {
  551. aTask.iNext->iPrev = NULL;
  552. iFirst = aTask.iNext;
  553. aTask.iNext = NULL;
  554. return;
  555. }
  556. }
  557. if (aTask.iNext == NULL) {
  558. aTask.iPrev->iNext = NULL;
  559. iLast = aTask.iPrev;
  560. aTask.iPrev = NULL;
  561. return;
  562. }
  563. aTask.iPrev->iNext = aTask.iNext;
  564. aTask.iNext->iPrev = aTask.iPrev;
  565. aTask.iPrev = NULL;
  566. aTask.iNext = NULL;
  567. }
  568. /** Disables all tasks in the execution chain
  569. * Convenient for error situations, when the only
  570. * task remaining active is an error processing task
  571. * @param aRecursive - if true, tasks of the higher priority chains are disabled as well recursively
  572. */
  573. void Scheduler::disableAll(bool aRecursive) {
  574. Task *current = iFirst;
  575. while (current) {
  576. current->disable();
  577. current = current->iNext;
  578. }
  579. #ifdef _TASK_PRIORITY
  580. if (aRecursive && iHighPriority) iHighPriority->disableAll(true);
  581. #endif // _TASK_PRIORITY
  582. }
  583. /** Enables all the tasks in the execution chain
  584. * @param aRecursive - if true, tasks of the higher priority chains are enabled as well recursively
  585. */
  586. void Scheduler::enableAll(bool aRecursive) {
  587. Task *current = iFirst;
  588. while (current) {
  589. current->enable();
  590. current = current->iNext;
  591. }
  592. #ifdef _TASK_PRIORITY
  593. if (aRecursive && iHighPriority) iHighPriority->enableAll(true);
  594. #endif // _TASK_PRIORITY
  595. }
  596. /** Sets scheduler for the higher priority tasks (support for layered task priority)
  597. * @param aScheduler - pointer to a scheduler for the higher priority tasks
  598. */
  599. #ifdef _TASK_PRIORITY
  600. void Scheduler::setHighPriorityScheduler(Scheduler* aScheduler) {
  601. if (aScheduler != this) iHighPriority = aScheduler; // Setting yourself as a higher priority one will create infinite recursive call
  602. #ifdef _TASK_SLEEP_ON_IDLE_RUN
  603. if (iHighPriority) {
  604. iHighPriority->allowSleep(false); // Higher priority schedulers should not do power management
  605. }
  606. #endif // _TASK_SLEEP_ON_IDLE_RUN
  607. };
  608. #endif // _TASK_PRIORITY
  609. #ifdef _TASK_SLEEP_ON_IDLE_RUN
  610. void Scheduler::allowSleep(bool aState) {
  611. iAllowSleep = aState;
  612. #ifdef ARDUINO_ARCH_ESP8266
  613. wifi_set_sleep_type( iAllowSleep ? LIGHT_SLEEP_T : NONE_SLEEP_T );
  614. #endif // ARDUINO_ARCH_ESP8266
  615. #ifdef ARDUINO_ARCH_ESP32
  616. // TO-DO; find a suitable replacement for ESP32 if possible.
  617. #endif // ARDUINO_ARCH_ESP32
  618. }
  619. #endif // _TASK_SLEEP_ON_IDLE_RUN
  620. void Scheduler::startNow( bool aRecursive ) {
  621. unsigned long t = _TASK_TIME_FUNCTION();
  622. iCurrent = iFirst;
  623. while (iCurrent) {
  624. if ( iCurrent->iStatus.enabled ) iCurrent->iPreviousMillis = t - iCurrent->iDelay;
  625. iCurrent = iCurrent->iNext;
  626. }
  627. #ifdef _TASK_PRIORITY
  628. if (aRecursive && iHighPriority) iHighPriority->startNow( true );
  629. #endif // _TASK_PRIORITY
  630. }
  631. /** Returns number millis or micros until next scheduled iteration of a given task
  632. *
  633. * @param aTask - reference to task which next iteration is in question
  634. */
  635. long Scheduler::timeUntilNextIteration(Task& aTask) {
  636. #ifdef _TASK_STATUS_REQUEST
  637. StatusRequest *s = aTask.getStatusRequest();
  638. if ( s != NULL && s->pending() )
  639. return (-1); // cannot be determined
  640. #endif
  641. if ( !aTask.isEnabled() )
  642. return (-1); // cannot be determined
  643. long d = (long) aTask.iDelay - ( (long) ((_TASK_TIME_FUNCTION() - aTask.iPreviousMillis)) );
  644. if ( d < 0 )
  645. return (0); // Task will run as soon as possible
  646. return ( d );
  647. }
  648. Task& Scheduler::currentTask() { return *iCurrent; }
  649. #ifdef _TASK_LTS_POINTER
  650. void* Scheduler::currentLts() { return iCurrent->iLTS; }
  651. #endif // _TASK_LTS_POINTER
  652. #ifdef _TASK_TIMECRITICAL
  653. bool Scheduler::isOverrun() { return (iCurrent->iOverrun < 0); }
  654. #endif // _TASK_TIMECRITICAL
  655. /** Makes one pass through the execution chain.
  656. * Tasks are executed in the order they were added to the chain
  657. * There is no concept of priority
  658. * Different pseudo "priority" could be achieved
  659. * by running task more frequently
  660. */
  661. bool Scheduler::execute() {
  662. bool idleRun = true;
  663. register unsigned long m, i; // millis, interval;
  664. #if defined (ARDUINO_ARCH_ESP8266) || defined (ARDUINO_ARCH_ESP32)
  665. unsigned long t1 = micros();
  666. unsigned long t2 = 0;
  667. #endif // ARDUINO_ARCH_ESP8266
  668. iCurrent = iFirst;
  669. while (iCurrent) {
  670. #ifdef _TASK_PRIORITY
  671. // If scheduler for higher priority tasks is set, it's entire chain is executed on every pass of the base scheduler
  672. if (iHighPriority) idleRun = iHighPriority->execute() && idleRun;
  673. iCurrentScheduler = this;
  674. #endif // _TASK_PRIORITY
  675. do {
  676. if ( iCurrent->iStatus.enabled ) {
  677. #ifdef _TASK_WDT_IDS
  678. // For each task the control points are initialized to avoid confusion because of carry-over:
  679. iCurrent->iControlPoint = 0;
  680. #endif // _TASK_WDT_IDS
  681. // Disable task on last iteration:
  682. if (iCurrent->iIterations == 0) {
  683. iCurrent->disable();
  684. break;
  685. }
  686. m = _TASK_TIME_FUNCTION();
  687. i = iCurrent->iInterval;
  688. #ifdef _TASK_TIMEOUT
  689. // Disable task on a timeout
  690. if ( iCurrent->iTimeout && (m - iCurrent->iStarttime > iCurrent->iTimeout) ) {
  691. iCurrent->iStatus.timeout = true;
  692. iCurrent->disable();
  693. break;
  694. }
  695. #endif
  696. #ifdef _TASK_STATUS_REQUEST
  697. // If StatusRequest object was provided, and still pending, and task is waiting, this task should not run
  698. // Otherwise, continue with execution as usual. Tasks waiting to StatusRequest need to be rescheduled according to
  699. // how they were placed into waiting state (waitFor or waitForDelayed)
  700. if ( iCurrent->iStatus.waiting ) {
  701. if ( (iCurrent->iStatusRequest)->pending() ) break;
  702. if (iCurrent->iStatus.waiting == _TASK_SR_NODELAY) {
  703. iCurrent->iPreviousMillis = m - (iCurrent->iDelay = i);
  704. }
  705. else {
  706. iCurrent->iPreviousMillis = m;
  707. }
  708. iCurrent->iStatus.waiting = 0;
  709. }
  710. #endif // _TASK_STATUS_REQUEST
  711. if ( m - iCurrent->iPreviousMillis < iCurrent->iDelay ) break;
  712. if ( iCurrent->iIterations > 0 ) iCurrent->iIterations--; // do not decrement (-1) being a signal of never-ending task
  713. iCurrent->iRunCounter++;
  714. iCurrent->iPreviousMillis += iCurrent->iDelay;
  715. #ifdef _TASK_TIMECRITICAL
  716. // Updated_previous+current interval should put us into the future, so iOverrun should be positive or zero.
  717. // If negative - the task is behind (next execution time is already in the past)
  718. unsigned long p = iCurrent->iPreviousMillis;
  719. iCurrent->iOverrun = (long) ( p + i - m );
  720. iCurrent->iStartDelay = (long) ( m - p );
  721. #endif // _TASK_TIMECRITICAL
  722. iCurrent->iDelay = i;
  723. if ( iCurrent->iCallback ) {
  724. iCurrent->iCallback();
  725. idleRun = false;
  726. }
  727. }
  728. } while (0); //guaranteed single run - allows use of "break" to exit
  729. iCurrent = iCurrent->iNext;
  730. #if defined (ARDUINO_ARCH_ESP8266) || defined (ARDUINO_ARCH_ESP32)
  731. yield();
  732. #endif // ARDUINO_ARCH_ESP8266
  733. }
  734. #ifdef _TASK_SLEEP_ON_IDLE_RUN
  735. if (idleRun && iAllowSleep) {
  736. #ifdef ARDUINO_ARCH_AVR // Could be used only for AVR-based boards.
  737. set_sleep_mode(SLEEP_MODE_IDLE);
  738. sleep_enable();
  739. /* Now enter sleep mode. */
  740. sleep_mode();
  741. /* The program will continue from here after the timer timeout ~1 ms */
  742. sleep_disable(); /* First thing to do is disable sleep. */
  743. #endif // ARDUINO_ARCH_AVR
  744. #ifdef CORE_TEENSY
  745. asm("wfi");
  746. #endif //CORE_TEENSY
  747. #ifdef ARDUINO_ARCH_ESP8266
  748. // to do: find suitable sleep function for esp8266
  749. t2 = micros() - t1;
  750. if (t2 < _TASK_ESP8266_DLY_THRESHOLD) delay(1); // ESP8266 implementation of delay() uses timers and yield
  751. #endif // ARDUINO_ARCH_ESP8266
  752. #ifdef ARDUINO_ARCH_ESP32
  753. //TODO Test this light sleep implementation for ESP32
  754. esp_sleep_enable_timer_wakeup(1000); //1 ms
  755. int ret= esp_light_sleep_start();
  756. #endif // ARDUINO_ARCH_ESP32
  757. }
  758. #endif // _TASK_SLEEP_ON_IDLE_RUN
  759. return (idleRun);
  760. }
  761. #endif /* _TASKSCHEDULER_H_ */