DeviceEvent - fdechaumont/micecraft GitHub Wiki

A DeviceEvent is an object that is transferred from devices to callback (listeners)

Its class is defined as follow:

from datetime import datetime

class DeviceEvent(object):

    def __init__(self, deviceType : str , deviceObject : object , description : str , data=None ):
        
        self.deviceType = deviceType
        self.deviceObject = deviceObject
        self.description = description
        
        self.data = data
        self.datetime = datetime.now()

Basic usage example:

If an object needs to send an event to another, it will create an event and fire it to listener. The DeviceEvent contains the generic name of the device, the instance of the caller, a description and a data field specific to the caller.

    myDeviceEvent = DeviceEvent( "gate", gate, "animal in A", myData )
    callBack( myDeviceEvent )

Using the DeviceEvent to send messages

Typically, if you send events within your object, you need other objects to be able to register to receive your messages. So you should get a structure like this one in your object:

class YourObject(object):

    def __init__(self):
        self.deviceListenerList = [] # list of listeners

    def _fireEvent(self, deviceEvent ): # used to send events to all your listeners
        for listener in self.deviceListenerList:
            listener( deviceEvent )

    def addDeviceListener(self , listener ): # other object can register their callback here
        self.deviceListenerList.append( listener )
        
    def removeDeviceListener(self , listener ):
        self.deviceListenerList.remove( listener )

[!TIP] Note that several objects can register to your object to listen to it.

[!TIP] You can also use the DeviceEvent to send messages between objects, no need to have devices to use it.

How client/user is expected to use it:

  • You can expect your user to check on the deviceType to get the generic name of the device ("gate","lever","fed3","touchscreen")...
  • The user will check the source (the caller) by comparing the deviceObject to the instance he should have stored.
  • Description will most likely be parsed to search for specific strings in it.
  • Data field is specific to the caller and can typically be a list of values.

[!NOTE] User will tend to use the same callback for all the devices and sort events in the same function.

[!WARNING] Typical problem may appear if a user launches an action within the callback that triggers a new event. In that case your user enters in a recursive call and will crash.