listener.rst 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. ..
  2. Copyright 2014 Modelling, Simulation and Design Lab (MSDL) at
  3. McGill University and the University of Antwerp (http://msdl.cs.mcgill.ca/)
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. Listening to realtime simulation
  14. ================================
  15. During realtime simulation, there frequently exists the need to listen to specific ports, monitoring the events passing over them. In PythonPDEVS, it is possible to register a function that is invoked for each event passing over that port. This is called a *listener* in PythonPDEVS.
  16. Example model
  17. -------------
  18. We can simply reuse the traffic light model from the previous section on realtime simulation (:download:`trafficLightModel.py <trafficLightModel.py>`). All that needs to be changed now, is adding a listener on an output port of a *coupled* DEVS model. First and foremost, therefore, we must put our traffic light in a container::
  19. class TrafficLightSystem(CoupledDEVS):
  20. def __init__(self):
  21. CoupledDEVS.__init__(self, "System")
  22. self.light = self.addSubModel(TrafficLight("Light"))
  23. self.observed = self.addOutPort(name="observed")
  24. In the experiment file, it is then possible to register a listener on this port as follows (:download:`injection.py <injection.py>`)::
  25. def my_function(event):
  26. print("Observed the following event: " + str(event))
  27. sim.setListenPorts(model.observed, my_function)
  28. Since this function is invoked with the complete bag, the received event will contain a list of events, exactly as how it would be invoked in the external transition function.
  29. .. note:: Listeners are only supported on output ports of Coupled DEVS models. This is because the listeners are invoked upon event routing, for which the source port is not checked.