Package SmootLight :: Package behaviors :: Module SwitchBehavior
[hide private]
[frames] | no frames]

Source Code for Module SmootLight.behaviors.SwitchBehavior

 1  from operationscore.Behavior import * 
 2  import util.ComponentRegistry as compReg 
 3  import json 
 4   
5 -class SwitchBehavior(Behavior):
6 """ 7 SwitchBehavior is a behavior that transform into different behaviors base on the input data. 8 The behavior expects a JSON formatted argument 'PrefixToBehavior' that maps prefixes to behaviors. The behavior detects the prefix on the data and use the corresponding Behavior to process the data and return the outputs. 9 In Config file, include: 10 <PrefixToBehavior>JSON format dict with prefix keys and behavior ID values</PrefixToBehavior> 11 <DefaultBehavior>Default behavior's ID</DefaultBehavior> 12 An example config excerpt: 13 <Behavior> 14 <Class>behaviors.SwitchBehavior</Class> 15 <Args> 16 <Id>switch</Id> 17 <PrefixToBehavior>{'@':'game1', '#':'game2', '$':'game3'}</PrefixToBehavior> 18 <DefaultBehavior>game1</DefaultBehavior> 19 </Args> 20 </Behavior> 21 """
22 - def behaviorInit(self):
23 self.defaultBehavior = compReg.getComponent(self['DefaultBehavior']) 24 self.prefixDict = json.loads(self['PrefixToBehavior']) 25 self.currBehavior = None 26 self.setBehavior(self.defaultBehavior)
27
28 - def processResponse(self, sInputs, rInputs):
29 dataStr = sInputs[-1]['Data'] 30 if dataStr[0] in self.prefixDict: 31 self.setBehavior(compReg.getComponent(self.prefixDict[dataStr[0]])) 32 sInputs[-1]['Data'] = sInputs[-1]['Data'][1:] # remove prefix 33 return self.currBehavior.processResponse(sInputs, rInputs)
34
35 - def setBehavior(self, behavior):
36 self.currBehavior = behavior
37