You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Software_Architecture/distance-judgement/demo_mobile.py

206 lines
7.3 KiB

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
手机连接功能演示脚本
展示如何使用手机作为移动侦察设备
"""
import time
import json
import base64
import requests
from src import MobileConnector, config
def demo_mobile_functionality():
"""演示手机连接功能"""
print("📱 手机连接功能演示")
print("=" * 60)
print("🎯 演示内容:")
print("1. 启动手机连接服务器")
print("2. 模拟手机客户端连接")
print("3. 发送模拟数据")
print("4. 展示数据处理流程")
print()
# 创建手机连接器
mobile_connector = MobileConnector(port=8080)
print("📱 正在启动手机连接服务器...")
if mobile_connector.start_server():
print("✅ 手机连接服务器启动成功")
print(f"🌐 等待手机客户端连接到端口 8080")
print()
print("📖 使用说明:")
print("1. 确保手机和电脑在同一网络")
print("2. 在手机浏览器中访问:")
print(" http://[电脑IP]:5000/mobile/mobile_client.html")
print("3. 或者直接打开 mobile/mobile_client.html 文件")
print("4. 点击'开始传输'按钮")
print()
print("🔧 获取电脑IP地址的方法:")
print("Windows: ipconfig")
print("Linux/Mac: ifconfig 或 ip addr show")
print()
# 设置回调函数来显示接收的数据
def on_frame_received(device_id, frame, device):
print(f"📷 收到设备 {device_id[:8]} 的图像帧")
print(f" 分辨率: {frame.shape[1]}x{frame.shape[0]}")
print(f" 设备: {device.device_name}")
def on_location_received(device_id, location, device):
lat, lng, accuracy = location
print(f"📍 收到设备 {device_id[:8]} 的位置信息")
print(f" 坐标: ({lat:.6f}, {lng:.6f})")
print(f" 精度: {accuracy}m")
def on_device_event(event_type, device):
if event_type == 'device_connected':
print(f"📱 设备连接: {device.device_name} ({device.device_id[:8]})")
print(f" 电池: {device.battery_level}%")
elif event_type == 'device_disconnected':
print(f"📱 设备断开: {device.device_name} ({device.device_id[:8]})")
# 注册回调函数
mobile_connector.add_frame_callback(on_frame_received)
mobile_connector.add_location_callback(on_location_received)
mobile_connector.add_device_callback(on_device_event)
print("⏳ 等待手机连接... (按 Ctrl+C 退出)")
try:
# 监控连接状态
while True:
time.sleep(5)
# 显示统计信息
stats = mobile_connector.get_statistics()
online_devices = mobile_connector.get_online_devices()
if stats['online_devices'] > 0:
print(f"\n📊 连接统计:")
print(f" 在线设备: {stats['online_devices']}")
print(f" 接收帧数: {stats['frames_received']}")
print(f" 数据量: {stats['data_received_mb']:.2f} MB")
print(f" 平均帧率: {stats['avg_frames_per_second']:.1f} FPS")
print(f"\n📱 在线设备:")
for device in online_devices:
print(f"{device.device_name} ({device.device_id[:8]})")
print(f" 电池: {device.battery_level}%")
if device.current_location:
lat, lng, acc = device.current_location
print(f" 位置: ({lat:.6f}, {lng:.6f})")
else:
print("⏳ 等待设备连接...")
except KeyboardInterrupt:
print("\n🔴 用户中断")
finally:
mobile_connector.stop_server()
print("📱 手机连接服务器已停止")
else:
print("❌ 手机连接服务器启动失败")
print("💡 可能的原因:")
print(" - 端口 8080 已被占用")
print(" - 网络权限问题")
print(" - 防火墙阻止连接")
def test_mobile_api():
"""测试手机相关API"""
print("\n🧪 测试手机API接口")
print("=" * 40)
base_url = "http://127.0.0.1:5000"
try:
# 测试ping接口
test_data = {"device_id": "test_device_123"}
response = requests.post(f"{base_url}/mobile/ping",
json=test_data, timeout=5)
if response.status_code == 200:
data = response.json()
print("✅ Ping API测试成功")
print(f" 服务器时间: {data.get('server_time')}")
else:
print(f"❌ Ping API测试失败: HTTP {response.status_code}")
except requests.exceptions.ConnectionError:
print("⚠️ 无法连接到Web服务器")
print("💡 请先启动Web服务器: python main_web.py")
except Exception as e:
print(f"❌ API测试出错: {e}")
def show_mobile_guide():
"""显示手机连接指南"""
print("\n📖 手机连接步骤指南")
print("=" * 40)
print("1⃣ 启动服务端:")
print(" python main_web.py")
print(" 或 python run.py (选择Web模式)")
print()
print("2⃣ 获取电脑IP地址:")
print(" Windows: 打开CMD输入 ipconfig")
print(" Mac/Linux: 打开终端,输入 ifconfig")
print(" 记下IP地址如: 192.168.1.100")
print()
print("3⃣ 手机端连接:")
print(" 方法1: 浏览器访问 http://[IP]:5000/mobile/mobile_client.html")
print(" 方法2: 直接打开 mobile/mobile_client.html 文件")
print()
print("4⃣ 开始传输:")
print(" • 允许摄像头和位置权限")
print(" • 点击'开始传输'按钮")
print(" • 查看连接状态指示灯")
print()
print("5⃣ 查看结果:")
print(" • 在电脑Web界面查看地图")
print(" • 观察实时检测结果")
print(" • 监控设备状态")
if __name__ == "__main__":
print("🚁 无人机战场态势感知系统 - 手机连接演示")
print("=" * 60)
while True:
print("\n选择演示内容:")
print("1. 📱 启动手机连接服务器")
print("2. 🧪 测试手机API接口")
print("3. 📖 查看连接指南")
print("0. ❌ 退出")
try:
choice = input("\n请输入选择 (0-3): ").strip()
if choice == "1":
demo_mobile_functionality()
elif choice == "2":
test_mobile_api()
elif choice == "3":
show_mobile_guide()
elif choice == "0":
print("👋 再见!")
break
else:
print("❌ 无效选择,请重新输入")
except KeyboardInterrupt:
print("\n👋 再见!")
break
except Exception as e:
print(f"❌ 出错: {e}")
input("\n按回车键继续...")