TaskScheduler.h 33 KB

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