├── EventManager ├── EventManager.cpp ├── EventManager.h ├── LGPL-2.1.txt ├── examples │ ├── WithInterrupts │ │ ├── WithInterrupts.ino │ │ └── WithInterrupts_ESP32.cpp │ └── WithoutInterrupts │ │ └── WithoutInterrupts.ino └── keywords.txt └── README.md /EventManager/EventManager.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * EventManager.cpp 3 | * 4 | 5 | * An event handling system for Arduino. 6 | * 7 | * Author: igormt@alumni.caltech.edu 8 | * Copyright (c) 2013 Igor Mikolic-Torreira 9 | * 10 | * Inspired by and adapted from the 11 | * Arduino Event System library by 12 | * Author: mromani@ottotecnica.com 13 | * Copyright (c) 2010 OTTOTECNICA Italy 14 | * 15 | * This library is free software; you can redistribute it 16 | * and/or modify it under the terms of the GNU Lesser 17 | * General Public License as published by the Free Software 18 | * Foundation; either version 2.1 of the License, or (at 19 | * your option) any later version. 20 | * 21 | * This library is distributed in the hope that it will 22 | * be useful, but WITHOUT ANY WARRANTY; without even the 23 | * implied warranty of MERCHANTABILITY or FITNESS FOR A 24 | * PARTICULAR PURPOSE. See the GNU Lesser General Public 25 | * License for more details. 26 | * 27 | * You should have received a copy of the GNU Lesser 28 | * General Public License along with this library; if not, 29 | * write to the Free Software Foundation, Inc., 30 | * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 31 | * 32 | */ 33 | 34 | 35 | #include "EventManager.h" 36 | 37 | namespace 38 | { 39 | // This class takes care of turning interrupts on and off. 40 | // There is a different implementation of this class for each architecture that 41 | // has a different interrupt model. #if macros ensure only one version is defined. 42 | 43 | #if defined( __AVR_ARCH__ ) 44 | 45 | class SuppressInterrupts 46 | { 47 | public: 48 | 49 | // Record the current state and suppress interrupts when the object is instantiated. 50 | SuppressInterrupts() 51 | { 52 | mInterruptsWereOn = (SREG & (1< 154 | 155 | class SuppressInterrupts 156 | { 157 | public: 158 | 159 | // Reference: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-guides/freertos-smp.html#critical-sections-disabling-interrupts 160 | // Enter critical section 161 | SuppressInterrupts() 162 | { 163 | portENTER_CRITICAL(&gMux); 164 | } 165 | 166 | // Exit critical section 167 | ~SuppressInterrupts() 168 | { 169 | portEXIT_CRITICAL(&gMux); 170 | } 171 | 172 | static portMUX_TYPE gMux; 173 | }; 174 | 175 | // gMux is globally accessible as a public static member variable 176 | portMUX_TYPE SuppressInterrupts::gMux = portMUX_INITIALIZER_UNLOCKED; 177 | 178 | #else 179 | 180 | #error "Unknown microcontroller: Need to implement class SuppressInterrupts for this microcontroller." 181 | 182 | #endif 183 | 184 | } 185 | 186 | 187 | 188 | 189 | #if EVENTMANAGER_DEBUG 190 | #define EVTMGR_DEBUG_PRINT( x ) Serial.print( x ); 191 | #define EVTMGR_DEBUG_PRINTLN( x ) Serial.println( x ); 192 | #define EVTMGR_DEBUG_PRINT_PTR( x ) Serial.print( reinterpret_cast( x ), HEX ); 193 | #define EVTMGR_DEBUG_PRINTLN_PTR( x ) Serial.println( reinterpret_cast( x ), HEX ); 194 | #else 195 | #define EVTMGR_DEBUG_PRINT( x ) 196 | #define EVTMGR_DEBUG_PRINTLN( x ) 197 | #define EVTMGR_DEBUG_PRINT_PTR( x ) 198 | #define EVTMGR_DEBUG_PRINTLN_PTR( x ) 199 | #endif 200 | 201 | 202 | EventManager::EventManager() 203 | { 204 | } 205 | 206 | 207 | int EventManager::processEvent() 208 | { 209 | int eventCode; 210 | int param; 211 | int handledCount = 0; 212 | 213 | if ( mHighPriorityQueue.popEvent( &eventCode, ¶m ) ) 214 | { 215 | handledCount = mListeners.sendEvent( eventCode, param ); 216 | 217 | EVTMGR_DEBUG_PRINT( "processEvent() hi-pri event " ) 218 | EVTMGR_DEBUG_PRINT( eventCode ) 219 | EVTMGR_DEBUG_PRINT( ", " ) 220 | EVTMGR_DEBUG_PRINT( param ) 221 | EVTMGR_DEBUG_PRINT( " sent to " ) 222 | EVTMGR_DEBUG_PRINTLN( handledCount ) 223 | } 224 | 225 | // If no high-pri events handled (either because there are no high-pri events or 226 | // because there are no listeners for them), then try low-pri events 227 | if ( !handledCount && mLowPriorityQueue.popEvent( &eventCode, ¶m ) ) 228 | { 229 | handledCount = mListeners.sendEvent( eventCode, param ); 230 | 231 | EVTMGR_DEBUG_PRINT( "processEvent() lo-pri event " ) 232 | EVTMGR_DEBUG_PRINT( eventCode ) 233 | EVTMGR_DEBUG_PRINT( ", " ) 234 | EVTMGR_DEBUG_PRINT( param ) 235 | EVTMGR_DEBUG_PRINT( " sent to " ) 236 | EVTMGR_DEBUG_PRINTLN( handledCount ) 237 | } 238 | 239 | return handledCount; 240 | } 241 | 242 | 243 | int EventManager::processAllEvents() 244 | { 245 | int eventCode; 246 | int param; 247 | int handledCount = 0; 248 | 249 | while ( mHighPriorityQueue.popEvent( &eventCode, ¶m ) ) 250 | { 251 | handledCount += mListeners.sendEvent( eventCode, param ); 252 | 253 | EVTMGR_DEBUG_PRINT( "processEvent() hi-pri event " ) 254 | EVTMGR_DEBUG_PRINT( eventCode ) 255 | EVTMGR_DEBUG_PRINT( ", " ) 256 | EVTMGR_DEBUG_PRINT( param ) 257 | EVTMGR_DEBUG_PRINT( " sent to " ) 258 | EVTMGR_DEBUG_PRINTLN( handledCount ) 259 | } 260 | 261 | while ( mLowPriorityQueue.popEvent( &eventCode, ¶m ) ) 262 | { 263 | handledCount += mListeners.sendEvent( eventCode, param ); 264 | 265 | EVTMGR_DEBUG_PRINT( "processEvent() lo-pri event " ) 266 | EVTMGR_DEBUG_PRINT( eventCode ) 267 | EVTMGR_DEBUG_PRINT( ", " ) 268 | EVTMGR_DEBUG_PRINT( param ) 269 | EVTMGR_DEBUG_PRINT( " sent to " ) 270 | EVTMGR_DEBUG_PRINTLN( handledCount ) 271 | } 272 | 273 | return handledCount; 274 | } 275 | 276 | 277 | 278 | /********************************************************************/ 279 | 280 | 281 | 282 | EventManager::ListenerList::ListenerList() : 283 | mNumListeners( 0 ), mDefaultCallback( 0 ) 284 | { 285 | } 286 | 287 | int EventManager::ListenerList::numListeners() 288 | { 289 | return mNumListeners; 290 | }; 291 | 292 | int EventManager::numListeners() 293 | { 294 | return mListeners.numListeners(); 295 | }; 296 | 297 | boolean EventManager::ListenerList::addListener( int eventCode, EventListener listener ) 298 | { 299 | EVTMGR_DEBUG_PRINT( "addListener() enter " ) 300 | EVTMGR_DEBUG_PRINT( eventCode ) 301 | EVTMGR_DEBUG_PRINT( ", " ) 302 | EVTMGR_DEBUG_PRINTLN_PTR( listener ) 303 | 304 | // Argument check 305 | if ( !listener ) 306 | { 307 | return false; 308 | } 309 | 310 | // Check for full dispatch table 311 | if ( isFull() ) 312 | { 313 | EVTMGR_DEBUG_PRINTLN( "addListener() list full" ) 314 | return false; 315 | } 316 | 317 | mListeners[ mNumListeners ].callback = listener; 318 | mListeners[ mNumListeners ].eventCode = eventCode; 319 | mListeners[ mNumListeners ].enabled = true; 320 | mNumListeners++; 321 | 322 | EVTMGR_DEBUG_PRINTLN( "addListener() listener added" ) 323 | 324 | return true; 325 | } 326 | 327 | 328 | boolean EventManager::ListenerList::removeListener( int eventCode, EventListener listener ) 329 | { 330 | EVTMGR_DEBUG_PRINT( "removeListener() enter " ) 331 | EVTMGR_DEBUG_PRINT( eventCode ) 332 | EVTMGR_DEBUG_PRINT( ", " ) 333 | EVTMGR_DEBUG_PRINTLN_PTR( listener ) 334 | 335 | if ( mNumListeners == 0 ) 336 | { 337 | EVTMGR_DEBUG_PRINTLN( "removeListener() no listeners" ) 338 | return false; 339 | } 340 | 341 | int k = searchListeners( eventCode, listener ); 342 | if ( k < 0 ) 343 | { 344 | EVTMGR_DEBUG_PRINTLN( "removeListener() not found" ) 345 | return false; 346 | } 347 | 348 | for ( int i = k; i < mNumListeners - 1; i++ ) 349 | { 350 | mListeners[ i ].callback = mListeners[ i + 1 ].callback; 351 | mListeners[ i ].eventCode = mListeners[ i + 1 ].eventCode; 352 | mListeners[ i ].enabled = mListeners[ i + 1 ].enabled; 353 | } 354 | mNumListeners--; 355 | 356 | EVTMGR_DEBUG_PRINTLN( "removeListener() removed" ) 357 | 358 | return true; 359 | } 360 | 361 | 362 | int EventManager::ListenerList::removeListener( EventListener listener ) 363 | { 364 | EVTMGR_DEBUG_PRINT( "removeListener() enter " ) 365 | EVTMGR_DEBUG_PRINTLN_PTR( listener ) 366 | 367 | if ( mNumListeners == 0 ) 368 | { 369 | EVTMGR_DEBUG_PRINTLN( " removeListener() no listeners" ) 370 | return 0; 371 | } 372 | 373 | int removed = 0; 374 | int k; 375 | while ((k = searchListeners( listener )) >= 0 ) 376 | { 377 | for ( int i = k; i < mNumListeners - 1; i++ ) 378 | { 379 | mListeners[ i ].callback = mListeners[ i + 1 ].callback; 380 | mListeners[ i ].eventCode = mListeners[ i + 1 ].eventCode; 381 | mListeners[ i ].enabled = mListeners[ i + 1 ].enabled; 382 | } 383 | mNumListeners--; 384 | removed++; 385 | } 386 | 387 | EVTMGR_DEBUG_PRINT( " removeListener() removed " ) 388 | EVTMGR_DEBUG_PRINTLN( removed ) 389 | 390 | return removed; 391 | } 392 | 393 | 394 | boolean EventManager::ListenerList::enableListener( int eventCode, EventListener listener, boolean enable ) 395 | { 396 | EVTMGR_DEBUG_PRINT( "enableListener() enter " ) 397 | EVTMGR_DEBUG_PRINT( eventCode ) 398 | EVTMGR_DEBUG_PRINT( ", " ) 399 | EVTMGR_DEBUG_PRINT_PTR( listener ) 400 | EVTMGR_DEBUG_PRINT( ", " ) 401 | EVTMGR_DEBUG_PRINTLN( enable ) 402 | 403 | if ( mNumListeners == 0 ) 404 | { 405 | EVTMGR_DEBUG_PRINTLN( "enableListener() no listeners" ) 406 | return false; 407 | } 408 | 409 | int k = searchListeners( eventCode, listener ); 410 | if ( k < 0 ) 411 | { 412 | EVTMGR_DEBUG_PRINTLN( "enableListener() not found fail" ) 413 | return false; 414 | } 415 | 416 | mListeners[ k ].enabled = enable; 417 | 418 | EVTMGR_DEBUG_PRINTLN( "enableListener() success" ) 419 | return true; 420 | } 421 | 422 | 423 | boolean EventManager::ListenerList::isListenerEnabled( int eventCode, EventListener listener ) 424 | { 425 | if ( mNumListeners == 0 ) 426 | { 427 | return false; 428 | } 429 | 430 | int k = searchListeners( eventCode, listener ); 431 | if ( k < 0 ) 432 | { 433 | return false; 434 | } 435 | 436 | return mListeners[ k ].enabled; 437 | } 438 | 439 | 440 | int EventManager::ListenerList::sendEvent( int eventCode, int param ) 441 | { 442 | EVTMGR_DEBUG_PRINT( "sendEvent() enter " ) 443 | EVTMGR_DEBUG_PRINT( eventCode ) 444 | EVTMGR_DEBUG_PRINT( ", " ) 445 | EVTMGR_DEBUG_PRINTLN( param ) 446 | 447 | int handlerCount = 0; 448 | for ( int i = 0; i < mNumListeners; i++ ) 449 | { 450 | if ( ( mListeners[ i ].callback != 0 ) && ( mListeners[ i ].eventCode == eventCode ) && mListeners[ i ].enabled ) 451 | { 452 | handlerCount++; 453 | (*mListeners[ i ].callback)( eventCode, param ); 454 | } 455 | } 456 | 457 | EVTMGR_DEBUG_PRINT( "sendEvent() sent to " ) 458 | EVTMGR_DEBUG_PRINTLN( handlerCount ) 459 | 460 | if ( !handlerCount ) 461 | { 462 | if ( ( mDefaultCallback != 0 ) && mDefaultCallbackEnabled ) 463 | { 464 | handlerCount++; 465 | (*mDefaultCallback)( eventCode, param ); 466 | 467 | EVTMGR_DEBUG_PRINTLN( "sendEvent() event sent to default" ) 468 | } 469 | 470 | #if EVENTMANAGER_DEBUG 471 | else 472 | { 473 | EVTMGR_DEBUG_PRINTLN( "sendEvent() no default" ) 474 | } 475 | #endif 476 | 477 | } 478 | 479 | return handlerCount; 480 | } 481 | 482 | 483 | boolean EventManager::ListenerList::setDefaultListener( EventListener listener ) 484 | { 485 | EVTMGR_DEBUG_PRINT( "setDefaultListener() enter " ) 486 | EVTMGR_DEBUG_PRINTLN_PTR( listener ) 487 | 488 | if ( listener == 0 ) 489 | { 490 | return false; 491 | } 492 | 493 | mDefaultCallback = listener; 494 | mDefaultCallbackEnabled = true; 495 | return true; 496 | } 497 | 498 | 499 | void EventManager::ListenerList::removeDefaultListener() 500 | { 501 | mDefaultCallback = 0; 502 | mDefaultCallbackEnabled = false; 503 | } 504 | 505 | 506 | void EventManager::ListenerList::enableDefaultListener( boolean enable ) 507 | { 508 | mDefaultCallbackEnabled = enable; 509 | } 510 | 511 | 512 | int EventManager::ListenerList::searchListeners( int eventCode, EventListener listener ) 513 | { 514 | 515 | for ( int i = 0; i < mNumListeners; i++ ) 516 | { 517 | 518 | 519 | if ( ( mListeners[i].eventCode == eventCode ) && ( mListeners[i].callback == listener ) ) 520 | { 521 | return i; 522 | } 523 | } 524 | 525 | return -1; 526 | } 527 | 528 | 529 | int EventManager::ListenerList::searchListeners( EventListener listener ) 530 | { 531 | for ( int i = 0; i < mNumListeners; i++ ) 532 | { 533 | if ( mListeners[i].callback == listener ) 534 | { 535 | return i; 536 | } 537 | } 538 | 539 | return -1; 540 | } 541 | 542 | 543 | int EventManager::ListenerList::searchEventCode( int eventCode ) 544 | { 545 | for ( int i = 0; i < mNumListeners; i++ ) 546 | { 547 | if ( mListeners[i].eventCode == eventCode ) 548 | { 549 | return i; 550 | } 551 | } 552 | 553 | return -1; 554 | } 555 | 556 | 557 | 558 | /******************************************************************************/ 559 | 560 | 561 | 562 | 563 | EventManager::EventQueue::EventQueue() : 564 | mEventQueueHead( 0 ), 565 | mEventQueueTail( 0 ), 566 | mNumEvents( 0 ) 567 | { 568 | for ( int i = 0; i < kEventQueueSize; i++ ) 569 | { 570 | mEventQueue[i].code = EventManager::kEventNone; 571 | mEventQueue[i].param = 0; 572 | } 573 | } 574 | 575 | 576 | 577 | boolean ISR_ATTR EventManager::EventQueue::queueEvent( int eventCode, int eventParam ) 578 | { 579 | /* 580 | * The call to noInterrupts() MUST come BEFORE the full queue check. 581 | * 582 | * If the call to isFull() returns FALSE but an asynchronous interrupt queues 583 | * an event, making the queue full, before we finish inserting here, we will then 584 | * corrupt the queue (we'll add an event to an already full queue). So the entire 585 | * operation, from the call to isFull() to completing the inserting (if not full) 586 | * must be atomic. 587 | * 588 | * Note that this race condition can only arise IF both interrupt and non-interrupt (normal) 589 | * code add events to the queue. If only normal code adds events, this can't happen 590 | * because then there are no asynchronous additions to the queue. If only interrupt 591 | * handlers add events to the queue, this can't happen because further interrupts are 592 | * blocked while an interrupt handler is executing. This race condition can only happen 593 | * when an event is added to the queue by normal (non-interrupt) code and simultaneously 594 | * an interrupt handler tries to add an event to the queue. This is the case that the 595 | * cli() (= noInterrupts()) call protects against. 596 | * 597 | * Contrast this with the logic in popEvent(). 598 | * 599 | */ 600 | 601 | SuppressInterrupts interruptsOff; // Interrupts automatically restored when exit block 602 | 603 | // ATOMIC BLOCK BEGIN 604 | boolean retVal = false; 605 | if ( !isFull() ) 606 | { 607 | // Store the event at the tail of the queue 608 | mEventQueue[ mEventQueueTail ].code = eventCode; 609 | mEventQueue[ mEventQueueTail ].param = eventParam; 610 | 611 | // Update queue tail value 612 | mEventQueueTail = ( mEventQueueTail + 1 ) % kEventQueueSize;; 613 | 614 | // Update number of events in queue 615 | mNumEvents++; 616 | 617 | retVal = true; 618 | } 619 | // ATOMIC BLOCK END 620 | 621 | return retVal; 622 | } 623 | 624 | 625 | boolean EventManager::EventQueue::popEvent( int* eventCode, int* eventParam ) 626 | { 627 | /* 628 | * The call to noInterrupts() MUST come AFTER the empty queue check. 629 | * 630 | * There is no harm if the isEmpty() call returns an "incorrect" TRUE response because 631 | * an asynchronous interrupt queued an event after isEmpty() was called but before the 632 | * return is executed. We'll pick up that asynchronously queued event the next time 633 | * popEvent() is called. 634 | * 635 | * If interrupts are suppressed before the isEmpty() check, we pretty much lock-up the Arduino. 636 | * This is because popEvent(), via processEvents(), is normally called inside loop(), which 637 | * means it is called VERY OFTEN. Most of the time (>99%), the event queue will be empty. 638 | * But that means that we'll have interrupts turned off for a significant fraction of the 639 | * time. We don't want to do that. We only want interrupts turned off when we are 640 | * actually manipulating the queue. 641 | * 642 | * Contrast this with the logic in queueEvent(). 643 | * 644 | */ 645 | 646 | if ( isEmpty() ) 647 | { 648 | return false; 649 | } 650 | 651 | SuppressInterrupts interruptsOff; // Interrupts automatically restored when exit block 652 | 653 | // Pop the event from the head of the queue 654 | // Store event code and event parameter into the user-supplied variables 655 | *eventCode = mEventQueue[ mEventQueueHead ].code; 656 | *eventParam = mEventQueue[ mEventQueueHead ].param; 657 | 658 | // Clear the event (paranoia) 659 | mEventQueue[ mEventQueueHead ].code = EventManager::kEventNone; 660 | 661 | // Update the queue head value 662 | mEventQueueHead = ( mEventQueueHead + 1 ) % kEventQueueSize; 663 | 664 | // Update number of events in queue 665 | mNumEvents--; 666 | 667 | return true; 668 | } 669 | -------------------------------------------------------------------------------- /EventManager/EventManager.h: -------------------------------------------------------------------------------- 1 | /* 2 | * EventManager.h 3 | * 4 | 5 | * An event handling system for Arduino. 6 | * 7 | * Author: igormt@alumni.caltech.edu 8 | * Copyright (c) 2013 Igor Mikolic-Torreira 9 | * 10 | * Inspired by and adapted from the 11 | * Arduino Event System library by 12 | * Author: mromani@ottotecnica.com 13 | * Copyright (c) 2010 OTTOTECNICA Italy 14 | * 15 | * This library is free software; you can redistribute it 16 | * and/or modify it under the terms of the GNU Lesser 17 | * General Public License as published by the Free Software 18 | * Foundation; either version 2.1 of the License, or (at 19 | * your option) any later version. 20 | * 21 | * This library is distributed in the hope that it will 22 | * be useful, but WITHOUT ANY WARRANTY; without even the 23 | * implied warranty of MERCHANTABILITY or FITNESS FOR A 24 | * PARTICULAR PURPOSE. See the GNU Lesser General Public 25 | * License for more details. 26 | * 27 | * You should have received a copy of the GNU Lesser 28 | * General Public License along with this library; if not, 29 | * write to the Free Software Foundation, Inc., 30 | * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 31 | * 32 | */ 33 | 34 | 35 | #ifndef EventManager_h 36 | #define EventManager_h 37 | 38 | #include 39 | 40 | // For ESP32, interrupt handling routines (and any functions called from them) should be placed in IRAM 41 | // This define allows an attribute to be specified for queueEvent() under these circumstances 42 | #if defined ( ESP32 ) 43 | #define ISR_ATTR IRAM_ATTR 44 | #else 45 | #define ISR_ATTR 46 | #endif 47 | 48 | // Size of the listener list. Adjust as appropriate for your application. 49 | // Requires a total of sizeof(*f())+sizeof(int)+sizeof(boolean) bytes of RAM for each unit of size 50 | #ifndef EVENTMANAGER_LISTENER_LIST_SIZE 51 | #define EVENTMANAGER_LISTENER_LIST_SIZE 8 52 | #endif 53 | 54 | // Size of the event two queues. Adjust as appropriate for your application. 55 | // Requires a total of 4 * sizeof(int) bytes of RAM for each unit of size 56 | #ifndef EVENTMANAGER_EVENT_QUEUE_SIZE 57 | #define EVENTMANAGER_EVENT_QUEUE_SIZE 8 58 | #endif 59 | 60 | 61 | class EventManager 62 | { 63 | 64 | public: 65 | 66 | // Type for an event listener (a.k.a. callback) function 67 | typedef void ( *EventListener )( int eventCode, int eventParam ); 68 | 69 | // EventManager recognizes two kinds of events. By default, events are 70 | // are queued as low priority, but these constants can be used to explicitly 71 | // set the priority when queueing events 72 | // 73 | // NOTE high priority events are always handled before any low priority events. 74 | enum EventPriority { kHighPriority, kLowPriority }; 75 | 76 | // Various pre-defined event type codes. These are completely optional and 77 | // provided for convenience. Any integer value can be used as an event code. 78 | enum EventType 79 | { 80 | // No event occurred; param: none 81 | kEventNone = 200, 82 | 83 | // A key was pressed; param: key code 84 | kEventKeyPress, 85 | 86 | // A key was released; param: key code 87 | kEventKeyRelease, 88 | 89 | // Use this to notify a character; param: the character to be notified 90 | kEventChar, 91 | 92 | // Generic time event 93 | // param: a time value (exact meaning is defined by the code inserting this event into the queue) 94 | kEventTime, 95 | 96 | // Generic timer events; param: same as EV_TIME 97 | kEventTimer0, 98 | kEventTimer1, 99 | kEventTimer2, 100 | kEventTimer3, 101 | 102 | // Analog read (last number = analog channel); param: value read 103 | kEventAnalog0, 104 | kEventAnalog1, 105 | kEventAnalog2, 106 | kEventAnalog3, 107 | kEventAnalog4, 108 | kEventAnalog5, 109 | 110 | // Menu events 111 | kEventMenu0, 112 | kEventMenu1, 113 | kEventMenu2, 114 | kEventMenu3, 115 | kEventMenu4, 116 | kEventMenu5, 117 | kEventMenu6, 118 | kEventMenu7, 119 | kEventMenu8, 120 | kEventMenu9, 121 | 122 | // Serial event, example: a new char is available 123 | // param: the return value of Serial.read() 124 | kEventSerial, 125 | 126 | // LCD screen needs to be refreshed 127 | kEventPaint, 128 | 129 | // User events 130 | kEventUser0, 131 | kEventUser1, 132 | kEventUser2, 133 | kEventUser3, 134 | kEventUser4, 135 | kEventUser5, 136 | kEventUser6, 137 | kEventUser7, 138 | kEventUser8, 139 | kEventUser9 140 | }; 141 | 142 | 143 | // Create an event manager 144 | // It always operates in interrupt safe mode, allowing you to queue events from interrupt handlers 145 | EventManager(); 146 | 147 | // Add a listener 148 | // Returns true if the listener is successfully installed, false otherwise (e.g. the dispatch table is full) 149 | boolean addListener( int eventCode, EventListener listener ); 150 | 151 | // Remove (event, listener) pair (all occurrences) 152 | // Other listeners with the same function or event code will not be affected 153 | boolean removeListener( int eventCode, EventListener listener ); 154 | 155 | // Remove all occurrances of a listener 156 | // Removes this listener regardless of the event code; returns number removed 157 | // Useful when one listener handles many different events 158 | int removeListener( EventListener listener ); 159 | 160 | // Enable or disable a listener 161 | // Return true if the listener was successfully enabled or disabled, false if the listener was not found 162 | boolean enableListener( int eventCode, EventListener listener, boolean enable ); 163 | 164 | // Returns the current enabled/disabled state of the (eventCode, listener) combo 165 | boolean isListenerEnabled( int eventCode, EventListener listener ); 166 | 167 | // The default listener is a callback function that is called when an event with no listener is processed 168 | // These functions set, clear, and enable/disable the default listener 169 | boolean setDefaultListener( EventListener listener ); 170 | void removeDefaultListener(); 171 | void enableDefaultListener( boolean enable ); 172 | 173 | // Is the ListenerList empty? 174 | boolean isListenerListEmpty(); 175 | 176 | // Is the ListenerList full? 177 | boolean isListenerListFull(); 178 | 179 | int numListeners(); 180 | 181 | // Returns true if no events are in the queue 182 | boolean isEventQueueEmpty( EventPriority pri = kLowPriority ); 183 | 184 | // Returns true if no more events can be inserted into the queue 185 | boolean isEventQueueFull( EventPriority pri = kLowPriority ); 186 | 187 | // Actual number of events in queue 188 | int getNumEventsInQueue( EventPriority pri = kLowPriority ); 189 | 190 | // tries to insert an event into the queue; 191 | // returns true if successful, false if the 192 | // queue if full and the event cannot be inserted 193 | boolean queueEvent( int eventCode, int eventParam, EventPriority pri = kLowPriority ); 194 | 195 | // this must be called regularly (usually by calling it inside the loop() function) 196 | int processEvent(); 197 | 198 | // this function can be called to process ALL events in the queue 199 | // WARNING: if interrupts are adding events as fast as they are being processed 200 | // this function might never return. YOU HAVE BEEN WARNED. 201 | int processAllEvents(); 202 | 203 | 204 | private: 205 | 206 | // EventQueue class used internally by EventManager 207 | class EventQueue 208 | { 209 | 210 | public: 211 | 212 | // Queue constructor 213 | EventQueue(); 214 | 215 | // Returns true if no events are in the queue 216 | boolean isEmpty(); 217 | 218 | // Returns true if no more events can be inserted into the queue 219 | boolean isFull(); 220 | 221 | // Actual number of events in queue 222 | int getNumEvents(); 223 | 224 | // Tries to insert an event into the queue; 225 | // Returns true if successful, false if the queue if full and the event cannot be inserted 226 | // 227 | // NOTE: if EventManager is instantiated in interrupt safe mode, this function can be called 228 | // from interrupt handlers. This is the ONLY EventManager function that can be called from 229 | // an interrupt. 230 | boolean queueEvent( int eventCode, int eventParam ); 231 | 232 | // Tries to extract an event from the queue; 233 | // Returns true if successful, false if the queue is empty (the parameteres are not touched in this case) 234 | boolean popEvent( int* eventCode, int* eventParam ); 235 | 236 | private: 237 | 238 | // Event queue size. 239 | // The maximum number of events the queue can hold is kEventQueueSize 240 | // Increasing this number will consume 2 * sizeof(int) bytes of RAM for each unit. 241 | static const int kEventQueueSize = EVENTMANAGER_EVENT_QUEUE_SIZE; 242 | 243 | struct EventElement 244 | { 245 | int code; // each event is represented by an integer code 246 | int param; // each event has a single integer parameter 247 | }; 248 | 249 | // The event queue 250 | EventElement mEventQueue[ kEventQueueSize ]; 251 | 252 | // Index of event queue head 253 | int mEventQueueHead; 254 | 255 | // Index of event queue tail 256 | int mEventQueueTail; 257 | 258 | // Actual number of events in queue 259 | int mNumEvents; 260 | }; 261 | 262 | 263 | // ListenerList class used internally by EventManager 264 | class ListenerList 265 | { 266 | 267 | public: 268 | 269 | // Create an event manager 270 | ListenerList(); 271 | 272 | // Add a listener 273 | // Returns true if the listener is successfully installed, false otherwise (e.g. the dispatch table is full) 274 | boolean addListener( int eventCode, EventListener listener ); 275 | 276 | // Remove event listener pair (all occurrences) 277 | // Other listeners with the same function or eventCode will not be affected 278 | boolean removeListener( int eventCode, EventListener listener ); 279 | 280 | // Remove all occurrances of a listener 281 | // Removes this listener regardless of the eventCode; returns number removed 282 | int removeListener( EventListener listener ); 283 | 284 | // Enable or disable a listener 285 | // Return true if the listener was successfully enabled or disabled, false if the listener was not found 286 | boolean enableListener( int eventCode, EventListener listener, boolean enable ); 287 | 288 | boolean isListenerEnabled( int eventCode, EventListener listener ); 289 | 290 | // The default listener is a callback function that is called when an event with no listener is processed 291 | boolean setDefaultListener( EventListener listener ); 292 | void removeDefaultListener(); 293 | void enableDefaultListener( boolean enable ); 294 | 295 | // Is the ListenerList empty? 296 | boolean isEmpty(); 297 | 298 | // Is the ListenerList full? 299 | boolean isFull(); 300 | 301 | // Send an event to the listeners; returns number of listeners that handled the event 302 | int sendEvent( int eventCode, int param ); 303 | 304 | int numListeners(); 305 | 306 | private: 307 | 308 | // Maximum number of event/callback entries 309 | // Can be changed to save memory or allow more events to be dispatched 310 | static const int kMaxListeners = EVENTMANAGER_LISTENER_LIST_SIZE; 311 | 312 | // Actual number of event listeners 313 | int mNumListeners; 314 | 315 | // Listener structure and corresponding array 316 | struct ListenerItem 317 | { 318 | EventListener callback; // The listener function 319 | int eventCode; // The event code 320 | boolean enabled; // Each listener can be enabled or disabled 321 | }; 322 | ListenerItem mListeners[ kMaxListeners ]; 323 | 324 | // Callback function to be called for event types which have no listener 325 | EventListener mDefaultCallback; 326 | 327 | // Once set, the default callback function can be enabled or disabled 328 | boolean mDefaultCallbackEnabled; 329 | 330 | // get the current number of entries in the dispatch table 331 | int getNumEntries(); 332 | 333 | // returns the array index of the specified listener or -1 if no such event/function couple is found 334 | int searchListeners( int eventCode, EventListener listener); 335 | int searchListeners( EventListener listener ); 336 | int searchEventCode( int eventCode ); 337 | 338 | }; 339 | 340 | EventQueue mHighPriorityQueue; 341 | EventQueue mLowPriorityQueue; 342 | 343 | ListenerList mListeners; 344 | }; 345 | 346 | //********* INLINES EventManager:: *********** 347 | 348 | inline boolean EventManager::addListener( int eventCode, EventListener listener ) 349 | { 350 | return mListeners.addListener( eventCode, listener ); 351 | } 352 | 353 | inline boolean EventManager::removeListener( int eventCode, EventListener listener ) 354 | { 355 | return mListeners.removeListener( eventCode, listener ); 356 | } 357 | 358 | inline int EventManager::removeListener( EventListener listener ) 359 | { 360 | return mListeners.removeListener( listener ); 361 | } 362 | 363 | inline boolean EventManager::enableListener( int eventCode, EventListener listener, boolean enable ) 364 | { 365 | return mListeners.enableListener( eventCode, listener, enable ); 366 | } 367 | 368 | inline boolean EventManager::isListenerEnabled( int eventCode, EventListener listener ) 369 | { 370 | return mListeners.isListenerEnabled( eventCode, listener ); 371 | } 372 | 373 | inline boolean EventManager::setDefaultListener( EventListener listener ) 374 | { 375 | return mListeners.setDefaultListener( listener ); 376 | } 377 | 378 | inline void EventManager::removeDefaultListener() 379 | { 380 | mListeners.removeDefaultListener(); 381 | } 382 | 383 | inline void EventManager::enableDefaultListener( boolean enable ) 384 | { 385 | mListeners.enableDefaultListener( enable ); 386 | } 387 | 388 | inline boolean EventManager::isListenerListEmpty() 389 | { 390 | return mListeners.isEmpty(); 391 | } 392 | 393 | inline boolean EventManager::isListenerListFull() 394 | { 395 | return mListeners.isFull(); 396 | } 397 | 398 | inline boolean EventManager::isEventQueueEmpty( EventPriority pri ) 399 | { 400 | return ( pri == kHighPriority ) ? mHighPriorityQueue.isEmpty() : mLowPriorityQueue.isEmpty(); 401 | } 402 | 403 | inline boolean EventManager::isEventQueueFull( EventPriority pri ) 404 | { 405 | return ( pri == kHighPriority ) ? mHighPriorityQueue.isFull() : mLowPriorityQueue.isFull(); 406 | } 407 | 408 | inline int EventManager::getNumEventsInQueue( EventPriority pri ) 409 | { 410 | return ( pri == kHighPriority ) ? mHighPriorityQueue.getNumEvents() : mLowPriorityQueue.getNumEvents(); 411 | } 412 | 413 | inline boolean EventManager::queueEvent( int eventCode, int eventParam, EventPriority pri ) 414 | { 415 | return ( pri == kHighPriority ) ? 416 | mHighPriorityQueue.queueEvent( eventCode, eventParam ) : mLowPriorityQueue.queueEvent( eventCode, eventParam ); 417 | } 418 | 419 | 420 | 421 | 422 | //********* INLINES EventManager::EventQueue:: *********** 423 | 424 | inline boolean EventManager::EventQueue::isEmpty() 425 | { 426 | return ( mNumEvents == 0 ); 427 | } 428 | 429 | 430 | inline boolean EventManager::EventQueue::isFull() 431 | { 432 | return ( mNumEvents == kEventQueueSize ); 433 | } 434 | 435 | 436 | inline int EventManager::EventQueue::getNumEvents() 437 | { 438 | return mNumEvents; 439 | } 440 | 441 | 442 | 443 | //********* INLINES EventManager::ListenerList:: *********** 444 | 445 | inline boolean EventManager::ListenerList::isEmpty() 446 | { 447 | return (mNumListeners == 0); 448 | } 449 | 450 | inline boolean EventManager::ListenerList::isFull() 451 | { 452 | return (mNumListeners == kMaxListeners); 453 | } 454 | 455 | inline int EventManager::ListenerList::getNumEntries() 456 | { 457 | return mNumListeners; 458 | } 459 | 460 | 461 | #endif 462 | -------------------------------------------------------------------------------- /EventManager/LGPL-2.1.txt: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | [This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.] 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | 474 | Copyright (C) 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 489 | 490 | Also add information on how to contact you by electronic and paper mail. 491 | 492 | You should also get your employer (if you work as a programmer) or your 493 | school, if any, to sign a "copyright disclaimer" for the library, if 494 | necessary. Here is a sample; alter the names: 495 | 496 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 497 | library `Frob' (a library for tweaking knobs) written by James Random Hacker. 498 | 499 | , 1 April 1990 500 | Ty Coon, President of Vice 501 | 502 | That's all there is to it! 503 | -------------------------------------------------------------------------------- /EventManager/examples/WithInterrupts/WithInterrupts.ino: -------------------------------------------------------------------------------- 1 | /* 2 | This sketch assumes an LED on pin 13 (built-in on Arduino Uno) and 3 | an LED on pin 8. It blinks boths LED using timer interrupts. 4 | 5 | Timer interrupts are generated using the MsTimer2 library available at 6 | http://playground.arduino.cc/Main/FlexiTimer2 7 | 8 | Author: igormt@alumni.caltech.edu 9 | Copyright (c) 2013 Igor Mikolic-Torreira 10 | 11 | This software is free software; you can redistribute it 12 | and/or modify it under the terms of the GNU Lesser 13 | General Public License as published by the Free Software 14 | Foundation; either version 2.1 of the License, or (at 15 | your option) any later version. 16 | 17 | This software is distributed in the hope that it will 18 | be useful, but WITHOUT ANY WARRANTY; without even the 19 | implied warranty of MERCHANTABILITY or FITNESS FOR A 20 | PARTICULAR PURPOSE. See the GNU Lesser General Public 21 | License for more details. 22 | 23 | You should have received a copy of the GNU Lesser 24 | General Public License along with this library; if not, 25 | write to the Free Software Foundation, Inc., 26 | 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 27 | 28 | */ 29 | 30 | 31 | #include 32 | 33 | #include 34 | 35 | 36 | struct Pins 37 | { 38 | int pinNbr; 39 | int pinState; 40 | }; 41 | 42 | Pins gPins[2] = { { 13, LOW }, { 8, LOW } }; 43 | 44 | EventManager gEM; 45 | 46 | 47 | 48 | // Our interrupt generates a toggle event for pin 13 (gPins[0]) every 49 | // time called (set to be every 1s) and and a toggle event for 50 | // pin 8 (gPins[1]) every third call (equivalent to every 3s) 51 | void interruptHandler() 52 | { 53 | static int oddEven = 0; 54 | 55 | gEM.queueEvent( EventManager::kEventUser0, 0 ); 56 | 57 | if ( !oddEven ) 58 | { 59 | gEM.queueEvent( EventManager::kEventUser0, 1 ); 60 | } 61 | 62 | ++oddEven; 63 | oddEven %= 3; 64 | } 65 | 66 | 67 | 68 | // Our listener will simply toggle the state of the pin 69 | void listener( int event, int pin ) 70 | { 71 | gPins[pin].pinState = gPins[pin].pinState ? false : true; 72 | digitalWrite( gPins[pin].pinNbr, gPins[pin].pinState ? HIGH : LOW ); 73 | } 74 | 75 | 76 | void setup() 77 | { 78 | // Setup 79 | Serial.begin( 115200 ); 80 | pinMode( gPins[0].pinNbr, OUTPUT ); 81 | pinMode( gPins[1].pinNbr, OUTPUT ); 82 | 83 | // Add our listener 84 | gEM.addListener( EventManager::kEventUser0, listener ); 85 | 86 | // Set up interrupts every second 87 | MsTimer2::set( 1000, interruptHandler ); // 1 sec period 88 | MsTimer2::start(); 89 | } 90 | 91 | 92 | void loop() 93 | { 94 | // Handle any events that are in the queue 95 | gEM.processEvent(); 96 | } 97 | 98 | -------------------------------------------------------------------------------- /EventManager/examples/WithInterrupts/WithInterrupts_ESP32.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #ifndef ESP32 4 | #error This code is designed to run on the ESP32 Arduino platform 5 | #endif 6 | 7 | // Using the master branch of arduino-EventManager 8 | // https://github.com/igormiktor/arduino-EventManager/tree/master 9 | #include 10 | 11 | // Using the ESP32TimerInterrupt library 12 | // https://github.com/khoih-prog/ESP32TimerInterrupt 13 | #include 14 | 15 | EventManager eventManager; 16 | 17 | struct Pins 18 | { 19 | int pinNumber; 20 | int pinState; 21 | }; 22 | 23 | Pins pins[2] = { { LED_BUILTIN, LOW }, { 4, LOW } }; 24 | 25 | #define TIMER0_INTERVAL_MS 100UL 26 | ESP32Timer interruptTimer0( 0 ); 27 | 28 | // IRAM_ATTR is required to place the handler in the right area of memory 29 | void IRAM_ATTR interruptHandler( void ) 30 | { 31 | static int oddEven = 0; 32 | 33 | eventManager.queueEvent( EventManager::kEventUser0, 0 ); 34 | 35 | if ( !oddEven ) 36 | { 37 | eventManager.queueEvent( EventManager::kEventUser0, 1 ); 38 | } 39 | 40 | ++oddEven; 41 | oddEven %= 3; 42 | } 43 | 44 | void listener( int event, int pin ) 45 | { 46 | pins[pin].pinState = pins[pin].pinState ? 0 : 1; 47 | digitalWrite( pins[pin].pinNumber, pins[pin].pinState ? HIGH : LOW ); 48 | } 49 | 50 | void setup() 51 | { 52 | Serial.begin( 115200 ); 53 | Serial.println( "Entering setup()" ); 54 | 55 | pinMode( pins[0].pinNumber, OUTPUT ); 56 | pinMode( pins[1].pinNumber, OUTPUT ); 57 | 58 | eventManager.addListener( EventManager::kEventUser0, listener ); 59 | 60 | interruptTimer0.attachInterruptInterval( TIMER0_INTERVAL_MS * 1000UL, interruptHandler ); 61 | } 62 | 63 | void loop() 64 | { 65 | eventManager.processEvent(); 66 | } 67 | -------------------------------------------------------------------------------- /EventManager/examples/WithoutInterrupts/WithoutInterrupts.ino: -------------------------------------------------------------------------------- 1 | /* 2 | This sketch assumes an LED on pin 13 (built-in on Arduino Uno) and 3 | an LED on pin 8. It blinks boths LED using events generated 4 | by checking elasped time against millis() -- no interrupts involved. 5 | 6 | Author: igormt@alumni.caltech.edu 7 | Copyright (c) 2013 Igor Mikolic-Torreira 8 | 9 | This software is free software; you can redistribute it 10 | and/or modify it under the terms of the GNU Lesser 11 | General Public License as published by the Free Software 12 | Foundation; either version 2.1 of the License, or (at 13 | your option) any later version. 14 | 15 | This software is distributed in the hope that it will 16 | be useful, but WITHOUT ANY WARRANTY; without even the 17 | implied warranty of MERCHANTABILITY or FITNESS FOR A 18 | PARTICULAR PURPOSE. See the GNU Lesser General Public 19 | License for more details. 20 | 21 | You should have received a copy of the GNU Lesser 22 | General Public License along with this library; if not, 23 | write to the Free Software Foundation, Inc., 24 | 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 25 | 26 | */ 27 | 28 | 29 | #include "EventManager.h" 30 | 31 | 32 | struct Pins 33 | { 34 | int pinNbr; 35 | int pinState; 36 | unsigned long lastToggled; 37 | }; 38 | 39 | Pins gPins[2] = { { 13, LOW, 0 }, { 8, LOW, 0 } }; 40 | 41 | 42 | EventManager gEM; 43 | 44 | 45 | 46 | // Our listener will simply toggle the state of the pin 47 | void listener( int event, int pin ) 48 | { 49 | gPins[pin].pinState = gPins[pin].pinState ? false : true; 50 | digitalWrite( gPins[pin].pinNbr, gPins[pin].pinState ? HIGH : LOW ); 51 | gPins[pin].lastToggled = millis(); 52 | Serial.println("free function called"); 53 | } 54 | 55 | 56 | 57 | 58 | void setup() 59 | { 60 | // Setup 61 | Serial.begin( 115200 ); 62 | pinMode( gPins[0].pinNbr, OUTPUT ); 63 | pinMode( gPins[1].pinNbr, OUTPUT ); 64 | 65 | // Add our listener 66 | gEM.addListener( EventManager::kEventUser0, listener ); 67 | Serial.print( "Number of listeners: " ); 68 | Serial.println( gEM.numListeners() ); 69 | } 70 | 71 | 72 | void loop() 73 | { 74 | // Handle any events that are in the queue 75 | gEM.processEvent(); 76 | 77 | // Add events into the queue 78 | addPin0Events(); 79 | addPin1Events(); 80 | } 81 | 82 | 83 | // Add events to toggle pin 13 (gPins[0]) every second 84 | // NOTE: doesn't handle millis() turnover 85 | void addPin0Events() 86 | { 87 | if ( ( millis() - gPins[0].lastToggled ) > 1000 ) 88 | { 89 | gEM.queueEvent( EventManager::kEventUser0, 0 ); 90 | } 91 | } 92 | 93 | // Add events to toggle pin 8 (gPins[1]) every second 94 | // NOTE: doesn't handle millis() turnover 95 | void addPin1Events() 96 | { 97 | if ( ( millis() - gPins[1].lastToggled ) > 3000 ) 98 | { 99 | gEM.queueEvent( EventManager::kEventUser0, 1 ); 100 | Serial.print("(addPin1Events)listeners number:"); 101 | Serial.println(gEM.numListeners()); 102 | 103 | } 104 | } 105 | 106 | 107 | 108 | -------------------------------------------------------------------------------- /EventManager/keywords.txt: -------------------------------------------------------------------------------- 1 | EventManager KEYWORD1 2 | 3 | addListener KEYWORD2 4 | removeListener KEYWORD2 5 | enableListener KEYWORD2 6 | isListenerEnabled KEYWORD2 7 | setDefaultListener KEYWORD2 8 | removeDefaultListener KEYWORD2 9 | enableDefaultListener KEYWORD2 10 | isListenerListEmpty KEYWORD2 11 | isListenerListFull KEYWORD2 12 | isEventQueueEmpty KEYWORD2 13 | isEventQueueFull KEYWORD2 14 | getNumEventsInQueue KEYWORD2 15 | queueEvent KEYWORD2 16 | processEvents KEYWORD2 17 | 18 | kNotInterruptSafe LITERAL1 19 | kInterruptSafe LITERAL1 20 | kEventNone LITERAL1 21 | kEventKeyPress LITERAL1 22 | kEventKeyRelease LITERAL1 23 | kEventChar LITERAL1 24 | kEventTime LITERAL1 25 | kEventTimer0 LITERAL1 26 | kEventTimer1 LITERAL1 27 | kEventTimer2 LITERAL1 28 | kEventTimer3 LITERAL1 29 | kEventAnalog0 LITERAL1 30 | kEventAnalog1 LITERAL1 31 | kEventAnalog2 LITERAL1 32 | kEventAnalog3 LITERAL1 33 | kEventAnalog4 LITERAL1 34 | kEventAnalog5 LITERAL1 35 | kEventMenu0 LITERAL1 36 | kEventMenu1 LITERAL1 37 | kEventMenu2 LITERAL1 38 | kEventMenu3 LITERAL1 39 | kEventMenu4 LITERAL1 40 | kEventMenu5 LITERAL1 41 | kEventMenu6 LITERAL1 42 | kEventMenu7 LITERAL1 43 | kEventMenu8 LITERAL1 44 | kEventMenu9 LITERAL1 45 | kEventSerial LITERAL1 46 | kEventUser0 LITERAL1 47 | kEventUser1 LITERAL1 48 | kEventUser2 LITERAL1 49 | kEventUser3 LITERAL1 50 | kEventUser4 LITERAL1 51 | kEventUser5 LITERAL1 52 | kEventUser6 LITERAL1 53 | kEventUser7 LITERAL1 54 | kEventUser8 LITERAL1 55 | kEventUser9 LITERAL1 56 | kEventPaint LITERAL1 57 | kHighPriority LITERAL1 58 | kLowPriority LITERAL1 59 | 60 | EVENTMANAGER_LISTENER_LIST_SIZE LITERAL1 61 | EVENTMANAGER_EVENT_QUEUE_SIZE LITERAL1 62 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Arduino EventManager 2 | 3 | Using an event-driven design is a common way to code Arduino projects that 4 | interact with the environment around them. **EventManager** is 5 | a single C++ class that provides an event handling system for Arduino. With 6 | **EventManager** you can register functions that "listen" 7 | for particular events and when things happen you can "post" events to 8 | **EventManager**. You then use the loop() function to regularly tell 9 | **EventManager** to process events and the appropriate listeners will be 10 | called. 11 | 12 | **EventManger** is designed to be interrupt safe, so that you can post events 13 | from interrupt handlers. The corresponding listeners will be 14 | called from outside the interrupt handler in your loop() function when you tell 15 | **EventManager** to process events. 16 | 17 | In keeping with the limited resources of an Arduino system, **EventManager** is 18 | light-weight. There is no dynamic memory allocation. Event 19 | queuing is very fast (so you can be comfortable queuing events from interrupt 20 | handlers). To keep the footprint minimal, the event queue and 21 | the listener list are both small (although you can make them bigger if needed). 22 | 23 | NOTE: There are two versions of **EventManager**. The master branch has a version 24 | of **EventManager** that uses functions as listeners (also known as event handlers). 25 | Most users will find that this version meets their needs. The `GenericListeners` 26 | branch contains a version of **EventManager** that accepts more general types of 27 | listeners such as callable member functions and callable objects. If you don't 28 | know what these are, stick to the master branch. 29 | 30 | 31 | ## Installation 32 | 33 | Copy the folder `EventManager` into your Arduino `Libraries` folder, as 34 | described in the 35 | [Arduino documentation](). 36 | 37 | 38 | ## Usage 39 | 40 | At the top of your sketch you must include the **EventManager** header file 41 | 42 | ```C 43 | #include 44 | ``` 45 | 46 | And then at global scope you should instantiate an **EventManager** object 47 | 48 | ```C 49 | EventManager gMyEventManager; 50 | ``` 51 | 52 | You can safely instantiate more than one **EventManager** object, if so desired, 53 | but the two objects will be completely independent. This might be useful if 54 | perhaps you need to have separate event processes in different components of 55 | your code. 56 | 57 | 58 | ## Events 59 | 60 | **EventManager** `Events` consist of an event code and an event parameter. Both 61 | of these are integer values. The event code identifies the type of event. For 62 | your convenience, `EventManager.h` provides a set of constants you can use to 63 | identify events 64 | 65 | ```C 66 | EventManager::kEventKeyPress 67 | EventManager::kEventKeyRelease 68 | EventManager::kEventChar 69 | EventManager::kEventTime 70 | EventManager::kEventTimer0 71 | EventManager::kEventTimer1 72 | EventManager::kEventTimer2 73 | EventManager::kEventTimer3 74 | EventManager::kEventAnalog0 75 | EventManager::kEventAnalog1 76 | EventManager::kEventAnalog2 77 | EventManager::kEventAnalog3 78 | EventManager::kEventAnalog4 79 | EventManager::kEventAnalog5 80 | EventManager::kEventMenu0 81 | EventManager::kEventMenu1 82 | EventManager::kEventMenu2 83 | EventManager::kEventMenu3 84 | EventManager::kEventMenu4 85 | EventManager::kEventMenu5 86 | EventManager::kEventMenu6 87 | EventManager::kEventMenu7 88 | EventManager::kEventMenu8 89 | EventManager::kEventMenu9 90 | EventManager::kEventSerial 91 | EventManager::kEventPaint 92 | EventManager::kEventUser0 93 | EventManager::kEventUser1 94 | EventManager::kEventUser2 95 | EventManager::kEventUser3 96 | EventManager::kEventUser4 97 | EventManager::kEventUser5 98 | EventManager::kEventUser6 99 | EventManager::kEventUser7 100 | EventManager::kEventUser8 101 | EventManager::kEventUser9 102 | ``` 103 | 104 | These are purely for your convenience; **EventManager** only uses the value to 105 | match events to listeners, so you are free to use any event codes you wish. The 106 | event parameter is also whatever you want it to be: for a key press event it 107 | could be the corresponding key code. For an analog event it could be the value 108 | read from that analog pin or a pin number. The event parameter will be passed 109 | to every listener that is associated with that event code. 110 | 111 | You post events using the `queueEvent()` function 112 | 113 | ```C++ 114 | gMyEventManager.queueEvent( EventManager::kEventUser0, 1234 ); 115 | ``` 116 | 117 | The `queueEvent()` function is lightweight and interrupt safe, so you can call 118 | it from inside an interrupt handler. 119 | 120 | By default the event queue holds 8 events, but you can make the queue any size 121 | you want by defining the macro `EVENTMANAGER_EVENT_QUEUE_SIZE` to whatever 122 | value you desire (see [Increase Event Queue Size](#increase-event-queue-size) below). 123 | 124 | 125 | ## Listeners 126 | 127 | Listeners are functions of type 128 | 129 | ```C++ 130 | typedef void ( *EventListener )( int eventCode, int eventParam ); 131 | ``` 132 | 133 | You add listeners using the `addListener()` function 134 | 135 | ```C++ 136 | void myListener( int eventCode, int eventParam ) 137 | { 138 | // Do something with the event 139 | } 140 | 141 | void setup() 142 | { 143 | gMyEventManager.addListener( EventManager::kEventUser0, myListener ); 144 | 145 | // Do more set up 146 | } 147 | ``` 148 | 149 | Do *not* add listeners from within an interrupt routine. 150 | 151 | By default the list of 152 | listeners holds 8 listeners, but you can make the list any size you want by 153 | defining the macro `EVENTMANAGER_LISTENER_LIST_SIZE` to whatever 154 | value you desire (see [Increase Listener List Size](#increase-listener-list-size) below). 155 | 156 | 157 | ## Processing Events 158 | 159 | To actually process events in the event queue and dispatch them to listeners you 160 | call the `processEvent()` function 161 | 162 | ```C++ 163 | void loop() 164 | { 165 | gMyEventManager.processEvent(); 166 | } 167 | ``` 168 | 169 | This call processes one event from the event queue every time it is called. 170 | The standard usage is to call `processEvent()` once in your `loop()` 171 | function so that one event is handled every time through the loop. This is 172 | usually more than adequate to keep up with incoming events. Events are 173 | normally processed in a first-in, first-out fashion (but see the section on 174 | `Event Priority` below). 175 | 176 | 177 | ## Example 178 | 179 | Here is a simple example illustrating how to blink the LED on pin 13 using 180 | **EventManager** 181 | 182 | ```C++ 183 | #include 184 | #include 185 | 186 | boolean pin13State; 187 | unsigned long lastToggled; 188 | 189 | EventManager gEM; 190 | 191 | // Our listener will simply toggle the state of pin 13 192 | void listener( int event, int param ) 193 | { 194 | // event and param are not used in this example function 195 | pin13State = pin13State ? false : true; 196 | digitalWrite( 13, pin13State ? HIGH : LOW ); 197 | lastToggled = millis(); 198 | } 199 | 200 | void setup() 201 | { 202 | // Setup 203 | pinMode( 13, OUTPUT ); 204 | digitalWrite( 13, HIGH ); 205 | pin13State = true; 206 | lastToggled = millis(); 207 | 208 | // Add our listener 209 | gEM.addListener( EventManager::kEventUser0, listener ); 210 | } 211 | 212 | void loop() 213 | { 214 | // Handle any events that are in the queue 215 | gEM.processEvent(); 216 | 217 | // Add events into the queue 218 | addPinEvents(); 219 | } 220 | 221 | // Add events to toggle pin 13 every second 222 | // NOTE: doesn't handle millis() turnover 223 | void addPinEvents() 224 | { 225 | if ( ( millis() - lastToggled ) > 1000 ) 226 | { 227 | gEM.queueEvent( EventManager::kEventUser0, 0 ); 228 | } 229 | } 230 | ``` 231 | 232 | The examples that come with the **EventManager** library (accessible via the 233 | Arduino `File/Examples` menu) provide more sophisticated illustrations of how 234 | you can use **EventManager**. 235 | 236 | 237 | ## Advanced Details 238 | 239 | ### Event Priority 240 | 241 | **EventManager** recognizes high and low priority events. You can specify the 242 | priority when you queue the event. By default, events are considered low 243 | priority. You indicate an event is high priority by passing an additional 244 | constant to `queueEvent()`, like so 245 | 246 | ```C++ 247 | gMyEventManager.queueEvent( EventManager::kEventUser0, 1234, EventManager::kHighPriority ); 248 | ``` 249 | 250 | The difference between high and low priority events is that `processEvent()` 251 | will process a high priority event ahead of any low priority 252 | events. In effect, high priority events jump to the front of the queue 253 | (multiple high priority events are processed first-in, 254 | first-out, but all of them are processed before any low priority events). 255 | 256 | Note that if high priority events are queued faster than low priority events, 257 | EventManager may never get to processing any of the low priority 258 | events. So use high priority events judiciously. 259 | 260 | 261 | ### Interrupt Safety 262 | 263 | **EventManager** was designed to be interrupt safe, so that you can queue events 264 | both from within interrupt handlers and also from normal functions without 265 | having to worry about queue corruption. However, this safety comes at the price 266 | of slightly slower `queueEvent()` and `processEvent()` functions and the 267 | need to globally disable interrupts while certain small snippets of code are 268 | executing. 269 | 270 | 271 | ### Processing All Events 272 | 273 | Normally calling `processEvent()` once every time through the `loop()` 274 | function is more than adequate to service incoming events. However, there may 275 | be times when you want to process all the events in the queue. For this purpose 276 | you can call `processAllEvents()`. Note that if you call this function at the 277 | same time that a series of events are being rapidly added to the queue 278 | asynchronously (via interrupt handlers), the `processAllEvents()` function 279 | might not return until the series of additions to the event queue stops. 280 | 281 | 282 | ### Increase Event Queue Size 283 | 284 | Define `EVENTMANAGER_EVENT_QUEUE_SIZE` to whatever size you need at 285 | the very beginning of `EventManager.h` like so 286 | 287 | ```C++ 288 | #ifndef EventManager_h 289 | #define EventManager_h 290 | 291 | #define EVENTMANAGER_EVENT_QUEUE_SIZE 16 292 | 293 | #include 294 | ``` 295 | 296 | If you are using the Arduino IDE, it is not enough to define this constant the 297 | usual C/C++ way by defining the constant *before* including `EventManager.h` 298 | in your own files. This is because the Arduino IDE has no way to pass the 299 | definition to the library code unless you actually edit `EventManager.h`. The 300 | Arduino IDE lacks a way to pass precompile constants to all the files in the 301 | project. Given that the underlying compiler is GCC, it would be nice if the 302 | Arduino IDE had a dialog to set things like `-D EVENTMANAGER_EVENT_QUEUE_SIZE=16` 303 | and have this constant definition passed directly to the compiler. 304 | 305 | The event queue requires `4*sizeof(int) = 8` bytes for each unit of size. 306 | There is a factor of 4 (instead of 2) because internally **EventManager** 307 | maintains two separate queues: a high-priority queue and a low-priority queue. 308 | 309 | 310 | ### Increase Listener List Size 311 | 312 | Define `EVENTMANAGER_LISTENER_LIST_SIZE` to whatever size you need at 313 | the very beginning of `EventManager.h` like so 314 | 315 | ```C++ 316 | #ifndef EventManager_h 317 | #define EventManager_h 318 | 319 | #define EVENTMANAGER_LISTENER_LIST_SIZE 16 320 | 321 | #include 322 | ``` 323 | 324 | If you are using the Arduino IDE, it is not enough to define this constant the 325 | usual C/C++ way by defining the constant *before* including `EventManager.h` 326 | in your own files. This is because the Arduino IDE has no way to pass the 327 | definition to the library code unless you actually edit `EventManager.h`. The 328 | Arduino IDE lacks a way to pass precompile constants to all the files in the 329 | project. Given that the underlying compiler is GCC, it would be nice if the 330 | Arduino IDE had a dialog to set things like `-D EVENTMANAGER_LISTENER_LIST_SIZE=16` 331 | and have this constant definition passed directly to the compiler. 332 | 333 | The listener list requires `sizeof(*f()) + sizeof(int) + sizeof(boolean) = 5` 334 | bytes for each unit of size. 335 | 336 | 337 | ### Additional Features 338 | 339 | There are various class functions for managing the listeners: 340 | 341 | * You can remove listeners (`removeListener()`), 342 | * Disable and enable specific listeners (`enableListener()`), 343 | * Set a default listener that will handle any events not handled by other listeners and manipulate the default listener just like any other listener (`setDefaultListener()`, `removeDefaultListener()`, and `enableDefaultListener()`) 344 | * Check the status of the listener list (`isListenerListEmpty()`, `isListenerListFull()`) 345 | 346 | There are various class functions that provide information about the event 347 | queue: 348 | 349 | * Check the status of the event queue (`isEventQueueEmpty()`, `isEventQueueFull()`) 350 | * See how many events are in the queue (`getNumEventsInQueue()`) 351 | 352 | For details on these functions you should review *EventManager.h*. 353 | 354 | 355 | ## Feedback 356 | 357 | If you find a bug or if you would like a specific feature, please report it at: 358 | 359 | https://github.com/igormiktor/arduino-EventManager/issues 360 | 361 | If you would like to hack on this project, don't hesitate to fork it on GitHub. 362 | If you would like me to incorporate changes you made, don't hesitate to send me 363 | a Pull Request. 364 | 365 | 366 | ## Credits 367 | 368 | **EventManager** was inspired by and adapted from the `Arduino Event System 369 | library` created by mromani@ottotecnica.com of OTTOTECNICA Italy, which was 370 | kindly released under a LGPL 2.1 license. 371 | 372 | 373 | ## License 374 | 375 | This library is free software; you can redistribute it and/or modify it under 376 | the terms of the GNU Lesser General Public License as published by the Free 377 | Software Foundation; either version 2.1 of the License, or (at your option) any 378 | later version. 379 | 380 | This library is distributed in the hope that it will be useful, but WITHOUT ANY 381 | WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A 382 | PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. 383 | 384 | A copy of the license is included in the **EventManager** package. 385 | 386 | 387 | ## Copyright 388 | 389 | Copyright (c) 2016 Igor Mikolic-Torreira 390 | 391 | Portions are Copyright (c) 2010 OTTOTECNICA Italy 392 | 393 | 394 | --------------------------------------------------------------------------------