#!/usr/bin/env python3
"""
检查Go2机器狗视频流状态
"""

import socket
import time
import subprocess

def check_go2_connection():
    """检查Go2机器狗连接"""
    print("=== 检查Go2机器狗连接 ===")
    
    # 常见的Go2 IP地址
    go2_ips = ['192.168.123.1', '192.168.123.10', '192.168.123.100']
    
    for ip in go2_ips:
        try:
            result = subprocess.run(['ping', '-c', '2', ip], 
                                  capture_output=True, text=True, timeout=5)
            if result.returncode == 0:
                print(f"✓ 找到Go2机器狗: {ip}")
                return ip
        except:
            continue
    
    print("✗ 未找到Go2机器狗")
    return None

def monitor_multicast_traffic():
    """监听多播流量"""
    print("\n=== 监听多播流量 ===")
    print("监听地址: 230.1.1.1:1720")
    print("等待30秒，检查是否有数据包...")
    
    try:
        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(1.0)
        
        packet_count = 0
        start_time = time.time()
        
        while time.time() - start_time < 30:
            try:
                data, addr = sock.recvfrom(2048)
                packet_count += 1
                print(f"收到数据包 #{packet_count}: {len(data)} 字节，来自 {addr}")
                
                # 检查是否是H.264数据
                if len(data) > 4:
                    # H.264 NAL单元通常以0x00000001或0x000001开头
                    if data[:4] == b'\x00\x00\x00\x01' or data[:3] == b'\x00\x00\x01':
                        print("  -> 检测到H.264数据流")
                    
            except socket.timeout:
                continue
            except Exception as e:
                print(f"接收错误: {e}")
                break
        
        sock.close()
        
        if packet_count > 0:
            print(f"\n✓ 总共收到 {packet_count} 个数据包")
            print("视频流正在传输！")
        else:
            print("\n✗ 未收到任何数据包")
            print("机器狗可能未开启视频流")
            
    except Exception as e:
        print(f"监听失败: {e}")

def test_gstreamer_direct():
    """直接使用GStreamer命令行测试"""
    print("\n=== GStreamer命令行测试 ===")
    
    pipeline = "udpsrc address=230.1.1.1 port=1720 ! application/x-rtp, media=video, encoding-name=H264 ! rtph264depay ! h264parse ! avdec_h264 ! videoconvert ! autovideosink"
    
    print(f"测试管道: {pipeline}")
    print("运行10秒...")
    
    try:
        # 使用gst-launch-1.0测试
        cmd = ['timeout', '10', 'gst-launch-1.0'] + pipeline.split(' ')
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        if result.returncode == 0:
            print("✓ GStreamer管道测试成功")
        else:
            print("✗ GStreamer管道测试失败")
            print(f"错误: {result.stderr}")
            
    except Exception as e:
        print(f"GStreamer测试失败: {e}")

def main():
    print("Go2视频流状态检查")
    print("=" * 40)
    
    # 检查机器狗连接
    go2_ip = check_go2_connection()
    
    if not go2_ip:
        print("\n请检查:")
        print("1. 机器狗是否已开机")
        print("2. 网线是否正确连接")
        print("3. 机器狗和灵芯派是否在同一网段")
        return
    
    # 监听多播流量
    monitor_multicast_traffic()
    
    # GStreamer测试
    test_gstreamer_direct()
    
    print("\n=== 总结 ===")
    print("如果未收到数据包，可能需要:")
    print("1. 在机器狗上启动视频流服务")
    print("2. 检查机器狗的网络配置")
    print("3. 确认机器狗支持多播视频流")

if __name__ == "__main__":
    main()