def main(request_dict): """ """ origin = request_dict['origin'] destination = request_dict['destination'] options = request_dict['options'] fcst_points = request_dict['fcst_points'] start_time = sort_time(request_dict['start_time']) google_req_url = google_dir_url.format(olat=origin["latitude"], olon=origin["longitude"], dlat=destination["latitude"], dlon=destination["longitude"], opts=options) directions_request = requests.get(google_req_url) directions_json = directions_request.json() # The directions_json is structured to hold multiple sets of directions for # multiple routes and legs. This module will only handle one route with one # leg. Check this and extract this leg, and call it the journey. journey_dict = get_journey(directions_json) journey_steps = create_steps(journey_dict) journey = Journey(journey_steps) # According to how many forecast points along the journey are required, # work out the distance between each point. travel_dist = journey.distance / (fcst_points - 1) # Open up datapoint connection conn = datapoint.connection(api_key=API_key) start_site = conn.get_nearest_site(journey.location.x, journey.location.y) start_forecast = get_forecast(conn, start_site, start_time) print start_time.isoformat() forecasts = [ create_forecast_dict(start_site.longitude, start_site.latitude, start_forecast, start_time.isoformat()) ] while journey.location != journey.destination: journey.travel_distance(travel_dist) time = start_time + \ datetime.timedelta(seconds=journey.duration_travelled) site = conn.get_nearest_site(journey.location.x, journey.location.y) forecast = get_forecast(conn, site, time) forecasts.append( create_forecast_dict(site.longitude, site.latitude, forecast, time.isoformat())) response_dict = convert_dict_to_json({"journey": forecasts}) print_response(response_dict)
def parse_request(self): cached = self.check_cache() if cached: print("CHACHED") return cached html = self.run_request() data_parser = WebsiteParser(html) departure = data_parser.departure_time() arival = data_parser.arival_time() prices = data_parser.prices() traveling_time = data_parser.traveling_time() carrier = data_parser.carriers() output = [ Journey( departure=departure[x], departure_date=self.data["search-datetime"], arival=arival[x], price=prices[x], traveling_time=traveling_time[x], carrier=carrier[x], departure_destination=self.data["search-from"], arival_destination=self.data["search-to"], ) for x in range(len(departure)) ] if output: self.cache(output) return [journey.beautify() for journey in output]
def get_journey_history_single_month(self, view_type, month, year): # view_type: "Payments" url = "/Statements/TravelStatement?pi=" + self.pi_ref response = self.user.session.tfl_get(url) statement_soup = getSoupFromHtml(response.text) verification_token = statement_soup.find( attrs={"name": "__RequestVerificationToken"}) verification_token = verification_token["value"] url = "/Statements/refresh" data = { "__RequestVerificationToken": verification_token, "SelectedStatementType": view_type, "SelectedStatementPeriod": str(month) + "|" + str(year), "PaymentCardId": self.pi_ref } response = self.user.session.tfl_post(url, data) statement_soup = getSoupFromHtml(response.text) html_statement_journeys = statement_soup.findAll( attrs={"data-pageobject": "statement-detaillink"}) for html_statement_journey in html_statement_journeys: journey = Journey(self, html_statement_journey["href"]) if journey.hash not in self.journeys: self.journeys[journey.hash] = journey return
def create_journeys(vehicle_id, positions_list, stops): print_events = False i = 0 journeys = [] for positions in positions_list: if len(positions) < 2: continue line = positions[0] route = positions[1:] start_id = route[0]["event.id"] #print("Start Pos: ", route[0]) journey = Journey(vehicle_id, line) last_i = None while i < len(stops): if stops[i]["ref.id"] < start_id: #print("Before Started: ", stops[i]["date"], stops[i]["event.type"], stops[i]["event.id"], stops[i]["ref.id"]) if stops[i]["event.type"] in ["ArrivedEvent", "PassedEvent"]: last_i = i i += 1 else: break if last_i is not None: journey.add_stop(stops[last_i]) for pos in route: if i == len(stops) or pos["event.id"] < stops[i]["ref.id"]: journey.route.append(pos) last_id = pos["event.id"] else: journey.add_stop(stops[i]) i += 1 else: #print("Last added:", journey.route[-1]) while i < len(stops): if stops[i]["ref.id"] <= last_id: journey.add_stop(stops[i]) i += 1 else: break journeys.append(journey) if print_events: last_print = None for j, event in enumerate(journey.route): if last_print is None or event["event.type"] != last_print: last_print = event["event.type"] if j > 0 and last_print != "ObservedPositionEvent": print(journey.route[j - 1]) print(event) print() print(i, len(stops)) return journeys
def checkIn(self, stationID): print stationID if(self.isCheckedIn()): self.journey.addWaypoint(stationID) else: self.journey = Journey(stationID) self.checkedIn = True return self.checkedIn
def get_bus_journeys(config, credentials): buses = transportapi.bus.get_live_json(config["stop_id"], credentials) buses = transportapi.bus.flatten_services(buses) try: buses = [Journey.from_bus_json(json) for json in buses["departures"]] except: get_module_logger().warning("Exception parsing bus times JSON for {}".format(config["stop_id"])) buses = [] return buses
def get_train_journeys(config, credentials): trains = transportapi.train.get_live_json(config["station_code"], credentials, {"calling_at":config["calling_at"]}) try: trains = [Journey.from_train_json(json) for json in trains["departures"]["all"]] except: get_module_logger().warning("Exception parsing train times JSON for {}".format(config["station_code"])) get_module_logger().warning("JSON: {}".format(trains)) trains = [] return trains
def schedule(self): count = 0 while True: count += 1 destination = random.choice(destinations) trip = Journey("A", destination) passenger = Passenger(count, self.env, trip) print("Sending passenger %d on the trip %s at %d" % (count, trip, self.env.now)) self.env.process(passenger.wait_for_train(self.train_stop)) yield self.env.timeout(5)
def _create_journeys(self, slices): """Creates a Journey object for each slice in this trip. Args: slices (dict[]): an array of "slice" objects from the query response. Returns: Journey[]: an array of Journey objects, each representing a slice on this trip. """ journeys = [] for slice in slices: journey = Journey(slice, self.ap_list, self.ac_list, self.city_list, self.carrier_list) journeys.append(journey) return journeys
def __init__(self, eventmanager): self._eventmanager = eventmanager self._world = world = eventmanager._world self.burst_deferred_maker = self._world.burst_deferred_maker # shortcuts to BurstDeferred factory. NOTE: don't get wrapped by BehaviorActions - should they? self.make = self.burst_deferred_maker.make self.wrap = self.burst_deferred_maker.wrap self.succeed = self.burst_deferred_maker.succeed self._motion = world.getMotionProxy() self._speech = world.getSpeechProxy() #self._video = world.getALVideoDeviceProxy() self._imops = world.getImopsProxy() self._current_camera = None # This is based on our commands only - we are the only ones changing it self._current_fps = burst_consts.INITIAL_FRAME_PER_SECOND self._joint_names = self._world.jointnames self._journey = Journey(self) self._movecoordinator = self._world._movecoordinator self.currentCamera = CAMERA_WHICH_BOTTOM_CAMERA self._camera_switch_time = world.time self.tracker = Tracker(self) # Please remember to stop # Todo - Locking self.centerer = Centerer(self) # Please remember to stop self.searcher = Searcher(self) # all of these behaviors self.localizer = Localizer(self) # when you stop the InitialBehavior. Thank you. self.headControllers = [self.tracker, self.centerer, self.searcher] # we keep track of the last head bd self._current_head_bd = self.succeed(self) self._current_motion_bd = self.succeed(self) # slight changes between 1.3.8 and 1.2.0 if is_120: self.setWalkConfig = self.setWalkConfig_120 else: self.setWalkConfig = self.setWalkConfig_138
def get_journeys_by_key(self, key): return [Journey(**data) for data in json.loads(self.get(key))]
def main(resource_path): with open(resource_path, 'r') as fd: l = Journey.loads(StepCountReporter(), fd.readline()) r = Journey.loads(StepCountReporter(), fd.readline()) print(l.distance_to_nearest_intersection(r))
querry += " WHERE " for key in kwargs: querry += querries[key] querry += " AND " if kwargs: cursor.execute(querry[0:len(querry) - 5], kwargs) else: cursor.execute(querry, kwargs) return cursor.fetchall() if __name__ == "__main__": db_controller = DbController() journey = Journey( **{ "departure": "8:00", "departure_date": "22-10-2018", "arival": "21:00", "price": "1090", "traveling_time": "07:10", "carrier": "kiwi", "departure_destination": "Split", "arival_destination": "Zagreb", }) print(journey.beautify()) print( db_controller.get_journey(departure_destination="Split", arival_destination="Zagreb"))
class Actions(object): """ High level class used by Player to initiate any action that the robot does, including basics: head moves, joint moves, joint scripts (executeMoves) high level moves: change location relative vision and head moves: head tracking, searching, localizing vision and head and body moves: ball kicking We put high level operations in Actions if: * it is an easily specified operation (head scanning) * it is short timed (ball kicking) We will put it in Player instead if: * it is complex, runs for a long time.. (not very well understood) """ verbose = False def __init__(self, eventmanager): self._eventmanager = eventmanager self._world = world = eventmanager._world self.burst_deferred_maker = self._world.burst_deferred_maker # shortcuts to BurstDeferred factory. NOTE: don't get wrapped by BehaviorActions - should they? self.make = self.burst_deferred_maker.make self.wrap = self.burst_deferred_maker.wrap self.succeed = self.burst_deferred_maker.succeed self._motion = world.getMotionProxy() self._speech = world.getSpeechProxy() #self._video = world.getALVideoDeviceProxy() self._imops = world.getImopsProxy() self._current_camera = None # This is based on our commands only - we are the only ones changing it self._current_fps = burst_consts.INITIAL_FRAME_PER_SECOND self._joint_names = self._world.jointnames self._journey = Journey(self) self._movecoordinator = self._world._movecoordinator self.currentCamera = CAMERA_WHICH_BOTTOM_CAMERA self._camera_switch_time = world.time self.tracker = Tracker(self) # Please remember to stop # Todo - Locking self.centerer = Centerer(self) # Please remember to stop self.searcher = Searcher(self) # all of these behaviors self.localizer = Localizer(self) # when you stop the InitialBehavior. Thank you. self.headControllers = [self.tracker, self.centerer, self.searcher] # we keep track of the last head bd self._current_head_bd = self.succeed(self) self._current_motion_bd = self.succeed(self) # slight changes between 1.3.8 and 1.2.0 if is_120: self.setWalkConfig = self.setWalkConfig_120 else: self.setWalkConfig = self.setWalkConfig_138 #=============================================================================== # High Level - anything that uses vision #=============================================================================== # These functions are generally a facade for internal objects, currently: # kicking.Kicker, headtracker.Searcher, headtracker.Tracker @returnsbd # must be first def kickInit(self, target_world_frame=None, side=LEFT): """ Kick the Ball. Returns an already initialized BallKicker instance which can be used to stop the current activity. If target is None it kicks towards the enemy goal (currently the Yellow - TODO). Otherwise target should be a location which will be used to short circuit the scanning process. (caller needs to supply a valid target) Kicking towards a target entails: * if target is default: scan for ball until found (using various strategies) * approach ball using different strategies (far, close) * kick TODO: target can be a robot name, then the kick becomes a pass. This requires being able to detect the location. TODO: have several kick types, one for passing, one for kicking towards goal. """ initkicker = InitialKicker(self, side=side) initkicker.start() return initkicker @returnsbd # must be first def kickBall(self, target_left_right_posts, target_world_frame=None): """ Kick the Ball. Returns an already initialized BallKicker instance which can be used to stop the current activity. If target is None it kicks towards the enemy goal (currently the Yellow - TODO). Otherwise target should be a location which will be used to short circuit the scanning process. (caller needs to supply a valid target) Kicking towards a target entails: * if target is default: scan for ball until found (using various strategies) * approach ball using different strategies (far, close) * kick TODO: target can be a robot name, then the kick becomes a pass. This requires being able to detect the location. TODO: have several kick types, one for passing, one for kicking towards goal. """ ballkicker = BallKicker(self, target_left_right_posts=target_left_right_posts) ballkicker.start() return ballkicker @returnsbd # must be first def runSecondary(self, direction): """ Go to a predefined point and then run kicker depending on the kick off side chosen. Returns an already initialized SecondaryStarter instance which can be used to stop the current activity """ second = SecondaryStarter(self, direction=LEFT) second.start() return second @returnsbd # must be first def passBall(self, target_world_frame=None): passingChallange = passBall(self._eventmanager, self) passingChallange.start() return passingChallange @stopped(['searcher', 'centerer']) @setfps(20) def track(self, target, lostCallback=None): """ Track an object that is seen. If the object is not seen, does nothing. """ return self.tracker.start(target=target, lostCallback=lostCallback) @returnsbd # must be first @stopped(['tracker', 'centerer']) @setfps(20) def search(self, targets, center_on_targets=True, stop_on_first=False): if stop_on_first: return self.searcher.search_one_of(targets, center_on_targets) else: return self.searcher.search(targets, center_on_targets) # TODO: returns centered, maybe_bd - I should wrap this too, but returnsbd # is too inflexible. def executeTracking(self, target, normalized_error_x=0.05, normalized_error_y=0.05, return_exact_error=False): if not all(x.stopped for x in self.headControllers): raise Exception("Can't start searching while tracking") return self.tracker.executeTracking(target, normalized_error_x=normalized_error_x, normalized_error_y=normalized_error_y) @returnsbd # must be first def localize(self): return self.localizer.start() # a Behavior, hence a BurstDeferred #=============================================================================== # Mid Level - any motion that uses callbacks #=============================================================================== @returnsbd # must be first (since other wrappers don't copy the attributes..) @legal_any @setfps(10) def changeLocationRelative(self, delta_x, delta_y = 0.0, delta_theta = 0.0, walk=walks.STRAIGHT_WALK, steps_before_full_stop=0): """ Add an optional addTurn and StraightWalk to ALMotion's queue. Will fire EVENT_CHANGE_LOCATION_DONE once finished. Coordinate frame for robot is same as world: x forward, y left (z up) What kind of walk this is: for simplicity we do a turn, walk, then final turn to wanted angle. @param steps_before_full_stop: Each steps_before_full_stop, the robot will halt, to regain its balance. If the parameter is not set, or is set to 0, the robot will execute its entire journey in one go. """ distance = (delta_x**2 + delta_y**2)**0.5 / 100 # convert cm to meter bearing = atan2(delta_y, delta_x) # TODO: Shouldn't this be the other way around? self._current_motion_bd = self._journey.start(walk=walk, steps_before_full_stop = steps_before_full_stop, delta_theta = delta_theta, distance=distance, bearing=bearing) return self._current_motion_bd @returnsbd # must be first @legal_any @setfps(10) def turn(self, deltaTheta, walk=walks.TURN_WALK): print walk self.setWalkConfig(walk.walkParameters) dgens = [] dgens.append(lambda _: self._motion.setSupportMode(SUPPORT_MODE_DOUBLE_LEFT)) print "ADD TURN (deltaTheta): %f" % (deltaTheta) dgens.append(lambda _: self._motion.addTurn(deltaTheta, walk.defaultSpeed)) duration = 1.0 # TODO - compute duration correctly d = chainDeferreds(dgens) self._current_motion_bd = self._movecoordinator.walk(d, duration=duration, description=('turn', deltaTheta, walk)) return self._current_motion_bd # TODO: Change to walkSideways() @returnsbd # must be first @legal_any @setfps(10) def changeLocationRelativeSideways(self, delta_x, delta_y = 0.0, walk=walks.SIDESTEP_WALK): """ Add an optional addWalkSideways and StraightWalk to ALMotion's queue. Will fire EVENT_CHANGE_LOCATION_DONE once finished. Coordinate frame for robot is same as world: x forward, y left (z up) X & Y are in radians! What kind of walk is this: for simplicity we do sidewalking then walking to target (we assume no orientation change is required) """ print "changeLocationRelativeSideways (delta_x: %3.3f delta_y: %3.3f)" % (delta_x, delta_y) distance, distanceSideways = delta_x / CM_TO_METER, delta_y / CM_TO_METER did_sideways = None dgens = [] # deferred generators. This is the DESIGN PATTERN to collect a bunch of # stuff that would have been synchronous and turn it asynchronous # All lambda's should have one parameter, the result of the last deferred. dgens.append(lambda _: self._motion.setSupportMode(SUPPORT_MODE_DOUBLE_LEFT)) # if abs(distanceSideways) >= MINIMAL_CHANGELOCATION_SIDEWAYS: # walk = walks.SIDESTEP_WALK dgens.append(lambda _: self.setWalkConfig(walk.walkParameters)) defaultSpeed = walk.defaultSpeed stepLength = walk[WalkParameters.StepLength] if distance >= MINIMAL_CHANGELOCATION_X: print "WALKING STRAIGHT (stepLength: %3.3f distance: %3.3f defaultSpeed: %3.3f)" % (stepLength, distance, defaultSpeed) #dgens.append(lambda _: self._motion.addWalkStraight( distance, defaultSpeed )) # Vova trick - start with slower walk, then do the faster walk. slow_walk_distance = min(distance, stepLength*2) if walks.FIRST_TWO_SLOW_STEPS and World.connected_to_nao: dgens.append(lambda _: self._motion.addWalkStraight( slow_walk_distance, DEFAULT_SLOW_WALK_STEPS )) dgens.append(lambda _: self._motion.addWalkStraight( distance - slow_walk_distance, defaultSpeed )) else: print "ADD WALK STRAIGHT: %f, %f" % (distance, defaultSpeed) dgens.append(lambda _: self._motion.addWalkStraight( distance, defaultSpeed )) # When asked to do side-stepping for a very short distance, do a minimal one if abs(distanceSideways) <= MINIMAL_CHANGELOCATION_SIDEWAYS: print "MINOR SIDEWAYS MOVEMENT ENLARGED! (%3.3f)" % distanceSideways if distanceSideways < 0: distanceSideways = -MINIMAL_CHANGELOCATION_SIDEWAYS else: distanceSideways = MINIMAL_CHANGELOCATION_SIDEWAYS print "WALKING SIDEWAYS (%3.3f)" % distanceSideways did_sideways = distanceSideways dgens.append(lambda _: self._motion.addWalkSideways(distanceSideways, defaultSpeed)) duration = (defaultSpeed * distance / stepLength + (did_sideways and defaultSpeed or self._eventmanager.dt) ) * 0.02 # 20ms steps print "Estimated duration: %3.3f" % (duration) d = chainDeferreds(dgens) self._current_motion_bd = self._movecoordinator.walk(d, duration=duration, description=('sideway', delta_x, delta_y, walk.name)) return self._current_motion_bd @returnsbd # must be first @legal_any @setfps(10) def changeLocationArc(self, delta_x, delta_y, walk=walks.STRAIGHT_WALK): #handle divide by zero if delta_y==0: return self.changeLocationRelativeSideways(delta_x, delta_y, walk) #calculate radius #r=((y{-,+}r)**2 + x**2)**0.5 #0= y**2 + r**2 {+/-}y*r*2 + x**2 - r**2 #r=abs( (y**2 + x**2) / (2*y) ) r= abs( delta_y/2 + (delta_x**2)/(2*delta_y) ) #sin angle = y/r angle = asin(delta_x/r) if delta_y<0: angle=-angle #print "Calculated radius: %f, calculated angle %f" % (r, angle) # TODO: Handle addWalkArc limitations (min/max radius) # TODO: Move to journey.py (???) dgens = [] # deferred generators. This is the DESIGN PATTERN to collect a bunch of # stuff that would have been synchronous and turn it asynchronous # All lambda's should have one parameter, the result of the last deferred. dgens.append(lambda _: self._motion.setSupportMode(SUPPORT_MODE_DOUBLE_LEFT)) dgens.append(lambda _: self.setWalkConfig(walk.walkParameters)) defaultSpeed = walk.defaultSpeed # give radius in meters!!! dgens.append(lambda _: self._motion.addWalkArc( angle, r / 100. , defaultSpeed )) # TODO: Calculate arc length to get possible duration (by arc_length/speed) duration = 10 d = chainDeferreds(dgens) self._current_motion_bd = self._movecoordinator.walk(d, duration=duration, description=('arc', delta_x, delta_y, walk.name)) return self._current_motion_bd @returnsbd # must be first @legal_any def sitPoseAndRelax(self): # TODO: This appears to be a blocking function! self._current_motion_bd = self.wrap(self.sitPoseAndRelax_returnDeferred(), data=self) return self._current_head_bd def sitPoseAndRelax_returnDeferred(self): # TODO: This appears to be a blocking function! dgens = [] def removeStiffness(_): if burst.options.debug: print "sitPoseAndRelax: removing body stiffness" return self._motion.setBodyStiffness(0) dgens.append(lambda _: self._clearFootsteps_returnDeferred()) #dgens.append(lambda _: self.executeMove(poses.STAND).getDeferred()) dgens.append(lambda _: self.executeMove(poses.SIT_POS).getDeferred()) dgens.append(removeStiffness) return chainDeferreds(dgens) def setWalkConfig_120(self, param): """ param should be one of the walks.WALK_X """ (ShoulderMedian, ShoulderAmplitude, ElbowMedian, ElbowAmplitude, LHipRoll, RHipRoll, HipHeight, TorsoYOrientation, StepLength, StepHeight, StepSide, MaxTurn, ZmpOffsetX, ZmpOffsetY) = param[:] # XXX we assume the order of these configs doesn't matter, hence the # DeferredList - does it? ds = [] ds.append(self._motion.setWalkArmsConfig( ShoulderMedian, ShoulderAmplitude, ElbowMedian, ElbowAmplitude )) ds.append(self._motion.setWalkArmsEnable(True)) # LHipRoll(degrees), RHipRoll(degrees), HipHeight(meters), TorsoYOrientation(degrees) ds.append(self._motion.setWalkExtraConfig( LHipRoll, RHipRoll, HipHeight, TorsoYOrientation )) ds.append(self._motion.setWalkConfig( StepLength, StepHeight, StepSide, MaxTurn, ZmpOffsetX, ZmpOffsetY )) return DeferredList(ds) def setWalkConfig_138(self, param): """ param should be one of the walks.WALK_X """ # 1.3.8: we currently plan to use the defaults of the new TrapezoidConfig: [5.0, -5.0] # default walk config is : [0.035, 0.01, 0.025, 0.2, 0.23, 3.0] # help said: pHipHeight must be in [0.15f 0.244f] (ShoulderMedian, ShoulderAmplitude, ElbowMedian, ElbowAmplitude, LHipRoll, RHipRoll, HipHeight, TorsoYOrientation, StepLength, StepHeight, StepSide, MaxTurn, ZmpOffsetX, ZmpOffsetY) = param[:] # XXX we assume the order of these configs doesn't matter, hence the # DeferredList - does it? ds = [] ds.append(self._motion.setWalkArmsConfig( ShoulderMedian, ShoulderAmplitude, ElbowMedian, ElbowAmplitude )) ds.append(self._motion.setWalkArmsEnable(True)) ds.append(self._motion.setWalkTrapezoidConfig(LHipRoll, RHipRoll)) ds.append(self._motion.setWalkConfig( StepLength, StepHeight, StepSide, MaxTurn, HipHeight, TorsoYOrientation )) return DeferredList(ds) @returnsbd @legal_head def chainHeads(self, moves): """ chain a number of headMoves, return a burstdeferred on the last move. Useful for debugging, or just for sign language. see nodtester.py """ assert(len(moves) > 0) bd = self.moveHead(*moves[0]) for move in moves[1:]: bd = bd.onDone(lambda _, move=move: self.moveHead(*move)) return bd #=============================================================================== # Low Level #=============================================================================== def switchToTopCamera(self): return self.succeed(self) #return self.setCamera(CAMERA_WHICH_TOP_CAMERA) def switchToBottomCamera(self): return self.succeed(self) #return self.setCamera(CAMERA_WHICH_BOTTOM_CAMERA) @returnsbd # must be first (doesn't add to call stack) # @whocalledme_outofclass def setCamera(self, whichCamera, force=False): """ Set camera used, we have two: top and bottom. whichCamera in [burst_consts.CAMERA_WHICH_TOP_CAMERA, burst_consts.CAMERA_WHICH_BOTTOM_CAMERA] """ # Switching camera's doesn't always work. So we need to actually check for it. # Not sure if this is a webots problem or not, but assuming it isn't webots. return self.succeed(self) def this_doesnt_exist(self): if self._current_camera == whichCamera and not force: return self.succeed(self) dt_since_last = self._world.time - self._camera_switch_time delay = False if dt_since_last < burst_consts.CAMERA_SWITCH_SINCE_LAST_WAIT: print "_"*20 + "Delaying camera switch" + "_"*20 delay = True self._camera_switch_time = self._world.time if whichCamera == CAMERA_WHICH_BOTTOM_CAMERA: s, switcher = 'bottom', self._imops.switchToBottomCamera else: s, switcher = 'top', self._imops.switchToTopCamera print ("_"*20 + "%3.2f: SWITCHING TO %s CAMERA in %3.2f secs (delta %3.2f)" % ( self._world.time, s, burst_consts.CAMERA_SWITCH_ON_SWITCH_WAIT, dt_since_last) + '_'*20) #import time # time.sleep(0.5) # HACK because of switching problem. self._current_camera = whichCamera bd = self.make(self) def onSwitchChilldownComplete(): # called when CAMERA_SWITCH_ON_SWITCH_WAIT time has passed since switcher() called #print "Actions: FINALLY %3.2f" % self._world.time bd.callOnDone() def doSwitch(): # called when CAMERA_SWITCH_SINCE_LAST_WAIT - dt_since_last time has passed self.wrap(switcher(), data=self).onDone(lambda: self._eventmanager.callLater(burst_consts.CAMERA_SWITCH_ON_SWITCH_WAIT, onSwitchChilldownComplete)) if delay: self._eventmanager.callLater( burst_consts.CAMERA_SWITCH_SINCE_LAST_WAIT - dt_since_last, doSwitch) else: doSwitch() return bd @returnsbd # must be first def setCameraFrameRate(self, fps): if self._current_fps == fps: return self._current_fps = fps print "_"*20 + "SETTING FPS TO %s" % fps + "_"*20 bd = self.make(self) self._eventmanager.updateTimeStep(1.0/fps) # convert number of frames per second to dt self._imops.setFramesPerSecond(float(fps)).addCallback(lambda _: bd.callOnDone()).addErrback(log.err) return bd def changeHeadAnglesRelative(self, delta_yaw, delta_pitch, interp_time = 0.15): cur_yaw, cur_pitch = self._world.getAngle("HeadYaw"), self._world.getAngle("HeadPitch") yaw, pitch = cur_yaw + delta_yaw, cur_pitch + delta_pitch if burst.options.debug: print "changeHeadAnglesRelative: %1.2f+%1.2f=%1.2f, %1.2f+%1.2f=%1.2f" % ( cur_yaw, delta_yaw, yaw, cur_pitch, delta_pitch, pitch) return self.executeHeadMove( (((yaw, pitch),interp_time),) ) def changeHeadAnglesRelativeChained(self, delta_yaw, delta_pitch): if burst.options.debug: print "changeHeadAnglesRelativeChained: delta_yaw %1.2f, delta_pitch %1.2f" % (delta_yaw, delta_pitch) return self._movecoordinator.changeChainAngles("Head", [delta_yaw, delta_pitch]) # Kick type - one of the kick types defined in actionconsts KICK_TYPE_STRAIGHT/KICK_TYPE_PASSING/etc... # Kick leg - the leg used to kick # Kick strength - strength of the kick (between 0..1) @setfps(10) def kick(self, kick_type, kick_leg, kick_dist): # TODO: Add support for kick_type/kick_leg tuple, along with kick_strength # OLDER KICKING (not including passing) #return self.executeMove(KICK_TYPES[(kick_type, kick_leg)], # description=('kick', kick_type, kick_leg, kick_strength)) # FOR PASSING: originalKick = KICK_TYPES[(kick_type, kick_leg)] orig_value = originalKick[4][4] if kick_dist > 0: kick_dist = kick_dist / 100 originalKick[4][4] = self.getSpeedFromDistance(kick_dist) bd = self.executeMove(originalKick) originalKick[4][4] = orig_value return bd @setfps(10) def inside_kick(self, kick_type, kick_leg): return self.executeMove(KICK_TYPES[(kick_type, kick_leg)]) @setfps(10) def adjusted_straight_kick(self, kick_leg, kick_side_offset=1.0): if kick_leg==LEFT: return self.executeMove(poses.getGreatKickLeft(kick_side_offset), description=('kick', 'ADJUSTED_KICK', kick_leg, 1.0, kick_side_offset)) else : return self.executeMove(poses.getGreatKickRight(kick_side_offset), description=('kick', 'ADJUSTED_KICK', kick_leg, 1.0, kick_side_offset)) @legal_any @setfps(10) def executeMoveChoreograph(self, (jointCodes, angles, times), whatmove): self._current_motion_bd = self._movecoordinator.doMove(jointCodes, angles, times, 1, description=('choreograph', whatmove)) return self._current_motion_bd
def __init__(self): self.balance = 0 self.journey_history = [] self.journey = Journey()
def __init__(self, session): self.session = session self.journey = Journey(self) self.refund = Refund(self) return