1. 创建组件
POX提供一系列API,使用户可以创建自己的组件,实现自己的功能
组件的注册
创建的组件需要注册到core中,使用core的一个主要目的就是为各个组件提供一个集结地。core是类POXcore的一个实例。
向core注册组件,有两种方法
(1)core.register()
register()方法注册一个类(组件)实例,使用两个参数,第一个参数是组件注册到core的名称,第二参数是组件实例
例子:
#!/usr/bin/python from pox.core import core class MyComponent(object): def __init__(self, an_arg): self.arg = an_arg print "MyComponent instance registered with arg:", self.arg def message(self): print "MyComponent with arg:", self.arg def launch(): component = MyComponent("chosen") core.register("square", component) core.square.message()
(2)core.registerNew()
registerNew()方法注册一个类(组件),若该组件有_core_name属性,则注册到core的组件名称为_core_name的值,否则就是类名称本身
例子
#!/usr/bin/python from pox.core import core class MyComponent(object): _core_name = "square" def __init__(self, an_arg): self.arg = an_arg print "MyComponent instance registered with arg:", self.arg def message(self): print "MyComponent with arg:", self.arg def launch(): core.registerNew(MyComponent, "chosen") core.square.message() #注意此处是用组件名称‘square’调用组件的函数
2. POX事件机制
POX的事件处理符合发布/订阅模式(publish/subscribe paradigm)。
某个对象publish事件(在revent术语中,称为”raising“一个事件,也叫“sourcing”,“firing”,“dispatching”事件)
另外的对象可以在这个对象上subscribe指定的事件(在revent术语中,称为“listening to”,也叫“handling”,或者“sinking”)
POX中的事件都是revent.Event的子类, raise事件的类继承自EventMixin, EventMixin中有个类级别变量_eventMixin_Events,在其中声明所需raise的事件
(1) 创建自己的事件类型,继承自Event
class RunningStarted(Event): def __init__(self, name = "nike"): Event.__init__(self) self.name = name @property def runner_start(self): return self.name == "nike"
(2) 创建raise事件的类,继承自EventMixin
class Game(EventMixin): _eventMixin_events = set([ RunningStarted, ])
(3) 创建处理事件的函数,通常带有一个参数,即event对象本身
def start_run(event): print "it's time now, start running"
(4) 侦听事件(侦听事件的方法有addListener()、addListenerByName()和addListeners())
侦听事件前创建类Game的实例game
game = Game()
侦听事件RunningStarted
game.addListener(RunningStarted, start_run)
(5) raise事件
game.raiseEvent(RunningStarted("nike")
注意:必须先侦听事件,再raise事件
(6) 最后注册组件
def launch(): core.registerNew(Game)
整个代码实现
from pox.lib.revent.revent import EventMixin, Event from pox.core import core # creating your owen Event Types class RunningStarted(Event): def __init__(self, name = "nike"): Event.__init__(self) self.name = name @property def runner_start(self): return self.name == "nike" class RunningFinished(Event): def __init__(self, name = "nike"): Event.__init__(self) self.name = name class Game(EventMixin): _eventMixin_events = set([ RunningStarted, RunningFinished, ]) class Runner(object): def __init__(self): game.addListeners(self) def _handle_RunningStarted(self, event): print "run now" def _handle_RunningFinished(self, event): print "stop run" game = Game() def launch(): core.registerNew(Game) core.registerNew(Runner) game.raiseEvent(RunningStarted("nike")) game.raiseEvent(RunningFinished("nike"))