TaskScheduler.h 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  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. #include <Arduino.h>
  123. #include "TaskSchedulerDeclarations.h"
  124. #ifndef _TASKSCHEDULER_H_
  125. #define _TASKSCHEDULER_H_
  126. // ----------------------------------------
  127. // The following "defines" control library functionality at compile time,
  128. // and should be used in the main sketch depending on the functionality required
  129. //
  130. // #define _TASK_TIMECRITICAL // Enable monitoring scheduling overruns
  131. // #define _TASK_SLEEP_ON_IDLE_RUN // Enable 1 ms SLEEP_IDLE powerdowns between tasks if no callback methods were invoked during the pass
  132. // #define _TASK_STATUS_REQUEST // Compile with support for StatusRequest functionality - triggering tasks on status change events in addition to time only
  133. // #define _TASK_WDT_IDS // Compile with support for wdt control points and task ids
  134. // #define _TASK_LTS_POINTER // Compile with support for local task storage pointer
  135. // #define _TASK_PRIORITY // Support for layered scheduling priority
  136. // #define _TASK_MICRO_RES // Support for microsecond resolution
  137. // #define _TASK_STD_FUNCTION // Support for std::function (ESP8266 ONLY)
  138. // #define _TASK_DEBUG // Make all methods and variables public for debug purposes
  139. #ifdef _TASK_MICRO_RES
  140. #undef _TASK_SLEEP_ON_IDLE_RUN // SLEEP_ON_IDLE has only millisecond resolution
  141. #define _TASK_TIME_FUNCTION() micros()
  142. #else
  143. #define _TASK_TIME_FUNCTION() millis()
  144. #endif // _TASK_MICRO_RES
  145. #ifdef _TASK_SLEEP_ON_IDLE_RUN
  146. #ifdef ARDUINO_ARCH_AVR
  147. #include <avr/sleep.h>
  148. #include <avr/power.h>
  149. #endif // ARDUINO_ARCH_AVR
  150. #ifdef ARDUINO_ARCH_ESP8266
  151. extern "C" {
  152. #include "user_interface.h"
  153. }
  154. #define _TASK_ESP8266_DLY_THRESHOLD 200L
  155. #endif // ARDUINO_ARCH_ESP8266
  156. #ifdef CORE_TEENSY
  157. #include <Snooze.h>
  158. #endif
  159. #endif // _TASK_SLEEP_ON_IDLE_RUN
  160. #ifndef ARDUINO_ARCH_ESP8266
  161. #ifdef _TASK_STD_FUNCTION
  162. #error Support for std::function only for ESP8266 architecture
  163. #undef _TASK_STD_FUNCTION
  164. #endif // _TASK_STD_FUNCTION
  165. #endif // ARDUINO_ARCH_ESP8266
  166. #ifdef _TASK_WDT_IDS
  167. static unsigned int __task_id_counter = 0; // global task ID counter for assiging task IDs automatically.
  168. #endif // _TASK_WDT_IDS
  169. #ifdef _TASK_PRIORITY
  170. Scheduler* iCurrentScheduler;
  171. #endif // _TASK_PRIORITY
  172. // ------------------ TaskScheduler implementation --------------------
  173. /** Constructor, uses default values for the parameters
  174. * so could be called with no parameters.
  175. */
  176. Task::Task( unsigned long aInterval, long aIterations, TaskCallback aCallback, Scheduler* aScheduler, bool aEnable, TaskOnEnable aOnEnable, TaskOnDisable aOnDisable ) {
  177. reset();
  178. set(aInterval, aIterations, aCallback, aOnEnable, aOnDisable);
  179. if (aScheduler) aScheduler->addTask(*this);
  180. #ifdef _TASK_STATUS_REQUEST
  181. iStatusRequest = NULL;
  182. #endif // _TASK_STATUS_REQUEST
  183. #ifdef _TASK_WDT_IDS
  184. iTaskID = ++__task_id_counter;
  185. #endif // _TASK_WDT_IDS
  186. if (aEnable) enable();
  187. }
  188. /** Destructor.
  189. * Makes sure the task disabled and deleted out of the chain
  190. * prior to being deleted.
  191. */
  192. Task::~Task() {
  193. disable();
  194. if (iScheduler)
  195. iScheduler->deleteTask(*this);
  196. }
  197. #ifdef _TASK_STATUS_REQUEST
  198. /** Constructor with reduced parameter list for tasks created for
  199. * StatusRequest only triggering (always immediate and only 1 iteration)
  200. */
  201. Task::Task( TaskCallback aCallback, Scheduler* aScheduler, TaskOnEnable aOnEnable, TaskOnDisable aOnDisable ) {
  202. reset();
  203. set(TASK_IMMEDIATE, TASK_ONCE, aCallback, aOnEnable, aOnDisable);
  204. if (aScheduler) aScheduler->addTask(*this);
  205. iStatusRequest = NULL;
  206. #ifdef _TASK_WDT_IDS
  207. iTaskID = ++__task_id_counter;
  208. #endif // _TASK_WDT_IDS
  209. }
  210. StatusRequest::StatusRequest()
  211. {
  212. iCount = 0;
  213. iStatus = 0;
  214. }
  215. void StatusRequest::setWaiting(unsigned int aCount) { iCount = aCount; iStatus = 0; }
  216. bool StatusRequest::pending() { return (iCount != 0); }
  217. bool StatusRequest::completed() { return (iCount == 0); }
  218. int StatusRequest::getStatus() { return iStatus; }
  219. int StatusRequest::getCount() { return iCount; }
  220. StatusRequest* Task::getStatusRequest() { return iStatusRequest; }
  221. StatusRequest* Task::getInternalStatusRequest() { return &iMyStatusRequest; }
  222. /** Signals completion of the StatusRequest by one of the participating events
  223. * @param: aStatus - if provided, sets the return code of the StatusRequest: negative = error, 0 (default) = OK, positive = OK with a specific status code
  224. * Negative status will complete Status Request fully (since an error occured).
  225. * @return: true, if StatusRequest is complete, false otherwise (still waiting for other events)
  226. */
  227. bool StatusRequest::signal(int aStatus) {
  228. if ( iCount) { // do not update the status request if it was already completed
  229. if (iCount > 0) --iCount;
  230. if ( (iStatus = aStatus) < 0 ) iCount = 0; // if an error is reported, the status is requested to be completed immediately
  231. }
  232. return (iCount == 0);
  233. }
  234. void StatusRequest::signalComplete(int aStatus) {
  235. if (iCount) { // do not update the status request if it was already completed
  236. iCount = 0;
  237. iStatus = aStatus;
  238. }
  239. }
  240. /** Sets a Task to wait until a particular event completes
  241. * @param: aStatusRequest - a pointer for the StatusRequest to wait for.
  242. * If aStatusRequest is NULL, request for waiting is ignored, and the waiting task is not enabled.
  243. */
  244. void Task::waitFor(StatusRequest* aStatusRequest, unsigned long aInterval, long aIterations) {
  245. if ( ( iStatusRequest = aStatusRequest) ) { // assign internal StatusRequest var and check if it is not NULL
  246. setIterations(aIterations);
  247. setInterval(aInterval);
  248. iStatus.waiting = _TASK_SR_NODELAY; // no delay
  249. enable();
  250. }
  251. }
  252. void Task::waitForDelayed(StatusRequest* aStatusRequest, unsigned long aInterval, long aIterations) {
  253. if ( ( iStatusRequest = aStatusRequest) ) { // assign internal StatusRequest var and check if it is not NULL
  254. setIterations(aIterations);
  255. if ( aInterval ) setInterval(aInterval); // For the dealyed version only set the interval if it was not a zero
  256. iStatus.waiting = _TASK_SR_DELAY; // with delay equal to the current interval
  257. enable();
  258. }
  259. }
  260. #endif // _TASK_STATUS_REQUEST
  261. bool Task::isEnabled() { return iStatus.enabled; }
  262. unsigned long Task::getInterval() { return iInterval; }
  263. long Task::getIterations() { return iIterations; }
  264. unsigned long Task::getRunCounter() { return iRunCounter; }
  265. void Task::setCallback(TaskCallback aCallback) { iCallback = aCallback; }
  266. void Task::setOnEnable(TaskOnEnable aCallback) { iOnEnable = aCallback; }
  267. void Task::setOnDisable(TaskOnDisable aCallback) { iOnDisable = aCallback; }
  268. /** Resets (initializes) the task/
  269. * Task is not enabled and is taken out
  270. * out of the execution chain as a result
  271. */
  272. void Task::reset() {
  273. iStatus.enabled = false;
  274. iStatus.inonenable = false;
  275. iPreviousMillis = 0;
  276. iInterval = iDelay = 0;
  277. iPrev = NULL;
  278. iNext = NULL;
  279. iScheduler = NULL;
  280. iRunCounter = 0;
  281. #ifdef _TASK_TIMECRITICAL
  282. iOverrun = 0;
  283. iStartDelay = 0;
  284. #endif // _TASK_TIMECRITICAL
  285. #ifdef _TASK_WDT_IDS
  286. iControlPoint = 0;
  287. #endif // _TASK_WDT_IDS
  288. #ifdef _TASK_LTS_POINTER
  289. iLTS = NULL;
  290. #endif // _TASK_LTS_POINTER
  291. #ifdef _TASK_STATUS_REQUEST
  292. iStatus.waiting = 0;
  293. iMyStatusRequest.signalComplete();
  294. #endif // _TASK_STATUS_REQUEST
  295. }
  296. /** Explicitly set Task execution parameters
  297. * @param aInterval - execution interval in ms
  298. * @param aIterations - number of iterations, use -1 for no limit
  299. * @param aCallback - pointer to the callback method which executes the task actions
  300. * @param aOnEnable - pointer to the callback method which is called on enable()
  301. * @param aOnDisable - pointer to the callback method which is called on disable()
  302. */
  303. void Task::set(unsigned long aInterval, long aIterations, TaskCallback aCallback, TaskOnEnable aOnEnable, TaskOnDisable aOnDisable) {
  304. setInterval(aInterval);
  305. iSetIterations = iIterations = aIterations;
  306. iCallback = aCallback;
  307. iOnEnable = aOnEnable;
  308. iOnDisable = aOnDisable;
  309. }
  310. /** Sets number of iterations for the task
  311. * if task is enabled, schedule for immediate execution
  312. * @param aIterations - number of iterations, use -1 for no limit
  313. */
  314. void Task::setIterations(long aIterations) {
  315. iSetIterations = iIterations = aIterations;
  316. }
  317. /** Prepare task for next step iteration following yielding of control to the scheduler
  318. * @param aCallback - pointer to the callback method for the next step
  319. */
  320. void Task::yield (TaskCallback aCallback) {
  321. iCallback = aCallback;
  322. forceNextIteration();
  323. // The next 2 lines adjust runcounter and number of iterations
  324. // as if it is the same run of the callback, just split between
  325. // a series of callback methods
  326. iRunCounter--;
  327. if ( iIterations >= 0 ) iIterations++;
  328. }
  329. /** Prepare task for next step iteration following yielding of control to the scheduler
  330. * @param aCallback - pointer to the callback method for the next step
  331. */
  332. void Task::yieldOnce (TaskCallback aCallback) {
  333. yield(aCallback);
  334. iIterations = 1;
  335. }
  336. /** Enables the task
  337. * schedules it for execution as soon as possible,
  338. * and resets the RunCounter back to zero
  339. */
  340. void Task::enable() {
  341. if (iScheduler) { // activation without active scheduler does not make sense
  342. iRunCounter = 0;
  343. if ( iOnEnable && !iStatus.inonenable ) {
  344. Task *current = iScheduler->iCurrent;
  345. iScheduler->iCurrent = this;
  346. iStatus.inonenable = true; // Protection against potential infinite loop
  347. iStatus.enabled = iOnEnable();
  348. iStatus.inonenable = false; // Protection against potential infinite loop
  349. iScheduler->iCurrent = current;
  350. }
  351. else {
  352. iStatus.enabled = true;
  353. }
  354. iPreviousMillis = _TASK_TIME_FUNCTION() - (iDelay = iInterval);
  355. #ifdef _TASK_STATUS_REQUEST
  356. if ( iStatus.enabled ) {
  357. iMyStatusRequest.setWaiting();
  358. }
  359. #endif
  360. }
  361. }
  362. /** Enables the task only if it was not enabled already
  363. * Returns previous state (true if was already enabled, false if was not)
  364. */
  365. bool Task::enableIfNot() {
  366. bool previousEnabled = iStatus.enabled;
  367. if ( !previousEnabled ) enable();
  368. return (previousEnabled);
  369. }
  370. /** Enables the task
  371. * and schedules it for execution after a delay = aInterval
  372. */
  373. void Task::enableDelayed(unsigned long aDelay) {
  374. enable();
  375. delay(aDelay);
  376. }
  377. /** Delays Task for execution after a delay = aInterval (if task is enabled).
  378. * leaves task enabled or disabled
  379. * if aDelay is zero, delays for the original scheduling interval from now
  380. */
  381. void Task::delay(unsigned long aDelay) {
  382. // if (!aDelay) aDelay = iInterval;
  383. iDelay = aDelay ? aDelay : iInterval;
  384. iPreviousMillis = _TASK_TIME_FUNCTION(); // - iInterval + aDelay;
  385. }
  386. /** Schedules next iteration of Task for execution immediately (if enabled)
  387. * leaves task enabled or disabled
  388. * Task's original schedule is shifted, and all subsequent iterations will continue from this point in time
  389. */
  390. void Task::forceNextIteration() {
  391. iPreviousMillis = _TASK_TIME_FUNCTION() - (iDelay = iInterval);
  392. }
  393. /** Sets the execution interval.
  394. * Task execution is delayed for aInterval
  395. * Use enable() to schedule execution ASAP
  396. * @param aInterval - new execution interval
  397. */
  398. void Task::setInterval (unsigned long aInterval) {
  399. iInterval = aInterval;
  400. delay(); // iDelay will be updated by the delay() function
  401. }
  402. /** Disables task
  403. * Task will no longer be executed by the scheduler
  404. * Returns status of the task before disable was called (i.e., if the task was already disabled)
  405. */
  406. bool Task::disable() {
  407. bool previousEnabled = iStatus.enabled;
  408. iStatus.enabled = false;
  409. iStatus.inonenable = false;
  410. if (previousEnabled && iOnDisable) {
  411. Task *current = iScheduler->iCurrent;
  412. iScheduler->iCurrent = this;
  413. iOnDisable();
  414. iScheduler->iCurrent = current;
  415. }
  416. #ifdef _TASK_STATUS_REQUEST
  417. iMyStatusRequest.signalComplete();
  418. #endif
  419. return (previousEnabled);
  420. }
  421. /** Restarts task
  422. * Task will run number of iterations again
  423. */
  424. void Task::restart() {
  425. iIterations = iSetIterations;
  426. enable();
  427. }
  428. /** Restarts task delayed
  429. * Task will run number of iterations again
  430. */
  431. void Task::restartDelayed(unsigned long aDelay) {
  432. iIterations = iSetIterations;
  433. enableDelayed(aDelay);
  434. }
  435. bool Task::isFirstIteration() { return (iRunCounter <= 1); }
  436. bool Task::isLastIteration() { return (iIterations == 0); }
  437. #ifdef _TASK_TIMECRITICAL
  438. long Task::getOverrun() { return iOverrun; }
  439. long Task::getStartDelay() { return iStartDelay; }
  440. #endif // _TASK_TIMECRITICAL
  441. #ifdef _TASK_WDT_IDS
  442. void Task::setId(unsigned int aID) { iTaskID = aID; }
  443. unsigned int Task::getId() { return iTaskID; }
  444. void Task::setControlPoint(unsigned int aPoint) { iControlPoint = aPoint; }
  445. unsigned int Task::getControlPoint() { return iControlPoint; }
  446. #endif // _TASK_WDT_IDS
  447. #ifdef _TASK_LTS_POINTER
  448. void Task::setLtsPointer(void *aPtr) { iLTS = aPtr; }
  449. void* Task::getLtsPointer() { return iLTS; }
  450. #endif // _TASK_LTS_POINTER
  451. // ------------------ Scheduler implementation --------------------
  452. /** Default constructor.
  453. * Creates a scheduler with an empty execution chain.
  454. */
  455. Scheduler::Scheduler() {
  456. init();
  457. }
  458. Scheduler::~Scheduler() {
  459. #ifdef _TASK_SLEEP_ON_IDLE_RUN
  460. #ifdef CORE_TEENSY
  461. delete config;
  462. delete timer;
  463. #endif //CORE_TEENSY
  464. #endif // _TASK_SLEEP_ON_IDLE_RUN
  465. }
  466. /** Initializes all internal varaibles
  467. */
  468. void Scheduler::init() {
  469. iFirst = NULL;
  470. iLast = NULL;
  471. iCurrent = NULL;
  472. #ifdef _TASK_PRIORITY
  473. iHighPriority = NULL;
  474. #endif // _TASK_PRIORITY
  475. #ifdef _TASK_SLEEP_ON_IDLE_RUN
  476. allowSleep(true);
  477. #ifdef CORE_TEENSY
  478. timer = new SnoozeTimer;
  479. config = new SnoozeBlock(*timer);
  480. timer->setTimer(1);
  481. #endif //CORE_TEENSY
  482. #endif // _TASK_SLEEP_ON_IDLE_RUN
  483. }
  484. /** Appends task aTask to the tail of the execution chain.
  485. * @param &aTask - reference to the Task to be appended.
  486. * @note Task can only be part of the chain once.
  487. */
  488. void Scheduler::addTask(Task& aTask) {
  489. // Avoid adding task twice to the same scheduler
  490. if (aTask.iScheduler == this)
  491. return;
  492. aTask.iScheduler = this;
  493. // First task situation:
  494. if (iFirst == NULL) {
  495. iFirst = &aTask;
  496. aTask.iPrev = NULL;
  497. }
  498. else {
  499. // This task gets linked back to the previous last one
  500. aTask.iPrev = iLast;
  501. iLast->iNext = &aTask;
  502. }
  503. // "Previous" last task gets linked to this one - as this one becomes the last one
  504. aTask.iNext = NULL;
  505. iLast = &aTask;
  506. }
  507. /** Deletes specific Task from the execution chain
  508. * @param &aTask - reference to the task to be deleted from the chain
  509. */
  510. void Scheduler::deleteTask(Task& aTask) {
  511. if (aTask.iPrev == NULL) {
  512. if (aTask.iNext == NULL) {
  513. iFirst = NULL;
  514. iLast = NULL;
  515. return;
  516. }
  517. else {
  518. aTask.iNext->iPrev = NULL;
  519. iFirst = aTask.iNext;
  520. aTask.iNext = NULL;
  521. return;
  522. }
  523. }
  524. if (aTask.iNext == NULL) {
  525. aTask.iPrev->iNext = NULL;
  526. iLast = aTask.iPrev;
  527. aTask.iPrev = NULL;
  528. return;
  529. }
  530. aTask.iPrev->iNext = aTask.iNext;
  531. aTask.iNext->iPrev = aTask.iPrev;
  532. aTask.iPrev = NULL;
  533. aTask.iNext = NULL;
  534. }
  535. /** Disables all tasks in the execution chain
  536. * Convenient for error situations, when the only
  537. * task remaining active is an error processing task
  538. * @param aRecursive - if true, tasks of the higher priority chains are disabled as well recursively
  539. */
  540. void Scheduler::disableAll(bool aRecursive) {
  541. Task *current = iFirst;
  542. while (current) {
  543. current->disable();
  544. current = current->iNext;
  545. }
  546. #ifdef _TASK_PRIORITY
  547. if (aRecursive && iHighPriority) iHighPriority->disableAll(true);
  548. #endif // _TASK_PRIORITY
  549. }
  550. /** Enables all the tasks in the execution chain
  551. * @param aRecursive - if true, tasks of the higher priority chains are enabled as well recursively
  552. */
  553. void Scheduler::enableAll(bool aRecursive) {
  554. Task *current = iFirst;
  555. while (current) {
  556. current->enable();
  557. current = current->iNext;
  558. }
  559. #ifdef _TASK_PRIORITY
  560. if (aRecursive && iHighPriority) iHighPriority->enableAll(true);
  561. #endif // _TASK_PRIORITY
  562. }
  563. /** Sets scheduler for the higher priority tasks (support for layered task priority)
  564. * @param aScheduler - pointer to a scheduler for the higher priority tasks
  565. */
  566. #ifdef _TASK_PRIORITY
  567. void Scheduler::setHighPriorityScheduler(Scheduler* aScheduler) {
  568. if (aScheduler != this) iHighPriority = aScheduler; // Setting yourself as a higher priority one will create infinite recursive call
  569. #ifdef _TASK_SLEEP_ON_IDLE_RUN
  570. if (iHighPriority) {
  571. iHighPriority->allowSleep(false); // Higher priority schedulers should not do power management
  572. }
  573. #endif // _TASK_SLEEP_ON_IDLE_RUN
  574. };
  575. #endif // _TASK_PRIORITY
  576. #ifdef _TASK_SLEEP_ON_IDLE_RUN
  577. void Scheduler::allowSleep(bool aState) {
  578. iAllowSleep = aState;
  579. #ifdef ARDUINO_ARCH_ESP8266
  580. wifi_set_sleep_type( iAllowSleep ? LIGHT_SLEEP_T : NONE_SLEEP_T );
  581. #endif // ARDUINO_ARCH_ESP8266
  582. }
  583. #endif // _TASK_SLEEP_ON_IDLE_RUN
  584. void Scheduler::startNow( bool aRecursive ) {
  585. unsigned long t = _TASK_TIME_FUNCTION();
  586. iCurrent = iFirst;
  587. while (iCurrent) {
  588. if ( iCurrent->iStatus.enabled ) iCurrent->iPreviousMillis = t - iCurrent->iDelay;
  589. iCurrent = iCurrent->iNext;
  590. }
  591. #ifdef _TASK_PRIORITY
  592. if (aRecursive && iHighPriority) iHighPriority->startNow( true );
  593. #endif // _TASK_PRIORITY
  594. }
  595. /** Returns number millis or micros until next scheduled iteration of a given task
  596. *
  597. * @param aTask - reference to task which next iteration is in question
  598. */
  599. long Scheduler::timeUntilNextIteration(Task& aTask) {
  600. #ifdef _TASK_STATUS_REQUEST
  601. StatusRequest *s = aTask.getStatusRequest();
  602. if ( s != NULL && s->pending() )
  603. return (-1); // cannot be determined
  604. #endif
  605. if ( !aTask.isEnabled() )
  606. return (-1); // cannot be determined
  607. long d = (long) aTask.iDelay - ( (long) ((_TASK_TIME_FUNCTION() - aTask.iPreviousMillis)) );
  608. if ( d < 0 )
  609. return (0); // Task will run as soon as possible
  610. return ( d );
  611. }
  612. Task& Scheduler::currentTask() { return *iCurrent; }
  613. #ifdef _TASK_LTS_POINTER
  614. void* Scheduler::currentLts() { return iCurrent->iLTS; }
  615. #endif // _TASK_LTS_POINTER
  616. #ifdef _TASK_TIMECRITICAL
  617. bool Scheduler::isOverrun() { return (iCurrent->iOverrun < 0); }
  618. #endif // _TASK_TIMECRITICAL
  619. /** Makes one pass through the execution chain.
  620. * Tasks are executed in the order they were added to the chain
  621. * There is no concept of priority
  622. * Different pseudo "priority" could be achieved
  623. * by running task more frequently
  624. */
  625. bool Scheduler::execute() {
  626. bool idleRun = true;
  627. register unsigned long m, i; // millis, interval;
  628. #ifdef ARDUINO_ARCH_ESP8266
  629. unsigned long t1 = micros();
  630. unsigned long t2 = 0;
  631. #endif // ARDUINO_ARCH_ESP8266
  632. iCurrent = iFirst;
  633. while (iCurrent) {
  634. #ifdef _TASK_PRIORITY
  635. // If scheduler for higher priority tasks is set, it's entire chain is executed on every pass of the base scheduler
  636. if (iHighPriority) idleRun = iHighPriority->execute() && idleRun;
  637. iCurrentScheduler = this;
  638. #endif // _TASK_PRIORITY
  639. do {
  640. if ( iCurrent->iStatus.enabled ) {
  641. #ifdef _TASK_WDT_IDS
  642. // For each task the control points are initialized to avoid confusion because of carry-over:
  643. iCurrent->iControlPoint = 0;
  644. #endif // _TASK_WDT_IDS
  645. // Disable task on last iteration:
  646. if (iCurrent->iIterations == 0) {
  647. iCurrent->disable();
  648. break;
  649. }
  650. m = _TASK_TIME_FUNCTION();
  651. i = iCurrent->iInterval;
  652. #ifdef _TASK_STATUS_REQUEST
  653. // If StatusRequest object was provided, and still pending, and task is waiting, this task should not run
  654. // Otherwise, continue with execution as usual. Tasks waiting to StatusRequest need to be rescheduled according to
  655. // how they were placed into waiting state (waitFor or waitForDelayed)
  656. if ( iCurrent->iStatus.waiting ) {
  657. if ( (iCurrent->iStatusRequest)->pending() ) break;
  658. if (iCurrent->iStatus.waiting == _TASK_SR_NODELAY) {
  659. iCurrent->iPreviousMillis = m - (iCurrent->iDelay = i);
  660. }
  661. else {
  662. iCurrent->iPreviousMillis = m;
  663. }
  664. iCurrent->iStatus.waiting = 0;
  665. }
  666. #endif // _TASK_STATUS_REQUEST
  667. if ( m - iCurrent->iPreviousMillis < iCurrent->iDelay ) break;
  668. if ( iCurrent->iIterations > 0 ) iCurrent->iIterations--; // do not decrement (-1) being a signal of never-ending task
  669. iCurrent->iRunCounter++;
  670. iCurrent->iPreviousMillis += iCurrent->iDelay;
  671. #ifdef _TASK_TIMECRITICAL
  672. // Updated_previous+current interval should put us into the future, so iOverrun should be positive or zero.
  673. // If negative - the task is behind (next execution time is already in the past)
  674. unsigned long p = iCurrent->iPreviousMillis;
  675. iCurrent->iOverrun = (long) ( p + i - m );
  676. iCurrent->iStartDelay = (long) ( m - p );
  677. #endif // _TASK_TIMECRITICAL
  678. iCurrent->iDelay = i;
  679. if ( iCurrent->iCallback ) {
  680. iCurrent->iCallback();
  681. idleRun = false;
  682. }
  683. }
  684. } while (0); //guaranteed single run - allows use of "break" to exit
  685. iCurrent = iCurrent->iNext;
  686. #ifdef ARDUINO_ARCH_ESP8266
  687. yield();
  688. #endif // ARDUINO_ARCH_ESP8266
  689. }
  690. #ifdef _TASK_SLEEP_ON_IDLE_RUN
  691. if (idleRun && iAllowSleep) {
  692. #ifdef ARDUINO_ARCH_AVR // Could be used only for AVR-based boards.
  693. set_sleep_mode(SLEEP_MODE_IDLE);
  694. sleep_enable();
  695. /* Now enter sleep mode. */
  696. sleep_mode();
  697. /* The program will continue from here after the timer timeout ~1 ms */
  698. sleep_disable(); /* First thing to do is disable sleep. */
  699. #endif // ARDUINO_ARCH_AVR
  700. #ifdef CORE_TEENSY
  701. Snooze.sleep(*config);
  702. #endif //CORE_TEENSY
  703. #ifdef ARDUINO_ARCH_ESP8266
  704. // to do: find suitable sleep function for esp8266
  705. t2 = micros() - t1;
  706. if (t2 < _TASK_ESP8266_DLY_THRESHOLD) delay(1); // ESP8266 implementation of delay() uses timers and yield
  707. #endif // ARDUINO_ARCH_ESP8266
  708. #ifdef ARDUINO_ARCH_ESP32
  709. #endif // ARDUINO_ARCH_ESP32
  710. }
  711. #endif // _TASK_SLEEP_ON_IDLE_RUN
  712. return (idleRun);
  713. }
  714. #endif /* _TASKSCHEDULER_H_ */