Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

276 lines
9.8KB

  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. if (!firstYield) return;
  158. // First, check if yield was called from an interrupt
  159. // never call normal handler functions from any interrupt context
  160. uint32_t ipsr;
  161. __asm__ volatile("mrs %0, ipsr\n" : "=r" (ipsr)::);
  162. if (ipsr != 0) return;
  163. // Next, check if any events have been triggered
  164. bool irq = disableInterrupts();
  165. EventResponder *first = firstYield;
  166. if (first == nullptr) {
  167. enableInterrupts(irq);
  168. return;
  169. }
  170. // Finally, make sure we're not being recursively called,
  171. // which can happen if the user's function does anything
  172. // that calls yield.
  173. if (runningFromYield) {
  174. enableInterrupts(irq);
  175. return;
  176. }
  177. // Ok, update the runningFromYield flag and process event
  178. runningFromYield = true;
  179. firstYield = first->_next;
  180. if (firstYield) {
  181. firstYield->_prev = nullptr;
  182. } else {
  183. lastYield = nullptr;
  184. }
  185. enableInterrupts(irq);
  186. first->_triggered = false;
  187. (*(first->_function))(*first);
  188. runningFromYield = false;
  189. }
  190. static void runFromInterrupt();
  191. operator bool() { return _triggered; }
  192. protected:
  193. void triggerEventNotImmediate();
  194. void detachNoInterrupts();
  195. int _status = 0;
  196. EventResponderFunction _function = nullptr;
  197. void *_data = nullptr;
  198. void *_context = nullptr;
  199. EventResponder *_next = nullptr;
  200. EventResponder *_prev = nullptr;
  201. EventType _type = EventTypeDetached;
  202. bool _triggered = false;
  203. static EventResponder *firstYield;
  204. static EventResponder *lastYield;
  205. static EventResponder *firstInterrupt;
  206. static EventResponder *lastInterrupt;
  207. static bool runningFromYield;
  208. private:
  209. static bool disableInterrupts() {
  210. uint32_t primask;
  211. __asm__ volatile("mrs %0, primask\n" : "=r" (primask)::);
  212. __disable_irq();
  213. return (primask == 0) ? true : false;
  214. }
  215. static void enableInterrupts(bool doit) {
  216. if (doit) __enable_irq();
  217. }
  218. };
  219. class MillisTimer
  220. {
  221. public:
  222. constexpr MillisTimer() {
  223. }
  224. ~MillisTimer() {
  225. end();
  226. }
  227. void begin(unsigned long milliseconds, EventResponderRef event);
  228. void beginRepeating(unsigned long milliseconds, EventResponderRef event);
  229. void end();
  230. static void runFromTimer();
  231. private:
  232. void addToWaitingList();
  233. void addToActiveList();
  234. unsigned long _ms = 0;
  235. unsigned long _reload = 0;
  236. MillisTimer *_next = nullptr;
  237. MillisTimer *_prev = nullptr;
  238. EventResponder *_event = nullptr;
  239. enum TimerStateType {
  240. TimerOff = 0,
  241. TimerWaiting,
  242. TimerActive
  243. };
  244. volatile TimerStateType _state = TimerOff;
  245. static MillisTimer *listWaiting; // single linked list of waiting to start timers
  246. static MillisTimer *listActive; // double linked list of running timers
  247. static bool disableTimerInterrupt() {
  248. uint32_t primask;
  249. __asm__ volatile("mrs %0, primask\n" : "=r" (primask)::);
  250. __disable_irq();
  251. return (primask == 0) ? true : false;
  252. }
  253. static void enableTimerInterrupt(bool doit) {
  254. if (doit) __enable_irq();
  255. }
  256. };
  257. #endif