You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Phyphox的F-16战斗机座舱虚拟仿真代码运行异常求助:窗口闪瞬即逝无显示

Troubleshooting Your F-16 Phyphox Cockpit Sim Immediate Crash

Hey there! I get how frustrating it is when your sim window pops up and vanishes before you can even see anything—let's dig into what's going wrong with your code and get that cockpit running smoothly.

First, Let's Fix the Silent Failure Problem

Your current code uses a super broad except: in get_data() that swallows every possible error without giving you any clues. If something goes wrong (like a failed Phyphox connection, missing sensor data, or even a missing Python package), you'll never know because it just returns None—and if the error is severe enough, it might crash the whole script outright.

Second, Stop the Window from Closing Instantly

On Windows, if your script crashes, the terminal window closes immediately so you can't read the error message. To fix this, either:

  • Run the script from a command prompt (open cmd, navigate to your script folder, and run python your_script.py), or
  • Add a pause at the end of your code to keep the window open if something breaks.

Third, Revised Code with Better Error Handling & Debugging

Here's a tweaked version of your code that adds clear error messages, validates Phyphox connectivity, and keeps the window open if a crash happens:

import requests
import time
import os

# --- CONFIGURATION ---
PHYPHOX_URL = "http://192.168.1.55:8080"

def get_data():
    try:
        # Requesting sensors including location
        url = f"{PHYPHOX_URL}/get?acc&att&light&location"
        print(f"Connecting to Phyphox at: {url}")  # Debug line to check connection target
        response = requests.get(url, timeout=2.0)  # Longer timeout for more reliable connection
        response.raise_for_status()  # Trigger error if HTTP request fails (e.g., wrong IP)
        data = response.json()
        
        # Check if core response structure exists
        if 'buffer' not in data:
            print("Error: Phyphox response missing 'buffer' key—did you enable the API?")
            return None
        
        r = data['buffer']
        # Validate each sensor is present before accessing
        sensor_status = {
            'acc': 'acc' in r,
            'att': 'att' in r,
            'light': 'light' in r,
            'location': 'location' in r
        }
        
        for sensor, is_present in sensor_status.items():
            if not is_present:
                print(f"Warning: {sensor} data not found in Phyphox response—enable it in Phyphox!")
        
        return {
            "acc": r['acc']['buffer'][0] if sensor_status['acc'] else 0.0,
            "pitch": r['att']['buffer'][0] if sensor_status['att'] else 0.0,
            "roll": r['att']['buffer'][1] if sensor_status['att'] else 0.0,
            "lux": r['light']['buffer'][0] if sensor_status['light'] else 0.0,
            "lat": r['location']['buffer'][0] if sensor_status['location'] else 0.0,
            "lon": r['location']['buffer'][1] if sensor_status['location'] else 0.0,
            "alt_gps": r['location']['buffer'][2] if sensor_status['location'] else 0.0,
            "speed_gps": r['location']['buffer'][3] if sensor_status['location'] else 0.0
        }
    except requests.exceptions.RequestException as e:
        print(f"Phyphox connection error: {str(e)}—check IP/Wi-Fi/API enabled?")
        return None
    except KeyError as e:
        print(f"Missing data key in Phyphox response: {str(e)}—sensor data format changed?")
        return None
    except Exception as e:
        print(f"Unexpected error: {str(e)}")
        return None

def main():
    try:
        while True:
            data = get_data()
            if data:
                # Convert GPS speed (m/s) to Knots
                speed_knots = data['speed_gps'] * 1.94384
                # Convert GPS altitude (m) to Feet
                alt_ft = data['alt_gps'] * 3.28084

                # --- RENDER COCKPIT ---
                os.system('cls' if os.name == 'nt' else 'clear')
                # HUD (Top Section)
                print(f"\033[92m") # Green HUD color
                print(f" SPD: {speed_knots:3.0f} KTS | V-ANGLE: {data['pitch']:+2.0f} | ALT: {alt_ft:5.0f} FT")
                print(f" " + "—"*50)
                print(f" Pitch: {data['pitch']:+4.1f}°")
                print(f" Roll: {data['roll']:+4.1f}°")
                print(f" AOA: {data['pitch']:4.1f}°")
                print(f" " + "—"*50)
                # MFDs (Lower Section)
                print(f"\n [ G-LOAD ] [ AMBIENT ] [ NAVIGATION ]")
                print(f" ---------- ----------- --------------")
                print(f" {data['acc']/9.81:4.2f} G {data['lux']:5.0f} LUX LAT: {data['lat']:.4f}")
                print(f" LON: {data['lon']:.4f}")
                print(f" ---------- ----------- --------------")
                print(f"\033[0m") # Reset color
            time.sleep(0.1)
    except KeyboardInterrupt:
        print("\nExiting sim...")
    except Exception as e:
        print(f"\nFatal error: {str(e)}")
        # Keep window open on crash (Windows-only)
        if os.name == 'nt':
            input("\nPress Enter to close...")

if __name__ == "__main__":
    main()

Quick Pre-Run Checks

  1. Phyphox Setup: Make sure Phyphox is running on your phone, Remote Access is enabled (Settings > Remote Access > Enable HTTP API), and your computer is on the same Wi-Fi network. Double-check the IP in PHYPHOX_URL matches what's shown in Phyphox's remote access settings.
  2. Dependencies: Run pip install requests if you haven't already to install the required library.
  3. Sensor Permissions: In Phyphox, ensure all sensors you're using (accelerometer, attitude, light, location) are enabled and have the necessary permissions on your phone.

Run the script from a command prompt now—if there's an issue, you'll see exactly what's wrong, making it easy to fix.

内容的提问来源于stack exchange,提问作者theguy inurcloset

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 09:22:40