You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

EventResponder.h 9.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. /* EventResponder - Simple event-based programming for Arduino
  2. * Copyright 2017 Paul Stoffregen
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining
  5. * a copy of this software and associated documentation files (the
  6. * "Software"), to deal in the Software without restriction, including
  7. * without limitation the rights to use, copy, modify, merge, publish,
  8. * distribute, sublicense, and/or sell copies of the Software, and to
  9. * permit persons to whom the Software is furnished to do so, subject to
  10. * the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be
  13. * included in all copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  16. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  18. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  19. * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  20. * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  21. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. * SOFTWARE.
  23. */
  24. /* EventResponder is an experimental API, almost certain to
  25. * incompatibly change as it develops. Please understand any
  26. * programs you write now using EventResponder may need to be
  27. * updated as EventResponder develops.
  28. *
  29. * Please post your EventResponder feedback here:
  30. * https://forum.pjrc.com/threads/44723-Arduino-Events
  31. */
  32. #if !defined(EventResponder_h) && defined(__cplusplus)
  33. #define EventResponder_h
  34. #include <Arduino.h>
  35. /* EventResponder lets you control how your program responds to an event.
  36. * Imagine a basketball or football (American soccer) player who gets the
  37. * ball. Usually they will pass to another player who has the best
  38. * opportunity to score. Similarly in Arduino programming, events are
  39. * often triggered within interrupts or other timing sensitive code.
  40. * EventResponder can call your function a short time later, giving you
  41. * the ability to use Arduino functions and libraries which would not
  42. * be safe to use from an interrupt. However, some situations do call
  43. * for the most immediate response, even if doing so is more difficult.
  44. * EventResponder lets you choose how your function will be called,
  45. * without editing the timers or libraries which trigger the events.
  46. *
  47. * Event handling functions called by EventResponder should complete
  48. * their work quickly. Avoid delays or operations which may take
  49. * substantial time. While your function runs, no other event functions
  50. * (attached the same way) are able to run.
  51. *
  52. * If your EventResponder is triggered more than once before your
  53. * function can run, only the last trigger is used. Prior triggering,
  54. * including the status integer and data pointer, are overwritten and
  55. * your function is called only one time, based on the last trigger
  56. * event.
  57. */
  58. class EventResponder;
  59. typedef EventResponder& EventResponderRef;
  60. typedef void (*EventResponderFunction)(EventResponderRef);
  61. class EventResponder
  62. {
  63. public:
  64. constexpr EventResponder() {
  65. }
  66. ~EventResponder() {
  67. detach();
  68. }
  69. enum EventType { // these are not meant for public consumption...
  70. EventTypeDetached = 0, // no function is called
  71. EventTypeYield, // function is called from yield()
  72. EventTypeImmediate, // function is called immediately
  73. EventTypeInterrupt, // function is called from interrupt
  74. EventTypeThread // function is run as a new thread
  75. };
  76. // Attach a function to be called from yield(). This should be the
  77. // default way to use EventResponder. Calls from yield() allow use
  78. // of Arduino libraries, String, Serial, etc.
  79. void attach(EventResponderFunction function, uint8_t priority=128) {
  80. bool irq = disableInterrupts();
  81. detachNoInterrupts();
  82. _function = function;
  83. _type = EventTypeYield;
  84. enableInterrupts(irq);
  85. }
  86. // Attach a function to be called immediately. This provides the
  87. // fastest possible response, but your function must be carefully
  88. // designed.
  89. void attachImmediate(EventResponderFunction function) {
  90. bool irq = disableInterrupts();
  91. detachNoInterrupts();
  92. _function = function;
  93. _type = EventTypeImmediate;
  94. enableInterrupts(irq);
  95. }
  96. // Attach a function to be called from a low priority interrupt.
  97. // Boards not supporting software triggered interrupts will implement
  98. // this as attachImmediate. On ARM and other platforms with software
  99. // interrupts, this allow fast interrupt-based response, but with less
  100. // disruption to other libraries requiring their own interrupts.
  101. void attachInterrupt(EventResponderFunction function, uint8_t priority=128) {
  102. bool irq = disableInterrupts();
  103. detachNoInterrupts();
  104. _function = function;
  105. _type = EventTypeInterrupt;
  106. SCB_SHPR3 |= 0x00FF0000; // configure PendSV, lowest priority
  107. enableInterrupts(irq);
  108. }
  109. // Attach a function to be called as its own thread. Boards not running
  110. // a RTOS or pre-emptive scheduler shall implement this as attach().
  111. void attachThread(EventResponderFunction function, void *param=nullptr) {
  112. attach(function); // for non-RTOS usage, compile as default attach
  113. }
  114. // Do not call any function. The user's program must occasionally check
  115. // whether the event has occurred, or use one of the wait functions.
  116. void detach() {
  117. bool irq = disableInterrupts();
  118. detachNoInterrupts();
  119. enableInterrupts(irq);
  120. }
  121. // Trigger the event. An optional status code and data may be provided.
  122. // The code triggering the event does NOT control which of the above
  123. // response methods will be used.
  124. virtual void triggerEvent(int status=0, void *data=nullptr) {
  125. _status = status;
  126. _data = data;
  127. if (_type == EventTypeImmediate) {
  128. (*_function)(*this);
  129. } else {
  130. triggerEventNotImmediate();
  131. }
  132. }
  133. // Clear an event which has been triggered, but has not yet caused a
  134. // function to be called.
  135. bool clearEvent();
  136. // Get the event's status code. Typically this will indicate if the event was
  137. // triggered due to successful completion, or how much data was successfully
  138. // processed (positive numbers) or an error (negative numbers). The
  139. // exact meaning of this status code depends on the code or library which
  140. // triggers the event.
  141. int getStatus() { return _status; }
  142. // Get the optional data pointer associated with the event. Often this
  143. // will be NULL, or will be the object instance which triggered the event.
  144. // Some libraries may use this to pass data associated with the event.
  145. void * getData() { return _data; }
  146. // An optional "context" may be associated with each EventResponder.
  147. // When more than one EventResponder has the same function attached, these
  148. // may be used to allow the function to obtain extra information needed
  149. // depending on which EventResponder called it.
  150. void setContext(void *context) { _context = context; }
  151. void * getContext() { return _context; }
  152. // Wait for event(s) to occur. These are most likely to be useful when
  153. // used with a scheduler or RTOS.
  154. bool waitForEvent(EventResponderRef event, int timeout);
  155. EventResponder * waitForEvent(EventResponder *list, int listsize, int timeout);
  156. static void runFromYield() {
  157. // First, check if yield was called from an interrupt
  158. // never call normal handler functions from any interrupt context
  159. uint32_t ipsr;
  160. __asm__ volatile("mrs %0, ipsr\n" : "=r" (ipsr)::);
  161. if (ipsr != 0) return;
  162. // Next, check if any events have been triggered
  163. bool irq = disableInterrupts();
  164. EventResponder *first = firstYield;
  165. if (first == nullptr) {
  166. enableInterrupts(irq);
  167. return;
  168. }
  169. // Finally, make sure we're not being recursively called,
  170. // which can happen if the user's function does anything
  171. // that calls yield.
  172. if (runningFromYield) {
  173. enableInterrupts(irq);
  174. return;
  175. }
  176. // Ok, update the runningFromYield flag and process event
  177. runningFromYield = true;
  178. firstYield = first->_next;
  179. if (firstYield) {
  180. firstYield->_prev = nullptr;
  181. } else {
  182. lastYield = nullptr;
  183. }
  184. enableInterrupts(irq);
  185. first->_triggered = false;
  186. (*(first->_function))(*first);
  187. runningFromYield = false;
  188. }
  189. static void runFromInterrupt();
  190. operator bool() { return _triggered; }
  191. protected:
  192. void triggerEventNotImmediate();
  193. void detachNoInterrupts();
  194. int _status = 0;
  195. EventResponderFunction _function = nullptr;
  196. void *_data = nullptr;
  197. void *_context = nullptr;
  198. EventResponder *_next = nullptr;
  199. EventResponder *_prev = nullptr;
  200. EventType _type = EventTypeDetached;
  201. bool _triggered = false;
  202. static EventResponder *firstYield;
  203. static EventResponder *lastYield;
  204. static EventResponder *firstInterrupt;
  205. static EventResponder *lastInterrupt;
  206. static bool runningFromYield;
  207. private:
  208. static bool disableInterrupts() {
  209. uint32_t primask;
  210. __asm__ volatile("mrs %0, primask\n" : "=r" (primask)::);
  211. __disable_irq();
  212. return (primask == 0) ? true : false;
  213. }
  214. static void enableInterrupts(bool doit) {
  215. if (doit) __enable_irq();
  216. }
  217. };
  218. class MillisTimer
  219. {
  220. public:
  221. constexpr MillisTimer() {
  222. }
  223. ~MillisTimer() {
  224. end();
  225. }
  226. void begin(unsigned long milliseconds, EventResponderRef event);
  227. void beginRepeating(unsigned long milliseconds, EventResponderRef event);
  228. void end();
  229. static void runFromTimer();
  230. private:
  231. void addToWaitingList();
  232. void addToActiveList();
  233. unsigned long _ms = 0;
  234. unsigned long _reload = 0;
  235. MillisTimer *_next = nullptr;
  236. MillisTimer *_prev = nullptr;
  237. EventResponder *_event = nullptr;
  238. enum TimerStateType {
  239. TimerOff = 0,
  240. TimerWaiting,
  241. TimerActive
  242. };
  243. volatile TimerStateType _state = TimerOff;
  244. static MillisTimer *listWaiting; // single linked list of waiting to start timers
  245. static MillisTimer *listActive; // double linked list of running timers
  246. static bool disableTimerInterrupt() {
  247. uint32_t primask;
  248. __asm__ volatile("mrs %0, primask\n" : "=r" (primask)::);
  249. __disable_irq();
  250. return (primask == 0) ? true : false;
  251. }
  252. static void enableTimerInterrupt(bool doit) {
  253. if (doit) __enable_irq();
  254. }
  255. };
  256. #endif