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.

257 lines
9.2KB

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