def monitor(): with xpc.XPlaneConnect() as client: posi = client.getPOSI() posi_temp = list(posi) posi_temp[2] += 500 client.sendPOSI(posi_temp[0:len(posi_temp) - 6]) client.sendPOSI(posi_temp[0:len(posi_temp) - 6], 1) time.sleep(0.02) posi_trash = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] while len(states) < SET_NUM_DATAPOINTS: posi = client.getPOSI() ctrl = client.getCTRL() if (posi != []): posi_temp = list(posi)[2:12] cntrl_temp = list(ctrl)[0:4] if len(states) != 0: cntrl_temp.extend(states[-1]) controls.append(cntrl_temp) else: cntrl_temp.append(range(1, len(posi_temp))) controls.append(cntrl_temp) states.append(posi_temp) #Height, airspeed, roll, pitch, yaw, aroll, apitch, ayaw #Throttle, roll, pitch, yaw # print "Loc: (%4f, %4f, %4f) Aileron:%2f Elevator:%2f Rudder:%2f\n"\ # % (posi[0], posi[1], posi[2], ctrl[1], ctrl[0], ctrl[2]) time.sleep(0.02) states.pop(0) controls.pop(0)
def __init__(self, dest_x, dest_y, dest_z, dest_airspeed, reward_function): self.client = xpc.XPlaneConnect() self.dest_x = dest_x self.dest_y = dest_y self.dest_z = dest_z self.dest_airspeed = dest_airspeed self.reward_function = reward_function
def ftest(a, b="sim/multiplayer/controls/rudder_trim"): with xpc.XPlaneConnect(xpHost=a) as client: dref = b try: value = client.getDREF(dref) return str(value[0]) except: return None
def getInfo(dref, host): with xpc.XPlaneConnect(xpHost=host) as client: value = client.getDREF(dref) #return value if '1' in str(value[0]): return 1 else: return 0
def monitor(): with xpc.XPlaneConnect() as client: while True: posi = client.getPOSI() ctrl = client.getCTRL() print "Loc: (%4f, %4f, %4f) Aileron:%2f Elevator:%2f Rudder:%2f\n"\ % (posi[0], posi[1], posi[2], ctrl[1], ctrl[0], ctrl[2])
def ex(): print("Setting up simulation") with xpc.XPlaneConnect(timeout=1000) as client: # Verify connection try: # If X-Plane does not respond to the request, a timeout error # will be raised. client.getDREF("sim/test/test_float") except: print("Error establishing connection to X-Plane.") print("Exiting...") return print("Entering Full Simulation") pe = PhysicsEngine(client) count = 0 start_t = time.time() state = 'xp' #or 'sharpy' while True: # main loop count += 1 try: if pe.controls[5] == 0: if state == 'xp': pe.client.pauseSim(True) pe.get_position() pe.reset_position() pe.update_position() state = 'sharpy' pe.get_position() pe.get_controls() pe.calculate_position() pe.update_position() else: if state == 'sharpy': state = 'xp' print("Not Simulating, raise flaps, press 1") pe.client.pauseSim(False) pe.get_controls() pe.get_position() time.sleep(0.5) except socket.timeout: print("Missed an update") sleep(10) break finish_t = time.time() print("Elapsed time") print(finish_t - start_t) print("Frequency") print(1000.0 / (finish_t - start_t)) input("Press any key to exit...")
def connect(self): self.client = xpc.XPlaneConnect(xpHost = '192.168.56.1') # Verify connection try: # If X-Plane does not respond to the request, a timeout error # will be raised. self.client.getDREF("sim/test/test_float") except: print "Error establishing connection to X-Plane." print "Exiting..." return
def connectToXPlane(self): self.client = xpc.XPlaneConnect('localhost', port=48000, timeout=1000) # Verify connection try: # If X-Plane does not respond to the request, a timeout error # will be raised. self.client.getDREF("sim/test/test_float") print("Connected to XPlane") except Exception as e: print("Error establishing connection to X-Plane.", e) print("Exiting...") return
def wrapper(*args, **kwargs): count = 0 while (count < 3): try: val = func(*args, **kwargs) return val except: count += 1 args[0].client = xpc.XPlaneConnect() print "recovered from disconnect" raise Exception( "Client disconnected and failed to reconnect three times")
def monitor(): with xpc.XPlaneConnect() as client: posi = client.getPOSI() posi_temp = list(posi) posi_temp[2] += 500 client.sendPOSI(posi_temp[0:len(posi_temp) - 6]) client.sendPOSI(posi_temp[0:len(posi_temp) - 6], 1) time.sleep(0.02) while len(posi_raw) < SET_NUM_DATAPOINTS: if posi != []: posi_raw.append(list(client.getPOSI())) controls_raw.append(list(client.getCTRL())) time.sleep(0.02)
def monitor(): with xpc.XPlaneConnect() as client: while True: posi = client.getPOSI(); ctrl = client.getCTRL(); states.append(list(posi)) controls.append(list(ctrl)) print(states) #Height, airspeed, roll, pitch, yaw, aroll, apitch, ayaw #Throttle, roll, pitch, yaw # print "Loc: (%4f, %4f, %4f) Aileron:%2f Elevator:%2f Rudder:%2f\n"\ # % (posi[0], posi[1], posi[2], ctrl[1], ctrl[0], ctrl[2]) time.sleep(0.01)
def ex(): print("X-Plane Connect example script") print("Setting up simulation") with xpc.XPlaneConnect() as client: # Verify connection try: # If X-Plane does not respond to the request, a timeout error # will be raised. client.getDREF("sim/test/test_float") except: print("Error establishing connection to X-Plane.") print("Exiting...") return
def check_xplane_connection(): while True: print("Trying to connect to X-Plane...") client = xpc.XPlaneConnect() try: # If X-Plane does not respond to the request, a timeout error # will be raised. client.getDREF("sim/test/test_float") # app.connected_to_xplane = True return except: print("Error establishing connection to X-Plane.") print("Retrying...") time.sleep(10)
def __init__(self): super(RootWidget, self).__init__() global client global event1 global start_time global current_time global elapsed_time global pausestate global airportagl global airportaglval pausestate=False elapsed_time=0 current_time=0 start_time=0 success = 0 # Connect the to the XPC plugin running inside xplane (localhost for same machine, other is for remote (ip will need to be changed to suit)) client=xpc.XPlaneConnect("localhost", 49009,49010) #client = xpc.XPlaneConnect("192.168.1.7", 49009, 49010) # Looping to wait for the connection while success == 0: try: client.getDREF("sim/test/test_float") success = 1 except: print 'Unable to Connect, retrying in 5s' sleep(5) # sleep to wait for setup, then setting clocks to tick to read data from xplane # and fail the set failures as needed # also handle the cloud layers based on the current UI state sleep(1) #event1= Clock.schedule_interval(self.getVars, 1) event2= Clock.schedule_interval(self.autoFail, 1) event3= Clock.schedule_interval(self.cloudController,1) event4= Clock.schedule_interval(self.adaptiveUI,1) event5=Clock.schedule_interval(self.fuelLeak,1) client.sendDREF("sim/private/controls/clouds/cloud_shadow_lighten_ratio",0) client.sendDREF("sim/cockpit/electrical/strobe_lights_on",0) airportagl=client.getDREF("sim/flightmodel/position/elevation") airportaglval=airportagl[0]#(airportagl[0]*0.3048)-3.6576
def playback(path, interval): try: fd = open(path, "r") except: print "Unable to open file." return with xpc.XPlaneConnect("localhost", 49009, 0, 1000) as client: print "Starting Playback..." for line in fd: try: posi = [float(x) for x in line.split(',')] posi = client.sendPOSI(posi) except: print "Error sending position" continue sleep(interval) print "Playback Complete" fd.close()
def monitor(): global nextTimestep,timestep,posi_raw,controls_raw,names_from_mpc,names_from_xplane,timestepWhichHasFinishedSendingToXPlane with xpc.XPlaneConnect() as client: posi = client.getPOSI() posi_temp = list(posi) posi_temp[2] += 500 client.sendPOSI(posi_temp[0:len(posi_temp)-6]) client.sendPOSI(posi_temp[0:len(posi_temp)-6], 1) time.sleep(0.02) while True: if timestep > timestepWhichHasFinishedSendingToXPlane: posi_temp = list(client.getPOSI()) if posi_temp != []: posi_raw = list(posi_temp) controls_raw = list(client.getCTRL()) control_list = [names_from_mpc["ele"], names_from_mpc["ail"], names_from_mpc["rud"], names_from_mpc["throttle"]] # print("control_list", control_list) client.sendCTRL(control_list) # timestep = timestep + 1 timestepWhichHasFinishedSendingToXPlane = timestep # print("Run") time.sleep(0.02)
def __init__(self, pilot, pilot_name): self.duration = 90 self.client = xpc.XPlaneConnect() self.state = PlaneState(0,0,0,0, reward_functions.fly_flat_reward) self.agent = pilot self.name = pilot_name self.episode = 0 self.steps_overall = 0 self.startLocation = { 'lat': 37.524, 'lon': -122.06899, 'alt': 2500, 'pitch': 0, 'roll': 0, 'heading': 0, 'gear': 0, 'attack': [18, 0, -998, 0, -998, -998, -998, -998, -998], 'velocity': [ 3, 300, 300, 300, 130, -998, -998, -998, -998], 'orientation': [16, 0, 0, 0, -998, -998, -998, -998, -998], } self.total_reward = 0 self.reward_curve_data = []
def record(path, interval=0.1, duration=60): try: fd = open(path, "w") except: print "Unable to open file." return count = int(duration / interval) if count < 1: print "duration is less than a single frame." return with xpc.XPlaneConnect("localhost", 49009, 0, 1000) as client: print "Recording..." for i in range(0, count): try: posi = client.getPOSI() fd.write("{0}, {1}, {2}, {3}, {4}, {5}, {6}\n".format(*posi)) except: print "Error reading position" continue sleep(interval) print "Recording Complete" fd.close()
def btn_taxi_lights_off(self): print("Taxi Lights Off") with xpc.XPlaneConnect() as client: taxi_lights_dref = "sim/cockpit/electrical/taxi_light_on" client.sendDREF(taxi_lights_dref, 0)
import xpc import sys import json with open("/var/www/html/sys/settings.json", "r+") as jsonFile: data = json.load(jsonFile) host = data[0]["ip"] with xpc.XPlaneConnect(xpHost=host) as client: drefs = ["sim/cockpit2/gauges/indicators/pitch_electric_deg_pilot", "sim/cockpit2/gauges/indicators/roll_electric_deg_pilot"] try: value = client.getDREFs(drefs) print(str(value)) except: print(None)
import xpc import threading from flask import Flask from flask import render_template from flask_socketio import SocketIO, emit, send from flask import copy_current_request_context app = Flask(__name__) #app.config['SECRET_KEY'] = 'secret!' app.debug = True socketio = SocketIO(app) client = xpc.XPlaneConnect(timeout=1000) panels = [ "xfmc/Panel_1", "xfmc/Panel_2", "xfmc/Panel_3", "xfmc/Panel_4", "xfmc/Panel_5", "xfmc/Panel_6", "xfmc/Panel_7", "xfmc/Panel_8", "xfmc/Panel_9", "xfmc/Panel_10", "xfmc/Panel_11", "xfmc/Panel_12", "xfmc/Upper", "xfmc/Scratch", "xfmc/Messages" ] old_messages = {} messages = {} status = None old_status = None status_dict = {} lon = None lat = None hdg = None position = {}
def btn_avionics_off(self): print("Avionics Off") with xpc.XPlaneConnect() as client: avionics_dref = "sim/cockpit/electrical/avionics_on" client.sendDREF(avionics_dref, 0)
def btn_battery_off(self): print("Battery Off") with xpc.XPlaneConnect() as client: battery_dref = "sim/cockpit/electrical/generator_on" client.sendDREF(battery_dref, 0)
def btn_ldn_lights_off(self): print("Landing Lights Off") with xpc.XPlaneConnect() as client: landinglights_dref = "sim/cockpit/electrical/landing_lights_on" client.sendDREF(landinglights_dref, 0)
def btn_beacon_lights_off(self): print("Beacon Lights Off") with xpc.XPlaneConnect() as client: beaconlights_dref = "sim/cockpit/electrical/beacon_lights_on" client.sendDREF(beaconlights_dref, 0)
async def send_data(websocket, path): print("Connection to X-Plane", flush=True) while not app.connected_to_xplane: await asyncio.sleep(1) client1 = xpc.XPlaneConnect() grossWt = "sim/flightmodel/weight/m_total" totalFuel = "sim/flightmodel/weight/m_fuel_total" egt = "sim/flightmodel2/engines/ITT_deg_C" n1 = "sim/cockpit2/engine/indicators/N1_percent" n2 = "sim/cockpit2/engine/indicators/N2_percent" tq = "sim/cockpit2/engine/indicators/torque_n_mtr" oilPress = "sim/cockpit2/engine/indicators/oil_pressure_psi" fuelTanks = "sim/flightmodel/weight/m_fuel" fuelFlow = "sim/cockpit2/engine/indicators/fuel_flow_kg_sec" oilTemp = "sim/cockpit2/engine/indicators/oil_temperature_deg_C" oilQty = "sim/flightmodel/engine/ENGN_oil_quan" lat = "sim/flightmodel/position/latitude" lon = "sim/flightmodel/position/longitude" hdg = "sim/flightmodel/position/true_psi" hyd1 = "sim/cockpit2/hydraulics/indicators/hydraulic_pressure_1" hyd2 = "sim/cockpit2/hydraulics/indicators/hydraulic_pressure_2" gen = "sim/cockpit2/electrical/generator_amps" genOn = "sim/cockpit/electrical/generator_on" bat = "sim/cockpit2/electrical/battery_voltage_actual_volts" mgbPress = "sim/flightmodel/transmissions/xmsn_press" mgbTemp = "sim/flightmodel/transmissions/xmsn_temp" payload = "sim/flightmodel/weight/m_fixed" pressure = "sim/weather/barometer_current_inhg" temperature = "sim/weather/temperature_ambient_c" while True: values = dict() try: res = client1.getDREFs([egt, n1, n2, tq, fuelTanks, fuelFlow, oilTemp, oilPress, oilQty, lat, lon, hyd1, hyd2, genOn, gen, bat, mgbTemp, mgbPress, hdg, grossWt, totalFuel, payload, pressure, temperature]) values["egt_1"] = round(res[0][0], 0) values["egt_2"] = round(res[0][1], 0) values["n1_1"] = "{:.1f}".format(round(res[1][0], 1)) values["n1_2"] = "{:.1f}".format(round(res[1][1], 1)) values["n2_1"] = "{:.1f}".format(abs(round(res[2][0], 1))) values["n2_2"] = "{:.1f}".format(abs(round(res[2][1], 1))) values["trq_1"] = "{:.1f}".format(abs(round(res[3][0]/118.5, 1))) values["trq_2"] = "{:.1f}".format(abs(round(res[3][1]/118.5, 1))) values["fuel_0"] = round(res[4][0] / 2, 0) values["fuel_1"] = round(res[4][1], 0) values["fuel_2"] = round(res[4][0] / 2, 0) values["fuelf_0"] = round(res[5][0] * 3600 / 2, 0) values["fuelf_1"] = round(res[5][1] * 3600 / 2, 0) values["oiltemp_1"] = "{:.1f}".format(round(res[6][0], 1)) values["oiltemp_2"] = "{:.1f}".format(round(res[6][1], 1)) values["oilpress_1"] = round(res[7][0], 1) values["oilpress_2"] = round(res[7][1], 1) values["oil_1"] = round(res[8][0], 1) values["oil_2"] = round(res[8][1], 1) values["lat"] = round(res[9][0], 4) values["lon"] = round(res[10][0], 4) values["hyd_1"] = round(res[11][0], 2) values["hyd_2"] = round(res[12][0], 2) values["gen_1"] = res[13][0] values["gen_2"] = res[13][1] values["genamps_1"] = "{:.1f}".format(round(res[14][0], 1)) values["genamps_2"] = "{:.1f}".format(round(res[14][1], 1)) values["bat"] = "{:.1f}".format(round(res[15][0], 1)) values["mgb_t"] = "{:.1f}".format(round(res[16][0], 1)) values["mgb_p"] = "{:.1f}".format(round(res[17][0], 1)) values["hdg"] = "{:0>3.0f}".format(round(res[18][0], 0)) values["weight"] = round(res[19][0], 0) values["fuel_t"] = round(res[20][0], 0) values["weight_p"] = round(res[21][0], 0) values["weight_e"] = round(res[19][0] - res[20][0] - res[21][0], 0) values["pressure"] = "{:.2f}".format(res[22][0]) values["temperature"] = "{:.1f}".format(res[23][0]) except ValueError: print("ValueError, reconnecting to X-Plane") values = {} except socket.timeout: print("Socket timeout") values = {} except Exception as inst: print(type(inst)) print(inst.args) #client = xpc.XPlaneConnect() continue json_val = json.dumps(values) await websocket.send(json_val) await asyncio.sleep(0.10)
def btn_nav_lights_off(self): print("Nav Lights Off") with xpc.XPlaneConnect() as client: nav_lights_dref = "sim/cockpit/electrical/nav_lights_on" client.sendDREF(nav_lights_dref, 0)
def btn_pitot_on(self): print("Pitot On") with xpc.XPlaneConnect() as client: pitot_dref = "sim/cockpit/switches/pitot_heat_on" client.sendDREF(pitot_dref, 1)
def btn_fuel_pump_off(self): print("Fuel Pump Off") with xpc.XPlaneConnect() as client: fuel_pump_dref = "sim/cockpit/engine/fuel_pump_on" client.sendDREF(fuel_pump_dref, 0)
def btn_strobe_lights_off(self): print("Strobe Lights Off") with xpc.XPlaneConnect() as client: strobe_lights_dref = "sim/cockpit/electrical/strobe_lights_on" client.sendDREF(strobe_lights_dref, 0)