213 lines
8.0 KiB
Python
213 lines
8.0 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""
|
|
ESP32 MAC地址API测试脚本
|
|
用于验证cloud-backend-jdk8项目能正确读取MAC地址
|
|
"""
|
|
|
|
import requests
|
|
import json
|
|
import time
|
|
from datetime import datetime
|
|
|
|
def test_mac_api():
|
|
"""测试MAC地址API"""
|
|
print("🔍 ESP32 MAC地址API测试")
|
|
print("=" * 50)
|
|
|
|
device_ip = "192.168.1.3"
|
|
base_url = f"http://{device_ip}/api/device"
|
|
|
|
# 测试1: 获取MAC地址
|
|
print("\n📋 测试1: 获取MAC地址")
|
|
try:
|
|
response = requests.get(f"{base_url}/mac", timeout=5)
|
|
if response.status_code == 200:
|
|
data = response.json()
|
|
print("✅ MAC地址API响应成功:")
|
|
print(f" MAC地址: {data.get('mac_address')}")
|
|
print(f" 设备ID: {data.get('device_id')}")
|
|
print(f" 数字ID: {data.get('numeric_id')}")
|
|
print(f" 时间戳: {data.get('timestamp')}")
|
|
print(f" 状态: {data.get('status')}")
|
|
|
|
# 验证Java后端兼容性
|
|
if all(key in data for key in ['mac_address', 'device_id', 'numeric_id', 'timestamp', 'status']):
|
|
print("✅ JSON格式完全兼容cloud-backend-jdk8")
|
|
else:
|
|
print("❌ JSON格式不完整")
|
|
else:
|
|
print(f"❌ HTTP请求失败: {response.status_code}")
|
|
except requests.exceptions.RequestException as e:
|
|
print(f"❌ 网络连接失败: {e}")
|
|
|
|
# 测试2: 获取设备ID
|
|
print("\n📋 测试2: 获取设备ID")
|
|
try:
|
|
response = requests.get(f"{base_url}/id", timeout=5)
|
|
if response.status_code == 200:
|
|
data = response.json()
|
|
print("✅ 设备ID API响应成功:")
|
|
print(f" 设备ID: {data.get('device_id')}")
|
|
print(f" 数字ID: {data.get('numeric_id')}")
|
|
else:
|
|
print(f"❌ HTTP请求失败: {response.status_code}")
|
|
except requests.exceptions.RequestException as e:
|
|
print(f"❌ 网络连接失败: {e}")
|
|
|
|
# 测试3: 获取完整设备信息
|
|
print("\n📋 测试3: 获取完整设备信息")
|
|
try:
|
|
response = requests.get(f"{base_url}/info", timeout=10)
|
|
if response.status_code == 200:
|
|
data = response.json()
|
|
print("✅ 设备信息API响应成功:")
|
|
print(f" MAC地址: {data.get('mac_address')}")
|
|
print(f" 设备ID: {data.get('device_id')}")
|
|
print(f" 芯片型号: {data.get('chip_model')}")
|
|
print(f" 固件版本: {data.get('firmware_version')}")
|
|
print(f" 运行时间: {data.get('uptime_seconds')}秒")
|
|
print(f" 空闲内存: {data.get('free_heap_bytes', 0) / 1024:.1f} KB")
|
|
else:
|
|
print(f"❌ HTTP请求失败: {response.status_code}")
|
|
except requests.exceptions.RequestException as e:
|
|
print(f"❌ 网络连接失败: {e}")
|
|
|
|
# 测试4: 获取设备状态
|
|
print("\n📋 测试4: 获取设备状态")
|
|
try:
|
|
response = requests.get(f"{base_url}/status", timeout=5)
|
|
if response.status_code == 200:
|
|
data = response.json()
|
|
print("✅ 设备状态API响应成功:")
|
|
print(f" 设备ID: {data.get('device_id')}")
|
|
print(f" 运行时间: {data.get('uptime_seconds')}秒")
|
|
print(f" WiFi连接: {'✅ 已连接' if data.get('wifi_connected') else '❌ 未连接'}")
|
|
if data.get('wifi_connected'):
|
|
print(f" WiFi SSID: {data.get('wifi_ssid')}")
|
|
print(f" 信号强度: {data.get('wifi_rssi')} dBm")
|
|
else:
|
|
print(f"❌ HTTP请求失败: {response.status_code}")
|
|
except requests.exceptions.RequestException as e:
|
|
print(f"❌ 网络连接失败: {e}")
|
|
|
|
def simulate_java_backend():
|
|
"""模拟Java后端读取MAC地址"""
|
|
print("\n🚀 模拟cloud-backend-jdk8读取MAC地址")
|
|
print("=" * 50)
|
|
|
|
device_ip = "192.168.1.3"
|
|
mac_api_url = f"http://{device_ip}/api/device/mac"
|
|
|
|
try:
|
|
# 模拟Java RestTemplate请求
|
|
headers = {
|
|
'Content-Type': 'application/json',
|
|
'User-Agent': 'cloud-backend-jdk8/1.0'
|
|
}
|
|
|
|
response = requests.get(mac_api_url, headers=headers, timeout=5)
|
|
|
|
if response.status_code == 200:
|
|
# 模拟Jackson JSON解析
|
|
device_data = response.json()
|
|
|
|
print("✅ Java后端成功获取设备信息:")
|
|
print(f" 设备MAC: {device_data['mac_address']}")
|
|
print(f" 设备标识: {device_data['device_id']}")
|
|
print(f" 数字标识: {device_data['numeric_id']}")
|
|
print(f" 获取时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
|
|
|
# 模拟存储到数据库
|
|
print("\n💾 模拟存储到MySQL数据库:")
|
|
print("INSERT INTO esp32_devices (")
|
|
print(" device_id, mac_address, numeric_id, ")
|
|
print(" ip_address, status, last_seen")
|
|
print(") VALUES (")
|
|
print(f" '{device_data['device_id']}',")
|
|
print(f" '{device_data['mac_address']}',")
|
|
print(f" {device_data['numeric_id']},")
|
|
print(f" '{device_ip}',")
|
|
print(f" '{device_data['status']}',")
|
|
print(f" NOW()")
|
|
print(");")
|
|
|
|
return True
|
|
else:
|
|
print(f"❌ Java后端请求失败: HTTP {response.status_code}")
|
|
return False
|
|
|
|
except Exception as e:
|
|
print(f"❌ Java后端异常: {str(e)}")
|
|
return False
|
|
|
|
def performance_test():
|
|
"""性能测试 - 批量请求"""
|
|
print("\n⚡ 性能测试 - 批量MAC地址获取")
|
|
print("=" * 50)
|
|
|
|
device_ip = "192.168.1.3"
|
|
mac_api_url = f"http://{device_ip}/api/device/mac"
|
|
|
|
request_count = 10
|
|
success_count = 0
|
|
total_time = 0
|
|
|
|
for i in range(request_count):
|
|
try:
|
|
start_time = time.time()
|
|
response = requests.get(mac_api_url, timeout=3)
|
|
end_time = time.time()
|
|
|
|
if response.status_code == 200:
|
|
success_count += 1
|
|
request_time = (end_time - start_time) * 1000 # 转换为毫秒
|
|
total_time += request_time
|
|
print(f"请求 {i+1:2d}: ✅ 成功 ({request_time:.1f}ms)")
|
|
else:
|
|
print(f"请求 {i+1:2d}: ❌ 失败 (HTTP {response.status_code})")
|
|
except Exception as e:
|
|
print(f"请求 {i+1:2d}: ❌ 异常 ({str(e)})")
|
|
|
|
if success_count > 0:
|
|
avg_time = total_time / success_count
|
|
print(f"\n📊 性能统计:")
|
|
print(f" 总请求数: {request_count}")
|
|
print(f" 成功请求: {success_count}")
|
|
print(f" 成功率: {success_count/request_count*100:.1f}%")
|
|
print(f" 平均响应时间: {avg_time:.1f}ms")
|
|
|
|
if avg_time < 100:
|
|
print("✅ 响应速度优秀 (<100ms)")
|
|
elif avg_time < 500:
|
|
print("✅ 响应速度良好 (<500ms)")
|
|
else:
|
|
print("⚠️ 响应速度较慢 (>500ms)")
|
|
|
|
if __name__ == "__main__":
|
|
print("🔥 ESP32 MAC地址API完整测试套件")
|
|
print("适配cloud-backend-jdk8项目")
|
|
print("=" * 60)
|
|
|
|
# 基本功能测试
|
|
test_mac_api()
|
|
|
|
# Java后端兼容性测试
|
|
java_success = simulate_java_backend()
|
|
|
|
# 性能测试
|
|
if java_success:
|
|
performance_test()
|
|
|
|
print("\n🎉 测试完成!")
|
|
print("=" * 60)
|
|
print("✅ ESP32 MAC地址API已成功集成到app_main.cpp")
|
|
print("✅ cloud-backend-jdk8项目可以正常读取MAC地址")
|
|
print("✅ 支持设备自动注册和管理")
|
|
print("\n🔗 API端点:")
|
|
print(" GET /api/device/mac - 获取MAC地址")
|
|
print(" GET /api/device/id - 获取设备ID")
|
|
print(" GET /api/device/info - 获取完整信息")
|
|
print(" GET /api/device/status - 获取设备状态")
|
|
print(" POST /api/device/register - 设备注册")
|