Tekkotsu Homepage
Demos
Overview
Downloads
Dev. Resources
Reference
Credits

EventBase.h

Go to the documentation of this file.
00001 //-*-c++-*-
00002 #ifndef INCLUDED_EventBase_h
00003 #define INCLUDED_EventBase_h
00004 
00005 #include "Shared/get_time.h"
00006 #include "Shared/XMLLoadSave.h"
00007 #include "Shared/FamilyFactory.h"
00008 #include <string>
00009 
00010 //! Forms the basis of communication between modules/behaviors in the framework
00011 /*! 
00012  *  Events are defined by a 3-tuple:
00013  *  - The @b generator indicates the class of the creator of the event, and in practice also generally implies the type (i.e. subclass) of the event itself.
00014  *  - The @b source indicates the instance of the creator of the event, which differentiates when more than one generator is available.
00015  *  - The @b type indicates the role of the event among other events from the source.
00016  *
00017  *  Each of these is represented by an ID, the #EventGeneratorID_t (EGID) and #EventTypeID_t (ETID) are
00018  *  defined here in EventBase.  Source IDs (SID) are defined separately by each generator, so the
00019  *  documentation in each entry of EventGeneratorID_t describes how to interpret the source field.
00020  *
00021  *  So for example, the button event which results from initially pressing the head button on an ERS-7
00022  *  robot would be:
00023  *  <center>(EventBase::buttonEGID, ERS7Info::HeadButOffset, EventBase::activateETID)</center>
00024  *
00025  *  While the button is held down, additional #statusETID events are used to report varying pressure values (if the button
00026  *  is pressure sensitive), and an event with #deactivateETID is sent when the button is released.
00027  *  Alternatively, an SID value from a vision detector (say #visObjEGID) refers to seeing a particular object, a completely
00028  *  different domain, values of which may overlap with other generators' source IDs.
00029  *  Thus, interpreting the source field requires knowing the generator as well.
00030  *
00031  *  When the generator doesn't have groups of activity with a 'begin' or 'end', it will use #statusETID
00032  *  for all of its events.  (in other words, not all generators necessarily have to use activate or deactivate)
00033  *  For example, sensor updates are continuously occuring, so you will only ever see
00034  *  <center>(EventBase::sensorEGID,SensorSrcID::UpdatedSID,EventBase::statusETID)</center>
00035  *  
00036  *  The #duration field is also generator specific - some may refer to
00037  *  the time since the last activation event (e.g. button events)
00038  *  where as others refer to time since last status (e.g. sensors
00039  *  updates)
00040  *
00041  *  If you want to make a new generator, all you have to do is add a new entry
00042  *  to the ID list (#EventGeneratorID_t) and then put its name in the 
00043  *  #EventGeneratorNames[] array.  Alternatively, there is an 'unlicensed spectrum' available under
00044  *  #unknownEGID.  You can send out events from that generator just
00045  *  like any other, but it should only be used for quick tests and hacking
00046  *  around...
00047  *
00048  *  The generator ID number is only that -- an ID number.  
00049  *  Events can be posted to the EventRouter anywhere, anytime,
00050  *  and do not require anything of the sender.  However, there is an EventGeneratorBase which
00051  *  can simplify some aspects of behaviors whose sole purpose is processing information
00052  *  and generating events.
00053  *
00054  *  If more information needs to be sent along with the event, the
00055  *  cleanest solution is to create a subclass of EventBase to hold the
00056  *  additional information.  For example, you can see the existing
00057  *  subclasses in the inheritance diagram above.  If you want to use a
00058  *  quick hack however, you could just pass a pointer to data as the SID if you
00059  *  don't need that field for something else, or use a DataEvent.
00060  *
00061  *  @note All subclasses must override getClassTypeID() and provide
00062  *  a unique value to allow fast polymorphic serialization for inter-process
00063  *  communication.  Implementing the load/save functions
00064  *  ({load,save}BinaryBuffer and {load,save}XML) for your addtional data fields
00065  *  would also be necessary in order to allow your event to be sent between
00066  *  processes, or eventually, between robots.
00067  * 
00068  *  @see EventRouter for discussion on sending and receiving of events
00069  *  @see Tutorials:
00070  *    - <a href="../FirstBehavior2.html">Steps 3, 4, & 5 of Tekkotsu's First Behavior Tutorial</a>
00071  *    - <a href="http://www.cs.cmu.edu/~dst/Tekkotsu/Tutorial/events.shtml">David Touretzky's Events Chapter</a>
00072  *    - <a href="http://www.cs.cmu.edu/afs/cs/academic/class/15494-s06/www/lectures/behaviors.pdf">CMU's Cognitive Robotics course slides</a>
00073  *    - <a href="../media/TekkotsuQuickReference_ERS7.pdf">ERS-7 Quick Reference Sheet</a>
00074  */
00075 class EventBase : public XMLLoadSave {
00076  public:
00077   //! Lists all possible event generator ids
00078   /*! An event generator is a abstract source of events, used for listening to and parsing certain classes of events
00079    *
00080    *  IF YOU ADD AN EVENT GENERATOR, DON'T FORGET TO NAME IT (EventBase::EventGeneratorNames, actual names are in EventBase.cc)*/
00081   enum EventGeneratorID_t {
00082     unknownEGID=0,    //!< default EGID, used if you forget to set it, probably not a good idea to use this for anything except errors or testing quick hacks
00083     aiEGID,           //!< not being used, yet (might use this when AI makes decisions?)
00084     audioEGID,        //!< Sends an event when a sound starts/ends playback, status events as chained sounds end; SID is SoundManager::Play_ID; duration is playtime
00085     buttonEGID,       //!< Sends activate event for button down, deactivate for button up.  Status events only for when pressure sensitive buttons' reading changes. (on sensorEGID updates); SIDs are from ButtonOffset_t in the namespace of the target model (e.g. ERS210Info::ButtonOffset_t); duration is button down time
00086     cameraResolutionEGID, //!< Sends a status event whenever the camera's resolution changes, such as a different camera than predicted by RobotInfo is being used, or a camera is hotswapped.  SID corresponds to the visOFbkEGID for that camera.
00087     erouterEGID,      //!< Sends activate event on first listener, deactivate on last listener, and status on other listener changes.; SID is the generator ID affected
00088     estopEGID,        //!< Sends an event when the estop is turned on or off; SID is the MotionManager::MC_ID of the EmergencyStopMC; duration is length of estop activation
00089     locomotionEGID,   //!< Sends events regarding transportation in the world; you can/should assume these will all be LocomotionEvent classes; SID is MotionManager::MC_ID of posting MotionCommand; duration is the time since last velocity change of that MC. (You could generate these for things other than walking...)
00090     lookoutEGID,      //!< Sends an event when Lookout request is complete; SID is the id for lookout request
00091     mapbuilderEGID,  //!< Sends a status event when map is completed
00092     micOSndEGID,      //!< Sends a DataEvent<OSoundVectorData> for every audio buffer received from the system; SID and duration are always 0 (This is generated by the MainObj instantiation of MMCombo)
00093     micRawEGID,       //!< reserved for future use
00094     micFFTEGID,       //!< reserved for future use
00095     micPitchEGID,       //!< Sends a PitchEvent when a particular frequency is detected; SID is a pointer to the PitchDetector, magnitude is product of amplitude and confidence
00096     motmanEGID,       //!< Sends events when a MotionCommand is added or removed, SID is is the MotionManager::MC_ID, duration is always 0; individual MotionCommands may throw status events to signal intermediary status
00097     pilotEGID,        //!< Sends events when position of agent is updated or pilot request is completed
00098     powerEGID,        //!< Sends events for low power warnings, temperature, etc. see PowerSrcID::PowerSourceID_t
00099     sensorEGID,       //!< Sends a status event when new sensor readings are available. see SensorSrcID::SensorSourceID_t
00100     stateMachineEGID, //!< Sends an event upon entering and leaving a StateNode; SID is pointer to the StateNode; duration is always 0; some state will throw a status event when they have completed their task and are now idling
00101     stateSignalEGID,  //!< Sends a DataEvent that can be monitored by a SignalTrans for triggering a state transition
00102     stateTransitionEGID, //!< Sends an event each time a transition is triggered; SID is a pointer to the transition; type is always status, duration is always 0; guaranteed to occur immediately *before* the transition actually occurs
00103     textmsgEGID,      //!< Sends status events when a text msg is received on console; generated by the Controller, SID is 0 if broadcast from ControllerGUI, 1 if "private" from BehaviorSwitchControl; duration is always 0 (see Controller for more information)
00104     timerEGID,        //!< Sends timer events; you set timers explicitly, you don't have to listen as well. (See EventRouter::addTimer()) There's no cross-talk, only the listener which requested the timer will receive it; SID is whatever you requested it to be; duration is the time (since boot, in ms) that the timer was supposed to go off; these are always status
00105     visOFbkEGID,      //!< Sends a DataEvent < OFbkImageVectorData > for every camera image received from the system; SID and duration are always 0 (This is generated by the MainObj instantiation of MMCombo)
00106     visRawCameraEGID, //!< Sends a FilterBankEvent when new raw camera images are available; SID is whatever value you gave during setup (typically in StartupBehavior_SetupVision.cc), duration is always 0
00107     visInterleaveEGID,//!< Sends a FilterBankEvent when new interleaved images are available; SID is whatever value you gave during setup (typically in StartupBehavior_SetupVision.cc), duration is always 0
00108     visJPEGEGID,      //!< Sends a FilterBankEvent when JPEG compressed images are available; SID is whatever value you gave during setup (typically in StartupBehavior_SetupVision.cc), duration is always 0
00109     visPNGEGID,      //!< Sends a FilterBankEvent when PNG compressed images are available; SID is whatever value you gave during setup (typically in StartupBehavior_SetupVision.cc), duration is always 0
00110     visSegmentEGID,   //!< Sends a SegmentedColorFilterBankEvent when color segmentated images are available; SID is whatever value you gave during setup (typically in StartupBehavior_SetupVision.cc), duration is always 0
00111     visRLEEGID,       //!< Sends a SegmentedColorFilterBankEvent when RLE encoded color segmentated images are available; SID is whatever value you gave during setup (typically in StartupBehavior_SetupVision.cc), duration is always 0
00112     visRegionEGID,    //!< Sends a SegmentedColorFilterBankEvent when color regions are available; SID is whatever value you gave during setup (typically in StartupBehavior_SetupVision.cc), duration is always 0
00113     visObjEGID,       //!< Sends VisionObjectEvents for objects detected in camera images; SID is whatever value you gave during setup (typically in StartupBehavior_SetupVision.cc), duration is always 0
00114     wmVarEGID,        //!< Sends an event when a watched memory is changed; source id is pointer to WMEntry
00115     worldModelEGID,   //!< not being used, yet (for when objects are detected/lost?)
00116     remoteStateEGID,  //!< Sent when remote state is updated
00117     numEGIDs          //!< the number of generators available
00118   };
00119 
00120   //! Holds string versions of each of the generator's names, handy for debugging so you can output the events as readable strings (you'll find this in EventBase.cc since it can't go in the header or we get multiply-defined errors during linking)
00121   static const char* const EventGeneratorNames[numEGIDs];
00122   
00123   //! an event type id is used to denote whether it's the first in a sequence (button down), in a sequence (button still down), or last (button up)
00124   enum EventTypeID_t {
00125     activateETID,   //!< Start of an event sequence, e.g. button down
00126     statusETID,     //!< Indicates a value has changed, e.g. new sensor readings
00127     deactivateETID, //!< Last of a series of events, e.g. button up
00128     numETIDs        //!< the number of different event types
00129   };
00130   
00131   //! holds string versions of EventTypeID_t
00132   static const char* const EventTypeNames[numETIDs];
00133   
00134   //! holds abbreviated string versions of EventTypeID_t
00135   static const char* const EventTypeAbbr[numETIDs];
00136   
00137   //! type used for class ids in the type registry (see getTypeRegistry())
00138   typedef unsigned int classTypeID_t;
00139   
00140   //! type used for the type registry
00141   typedef FamilyFactory<EventBase,classTypeID_t> registry_t;
00142 
00143   //! returns a FamilyFactory with which you can look up classTypeID_t's to make new instances from serialized data
00144   static registry_t& getTypeRegistry();
00145   
00146   /*! @name Constructors/Destructors */
00147   //! constructor
00148   /*! @see EventRouter::postEvent() */
00149   EventBase(); 
00150   EventBase(EventGeneratorID_t gid, size_t sid, EventTypeID_t tid, unsigned int dur=0);
00151   EventBase(EventGeneratorID_t gid, size_t sid, EventTypeID_t tid, unsigned int dur, const std::string& n);
00152   EventBase(EventGeneratorID_t gid, size_t sid, EventTypeID_t tid, unsigned int dur, const std::string& n, float mag);
00153   virtual ~EventBase() {} //!< destructor
00154 
00155   //! allows a copy to be made of an event, supporting polymorphism
00156   /*! Must be overridden by all subclasses to allow this to happen
00157    * 
00158    *  I would like to switch this over to the cloneable interface once
00159    *  the compiler gets updated out of the 3.3 branch... see
00160    *  Cloneable::clone() for a discussion of the issue and
00161    *  implementation notes. */
00162   virtual EventBase* clone() const { return new EventBase(*this); }
00163   //@}
00164 
00165   /*! @name Methods */
00166   virtual const std::string& getName() const { return stim_id; } //!< gets the name of the event - useful for debugging output, see also getDescription()
00167   virtual EventBase& setName(const std::string& n); //!< sets name to a given string, prevents overwriting by generated names
00168 
00169   virtual float getMagnitude() const { return magnitude; } //!< gets "strength" of event - by default 1 for activate and status events, 0 for deactivate events
00170   virtual EventBase& setMagnitude(float m) { magnitude=m; return *this; }//!< sets "strength" of event - you may want to override the default values (see getMagnitude())
00171 
00172   virtual unsigned int getTimeStamp() const { return timestamp; } //!< time event was created
00173   virtual void setTimeStamp(unsigned int t) { timestamp=t; } //!< resets time event was created
00174 
00175   virtual EventGeneratorID_t getGeneratorID() const { return genID; } /*!< @brief gets the generator ID for this event @see EventGeneratorID_t */
00176   virtual EventBase& setGeneratorID(EventGeneratorID_t gid) { genID=gid; genName(); return *this; } /*!< @brief sets the generator ID for this event @see EventGeneratorID_t */
00177   
00178   virtual size_t getSourceID() const { return sourceID; } /*!< @brief gets the source ID for this event @see sourceID */
00179   virtual EventBase& setSourceID(size_t sid) { sourceID=sid; genName(); return *this; } /*!< @brief sets the source ID for this event @see sourceID */
00180   
00181   virtual EventTypeID_t getTypeID() const { return typeID; } /*!< @brief gets the type ID @see EventTypeID_t */
00182   virtual EventBase& setTypeID(EventTypeID_t tid) { typeID=tid; unsigned int n=strlen(EventTypeAbbr[typeID]); stim_id.replace(stim_id.size()-n-1,n,EventTypeAbbr[typeID]); return *this; } /*!< @brief sets the type ID @see EventTypeID_t */
00183 
00184 
00185   virtual int getHostID() const { return hostID; }
00186   virtual EventBase& setHostID(int host) { hostID = host; genName(); return *this; }
00187   
00188   virtual unsigned int getDuration() const { return duration; } /*!< @brief gets the time since the beginning of this sequence (the timestamp of the activate event) @see duration */
00189   virtual EventBase& setDuration(unsigned int d) { duration = d; return *this; }/*!< @brief sets the time since the beginning of this sequence (the timestamp of the activate event) @see duration */
00190 
00191   virtual const std::string& resetName() { nameisgen=true; genName(); return stim_id; } //!< resets name to generated form, overwriting any previous name
00192   virtual bool isCustomName() const { return !nameisgen; } //!< returns true if not using the generated name
00193 
00194   //! generates a description of the event with variable verbosity 
00195   /*! @param showTypeSpecific should be read by subclasses to add additional information
00196    *  @param verbosity can be one of the following values:
00197    *    - 0 - Basic: <i>event_name</i> \\t <i>generator_id</i> \\t <i>source_id</i> \\t <i>type_id</i>
00198    *    - 1 - Numerics: <i>event_name</i> \\t <i>generator_id</i> \\t <i>source_id</i> \\t <i>type_id</i>
00199    *    - 2 - Timing: <i>event_name</i> \\t <i>generator_id</i> \\t <i>source_id</i> \\t <i>type_id</i> \\t <i>duration</i> \\t <i>timestamp</i>
00200    *    - 3 and above - Full: <i>event_name</i> \\t <i>generator_id</i> \\t <i>source_id</i> \\t <i>type_id</i> \\t <i>duration</i> \\t <i>timestamp</i> \\t <i>magnitude</i>
00201    *  if showTypeSpecific, additional fields will be added after the common fields listed above. */
00202   virtual std::string getDescription(bool showTypeSpecific=true, unsigned int verbosity=0) const; 
00203 
00204   inline bool operator<(const EventBase& e) const { return timestamp<e.timestamp; }
00205 
00206   //! is true if the genID, typeID, and sourceID's all match
00207   virtual bool operator==(const EventBase& eb) const {
00208     return (sourceID==eb.sourceID && genID==eb.genID && typeID==eb.typeID);
00209   }
00210   //!tests to see if events have the same generator and source IDs
00211   bool sameGenSource(const EventBase& eb) const { return genID==eb.genID && sourceID==eb.sourceID; }
00212   
00213   bool longerThan(const EventBase& eb) const { return duration>eb.duration && *this==eb; } //!< compares event duration and ensures same event generator, source, and type - useful for event masks
00214   bool shorterThan(const EventBase& eb) const { return duration<eb.duration && *this==eb; }//!< compares event duration and ensures same event generator, source, and type - useful for event masks
00215   bool equalOrLongerThan(const EventBase& eb) const { return duration>=eb.duration && *this==eb; }//!< compares event duration and ensures same event generator, source, and type - useful for event masks
00216   bool equalOrShorterThan(const EventBase& eb) const { return duration<=eb.duration && *this==eb; }//!< compares event duration and ensures same event generator, source, and type - useful for event masks
00217   
00218   static bool isValidGeneratorID(unsigned int egid) { return egid<numEGIDs; }
00219   //@}
00220 
00221   //! Useful for serializing events to send between processes
00222   /*! @name LoadSave interface */
00223 
00224   //! All subclasses should override this and return a unique ID for their class.
00225   /*! All IDs corresponding to all-capital letters are reserved for future
00226    *  framework expansion.  (Thus, user subclasses should contain at least one
00227    *  lower-case letter.)  This code can be used when serializing to allow quick
00228    *  identification of the class type by the receiver. */
00229   virtual classTypeID_t getClassTypeID() const { return autoRegisterEventBase; }
00230 
00231   virtual unsigned int getBinSize() const; //!< should return the minimum size needed if using binary format (i.e. not XML)
00232   virtual unsigned int loadBinaryBuffer(const char buf[], unsigned int len); //!< load from binary format
00233   virtual unsigned int saveBinaryBuffer(char buf[], unsigned int len) const; //!< save to binary format
00234   virtual void loadXML(xmlNode* node); //!< load from XML format
00235   virtual void saveXML(xmlNode * node) const; //!< save to XML format
00236   
00237   //! no longer need to override this -- will automatically call either loadXML() or loadBinaryBuffer() based on #saveFormat
00238   /*! tries to be smart so if the load based on the current #saveFormat fails, retries with the alternative format */
00239   virtual unsigned int loadBuffer(const char buf[], unsigned int len)  {
00240     unsigned int test = saveFormat!=BINARY ? XMLLoadSave::loadBuffer(buf,len) : loadBinaryBuffer(buf,len);
00241     if(test!=0) //if the default didn't work, try the other format too...
00242       return test;
00243     return saveFormat!=BINARY ? loadBinaryBuffer(buf,len) : XMLLoadSave::loadBuffer(buf,len);
00244   }
00245   //! no longer need to override this -- will automatically call either saveXML() or saveBinaryBuffer() based on #saveFormat
00246   virtual unsigned int saveBuffer(char buf[], unsigned int len) const { return saveFormat!=BINARY ? XMLLoadSave::saveBuffer(buf,len) : saveBinaryBuffer(buf,len); }
00247 
00248   //! automatically calls either XMLLoadSave::loadFile or LoadSave::loadFile based on #saveFormat
00249   /*! tries to be smart so if the load based on the current #saveFormat fails, retries with the alternative format */
00250   virtual unsigned int loadFile(const char* filename) {
00251     unsigned int test = saveFormat!=BINARY ? XMLLoadSave::loadFile(filename) : LoadSave::loadFile(filename);
00252     if(test!=0) //if the default didn't work, try the other format too...
00253       return test;
00254     return saveFormat!=BINARY ? LoadSave::loadFile(filename) : XMLLoadSave::loadFile(filename);
00255   }
00256   //! automatically calls either XMLLoadSave::saveFile or LoadSave::saveFile based on #saveFormat
00257   virtual unsigned int saveFile(const char* filename) const { return saveFormat!=BINARY ? XMLLoadSave::saveFile(filename) : LoadSave::saveFile(filename); }
00258   
00259   //! automatically calls either XMLLoadSave::loadFileStream or LoadSave::loadFileStream based on #saveFormat
00260   virtual unsigned int loadFileStream(FILE* f) { return saveFormat!=BINARY ? XMLLoadSave::loadFileStream(f) : LoadSave::loadFileStream(f); }
00261   //! automatically calls either XMLLoadSave::loadFileStream or LoadSave::loadFileStream based on #saveFormat
00262   virtual unsigned int saveFileStream(FILE* f) const { return saveFormat!=BINARY ? XMLLoadSave::saveFileStream(f) : LoadSave::saveFileStream(f); }
00263   
00264   //! values to pass to setSaveFormat()
00265   enum SaveFormat {
00266     BINARY, //!< saves will be in packed binary, loads will try binary first
00267     XML //!< saves will be in xml, loads will try xml first
00268   };
00269   virtual void setSaveFormat(SaveFormat sf) const { saveFormat=sf; } //!< set #saveFormat
00270   virtual SaveFormat getSaveFormat() const { return saveFormat; } //!< return #saveFormat
00271   //@}
00272   
00273  protected:
00274   //! converts the first 4 characters of @a str to an unsigned int, should ensure consistent byte ordering across platforms
00275   static unsigned int makeClassTypeID(const char* str) {
00276 #if LOADSAVE_SWAPBYTES
00277     unsigned int x;
00278     byteswap(x,*reinterpret_cast<const unsigned int*>(str));
00279     return x;
00280 #else
00281     return *reinterpret_cast<const unsigned int*>(str);
00282 #endif
00283   }
00284 
00285   std::string stim_id; //!< the name of the event, use the same name consistently or else will be seen as different stimuli
00286   float magnitude; //!< the current "strength" of the event/stimuli... MAKE SURE this gets set to ZERO IF event is DEACTIVATE
00287   unsigned int timestamp; //!< the time the event was created - set automatically by constructor
00288 
00289   mutable SaveFormat saveFormat; //!< controls the format used during the next call to saveBuffer() (packed binary or XML)
00290 
00291   bool nameisgen; //!< tracks whether the current name (stim_id) was generated by genName() (true) or setName() (false)
00292   virtual void genName(); //!< calls setName() with a string version of sourceID, decimal notation
00293 
00294   EventGeneratorID_t genID; //!< generator ID, see EventGeneratorID_t
00295   EventTypeID_t typeID; //!< type ID, see EventTypeID_t
00296   size_t sourceID;       /*!< @brief the source ID for this event
00297                           * Source IDs are defined by the generator that made it.  This should
00298                           * give authors flexibility to design their modules without having to
00299                           * worry about ID space collision */
00300   int hostID;
00301   unsigned int duration; /*!< @brief the time since this sequence started (like, how long the
00302                           *   button has been pressed); not all generators will set this;
00303                           *   Typically, this would be 0 for activate,
00304                           *   (activate.timestamp-::get_time()) for status and deactivate */
00305 
00306   //! causes class type id to automatically be regsitered with EventBase's FamilyFactory (getTypeRegistry())
00307   static const EventBase::classTypeID_t autoRegisterEventBase;
00308 };
00309 
00310 /*! @file
00311  * @brief Describes EventBase, the basic class for sending events around the system
00312  * @author ejt (Creator)
00313  *
00314  * $Author: ejt $
00315  * $Name: tekkotsu-4_0 $
00316  * $Revision: 1.57 $
00317  * $State: Exp $
00318  * $Date: 2007/11/13 04:16:02 $
00319  */
00320 
00321 #endif

Tekkotsu v4.0
Generated Thu Nov 22 00:54:52 2007 by Doxygen 1.5.4