#!/usr/bin/env python3
"""
Go2网络和视频流详细诊断程序
用于排查灵芯派上的连接问题
"""

import os
import sys
import time
import subprocess
import socket
import cv2

def check_opencv_version():
    """检查OpenCV版本和功能"""
    print("=== OpenCV信息 ===")
    try:
        print(f"OpenCV版本: {cv2.__version__}")
        
        # 检查可用的方法
        methods = ['getCvBuildInformation', 'CAP_GSTREAMER', 'VideoCapture']
        for method in methods:
            if hasattr(cv2, method):
                print(f"✓ cv2.{method} 可用")
            else:
                print(f"✗ cv2.{method} 不可用")
        
        # 尝试获取构建信息
        if hasattr(cv2, 'getCvBuildInformation'):
            try:
                info = cv2.getCvBuildInformation()
                if 'GStreamer' in info:
                    print("✓ GStreamer支持: 是")
                else:
                    print("✗ GStreamer支持: 否")
            except:
                print("? GStreamer支持: 无法检测")
        else:
            print("? GStreamer支持: 无法检测 (getCvBuildInformation不存在)")
            
    except Exception as e:
        print(f"检查OpenCV失败: {e}")

def check_network_interface(interface_name):
    """检查网络接口状态"""
    print(f"\n=== 网络接口检查: {interface_name} ===")
    
    try:
        # 检查接口是否存在
        result = subprocess.run(['ip', 'link', 'show', interface_name], 
                              capture_output=True, text=True)
        if result.returncode == 0:
            print(f"✓ 网络接口 {interface_name} 存在")
            print(result.stdout)
        else:
            print(f"✗ 网络接口 {interface_name} 不存在")
            return False
            
        # 检查接口IP地址
        result = subprocess.run(['ip', 'addr', 'show', interface_name], 
                              capture_output=True, text=True)
        if 'inet ' in result.stdout:
            print(f"✓ 接口已配置IP地址")
            # 提取IP地址
            import re
            ip_match = re.search(r'inet (\d+\.\d+\.\d+\.\d+)', result.stdout)
            if ip_match:
                print(f"  IP地址: {ip_match.group(1)}")
        else:
            print(f"✗ 接口未配置IP地址")
            
    except Exception as e:
        print(f"检查网络接口失败: {e}")
        return False
    
    return True

def check_multicast_receive():
    """检查多播接收能力"""
    print("\n=== 多播接收测试 ===")
    
    try:
        # 创建UDP套接字
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        
        # 绑定到多播地址和端口
        sock.bind(('230.1.1.1', 1720))
        
        # 加入多播组
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, 
                       socket.inet_aton('230.1.1.1') + socket.inet_aton('0.0.0.0'))
        
        sock.settimeout(5.0)  # 5秒超时
        
        print("监听多播地址 230.1.1.1:1720 (等待5秒)...")
        
        try:
            data, addr = sock.recvfrom(2048)
            print(f"✓ 接收到数据: {len(data)} 字节，来自 {addr}")
            print("✓ 多播接收正常")
            return True
        except socket.timeout:
            print("✗ 5秒内未接收到数据")
            print("可能原因:")
            print("  - 机器狗未发送视频流")
            print("  - 网络连接问题")
            print("  - 防火墙阻止")
            return False
        finally:
            sock.close()
            
    except Exception as e:
        print(f"多播测试失败: {e}")
        return False

def test_gstreamer_pipeline(interface_name):
    """测试GStreamer管道的不同配置"""
    print(f"\n=== GStreamer管道测试 ===")
    
    # 测试不同的管道配置
    pipelines = [
        # 基础配置
        f"udpsrc address=230.1.1.1 port=1720 multicast-iface={interface_name} ! application/x-rtp, media=video, encoding-name=H264 ! rtph264depay ! h264parse ! avdec_h264 ! videoconvert ! video/x-raw,format=BGR ! appsink",
        
        # 添加错误处理
        f"udpsrc address=230.1.1.1 port=1720 multicast-iface={interface_name} ! application/x-rtp, media=video, encoding-name=H264 ! rtph264depay ! h264parse ! avdec_h264 ! videoconvert ! video/x-raw,format=BGR ! appsink drop=1 sync=false",
        
        # 简化配置
        f"udpsrc address=230.1.1.1 port=1720 multicast-iface={interface_name} ! application/x-rtp ! rtph264depay ! h264parse ! avdec_h264 ! videoconvert ! appsink",
    ]
    
    for i, pipeline in enumerate(pipelines, 1):
        print(f"\n测试配置 {i}:")
        print(f"管道: {pipeline}")
        
        try:
            cap = cv2.VideoCapture(pipeline, cv2.CAP_GSTREAMER)
            if cap.isOpened():
                print("✓ 管道打开成功")
                
                # 尝试读取一帧
                ret, frame = cap.read()
                if ret:
                    print(f"✓ 成功读取帧: {frame.shape}")
                    cap.release()
                    return True
                else:
                    print("✗ 无法读取帧")
                cap.release()
            else:
                print("✗ 管道打开失败")
                
        except Exception as e:
            print(f"✗ 测试失败: {e}")
    
    return False

def check_system_info():
    """检查系统信息"""
    print("\n=== 系统信息 ===")
    
    try:
        # 检查操作系统
        result = subprocess.run(['uname', '-a'], capture_output=True, text=True)
        print(f"系统: {result.stdout.strip()}")
        
        # 检查Python版本
        print(f"Python版本: {sys.version}")
        
        # 检查GStreamer是否安装
        try:
            result = subprocess.run(['gst-launch-1.0', '--version'], 
                                  capture_output=True, text=True)
            print(f"✓ GStreamer已安装: {result.stdout.strip()}")
        except FileNotFoundError:
            print("✗ GStreamer未安装或不在PATH中")
            
        # 检查网络连接
        result = subprocess.run(['ping', '-c', '1', '8.8.8.8'], 
                              capture_output=True, text=True)
        if result.returncode == 0:
            print("✓ 外网连接正常")
        else:
            print("✗ 外网连接异常")
            
    except Exception as e:
        print(f"系统信息检查失败: {e}")

def main():
    print("Go2网络和视频流详细诊断")
    print("=" * 50)
    
    # 获取网络接口名称
    interface = "enx00e0986113a6"  # 从之前的输出获取
    
    # 执行各项检查
    check_system_info()
    check_opencv_version()
    
    if not check_network_interface(interface):
        print("\n❌ 网络接口检查失败，请检查硬件连接")
        return
    
    if not check_multicast_receive():
        print("\n❌ 多播接收测试失败")
        print("建议:")
        print("1. 确认机器狗已开机")
        print("2. 确认机器狗连接到同一网络")
        print("3. 检查防火墙设置")
        return
    
    if not test_gstreamer_pipeline(interface):
        print("\n❌ GStreamer管道测试失败")
        print("建议:")
        print("1. 重新安装支持GStreamer的OpenCV")
        print("2. 安装GStreamer开发包")
        print("3. 检查GStreamer插件是否完整")
        return
    
    print("\n✅ 所有测试通过！视频流应该可以正常工作")

if __name__ == "__main__":
    main()