本文整理汇总了Python中driver.Driver.stop方法的典型用法代码示例。如果您正苦于以下问题:Python Driver.stop方法的具体用法?Python Driver.stop怎么用?Python Driver.stop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类driver.Driver
的用法示例。
在下文中一共展示了Driver.stop方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: rGPIO
# 需要导入模块: from driver import Driver [as 别名]
# 或者: from driver.Driver import stop [as 别名]
class rGPIO(object):
def __init__(self, logger):
self.logger = logger
logger.info("Starting GPIODaemon...")
self.driver = Driver()
logger.info("Initialized driver")
def handle_cmd(self, cmd):
# New handle command class that's simpler
cmd = cmd.strip()
self.logger.info("cmd: '%s'" % cmd)
return self._handle_cmd(cmd)
def _handle_cmd(self, internal_cmd):
# Internal cmd is the actual command (triggered by the user command).
# Any return value will be sent to the socket connection.
self.logger.info("execute> %s" % internal_cmd)
cmd_parts = internal_cmd.split(" ")
cmd = cmd_parts[0]
if cmd == "forward":
self.logger.info("in command forward")
self.driver.forward()
return "going forward"
elif cmd == "turn_left":
self.logger.info("in command turn_left")
self.driver.turn_left()
return "turn left"
elif cmd == "turn_right":
self.logger.info("in command turn_right")
self.driver.turn_right()
return "turning_right"
elif cmd == "stop":
self.logger.info("in command stop")
self.driver.stop()
return "stop"
elif cmd == "backward":
self.logger.info("in command backward")
self.driver.backward()
return "backwards"
else:
self.logger.warn("command '%s' not recognized", cmd)
示例2: Connection
# 需要导入模块: from driver import Driver [as 别名]
# 或者: from driver.Driver import stop [as 别名]
#.........这里部分代码省略.........
@rtype: Session
@return: the named Session
"""
if name is None:
name = "%s:%s" % (self.id, self.session_counter)
self.session_counter += 1
else:
name = "%s:%s" % (self.id, name)
if self.sessions.has_key(name):
return self.sessions[name]
else:
ssn = Session(self, name, transactional)
self.sessions[name] = ssn
self._wakeup()
return ssn
@synchronized
def _remove_session(self, ssn):
self.sessions.pop(ssn.name, 0)
@synchronized
def open(self, timeout=None):
"""
Opens a connection.
"""
if self._open:
raise ConnectionError("already open")
self._open = True
if self.reconnect and self.reconnect_timeout > 0:
timeout = self.reconnect_timeout
self.attach(timeout=timeout)
@synchronized
def opened(self):
"""
Return true if the connection is open, false otherwise.
"""
return self._open
@synchronized
def attach(self, timeout=None):
"""
Attach to the remote endpoint.
"""
if not self._connected:
self._connected = True
self._driver.start()
self._wakeup()
if not self._ewait(lambda: self._transport_connected and not self._unlinked(), timeout=timeout):
self.reconnect = False
raise Timeout("Connection attach timed out")
def _unlinked(self):
return [
l
for ssn in self.sessions.values()
if not (ssn.error or ssn.closed)
for l in ssn.senders + ssn.receivers
if not (l.linked or l.error or l.closed)
]
@synchronized
def detach(self, timeout=None):
"""
Detach from the remote endpoint.
"""
if self._connected:
self._connected = False
self._wakeup()
cleanup = True
else:
cleanup = False
try:
if not self._wait(lambda: not self._transport_connected, timeout=timeout):
raise Timeout("detach timed out")
finally:
if cleanup:
self._driver.stop()
self._condition.gc()
@synchronized
def attached(self):
"""
Return true if the connection is attached, false otherwise.
"""
return self._connected
@synchronized
def close(self, timeout=None):
"""
Close the connection and all sessions.
"""
try:
for ssn in self.sessions.values():
ssn.close(timeout=timeout)
finally:
self.detach(timeout=timeout)
self._open = False
示例3:
# 需要导入模块: from driver import Driver [as 别名]
# 或者: from driver.Driver import stop [as 别名]
time.sleep(.2)
robot1.right()
time.sleep(1)
robot1.backward()
time.sleep(.2)
robot1.backRight()
time.sleep(1)
robot1.forward()
time.sleep(.2)
robot1.right()
time.sleep(1)
robot1.backward()
time.sleep(.2)
robot1.backRight()
time.sleep(1)
robot1.stop()
robot1.forward()
time.sleep(.2)
robot1.left()
time.sleep(1)
robot1.backward()
time.sleep(.2)
robot1.backLeft()
time.sleep(1)
robot1.forward()
time.sleep(.2)
robot1.left()
time.sleep(1)
robot1.backward()
time.sleep(.2)
robot1.backLeft()
示例4: __init__
# 需要导入模块: from driver import Driver [as 别名]
# 或者: from driver.Driver import stop [as 别名]
class ElevatorWrapper:
topFloor = 3
botFloor = 0
def __init__(self):
self.elevator = Driver()
self.direction = 0
self.lastFloor = self.getFloor() if self.getFloor() != None else -1
self.destination = 0
self.externalFloorListener = None
self.stop = self.elevator.stop
self.addListener = self.elevator.addListener
for i, floor in enumerate(INPUT.SENSORS):
self.elevator.addListener(floor, partial(self.floorListener, i))
self.addListener(INPUT.STOP, self.stopstruction)
self.addListener(INPUT.OBSTRUCTION, self.stopstruction)
def moveToFloor(self, floor):
if self.elevator.readChannel(INPUT.OBSTRUCTION):
print "Obstruction"
return
if floor > self.topFloor:
print "Too much floor: %i > %i , WAT" % (floor, self.topFloor)
return
print "Moving to floor", floor
if floor > self.lastFloor:
print "Going up"
self.elevator.move(OUTPUT.MOTOR_UP)
self.direction = 1
elif floor < self.lastFloor:
print "Going down"
self.elevator.move(OUTPUT.MOTOR_DOWN)
self.direction = 0
else:
print "Open doors"
self.destination = floor
def floorListener(self, floor, en, to): # TODO: en, to
print "At floor", floor
if floor == self.destination and self.floorListener == None:
print "At destination"
self.elevator.stop()
elif floor >= self.topFloor and self.direction == 1:
print "Stop it! (top)", floor, self.topFloor, self.direction
self.elevator.stop()
elif floor <= self.botFloor and self.direction == 0:
print "Stop it! (bot)", floor, self.botFloor, self.direction
self.elevator.stop()
"""if self.lastFloor < floor: self.direction = 1
elif self.lastFloor > floor: self.direction = 0
else: print "derp" """
self.lastFloor = floor;
print type(floor)
self.elevator.setFloorIndicator(floor)
self.externalFloorListener(floor)
def buttonListener(self, where, what, floor, en, to): #TODO en, to
print where, what, floor
if where == "in":
self.moveToFloor(floor)
elif where == "out":
if what == "up":
self.moveToFloor(floor)
elif what == "down":
self.moveToFloor(floor)
else:
raise ValueError("Invalid \"where\"")
def stopstruction(self, en, to): # TODO: en, to
self.elevator.stop()
if self.lastFloor % 1.0 != 0.5 and self.getFloor() == None: self.lastFloor = self.lastFloor + (0.5 if self.direction else -0.5)
print "Stopped, now at", self.lastFloor
def isObstructed(self):
return self.elevator.readChannel(INPUT.OBSTRUCTION)
def down(self):
self.elevator.move(OUTPUT.MOTOR_DOWN)
sleep(2.0)
self.elevator.stop()
def getFloor(self):
return self.elevator.getCurrentFloor()
def addButtonListener(self, listener):
self.addListener(INPUT.FLOOR_UP1, partial(listener, "out", "up", 0))
self.addListener(INPUT.FLOOR_UP2, partial(listener, "out", "up", 1))
self.addListener(INPUT.FLOOR_UP3, partial(listener, "out", "up", 2))
self.addListener(INPUT.FLOOR_DOWN2, partial(listener, "out", "down", 1))
#.........这里部分代码省略.........
示例5: __init__
# 需要导入模块: from driver import Driver [as 别名]
# 或者: from driver.Driver import stop [as 别名]
class FieldRobot:
rowWidth = 0.75
rowPotsWidth = 0 #0.45
def __init__( self, robot, configFilename, verbose = False ):
self.robot = robot
self.robot.insideField = True
# self.robot.fnSpeedLimitController = [self.robot.pauseSpeedFn]
self.robot.fnSpeedLimitController = []
self.robot.addExtension( emergencyStopExtension )
# self.robot.attachGPS()
self.robot.attachLaser( remission=True )
self.robot.laser.stopOnExit = False # for faster boot-up
# self.robot.attachCamera( cameraExe = "../robotchallenge/rc" ) # TODO what was used?!
# self.robot.attachCamera( cameraExe = "../robotchallenge/redcone" ) # FRE2015 - task2
self.robot.attachCamera( cameraExe = "../robotchallenge/dark" ) # FRE2015 - task3
self.robot.attachHand()
self.robot.rfidData = None # hack 2013
self.robot.gpsData = None
self.driver = Driver( self.robot, maxSpeed = 0.7, maxAngularSpeed = math.radians(60) )
# self.robot.localisation = KalmanFilter() # needed for better direction handling
self.robot.localisation = SimpleOdometry()
self.verbose = verbose
self.configFilename = configFilename
self.rowHeading = None
def waitForStart( self ):
print "Waiting for start cable insertion ..."
while self.robot.startCableIn is None or not self.robot.startCableIn:
self.robot.setSpeedPxPa( 0.0, 0.0 )
self.robot.update()
print "READY & waiting for start ..."
while self.robot.startCableIn is None or self.robot.startCableIn:
self.robot.setSpeedPxPa( 0.0, 0.0 )
if self.robot.laserData:
self.robot.toDisplay = 'O'
if self.robot.remissionData:
self.robot.toDisplay = 'R'
else:
self.robot.toDisplay = '-'
if self.robot.rfidData:
self.robot.toDisplay += str( self.robot.rfidData[0] % 10 )
else:
self.robot.toDisplay += '-'
self.robot.update()
print "!!! GO !!!"
def ver2( self, code, detectWeeds = True, detectBlockedRow = True ):
print "Field Robot - LASER & CAMERA"
try:
# start GPS sooner to get position fix
# self.robot.gps.start()
self.robot.laser.start()
self.waitForStart()
if not self.robot.switchBlueSelected:
print "RED -> mirroring code directions!!!"
code = [-x for x in code]
print code
if self.robot.compass:
self.rowHeading = compassHeading(self.robot.compass)
self.robot.camera.start()
laserRow = LaserRow( verbose = self.verbose, rowHeading = self.robot.localisation.pose()[2] )
self.robot.addExtension( laserRow.updateExtension )
cameraRow = CameraRow( verbose = self.verbose )
self.robot.addExtension( cameraRow.updateExtension )
angularSpeed = 0.0
self.robot.maxSpeed = 0.2
speed = 0 # wait for first camera image (maybe beep?? if no route to host)
startTime = self.robot.time
row = laserRow
row.reset( offsetDeg=None ) # just for test, try to find the gap (kitchen test)
# row = cameraRow
for action in code:
self.robot.insideFiled = True
print "================= ACTION ", action, "================="
print "battery:", self.robot.battery
while not row.endOfRow:
# sprayer( self.robot, True, True )
for (speed, angularSpeed) in self.driver.followLineG( row.line ):
# print "TEST %.2f" % (math.degrees(normalizeAnglePIPI(row.line.angle - self.robot.localisation.pose()[2])))
if abs(normalizeAnglePIPI(row.line.angle - self.robot.localisation.pose()[2])) > SLOW_DOWN_ANGLE:
speed *= 0.9
if self.robot.laserData:
self.robot.toDisplay = 'OK'
else:
self.robot.toDisplay = '--'
speed, angularSpeed = 0.0, 0.0
# if detectBlockedRow and row.collisionAhead[1] < 0.25:
blockedCamCount = 0
if detectBlockedRow and self.robot.cameraData:
camDat, fileName = self.robot.cameraData
if camDat:
blockedCamCount = int(camDat.split()[0])
if blockedCamCount > RED_ALERT:
print "CAMERA BLOCKED!!", blockedCamCount
#.........这里部分代码省略.........
示例6: Car
# 需要导入模块: from driver import Driver [as 别名]
# 或者: from driver.Driver import stop [as 别名]
#.........这里部分代码省略.........
if message.type == Message.STAY:
collision.state = CollisionState.WAITING
collision.message = None
print "WE STAY"
else:
collision.state = CollisionState.RESOLVED
collision.message = None
print "RESOLVED... WE GO"
else:
print "ERROR: got response without having sent a message"
collision.lock.release()
time.sleep(utils.THREAD_SLEEP)
def _process_collisions(self):
"""
Collision Processor:
- main loop
- drives car
- processes Collision objects and decides course of action
- constructs messages to other cars
"""
while not self._kill:
collisions_to_delete = set()
for car_name, collision in self._collisions.iteritems():
# TODO might need this not to block so we can keep moving
collision.lock.acquire()
if collision.critical:
# stop driver, send ROW
self._driver.stop()
self.state = CarState.STOPPED
collision.critical = False
if collision.state == CollisionState.SENT_MESSAGE:
pass # wait for reply
elif collision.state == CollisionState.WAITING:
self._driver.stop() # repeated calls are benign
self.state = CarState.STOPPED
if collision.safe_to_drive(self.frames[-1][car_name]):
print "SAFE TO PROCEED"
collision.state = CollisionState.RESOLVED
elif collision.state == CollisionState.RESOLVED:
print "RESOLVED: going..."
self._driver.go() # repated calls are benign
self._state = CarState.DRIVING
collisions_to_delete.add(car_name)
elif collision.state == CollisionState.NEW:
# send ROW
priority = Car._generate_priority()
self._talker.send_message(Message(Message.ROW, self.name, collision.car_name,
collision.location, collision.frame_num, priority_val=priority))
collision.state = CollisionState.SENT_MESSAGE
collision.priority_val = priority
print "ROW SENT"
elif collision.state == CollisionState.RECEIVED_MESSAGE:
assert collision.message != None
# process collision message
示例7: __init__
# 需要导入模块: from driver import Driver [as 别名]
# 或者: from driver.Driver import stop [as 别名]
class SICKRobotDay2016:
def __init__(self, robot, code, verbose = False):
self.random = random.Random(0).uniform
self.robot = robot
self.verbose = verbose
self.code = code
self.robot.attachEmergencyStopButton()
# change robot wheel calibration
wd = 427.0 / 445.0 * 0.26/4.0 # with gear 1:4
delta = -0.00015
self.robot._WHEEL_DIAMETER = {SIDE_LEFT: wd+delta, SIDE_RIGHT: wd-delta}
self.robot.attachCamera(sleep=0.5)
self.robot.attachLaser( remission=True, pose=((0.24, -0.13, 0.08), (0,math.radians(180),0)) )
self.robot.attachRFU620()
self.driver = Driver( self.robot, maxSpeed = 0.5, maxAngularSpeed = math.radians(180) )
self.robot.localisation = SimpleOdometry()
self.robot.last_valid_rfid = None, None # tag, position
self.robot.addExtension(draw_rfu620_extension)
self.robot.addExtension(draw_cubes_extension)
self.robot.laser.stopOnExit = False # for faster boot-up
def load_cube(self):
print "load cube (time = {:.1f}s)".format(self.robot.time - self.start_time)
self.driver.goStraight(0.3, timeout=30)
gripperClose(self.robot)
def place_cube(self):
pos = combinedPose(self.robot.localisation.pose(), (0.2, 0, 0))[:2] # TODO check proper offset
print "place cube at ({:.2f}, {:.2f} (time = {:.1f}))".format(pos[0], pos[1], self.robot.time - self.start_time)
viewlog.dumpBeacon(pos, color=(255, 255, 255))
viewlog.dumpObstacles([[pos]])
gripperOpen(self.robot)
self.driver.goStraight(-0.4, timeout=30)
def game_over(self):
print 'Game over (battery status = {}V)'.format(self.robot.battery)
for k in xrange(10):
self.robot.setSpeedPxPa(0.0, 0.0)
self.robot.update()
raise EmergencyStopException() # TODO: Introduce GameOverException as in Eurobot
def find_cube(self, timeout):
print "find_cube-v1"
prev = None
cd = CubeDetector(self.robot.laser.pose)
startTime = self.robot.time
while self.robot.time < startTime + timeout:
self.robot.update()
if prev != self.robot.laserData:
prev = self.robot.laserData
cubes = cd.detect_cubes_xy(self.robot.laserData, limit=4)
if len(cubes) > 0:
for i, (cube_x, cube_y) in enumerate(cubes):
goal = combinedPose(self.robot.localisation.pose(), (cube_x, cube_y, 0))[:2]
viewlog.dumpBeacon(goal, color=(200, 200, 0) if i > 0 else (255, 255, 0))
cube_x, cube_y = cubes[0]
cube_y += 0.05 # hack for bended(?) laser
print "{:.2f}\t{:.2f}".format(cube_x, cube_y)
speed = 0.0
tolerance = 0.01
if cube_x > 0.5:
tolerance = 0.05
angle = math.atan2(cube_y, cube_x)
turnStep = math.radians(10)
if abs(angle) > math.radians(10):
turnStep = math.radians(50)
if cube_y > tolerance:
angularSpeed = turnStep
elif cube_y < -tolerance:
angularSpeed = -turnStep
else:
angularSpeed = 0
speed = 0.1
if cube_x > 0.5:
speed = 0.3 # move faster toward further goals
if cube_x < 0.30:
return True
self.robot.setSpeedPxPa(speed, angularSpeed)
else:
self.robot.setSpeedPxPa(0.0, 0.0)
print "TIMEOUT"
return False
def ver0( self, verbose=False ):
# Go straight for 2 meters
print "ver0", self.robot.battery
#.........这里部分代码省略.........
示例8: __init__
# 需要导入模块: from driver import Driver [as 别名]
# 或者: from driver.Driver import stop [as 别名]
class Elevator:
DIRECTION_UP = 1
DIRECTION_DOWN = -1
DIRECTION_STAND = 0
LEAVE_DOORS_OPEN = 2
def __init__(self):
self.driver = Driver()
self.previous_floor = 1
self.direction = self.DIRECTION_UP
self.queue = [] # A Queue of orders
self.task = [] # The current order that is being taken care of
self.motor_speed = 1000
self.elevator = None # *** hva brukes denne til og hvor settes den til en verdi? ***
def go_to_floor(self, floor, lock):
"""does what its name implies"""
current_floor = self.driver.getCurrentFloor()
if not current_floor:
current_floor = self.previous_floor
if current_floor < floor:
self.direction = self.DIRECTION_UP
self.driver.move(OUTPUT.MOTOR_UP, self.motor_speed)
elif current_floor == floor:
self.driver.stop()
self.pop_task(lock)
elif current_floor > floor:
self.driver.move(OUTPUT.MOTOR_DOWN, self.motor_speed)
self.direction = self.DIRECTION_DOWN
def pop_task(self, lock):
"""removes a task from the list of tasks and preforms cleanup"""
lock.acquire()
floor = self.task.pop()
lock.release()
light = self.driver.getAccordingLight(INPUT.IN_BUTTONS, floor)
self.driver.setChannel(light, 0)
self.open_doors()
def open_doors(self):
"""simulates opening the doors of the elevator and waiting"""
start = time.clock()
while time.clock() < self.LEAVE_DOORS_OPEN + start:
self.driver.stop()
def add_job(self, floor, direction, lock):
"""adds a job to the queue or task"""
if task:
# check whether this could be added as a subtask
if (
self.direction == self.DIRECTION_UP == direction
and self.previous_floor < floor <= self.task[len(self.task) - 1][0]
):
self.add_subtask(floor, direction, lock)
elif (
self.direction == self.DIRECTION_DOWN == direction
and self.previous_floor > floor >= self.task[len(self.task) - 1][0]
):
self.add_subtask(floor, direction, lock)
else:
lock.acquire()
self.queue.append((floor, direction))
lock.release()
else:
lock.acquire()
task.append((floor, direction))
lock.release()
def add_subtask(self, floor, direction, lock):
"""adds a subtask to the task in correct order"""
lock.acquire()
for i, sub in enumerate(self.task):
if direction == self.DIRECTION_DOWN:
if sub >= self.task[i]:
self.task.insert(sub, i)
else:
if sub <= self.task[i]:
self.task.insert(sub, i)
lock.release()
def read_inputs(self, lock):
"""reads inputs and processes them"""
for sig in INPUT.BUTTONS:
if self.driver.readChannel(sig):
(floor, type) = self.driver.channelToFloor(sig)
light = self.driver.getAccordingLight(type, floor)
self.driver.setChannel(light, 1)
if type == INPUT.IN_BUTTONS:
self.add_subtask(floor, self.direction, lock)
elif type == INPUT.DOWN_BUTTONS:
job = (floor, self.DIRECTION_DOWN)
if self.check_job(job):
self.add_job(floor, self.DIRECTION_DOWN, lock)
else:
ElevatorProcess(target=self.elevator.send_job, args=(self.elevator, job)).start()
elif type == INPUT.UP_BUTTONS:
job = (floor, self.DIRECTION_UP)
if self.check_job(job):
self.add_job(floor, self.DIRECTION_UP, lock)
#.........这里部分代码省略.........