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

Source Code for Module InfraredSensor

 1  # InfraredSensor.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 code 
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 InfraredSensor():
19 ''' 20 Class that represents an infrared sensor. 21 '''
22 - def __init__(self, id, **kwargs):
23 ''' 24 Creates an infrared sensor at given port. 25 For the Pi2Go the following infrared sensors are used: 26 id = 0: front center; id = 1: front left; id = 2: front right; 27 id = 3: line left; id = 4: line right. The following global constants are defined: 28 IR_CENTER = 0, IR_LEFT = 1, IR_RIGHT = 2, IR_LINE_LEFT = 3, IR_LINE_RIGHT = 4 29 @param id: sensor identifier 30 ''' 31 self.id = id 32 self.device = "irs" + str(id) 33 self.sensorState = "PASSIVATED" 34 self.sensorType = "InfraredSensor" 35 self.activateCallback = None 36 self.passivateCallback = None 37 for key in kwargs: 38 if key == "activated": 39 self.activateCallback = kwargs[key] 40 elif key == "passivated": 41 self.passivateCallback = 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 Tools.debug("InfraredSensor instance with ID " + str(id) + " created")
48
49 - def _setup(self, robot):
50 robot.sendCommand(self.device + ".create") 51 if self.activateCallback != None or self.passivateCallback != None: 52 robot.registerSensor(self)
53
54 - def getValue(self):
55 ''' 56 Checks, if reflected light is detected. 57 @return: 1, if the sensor detects reflected light; otherwise 0 58 @rtype: int 59 ''' 60 Tools.delay(1) 61 self._checkRobot() 62 return int(RobotInstance.getRobot().sendCommand(self.device + ".getValue"))
63
64 - def getSensorState(self):
65 return self.sensorState
66
67 - def setSensorState(self, state):
68 self.sensorState = state
69
70 - def getSensorType(self):
71 return self.sensorType
72
73 - def onActivated(self):
74 if self.activateCallback != None: 75 self.activateCallback(self.id)
76
77 - def onPassivated(self):
78 if self.passivateCallback != None: 79 self.passivateCallback(self.id)
80
81 - def _checkRobot(self):
82 if RobotInstance.getRobot() == None: 83 raise Exception("Create Robot instance first")
84