多设备启动,端口固定,时间接口未返回

This commit is contained in:
2026-02-04 10:58:46 +08:00
parent cc59e8b8da
commit 9ce1dbadc1
22 changed files with 1344 additions and 297 deletions

204
main.py
View File

@@ -32,156 +32,11 @@ logging.basicConfig(
]
)
class DeviceAutomation:
@staticmethod
def get_device_id() -> str:
class DeviceAutomation(object):
# """
# 获取设备ID优先使用已连接设备否则使用全局配置
# """
# try:
# # 检查已连接设备
# result = subprocess.run(
# ["adb", "devices"],
# capture_output=True,
# text=True,
# timeout=10
# )
# # 解析设备列表
# for line in result.stdout.strip().split('\n')[1:]:
# if line.strip() and "device" in line and "offline" not in line:
# device_id = line.split('\t')[0]
# logging.info(f"使用已连接设备: {device_id}")
# global_variable.GLOBAL_DEVICE_ID = device_id
# return device_id
# except Exception as e:
# logging.warning(f"设备检测失败: {e}")
"""
获取设备ID优先使用无线连接设备否则尝试开启无线调试最后使用全局配置
"""
try:
# 检查已连接设备
result = subprocess.run(
["adb", "devices"],
capture_output=True,
text=True,
timeout=10
)
# 解析设备列表
wireless_device_id = None
usb_device_id = None
# 先查找无线连接的设备IP:端口格式)
for line in result.stdout.strip().split('\n')[1:]:
if line.strip() and "device" in line and "offline" not in line:
current_device = line.split('\t')[0]
# 检查是否为IP:端口格式的无线连接
if ":" in current_device and any(char.isdigit() for char in current_device):
wireless_device_id = current_device
logging.info(f"使用无线连接设备: {wireless_device_id}")
global_variable.GLOBAL_DEVICE_ID = wireless_device_id
return wireless_device_id
else:
# 记录第一个USB连接的设备
if not usb_device_id:
usb_device_id = current_device
# 如果没有找到无线连接的设备尝试使用USB设备开启无线调试
if not wireless_device_id and usb_device_id:
logging.info(f"未找到无线连接设备尝试使用USB设备 {usb_device_id} 开启无线调试")
# 尝试获取设备IP地址
try:
import re
import time
ip_result = subprocess.run(
["adb", "-s", usb_device_id, "shell", "ip", "-f", "inet", "addr", "show", "wlan0"],
capture_output=True,
text=True,
timeout=10
)
# 解析IP地址
ip_output = ip_result.stdout
if "inet " in ip_output:
# 提取IP地址
ip_match = re.search(r'inet\s+(\d+\.\d+\.\d+\.\d+)', ip_output)
if ip_match:
device_ip = ip_match.group(1)
logging.info(f"获取到设备IP地址: {device_ip}")
# 开启无线调试
tcpip_result = subprocess.run(
["adb", "-s", usb_device_id, "tcpip", "5555"],
capture_output=True,
text=True,
timeout=10
)
if "restarting in TCP mode port: 5555" in tcpip_result.stdout:
logging.info("无线调试已开启,端口: 5555")
# 等待几秒钟让设备准备好
time.sleep(3)
# 连接到无线设备
connect_result = subprocess.run(
["adb", "connect", f"{device_ip}:5555"],
capture_output=True,
text=True,
timeout=10
)
if "connected to" in connect_result.stdout:
logging.info(f"成功连接到无线设备: {device_ip}:5555")
global_variable.GLOBAL_DEVICE_ID = f"{device_ip}:5555"
return f"{device_ip}:5555"
else:
logging.warning(f"连接无线设备失败: {connect_result.stderr}")
logging.info(f"使用USB设备: {usb_device_id}")
global_variable.GLOBAL_DEVICE_ID = usb_device_id
return usb_device_id
else:
logging.warning(f"开启无线调试失败: {tcpip_result.stderr}")
logging.info(f"使用USB设备: {usb_device_id}")
global_variable.GLOBAL_DEVICE_ID = usb_device_id
return usb_device_id
else:
logging.warning("未找到设备IP地址")
logging.info(f"使用USB设备: {usb_device_id}")
global_variable.GLOBAL_DEVICE_ID = usb_device_id
return usb_device_id
else:
logging.warning("无法获取设备IP地址可能设备未连接到WiFi")
logging.info(f"使用USB设备: {usb_device_id}")
global_variable.GLOBAL_DEVICE_ID = usb_device_id
return usb_device_id
except Exception as e:
logging.warning(f"开启无线调试时出错: {str(e)}")
logging.info(f"使用USB设备: {usb_device_id}")
global_variable.GLOBAL_DEVICE_ID = usb_device_id
return usb_device_id
except Exception as e:
logging.warning(f"设备检测失败: {e}")
# 使用全局配置
device_id = global_variable.GLOBAL_DEVICE_ID
logging.info(f"使用全局配置设备: {device_id}")
return device_id
def __init__(self, device_id=None):
# 如果没有提供设备ID则自动获取
if device_id is None:
self.device_id = self.get_device_id()
else:
self.device_id = device_id
self.device_id = device_id
# 初始化权限
if permissions.grant_appium_permissions(self.device_id):
@@ -282,7 +137,7 @@ class DeviceAutomation:
return False
# 获取状态为3的线路。
apis.get_line_info_and_save_global(user_name=global_variable.GLOBAL_USERNAME);
apis.get_line_info_and_save_global(user_name=global_variable.get_username());
# # 虚拟数据替代
# global_variable.GLOBAL_UPLOAD_BREAKPOINT_DICT = {'CDWZQ-2标-龙骨湾右线大桥-0-7号墩-平原': 'L156372', 'CDWZQ-2标-蓝家湾特大 桥-31-31-平原': 'L159206'}
# global_variable.GLOBAL_UPLOAD_BREAKPOINT_LIST = list(global_variable.GLOBAL_UPLOAD_BREAKPOINT_DICT.keys())
@@ -299,7 +154,7 @@ class DeviceAutomation:
# 检查是否有需要上传的断点
if not global_variable.GLOBAL_UPLOAD_BREAKPOINT_LIST:
if not global_variable.get_upload_breakpoint_list():
logging.info(f"设备 {self.device_id} 断点列表为空,无需执行上传操作")
return False
@@ -312,12 +167,12 @@ class DeviceAutomation:
# 遍历断点列表,逐个执行上传操作
upload_success_count = 0
for breakpoint_name in global_variable.GLOBAL_UPLOAD_BREAKPOINT_LIST:
for breakpoint_name in global_variable.get_upload_breakpoint_list():
try:
logging.info(f"设备 {self.device_id} 开始处理断点 '{breakpoint_name}' 的上传")
# 安全地获取断点信息
line_num = global_variable.GLOBAL_UPLOAD_BREAKPOINT_DICT.get(breakpoint_name)
line_num = global_variable.get_upload_breakpoint_dict().get(breakpoint_name)
if line_num is None:
logging.warning(f"设备 {self.device_id} 断点 '{breakpoint_name}' 在字典中未找到,跳过上传")
continue
@@ -335,25 +190,25 @@ class DeviceAutomation:
except Exception as e:
logging.error(f"设备 {self.device_id} 处理断点 '{breakpoint_name}' 时发生异常: {str(e)}")
logging.info(f"设备 {self.device_id} 上传配置管理执行完成,成功上传 {upload_success_count}/{len(global_variable.GLOBAL_UPLOAD_BREAKPOINT_LIST)} 个断点")
logging.info(f"设备 {self.device_id} 上传配置管理执行完成,成功上传 {upload_success_count}/{len(global_variable.get_upload_breakpoint_list())} 个断点")
# 如果所有断点都上传成功返回True否则返回False
all_upload_success = upload_success_count == len(global_variable.GLOBAL_UPLOAD_BREAKPOINT_LIST)
all_upload_success = upload_success_count == len(global_variable.get_upload_breakpoint_list())
if all_upload_success:
logging.info(f"设备 {self.device_id} 所有断点上传成功")
# 把上传成功的断点写入日志文件"上传成功的断点.txt"
with open(os.path.join(self.results_dir, "上传成功的断点.txt"), "w", encoding='utf-8') as f:
for bp in global_variable.GLOBAL_UPLOAD_SUCCESS_BREAKPOINT_LIST:
for bp in global_variable.get_upload_success_breakpoint_list():
f.write(f"{bp}\n")
else:
logging.warning(f"设备 {self.device_id} 部分断点上传失败")
# 把上传成功的断点写入日志文件"上传成功的断点.txt"
with open(os.path.join(self.results_dir, "上传成功的断点.txt"), "w", encoding='utf-8') as f:
for bp in global_variable.GLOBAL_UPLOAD_SUCCESS_BREAKPOINT_LIST:
for bp in global_variable.get_upload_success_breakpoint_list():
f.write(f"{bp}\n")
# 把上传失败的断点写入日志文件"上传失败的断点.txt"
with open(os.path.join(self.results_dir, "上传失败的断点.txt"), "w", encoding='utf-8') as f:
for bp in set(global_variable.GLOBAL_UPLOAD_BREAKPOINT_LIST)-set(global_variable.GLOBAL_UPLOAD_SUCCESS_BREAKPOINT_LIST):
for bp in set(global_variable.get_upload_breakpoint_list())-set(global_variable.get_upload_success_breakpoint_list()):
f.write(f"{bp}\n")
return all_upload_success
@@ -457,13 +312,48 @@ class DeviceAutomation:
"""关闭驱动"""
safe_quit_driver(getattr(self, 'driver', None), self.device_id)
@staticmethod
def start_upload(device_id=None, upload_time=None):
"""
供其他页面或模块调用的静态方法
执行完整的自动化流程
参数:
device_id: 可选的设备ID如果为None则自动获取
返回:
bool: 自动化流程执行结果True/False
"""
automation = None
try:
# 创建自动化实例
automation = DeviceAutomation(device_id=device_id)
# 执行自动化流程
success = automation.run_automation()
if success:
logging.info("自动化流程执行成功")
else:
logging.error("自动化流程执行失败")
return success
except Exception as e:
logging.error(f"自动化流程执行出错: {str(e)}")
return False
finally:
# 确保资源被清理
if automation:
automation.quit()
# 主执行逻辑
if __name__ == "__main__":
# 单个设备配置 - 现在DeviceAutomation会自动获取设备ID
try:
automation = DeviceAutomation()
automation = DeviceAutomation(device_id="192.168.1.100:5556")
success = automation.run_automation()
if success: