def test_wrong_stream_port(self): with self.assertRaises(socket.error): krpc.connect(name='python_client_test_wrong_stream_port', address='localhost', rpc_port=ServerTestCase.rpc_port(), stream_port=ServerTestCase.rpc_port() ^ ServerTestCase.stream_port())
def launch_vessel_from_vab(name): conn = krpc.connect() # Copy craft file to save directory fixtures_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'fixtures') save_path = os.path.join(os.getenv('KSP_DIR'), 'saves', conn.testing_tools.current_save) if not os.path.exists(save_path): os.makedirs(save_path) ships_path = os.path.join(save_path, 'Ships', 'VAB') if not os.path.exists(ships_path): os.makedirs(ships_path) shutil.copy(os.path.join(fixtures_path, name + '.craft'), os.path.join(ships_path, name + '.craft')) # Launch the craft conn.testing_tools.launch_vessel_from_vab(name) del conn # Wait until server comes back up time.sleep(1) while True: try: conn = krpc.connect() del conn break except: time.sleep(0.2) #TODO: remove sleep time.sleep(3)
def launch_vessel_from_vab(name): # Copy craft file to save directory with krpc.connect(name='testingtools.launch_vessel_from_vab') as conn: fixtures_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'fixtures') save_path = os.path.join(get_ksp_dir(), 'saves', conn.testing_tools.current_save) if not os.path.exists(save_path): os.makedirs(save_path) ships_path = os.path.join(save_path, 'Ships', 'VAB') if not os.path.exists(ships_path): os.makedirs(ships_path) shutil.copy(os.path.join(fixtures_path, name + '.craft'), os.path.join(ships_path, name + '.craft')) # Launch the craft with krpc.connect(name='testingtools.launch_vessel_from_vab') as conn: conn.testing_tools.launch_vessel_from_vab(name) # Wait until server comes back up time.sleep(1) while True: try: conn = krpc.connect(name='testingtools.launch_vessel_from_vab') conn.close() break except: time.sleep(0.2) #TODO: remove sleep time.sleep(10)
def new_save(name='test'): conn = krpc.connect() # Return if the save is already running if conn.testing_tools.current_save == name: del conn return # Load a new save using template from fixtures directory fixtures_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'fixtures') save_path = os.path.join(os.getenv('KSP_DIR'), 'saves', name) if not os.path.exists(save_path): os.makedirs(save_path) shutil.copy(os.path.join(fixtures_path, 'blank.sfs'), os.path.join(save_path, 'persistent.sfs')) conn.testing_tools.load_save('test', 'persistent') del conn # Wait until server comes back up time.sleep(1) while True: try: conn = krpc.connect() del conn break except: time.sleep(0.2) #TODO: remove sleep time.sleep(3)
def __init__(self): self.craft_name = krpc.connect(name="get_craft_name").space_center.active_vessel.name # try to remove get_craft_name script created by above code krpc.connect("get_craft_name").close() # setting up craft config json_config = self.select_craft_config() with open(json_config, "r") as json_file: craft_params = json.load(json_file) self.craft_params = craft_params self.launch_params = self.craft_params['launch_params'] # connections self.conn = krpc.connect(name=self.craft_name) self.canvas = self.conn.ui.stock_canvas self.vessel = self.conn.space_center.active_vessel self.srf_frame = self.vessel.orbit.body.reference_frame # flight info self.ut = self.conn.add_stream(getattr, self.conn.space_center, 'ut') self.altitude = self.conn.add_stream(getattr, self.vessel.flight(), 'mean_altitude') self.surface_altitude = self.conn.add_stream(getattr, self.vessel.flight(), 'surface_altitude') self.apoapsis = self.conn.add_stream(getattr, self.vessel.orbit, 'apoapsis_altitude') self.periapsis = self.conn.add_stream(getattr, self.vessel.orbit, 'periapsis_altitude') orbit_body_ref_frame = self.vessel.orbit.body.reference_frame self.vertical_speed = self.conn.add_stream(getattr, self.vessel.flight(orbit_body_ref_frame), 'vertical_speed')
def load_save(name): # Copy save file to save directory fixtures_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'fixtures') save_path = os.path.join(os.getenv('KSP_DIR'), 'saves', 'test') if not os.path.exists(save_path): os.makedirs(save_path) shutil.copy(os.path.join(fixtures_path, name + '.sfs'), os.path.join(save_path, name + '.sfs')) # Load the save file conn = krpc.connect() ksp.testing_tools.load_save('test', name) del conn # Wait until server comes back up time.sleep(1) while True: try: conn = krpc.connect() del conn break except: time.sleep(0.2) #TODO: remove sleep time.sleep(3)
def setUpClass(cls): if krpc.connect().space_center.active_vessel.name != 'Parts': testingtools.new_save() testingtools.launch_vessel_from_vab('Parts') testingtools.remove_other_vessels() cls.conn = krpc.connect(name='TestPartsReactionWheel') cls.vessel = cls.conn.space_center.active_vessel cls.parts = cls.vessel.parts
def setUpClass(cls): if krpc.connect().space_center.active_vessel.name != 'Parts': testingtools.new_save() testingtools.launch_vessel_from_vab('Parts') testingtools.remove_other_vessels() cls.conn = krpc.connect(name='TestParts') cls.vessel = cls.conn.space_center.active_vessel cls.parts = cls.vessel.parts cls.expectedAmbientTemperature = 273+20
def test_wrong_stream_server(self): with self.assertRaises(krpc.error.ConnectionError) as cm: krpc.connect(name='python_client_test_wrong_stream_server', address='localhost', rpc_port=ServerTestCase.rpc_port(), stream_port=ServerTestCase.rpc_port()) self.assertEqual( 'Connection request was for the stream server, ' + 'but this is the rpc server. ' + 'Did you connect to the wrong port number?', str(cm.exception))
def setUpClass(cls): if krpc.connect().space_center.active_vessel.name != 'Parts': testingtools.new_save() testingtools.launch_vessel_from_vab('Parts') testingtools.remove_other_vessels() cls.conn = krpc.connect(name='TestPartsLandingLeg') cls.vessel = cls.conn.space_center.active_vessel cls.parts = cls.vessel.parts cls.state = cls.conn.space_center.LandingLegState cls.leg = cls.parts.landing_legs[0]
def launch_vessel_from_vab(name): # Copy craft file to save directory with krpc.connect(name='testingtools.launch_vessel_from_vab') as conn: fixtures_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'fixtures') save_path = os.path.join(get_ksp_dir(), 'saves', conn.testing_tools.current_save) if not os.path.exists(save_path): os.makedirs(save_path) ships_path = os.path.join(save_path, 'Ships', 'VAB') if not os.path.exists(ships_path): os.makedirs(ships_path) shutil.copy(os.path.join(fixtures_path, name + '.craft'), os.path.join(ships_path, name + '.craft')) # Launch the craft with krpc.connect(name='testingtools.launch_vessel_from_vab') as conn: conn.space_center.launch_vessel_from_vab(name)
def test_orbit_kerbin(self): load_save("orbit-kerbin") ksp = krpc.connect() vessel = ksp.space_center.active_vessel orbit = vessel.orbit # inc 0 # e 0 # sma 70000 # lan 0 # w 0 # mEp 0 # epoch 0 # body Kerbin self.assertEqual("Kerbin", orbit.body.name) self.assertClose(100000 + 600000, orbit.apoapsis, error=10) self.assertClose(100000 + 600000, orbit.periapsis, error=10) self.assertClose(100000, orbit.apoapsis_altitude, error=10) self.assertClose(100000, orbit.periapsis_altitude, error=10) self.assertClose(100000 + 600000, orbit.semi_major_axis, error=10) self.assertClose(100000, orbit.semi_major_axis_altitude, error=10) self.assertClose(700000, orbit.radius, error=10) self.assertClose(2246.1, orbit.speed, error=1) self.assertClose(603.48, orbit.time_to_apoapsis, error=1) self.assertClose(1582.5, orbit.time_to_periapsis, error=1) self.assertTrue(math.isnan(orbit.time_to_soi_change)) self.assertClose(0, orbit.eccentricity, error=0.1) self.assertClose(0, orbit.inclination, error=0.1) self.assertClose(0, orbit.longitude_of_ascending_node, error=0.1) self.assertClose(0, orbit.argument_of_periapsis, error=0.1) self.assertClose(0, orbit.mean_anomaly_at_epoch, error=0.1) self.assertEqual(None, orbit.next_orbit)
def test_disengage_on_disconnect(self): self.ap.set_rotation(90,0) self.assertGreater(self.ap.error, 0) self.conn.close() conn = krpc.connect() ap = conn.space_center.active_vessel.auto_pilot self.assertTrue(math.isnan(ap.error))
def connect(): global connection try: connection = krpc.connect(name="Sounding Probe 1") return True except socket.error: return False
def process_time(): global conn, sc, vessel, orbit, body, bcbf, pcpf global position_stream, velocity_stream, mass_stream, met_stream conn = krpc.connect(address='192.168.1.181') sc = conn.space_center vessel = sc.active_vessel orbit = vessel.orbit body = orbit.body bcbf = body.reference_frame pcpf = conn.space_center.ReferenceFrame.create_relative( bcbf, position=vessel.position(bcbf), rotation=vessel.rotation(bcbf)) position_stream = conn.add_stream(vessel.position, pcpf) position_stream.add_callback(position_callback) position_stream.start() velocity_stream = conn.add_stream(vessel.velocity, pcpf) velocity_stream.add_callback(velocity_callback) velocity_stream.start() mass_stream = conn.add_stream(getattr, vessel, 'mass') mass_stream.add_callback(mass_callback) mass_stream.start() met_stream = conn.add_stream(getattr, vessel, 'met') met_stream.add_callback(met_callback) met_stream.start() while True: pass
def setUpClass(cls): testingtools.new_save() testingtools.launch_vessel_from_vab('PartsEngine') testingtools.remove_other_vessels() testingtools.set_circular_orbit('Kerbin', 250000) cls.conn = krpc.connect(name='TestPartsEngineMSL') cls.vessel = cls.conn.space_center.active_vessel cls.parts = cls.vessel.parts cls.add_engine_data( 'LV-T30 "Reliant" Liquid Fuel Engine', {'max_thrust': 215000, 'isp': 300}) cls.add_engine_data( 'LV-T45 "Swivel" Liquid Fuel Engine', {'max_thrust': 200000, 'isp': 320}) cls.add_engine_data( 'LV-N "Nerv" Atomic Rocket Motor', {'max_thrust': 60000, 'isp': 800}) cls.add_engine_data( 'IX-6315 "Dawn" Electric Propulsion System', {'max_thrust': 2000, 'isp': 4200}) cls.add_engine_data( 'O-10 "Puff" MonoPropellant Fuel Engine', {'max_thrust': 20000, 'isp': 250}) cls.add_engine_data( 'RT-10 "Hammer" Solid Fuel Booster', {'max_thrust': 227000, 'isp': 162})
def init_globals(craft_cfg): global conn, rframe, vessel, stream conn = krpc.connect(name='RSP-OrbiterMk2') vessel = conn.space_center.active_vessel stages = [ vessel.resources_in_decouple_stage(stage=x, cumulative=False) for x in range(0, craft_cfg.num_stages) ] rframe = vessel.orbit.body.reference_frame stream = { 'time': conn.add_stream(getattr, conn.space_center, 'ut'), 'alt': conn.add_stream(getattr, vessel.flight(rframe), 'surface_altitude'), 'speed': conn.add_stream(getattr, vessel.flight(rframe), 'speed'), 'vspeed': conn.add_stream(getattr, vessel.flight(rframe), 'vertical_speed'), 'hspeed': conn.add_stream(getattr, vessel.flight(rframe), 'horizontal_speed'), 'termv': conn.add_stream(getattr, vessel.flight(rframe), 'terminal_velocity'), 'apo': conn.add_stream(getattr, vessel.orbit, 'apoapsis_altitude'), 'apotime': conn.add_stream(getattr, vessel.orbit, 'time_to_apoapsis'), 'peri': conn.add_stream(getattr, vessel.orbit, 'periapsis_altitude'), 'peritime': conn.add_stream(getattr, vessel.orbit, 'time_to_periapsis'), 'ecc': conn.add_stream(getattr, vessel.orbit, 'eccentricity'), 'liquid': [ conn.add_stream(stages[i].amount, 'LiquidFuel') for i in range(0, craft_cfg.num_stages) ][::-1], 'solid': [ conn.add_stream(stages[i].amount, 'SolidFuel') for i in range(0, craft_cfg.num_stages) ][::-1], } vessel.auto_pilot.engage() vessel.auto_pilot.target_pitch_and_heading(90, 90) vessel.auto_pilot.sas = True
def connectToServ(): # Connect to server conn = krpc.connect(name='GOPOTATOE') conn.space_center.save('launch') # Connect to vessels vessel = conn.space_center.active_vessel return conn, vessel
def connect(): global connection try: connection = krpc.connect(name="Mjolnir1b") return True except socket.error: return False
def __init__(self, target_altitude, target_inclination=0): """Create a connection to krpc and initialize from active vessel.""" self.conn = krpc.connect(name='Launcher') self.vessel = self.conn.space_center.active_vessel self.target_altitude = target_altitude self.target_inclination = target_inclination return
def connect(): global connection try: connection = krpc.connect(name="Staedler 1 (PT5)") return True except socket.error: return False
def setUp(self): load_save('autopilot') self.conn = krpc.connect() self.vessel = self.conn.space_center.active_vessel self.ap = self.vessel.auto_pilot self.sas_mode = self.conn.space_center.SASMode self.speed_mode = self.conn.space_center.SpeedMode
def surveyor1(name_): cx = krpc.connect(name=name_) print('Connected to server, version', cx.krpc.get_status().version) vessel = cx.space_center.active_vessel control = vessel.control resources = vessel.resources # wait for liftoff while vessel.situation.name == 'pre-launch': time.sleep(1) print("Vessel situation: {}".format(vessel.situation.name)) with cx.stream(resources.amount, 'SolidFuel') as fuel: # fuel = resources.amount('SolidFuel') while fuel() > 0.1: time.sleep(0.1) print("Fuel: {}".format(fuel())) control.activate_next_stage() while True: lox = resources.amount('LiquidFuel') if lox < 0.1: control.activate_next_stage() break time.sleep(0.1)
def __init__(self, shared_state): self.shared_state = shared_state self.kerbal = krpc.connect(name=__name__, address='127.0.0.1') self.vessel = self.kerbal.space_center.active_vessel self.control = self.vessel.control self.arduino = None self.state = None self.staging_enabled = False self.handlers = { # switch, (parent, attribute, toggle) or callable 0: self._fuel, 1: self._life_support, 16: self._ascent_mode, 18: (self.control, 'sas', True), 19: (self.control, 'rcs', True), 20: (self.control, 'lights', True), 21: self._undock, 22: self._orbit_mode, 23: self._descent_mode, 24: (self.vessel.control, 'gear', False), 25: (self.vessel.control, 'solar_panels', False), 26: self._engines, 27: self._staging, 28: self._docking_mode, 30: (self.vessel.control, 'brakes', False), 31: self._stage, }
def connect(): global connection try: connection = krpc.connect(name="Mjolnir 2") return True except socket.error: return False
def connect(): global connection try: connection = krpc.connect(name="Tenacity 1") return True except socket.error: return False
def keep_level_throttle(pitch, roll): import krpc from time import sleep conn = krpc.connect(name='keep_level_throttle') vessel = conn.space_center.active_vessel ref_frame = vessel.surface_reference_frame flight = vessel.flight ap = vessel.auto_pilot ap.reference_frame = vessel.orbital_reference_frame vertical_speed = conn.add_stream(getattr, flight(ref_frame), 'vertical_speed') ap.target_pitch = pitch ap.target_roll = roll ap.engage() try: while True: if vertical_speed < 0: vessel.control.throttle += 0.01 elif vertical_speed > 0: vessel.control.throttle -= 0.01 sleep(0.01) except KeyboardInterrupt: print('Interupted') ap.disengage() vertical_speed.remove() conn.close()
def setUpClass(cls): testingtools.new_save() testingtools.launch_vessel_from_vab('PartsEngine') testingtools.remove_other_vessels() cls.conn = krpc.connect(name='TestPartsEngineMSL') cls.vessel = cls.conn.space_center.active_vessel cls.parts = cls.vessel.parts cls.add_engine_data( 'LV-T30 "Reliant" Liquid Fuel Engine', {'max_thrust': 201000, 'isp': 280.5}) cls.add_engine_data( 'LV-T45 "Swivel" Liquid Fuel Engine', {'max_thrust': 169200, 'isp': 270.7}) cls.add_engine_data( 'LV-N "Nerv" Atomic Rocket Motor', {'max_thrust': 14300, 'isp': 190.6}) cls.add_engine_data( 'IX-6315 "Dawn" Electric Propulsion System', {'max_thrust': 63, 'isp': 132.1}) cls.add_engine_data( 'O-10 "Puff" MonoPropellant Fuel Engine', {'max_thrust': 9700, 'isp': 121.2}) cls.add_engine_data( 'RT-10 "Hammer" Solid Fuel Booster', {'max_thrust': 210600, 'isp': 150.3}) cls.add_engine_data( 'J-33 "Wheesley" Basic Jet Engine', {'max_thrust': 115000, 'isp': 19200})
def keep_level_pitch(): import krpc from time import sleep conn = krpc.connect(name='keep_level_pitch') vessel = conn.space_center.active_vessel ref_frame = vessel.surface_reference_frame flight = vessel.flight ap = vessel.auto_pilot ap.reference_frame = vessel.orbital_reference_frame vertical_speed = conn.add_stream(getattr, flight(ref_frame), 'vertical_speed') pitch_stream = conn.add_stream(getattr, flight(ref_frame), 'pitch') ap.target_pitch = 0 ap.target_roll = 0 ap.engage() try: while True: if vertical_speed > 0: if pitch_stream() > -5: ap.target_pitch -= 1 else: ap.target_pitch += 1 elif vertical_speed < 0: ap.target_pitch += 1 sleep(0.5) except KeyboardInterrupt: print('Interupted') ap.disengage() vertical_speed.remove() conn.close()
def setUpClass(cls): testingtools.new_save() testingtools.launch_vessel_from_vab('PartsDockingPortPreAttachedTo') testingtools.remove_other_vessels() cls.conn = krpc.connect(name='TestPartsDockingPortPreAttachedTo') cls.vessel = cls.conn.space_center.active_vessel cls.state = cls.conn.space_center.DockingPortState # Stack is as follows, from top to bottom: # parts[0] - Pod # parts[1] - Docking port (facing down) # parts[2] - Docking port (facing up) # parts[3] - Tank # parts[4] - Docking port (facing up) # parts[5] - Tank # parts[6] - Docking port (facing down) # parts[7] - Tank cls.parts = [cls.vessel.parts.root] cls.parts.append(filter(lambda p: p.docking_port != None, cls.parts[0].children)[0]) part = cls.parts[-1] while len(part.children) == 1: part = part.children[0] cls.parts.append(part) cls.port1 = cls.parts[1].docking_port cls.port2 = cls.parts[2].docking_port cls.port4 = cls.parts[4].docking_port cls.port6 = cls.parts[6].docking_port
def setUpClass(cls): testingtools.new_save() testingtools.launch_vessel_from_vab('Basic') cls.conn = krpc.connect(name='TestFlightAtLaunchpad') cls.vessel = cls.conn.space_center.active_vessel cls.conn.testing_tools.remove_other_vessels() cls.far = cls.conn.space_center.far_available
def establish_connection_and_run(self): error = None dots = 0 connection = None while not self.terminate: try: if connection is None: connection = krpc.connect(name=self.name) self.run_with_connection(connection) error = None dots = 0 except Exception as e: if error != e.args[0]: error = e.args[0] print('\n') print(traceback.format_exc()) sys.stdout.write('Retrying...\n') if dots > 80: dots = 0 sys.stdout.write('\n') sys.stdout.write('.') dots += 1 sys.stdout.flush() time.sleep(1) if connection is not None: connection.close()
async def start(self): while True: try: # TODO: this does not time-out but just hangs the loop # if the server is up but not accepting connections self.conn = krpc.connect(name=self.name, address=self.address, rpc_port=self.rpc_port, stream_port=self.stream_port) except: self.logger.info( "Failed to connect to KSP, trying again in 5 seconds.") await asyncio.sleep(5) else: self.logger.info("Connected to KSP.") self.ok = True try: self.commander.send_status() except protocol.NoConnectionError: # If we connect to ksp before the coordinator # status will be sent on connection event pass finally: break self.initialise()
def sync(self, name, addr, rpc_port, stream_port): if self.value != None: self.close() try: value = krpc.connect(name=name, address=addr, rpc_port=rpc_port, stream_port=stream_port) self.value = value self.name = name self.addr = addr self.rpc_port = rpc_port self.stream_port = stream_port self.connected = True self.synced.emit() show_info( "Connection established.", "Successfully\ connected to %s." % addr, "Connected to %s as %s\ with rpc and stream ports respectively %s and %s" % (addr, name, rpc_port, stream_port)) except (socket_error) as serr: if serr.errno == errno.ECONNREFUSED: show_error("Connection refused.", None, None) else: raise serr except krpc.error.ConnectionError as cerr: show_error("Connection Error.", "Connection to krpc server raised error.", str(cerr))
def setUp(self): load_save('autopilot') self.conn = krpc.connect() self.vessel = self.conn.space_center.active_vessel self.ref = self.conn.space_center.ReferenceFrame self.ap = self.vessel.auto_pilot self.vessel.control.sas = False
def run(): conn = krpc.connect() vessel = conn.space_center.active_vessel contracts = conn.space_center.contract_manager.active_contracts travel = {} for contract in contracts: if contract.completed: continue if not contract.title.startswith('Ferry'): continue for param in contract.parameters: if param.completed: continue if not param.title in travel: travel[param.title] = [] for sub in param.children: if sub.completed: continue travel[param.title].append(sub.title) for t in sorted(travel.keys()): if not len(travel[t]): continue print(t) for s in sorted(travel[t]): print("\t", s)
def test_orbit_bop(self): load_save("orbit-bop") ksp = krpc.connect() vessel = ksp.space_center.active_vessel orbit = vessel.orbit # inc 27 # e 0.18 # sma 320000 # lan 38 # w 241 # mEp 2.3 # epoch 0 # body Kerbin self.assertEqual("Bop", orbit.body.name) self.assertClose(377600, orbit.apoapsis, error=10) self.assertClose(262400, orbit.periapsis, error=10) self.assertClose(377600 - 65000, orbit.apoapsis_altitude, error=10) self.assertClose(262400 - 65000, orbit.periapsis_altitude, error=10) self.assertClose(0.5 * (377600 + 262400), orbit.semi_major_axis, error=10) self.assertClose(0.5 * (377600 - 65000 + 262400 - 65000), orbit.semi_major_axis_altitude, error=10) self.assertClose(366329, orbit.radius, error=10) self.assertClose(76, orbit.speed, error=1) self.assertClose(2698.33, orbit.time_to_apoapsis, error=1) self.assertClose(14102.17, orbit.time_to_periapsis, error=1) self.assertTrue(math.isnan(orbit.time_to_soi_change)) self.assertClose(0.18, orbit.eccentricity, error=0.1) self.assertClose(27, orbit.inclination, error=0.1) self.assertClose(38, orbit.longitude_of_ascending_node, error=0.1) self.assertClose(241, orbit.argument_of_periapsis, error=0.1) self.assertClose(2.3, orbit.mean_anomaly_at_epoch, error=0.1) self.assertEqual(None, orbit.next_orbit)
def setUpClass(cls): testingtools.new_save() testingtools.set_circular_orbit('Kerbin', 100000) cls.conn = krpc.connect(name='TestReferenceFrame') cls.sc = cls.conn.space_center cls.vessel = cls.conn.space_center.active_vessel cls.bodies = cls.conn.space_center.bodies
def main(): conn = krpc.connect() vessel = conn.space_center.active_vessel streams = init_streams(conn,vessel) print vessel.control.throttle plt.axis([0, 100, 0, .1]) plt.ion() plt.show() t0 = time.time() timeSeries = [] vessel.control.abort = False while not vessel.control.abort: t_now = time.time()-t0 tel = Telemetry(streams,t_now) timeSeries.append(tel) timeSeriesRecent = timeSeries[-40:] plt.cla() plt.semilogy([tel.t for tel in timeSeriesRecent], [norm(tel.angular_velocity) for tel in timeSeriesRecent]) #plt.semilogy([tel.t for tel in timeSeriesRecent[1:]], [quat_diff_test(t1,t2) for t1,t2 in zip(timeSeriesRecent,timeSeriesRecent[1:])]) #plt.axis([t_now-6, t_now, 0, .1]) plt.draw() plt.pause(0.0000001) #time.sleep(0.0001) with open('log.json','w') as f: f.write(json.dumps([tel.__dict__ for tel in timeSeries],indent=4)) print 'The End'
def __init__(self, sas=True, max_altitude=500, max_step=100, interval=0.085): self.conn = krpc.connect(name='hover') self.vessel = self.conn.space_center.active_vessel self.step_count = 0 self.done = False self.reward = 0 self.interval = interval self.max_altitude = max_altitude self.observation_space = 1 # Action space : 0.0 ~ 1.0 (Thrust ratio) self.action_space = 1 self.action_max = 1. self.action_min = -1. self.initial_throttle = self.action_min # Initializing self.sas = sas self.target_altitude = 100 self.relative_goal = self.target_altitude self.max_step = max_step
def D_connect(self, ip=None, port=None): if self.fp: raise PynetException("Already connected") conn = krpc.connect(name="{}.{}".format("KSP-PyNet", os.getpid())) vessel = conn.space_center.active_vessel self.fp = flight_plan.FlightPlan(conn, vessel, self.message) return "Connected with IP {}, PORT {}".format(ip, port)
def __init__(self, name, mission_parameters=None): ''' Mission parameters are provided through a MissionParameters object, if none are given, defaults are used name: string, the name of the connection in KSP mission_parameters: MissionParameters, things like target alt, etc. ''' # flight parameters if mission_parameters == None: self.param = MissionParameters() else: self.param = mission_parameters # set process variables self.conn = krpc.connect(name=name) self.sc = self.conn.space_center self.vessel = self.sc.active_vessel self.flight = self.vessel.flight(self.vessel.orbit.body.reference_frame) self.status = Status.IDLE # initialize controllers self.controllers = ('guidance', 'throttle', 'staging', 'warp', 'finalize') self.guidance = self.create_controller(GuidanceController) self.throttle = self.create_controller(ThrottleController) self.staging = self.create_controller(StagingController) self.warp = self.create_controller(WarpController) self.finalize = self.create_controller(FinalizeController) # create a hook to the display functions # a simple print-to-console class if nothing else if provided self.D = Display() self.display_telemetry = self.D.telemetry self.display_status = self.D.status self.last_telemetry = time.time()
def __init__(self, sas=True, max_altitude=1000, max_step=100, epsilon=1, interval=0.085): self.conn = krpc.connect(name='hover') self.vessel = self.conn.space_center.active_vessel self.step_count = 0 self.done = False self.reward = 0 self.interval = interval self.max_altitude = max_altitude self.observation_space = 1 # error tolerance(meter). # If epsilon is 1 and target_altitude is 100m, the error tolerance is between 99m and 101m self.epsilon = epsilon # Action space : 0.0 ~ 1.0 (Thrust ratio) self.action_space = 1 self.action_max = 1. self.action_min = 0.0 self.initial_throttle = self.action_min # Initializing self.sas = sas self.target_altitude = 100 self.max_step = max_step
def connect(): global connection try: connection = krpc.connect(name="testscript") return True except socket.error: return False
def setUpClass(cls): testingtools.new_save() testingtools.launch_vessel_from_vab('PartsSolarPanel') testingtools.remove_other_vessels() cls.conn = krpc.connect(name='TestPartsLaunchClamp') cls.vessel = cls.conn.space_center.active_vessel cls.parts = cls.vessel.parts
def main(): # Setup KRPC conn = krpc.connect() sc = conn.space_center v = sc.active_vessel telem = v.flight(v.orbit.body.reference_frame) # Create PID controller. p = PID(P=.25, I=0.025, D=0.0025) p.ClampI = 20 p.setpoint(Target_Velocity) # starting with locked SAS and throttle at full v.control.sas = True v.control.throttle = 1.0 while not v.thrust: # stage if we just launched a new rocket v.control.activate_next_stage() # Loop Forever, or until you get the point of this example and stop it. while True: the_pids_output = p.update(telem.vertical_speed) v.control.throttle = the_pids_output print('Vertical V:{:03.2f} PID returns:{:03.2f} Throttle:{:03.2f}'. format(telem.vertical_speed, the_pids_output, v.control.throttle)) time.sleep(.1)
def __init__(self, script_name): # Connecting to the game and getting the vessel info conn = krpc.connect(name=script_name) self.conn = conn self.ksc = conn.space_center self.vessel = self.ksc.active_vessel # Setting up value streams self.altitude = conn.add_stream(getattr, self.vessel.flight(), 'mean_altitude') self.apoapsis = conn.add_stream(getattr, self.vessel.orbit, 'apoapsis_altitude') self.thrust = conn.add_stream(getattr, self.vessel, 'thrust') self.mass = conn.add_stream(getattr, self.vessel, 'mass') self.vertical_speed = conn.add_stream( getattr, self.vessel.flight(self.vessel.orbit.body.reference_frame), 'vertical_speed' ) # Control Parameters self.ascent_angle_flatten_alt = 33000 self.parking_orbit_alt = 85000 self.close_in_factor = 0.95 self.inclination = 90 self.slow_burn_throttle = 0.2 self.twr_pid = PidController( gains=(0.05, 0.001, 0.0001), effort_bounds=(-1.0, 1.0), )
def main(): agent, network_weights = load_network() print("Agent loaded.") print("Connecting to server...") # connect to server connection = krpc.connect( name='yolo', address='localhost', rpc_port=50000, stream_port=50001) #Default ports are 50000, 50001 print("Successfully connected to server.") print("Loading quick save...") reset_trial(connection) print("Loaded quick save") pygame.init() screen = pygame.display.set_mode((600, 500)) weight_render = pygame.Surface((600, 500)) weight_render.fill((100, 100, 100)) render_weights = True running = True cycle_count = 0 while running: cycle_count += 1 # get inputs to NN inputs = get_inputs(connection) # Calculate output of NN outputs = agent.calculate_output(inputs) # Use the output to control the agent control = connection.space_center.active_vessel.control control.throttle = (outputs[0][0] + 1) / 2 if outputs[1][0] > 0: control.sas_mode = connection.space_center.SASMode.retrograde else: control.sas_mode = connection.space_center.SASMode.stability_assist #print(outputs[0][0],(outputs[0][0]+1)/2) if str(connection.space_center.active_vessel.situation ) == "VesselSituation.landed": # reset throttle if the lander has touched the ground control.throttle = 0.0 print("Landed") running = False # Every Kth cycle, display network if RENDER_NETWORK and cycle_count % 10 == 0: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False screen.fill((255, 255, 255)) render_network(agent, screen, inputs, weight_render, render_weights, network_weights) render_weights = False pygame.display.update() connection.close()
def __init__(self): self.conn = ksp.connect(address='127.0.0.1', rpc_port=5002, stream_port=5003) self.vessel = self.conn.space_center.active_vessel self.kerbin = self.conn.space_center.bodies['Kerbin'] self.vessel.control.input_mode = self.vessel.control.input_mode.override self.StartRun()
def main(): conn = krpc.connect() planes = [] commandQueue = [] game = gameLoop(conn,commandQueue) for i in range(100): game.update() time.sleep(2)
def ksp_initialize(): print "Initialization of KRPC connection" print "Output structure: (connection,vessel,control,autopilot)" conn = krpc.connect(name='Arduino_Interface') vessel = conn.space_center.active_vessel control = vessel.control ap = vessel.auto_pilot return (conn, vessel, control, ap)
def __init__(self): logging.info("KRPC: Connecting") self.client = krpc.connect(name="Meowth") self.vessel = self.client.space_center.active_vessel self.vessel.auto_pilot.engage() logging.info("KRPC: Connected") self.lastStage = time()
def connect(self): try: self.conn = krpc.connect(name="KRPC Client") self.isConnected = True self.statusLabel_setText_trigger.emit("Connected") except: self.isConnected = False self.statusLabel_setText_trigger.emit("Not Connected")
def script_connect(): global connection try: print 'trying to connect' connection = krpc.connect(name="kRPC dev") return True except socket.error: return False
def __init__(self, settings: Settings): conn_settings: dict = { "address": settings.krpc_address, "rpc_port": settings.krpc_rpc_port, "stream_port": settings.krpc_stream_port } self.settings: Settings = settings self.conn = krpc.connect(**conn_settings)