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.

279 line
10KB

  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. extern "C" void systick_isr_with_timer_events(void);
  59. class EventResponder;
  60. typedef EventResponder& EventResponderRef;
  61. typedef void (*EventResponderFunction)(EventResponderRef);
  62. class EventResponder
  63. {
  64. public:
  65. constexpr EventResponder() {
  66. }
  67. ~EventResponder() {
  68. detach();
  69. }
  70. enum EventType { // these are not meant for public consumption...
  71. EventTypeDetached = 0, // no function is called
  72. EventTypeYield, // function is called from yield()
  73. EventTypeImmediate, // function is called immediately
  74. EventTypeInterrupt, // function is called from interrupt
  75. EventTypeThread // function is run as a new thread
  76. };
  77. // Attach a function to be called from yield(). This should be the
  78. // default way to use EventResponder. Calls from yield() allow use
  79. // of Arduino libraries, String, Serial, etc.
  80. void attach(EventResponderFunction function, uint8_t priority=128) {
  81. bool irq = disableInterrupts();
  82. detachNoInterrupts();
  83. _function = function;
  84. _type = EventTypeYield;
  85. yield_active_check_flags |= YIELD_CHECK_EVENT_RESPONDER; // user setup a yield type...
  86. enableInterrupts(irq);
  87. }
  88. // Attach a function to be called immediately. This provides the
  89. // fastest possible response, but your function must be carefully
  90. // designed.
  91. void attachImmediate(EventResponderFunction function) {
  92. bool irq = disableInterrupts();
  93. detachNoInterrupts();
  94. _function = function;
  95. _type = EventTypeImmediate;
  96. enableInterrupts(irq);
  97. }
  98. // Attach a function to be called from a low priority interrupt.
  99. // Boards not supporting software triggered interrupts will implement
  100. // this as attachImmediate. On ARM and other platforms with software
  101. // interrupts, this allow fast interrupt-based response, but with less
  102. // disruption to other libraries requiring their own interrupts.
  103. void attachInterrupt(EventResponderFunction function, uint8_t priority=128) {
  104. bool irq = disableInterrupts();
  105. detachNoInterrupts();
  106. _function = function;
  107. _type = EventTypeInterrupt;
  108. SCB_SHPR3 |= 0x00FF0000; // configure PendSV, lowest priority
  109. // Make sure we are using the systic ISR that process this
  110. _VectorsRam[15] = systick_isr_with_timer_events;
  111. enableInterrupts(irq);
  112. }
  113. // Attach a function to be called as its own thread. Boards not running
  114. // a RTOS or pre-emptive scheduler shall implement this as attach().
  115. void attachThread(EventResponderFunction function, void *param=nullptr) {
  116. attach(function); // for non-RTOS usage, compile as default attach
  117. }
  118. // Do not call any function. The user's program must occasionally check
  119. // whether the event has occurred, or use one of the wait functions.
  120. void detach() {
  121. bool irq = disableInterrupts();
  122. detachNoInterrupts();
  123. enableInterrupts(irq);
  124. }
  125. // Trigger the event. An optional status code and data may be provided.
  126. // The code triggering the event does NOT control which of the above
  127. // response methods will be used.
  128. virtual void triggerEvent(int status=0, void *data=nullptr) {
  129. _status = status;
  130. _data = data;
  131. if (_type == EventTypeImmediate) {
  132. (*_function)(*this);
  133. } else {
  134. triggerEventNotImmediate();
  135. }
  136. }
  137. // Clear an event which has been triggered, but has not yet caused a
  138. // function to be called.
  139. bool clearEvent();
  140. // Get the event's status code. Typically this will indicate if the event was
  141. // triggered due to successful completion, or how much data was successfully
  142. // processed (positive numbers) or an error (negative numbers). The
  143. // exact meaning of this status code depends on the code or library which
  144. // triggers the event.
  145. int getStatus() { return _status; }
  146. // Get the optional data pointer associated with the event. Often this
  147. // will be NULL, or will be the object instance which triggered the event.
  148. // Some libraries may use this to pass data associated with the event.
  149. void * getData() { return _data; }
  150. // An optional "context" may be associated with each EventResponder.
  151. // When more than one EventResponder has the same function attached, these
  152. // may be used to allow the function to obtain extra information needed
  153. // depending on which EventResponder called it.
  154. void setContext(void *context) { _context = context; }
  155. void * getContext() { return _context; }
  156. // Wait for event(s) to occur. These are most likely to be useful when
  157. // used with a scheduler or RTOS.
  158. bool waitForEvent(EventResponderRef event, int timeout);
  159. EventResponder * waitForEvent(EventResponder *list, int listsize, int timeout);
  160. static void runFromYield() {
  161. if (!firstYield) return;
  162. // First, check if yield was called from an interrupt
  163. // never call normal handler functions from any interrupt context
  164. uint32_t ipsr;
  165. __asm__ volatile("mrs %0, ipsr\n" : "=r" (ipsr)::);
  166. if (ipsr != 0) return;
  167. // Next, check if any events have been triggered
  168. bool irq = disableInterrupts();
  169. EventResponder *first = firstYield;
  170. if (first == nullptr) {
  171. enableInterrupts(irq);
  172. return;
  173. }
  174. // Finally, make sure we're not being recursively called,
  175. // which can happen if the user's function does anything
  176. // that calls yield.
  177. if (runningFromYield) {
  178. enableInterrupts(irq);
  179. return;
  180. }
  181. // Ok, update the runningFromYield flag and process event
  182. runningFromYield = true;
  183. firstYield = first->_next;
  184. if (firstYield) {
  185. firstYield->_prev = nullptr;
  186. } else {
  187. lastYield = nullptr;
  188. }
  189. enableInterrupts(irq);
  190. first->_triggered = false;
  191. (*(first->_function))(*first);
  192. runningFromYield = false;
  193. }
  194. static void runFromInterrupt();
  195. operator bool() { return _triggered; }
  196. protected:
  197. void triggerEventNotImmediate();
  198. void detachNoInterrupts();
  199. int _status = 0;
  200. EventResponderFunction _function = nullptr;
  201. void *_data = nullptr;
  202. void *_context = nullptr;
  203. EventResponder *_next = nullptr;
  204. EventResponder *_prev = nullptr;
  205. EventType _type = EventTypeDetached;
  206. bool _triggered = false;
  207. static EventResponder *firstYield;
  208. static EventResponder *lastYield;
  209. static EventResponder *firstInterrupt;
  210. static EventResponder *lastInterrupt;
  211. static bool runningFromYield;
  212. private:
  213. static bool disableInterrupts() {
  214. uint32_t primask;
  215. __asm__ volatile("mrs %0, primask\n" : "=r" (primask)::);
  216. __disable_irq();
  217. return (primask == 0) ? true : false;
  218. }
  219. static void enableInterrupts(bool doit) {
  220. if (doit) __enable_irq();
  221. }
  222. };
  223. class MillisTimer
  224. {
  225. public:
  226. constexpr MillisTimer() {
  227. }
  228. ~MillisTimer() {
  229. end();
  230. }
  231. void begin(unsigned long milliseconds, EventResponderRef event);
  232. void beginRepeating(unsigned long milliseconds, EventResponderRef event);
  233. void end();
  234. static void runFromTimer();
  235. private:
  236. void addToWaitingList();
  237. void addToActiveList();
  238. unsigned long _ms = 0;
  239. unsigned long _reload = 0;
  240. MillisTimer *_next = nullptr;
  241. MillisTimer *_prev = nullptr;
  242. EventResponder *_event = nullptr;
  243. enum TimerStateType {
  244. TimerOff = 0,
  245. TimerWaiting,
  246. TimerActive
  247. };
  248. volatile TimerStateType _state = TimerOff;
  249. static MillisTimer *listWaiting; // single linked list of waiting to start timers
  250. static MillisTimer *listActive; // double linked list of running timers
  251. static bool disableTimerInterrupt() {
  252. uint32_t primask;
  253. __asm__ volatile("mrs %0, primask\n" : "=r" (primask)::);
  254. __disable_irq();
  255. return (primask == 0) ? true : false;
  256. }
  257. static void enableTimerInterrupt(bool doit) {
  258. if (doit) __enable_irq();
  259. }
  260. };
  261. #endif