#!/usr/bin/env python3
"""
Go2管道方法详细调试程序
"""

import os
import subprocess
import time
import signal

def check_gstreamer_installation():
    """检查GStreamer安装情况"""
    print("=== 检查GStreamer安装 ===")
    
    try:
        # 检查gst-launch-1.0
        result = subprocess.run(['gst-launch-1.0', '--version'], 
                              capture_output=True, text=True)
        print(f"✓ GStreamer版本: {result.stdout.strip()}")
    except FileNotFoundError:
        print("✗ gst-launch-1.0 未找到")
        return False
    
    # 检查关键插件
    plugins = ['udpsrc', 'rtph264depay', 'h264parse', 'avdec_h264', 'videoconvert', 'filesink']
    print("\n检查GStreamer插件:")
    for plugin in plugins:
        try:
            result = subprocess.run(['gst-inspect-1.0', plugin], 
                                  capture_output=True, text=True)
            if result.returncode == 0:
                print(f"✓ {plugin}")
            else:
                print(f"✗ {plugin} - 未找到")
        except:
            print(f"? {plugin} - 无法检查")
    
    return True

def test_simple_gstreamer():
    """测试简单的GStreamer管道"""
    print("\n=== 测试简单GStreamer管道 ===")
    
    # 测试1: 最简单的测试源
    print("测试1: videotestsrc")
    cmd = ['timeout', '3', 'gst-launch-1.0', 'videotestsrc', '!', 'fakesink']
    result = subprocess.run(cmd, capture_output=True, text=True)
    if result.returncode == 0:
        print("✓ videotestsrc 正常")
    else:
        print(f"✗ videotestsrc 失败: {result.stderr}")
    
    # 测试2: UDP源
    print("\n测试2: udpsrc (无数据)")
    cmd = ['timeout', '3', 'gst-launch-1.0', 'udpsrc', 'port=5000', '!', 'fakesink']
    result = subprocess.run(cmd, capture_output=True, text=True)
    print(f"udpsrc测试: {'成功' if result.returncode == 0 else '失败'}")

def test_go2_gstreamer_manual(interface="enx00e0986113a6"):
    """手动测试Go2的GStreamer管道"""
    print(f"\n=== 手动测试Go2 GStreamer管道 ===")
    print(f"接口: {interface}")
    
    # 构建管道命令
    pipeline = (
        f"udpsrc address=230.1.1.1 port=1720 multicast-iface={interface} "
        "! application/x-rtp, media=video, encoding-name=H264 ! rtph264depay ! h264parse "
        "! avdec_h264 ! videoconvert ! video/x-raw,format=BGR,width=1280,height=720 "
        "! filesink location=/tmp/test_video.raw"
    )
    
    print(f"管道: {pipeline}")
    
    # 启动GStreamer
    try:
        proc = subprocess.Popen(['gst-launch-1.0'] + pipeline.split(), 
                               stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        
        print("GStreamer进程已启动，PID:", proc.pid)
        print("等待5秒...")
        time.sleep(5)
        
        # 检查进程状态
        if proc.poll() is None:
            print("✓ GStreamer进程仍在运行")
            proc.terminate()
            proc.wait(timeout=3)
            print("✓ 进程已终止")
        else:
            print(f"✗ GStreamer进程已退出，返回码: {proc.returncode}")
            print(f"错误输出: {proc.stderr.decode()}")
            
    except Exception as e:
        print(f"启动GStreamer失败: {e}")

def test_pipe_creation():
    """测试命名管道创建"""
    print("\n=== 测试命名管道创建 ===")
    
    pipe_path = "/tmp/test_pipe"
    
    try:
        # 清理旧管道
        if os.path.exists(pipe_path):
            os.remove(pipe_path)
            print(f"清理旧管道: {pipe_path}")
        
        # 创建管道
        os.mkfifo(pipe_path)
        print(f"✓ 创建管道成功: {pipe_path}")
        
        # 测试写入
        test_data = b"test data"
        proc = subprocess.Popen(['tee', pipe_path], stdin=subprocess.PIPE)
        proc.communicate(input=test_data, timeout=2)
        print("✓ 管道写入测试成功")
        
        # 清理
        os.remove(pipe_path)
        print("✓ 管道清理完成")
        
    except Exception as e:
        print(f"✗ 管道测试失败: {e}")

def check_system_resources():
    """检查系统资源"""
    print("\n=== 检查系统资源 ===")
    
    # 检查权限
    print(f"当前用户: {os.getenv('USER', 'unknown')}")
    print(f"当前目录: {os.getcwd()}")
    print(f"TMP目录权限: {oct(os.stat('/tmp').st_mode)[-3:]}")
    
    # 检查进程
    try:
        result = subprocess.run(['ps', 'aux'], capture_output=True, text=True)
        gst_processes = [line for line in result.stdout.split('\n') if 'gst-launch' in line]
        if gst_processes:
            print(f"发现 {len(gst_processes)} 个GStreamer进程:")
            for proc in gst_processes:
                print(f"  {proc}")
        else:
            print("✓ 没有残留的GStreamer进程")
    except:
        print("无法检查进程")

def main():
    print("Go2管道方法详细调试")
    print("=" * 50)
    
    # 设置环境
    os.environ["DISPLAY"] = ":0"
    
    # 执行各项检查
    if not check_gstreamer_installation():
        print("\n❌ GStreamer安装有问题，请先安装GStreamer")
        return
    
    test_simple_gstreamer()
    test_pipe_creation()
    check_system_resources()
    test_go2_gstreamer_manual()
    
    print("\n=== 调试完成 ===")
    print("如果所有测试都通过，问题可能是:")
    print("1. 机器狗未发送视频流")
    print("2. 网络接口名称不正确")
    print("3. 防火墙阻止UDP端口1720")
    print("4. GStreamer插件版本不兼容")

if __name__ == "__main__":
    main()