Module LightSensor
[hide private]
[frames] | no frames]

Source Code for Module LightSensor

 1  # LightSensor.py 
 2  # Remote mode 
 3   
 4  ''' 
 5   This software is part of the raspibrick module. 
 6   It is Open Source Free Software, so you may 
 7   - run the code for any purpose 
 8   - study how the code works and adapt it to your needs 
 9   - integrate all or parts of the code in your own programs 
10   - redistribute copies of the code777 
11   - improve the code and release your improvements to the public 
12   However the use of the code is entirely your responsibility. 
13   ''' 
14   
15  from RobotInstance import RobotInstance 
16  from Tools import Tools 
17   
18 -class LightSensor():
19 ''' 20 Class that represents an light sensor. 21 '''
22 - def __init__(self, id, **kwargs):
23 ''' 24 Creates a light sensor instance with given id. 25 IDs: 0: front left, 1: front right, 2: rear left, 3: rear right 26 The following global constants are defined: 27 LS_FRONT_LEFT = 0, LS_FRONT_RIGHT = 1, LS_REAR_LEFT = 2, LS_REAR_RIGHT = 3. 28 @param id: the LightSensor identifier 29 ''' 30 self.id = id 31 self.device = "lss" + str(id) 32 self.sensorState = "DARK" 33 self.sensorType = "LightSensor" 34 self.triggerLevel = 500 35 self.brightCallback = None 36 self.darkCallback = None 37 for key in kwargs: 38 if key == "bright": 39 self.brightCallback = kwargs[key] 40 elif key == "dark": 41 self.darkCallback = kwargs[key] 42 robot = RobotInstance.getRobot() 43 if robot == None: # deferred registering, because Robot not yet created 44 RobotInstance._partsToRegister.append(self) 45 else: 46 self._setup(robot)
47
48 - def _setup(self, robot):
49 robot.sendCommand(self.device + ".create") 50 if self.brightCallback != None or self.darkCallback != None: 51 robot.registerSensor(self)
52
53 - def getValue(self):
54 ''' 55 Returns the current intensity value (0..1000). 56 @return: the measured light intensity 57 @rtype: int 58 ''' 59 Tools.delay(1) 60 self._checkRobot() 61 return int(RobotInstance.getRobot().sendCommand(self.device + ".getValue"))
62
63 - def getTriggerLevel(self):
64 return self.triggerLevel
65
66 - def setTriggerLevel(self, level):
67 self.triggerLevel = level
68
69 - def getSensorState(self):
70 return self.sensorState
71
72 - def setSensorState(self, state):
73 self.sensorState = state
74
75 - def getSensorType(self):
76 return self.sensorType
77
78 - def onBright(self, v):
79 if self.brightCallback != None: 80 self.brightCallback(self.id, v)
81
82 - def onDark(self, v):
83 if self.darkCallback != None: 84 self.darkCallback(self.id, v)
85
86 - def _checkRobot(self):
87 if RobotInstance.getRobot() == None: 88 raise Exception("Create Robot instance first")
89