Compare commits

..

2 Commits

15 changed files with 2317 additions and 100 deletions

View File

@@ -1,7 +1,9 @@
import logging import logging
import os import os
import sys
import time import time
import subprocess import subprocess
import argparse
from tkinter import E from tkinter import E
from appium import webdriver from appium import webdriver
from appium.options.android import UiAutomator2Options from appium.options.android import UiAutomator2Options
@@ -24,27 +26,6 @@ import globals.create_link as create_link
class DeviceAutomation: class DeviceAutomation:
# def __init__(self, device_id=None):
# # 如果没有提供设备ID则自动获取
# if device_id is None:
# self.device_id = driver_utils.get_device_id()
# else:
# self.device_id = device_id
# # 初始化权限
# if driver_utils.grant_appium_permissions(self.device_id):
# logging.info(f"设备 {self.device_id} 授予Appium权限成功")
# else:
# logging.warning(f"设备 {self.device_id} 授予Appium权限失败")
# # 确保Appium服务器正在运行,不在运行则启动
# if not driver_utils.check_server_status(4723):
# driver_utils.start_appium_server()
# # 初始化Appium驱动和页面对象
# self.init_driver()
# # 创建测试结果目录
# self.results_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'test_results')
def __init__(self, driver=None, wait=None, device_id=None): def __init__(self, driver=None, wait=None, device_id=None):
self.driver = driver self.driver = driver
self.wait = wait self.wait = wait
@@ -164,8 +145,14 @@ class DeviceAutomation:
logging.error(f"设备 {self.device_id} 初始化驱动失败: {str(e)}") logging.error(f"设备 {self.device_id} 初始化驱动失败: {str(e)}")
raise raise
def run_automation(self): def run_automation(self, task_data=None):
"""根据当前应用状态处理相应的操作""" """根据当前应用状态处理相应的操作
Args:
task_data: 可选的任务数据字典,包含 user_name, line_name, line_num, id 等字段。
如果传入,则使用传入值设置全局变量;
如果不传,则使用硬编码的默认值。
"""
try: try:
max_retry = 3 # 限制最大重试次数 max_retry = 3 # 限制最大重试次数
retry_count = 0 retry_count = 0
@@ -213,22 +200,22 @@ class DeviceAutomation:
return False return False
task_count = 0 task_count = 0
max_tasks = 1 # 最大任务数量,防止无限循环
# while task_count < max_tasks: # 获取测量任务:优先使用传入的 task_data否则使用硬编码默认值
# 获取测量任务 if task_data is None:
logging.info(f"设备 {self.device_id} 获取测量任务 (第{task_count + 1}次)") logging.info(f"设备 {self.device_id} 获取测量任务 (第{task_count + 1}次)")
# task_data = apis.get_measurement_task() # task_data = apis.get_measurement_task()
# logging.info(f"设备 {self.device_id} 获取到的测量任务: {task_data}") # logging.info(f"设备 {self.device_id} 获取到的测量任务: {task_data}")
task_data = { task_data = {
"id": 21, "id": 21,
"user_name": "czsczq115ykl", "user_name": "czsczq115ykl",
"name": "czsczq115ykl", "name": "czsczq115ykl",
"line_num": "L220076", "line_num": "L220179",
"line_name": "CZSCZQ-11-五工区-列衣隧道进口-D3K638+507-D3K638+607-山区", "line_name": "CZSCZQ-11-五工区-德达隧道6#斜井左线-DK632+707-DK632+705-山区",
"remaining": "0", "remaining": "0",
"status": 0 "status": 0
} }
if not task_data: if not task_data:
logging.info(f"设备 {self.device_id} 未获取到状态为1的测量任务等待后重试") logging.info(f"设备 {self.device_id} 未获取到状态为1的测量任务等待后重试")
time.sleep(1) # 等待1秒后重试 time.sleep(1) # 等待1秒后重试
@@ -243,15 +230,9 @@ class DeviceAutomation:
logging.info(f"设备 {self.device_id} 当前要处理的项目名称:{global_variable.GLOBAL_CURRENT_PROJECT_NAME}") logging.info(f"设备 {self.device_id} 当前要处理的项目名称:{global_variable.GLOBAL_CURRENT_PROJECT_NAME}")
# 执行测量操作 # 执行测量操作
# logging.info(f"设备 {self.device_id} 开始执行测量操作")
if not self.measure_tabbar_page.measure_tabbar_page_manager(): if not self.measure_tabbar_page.measure_tabbar_page_manager():
logging.error(f"设备 {self.device_id} 测量操作执行失败") logging.error(f"设备 {self.device_id} 测量操作执行失败")
# # 返回到测量页面
# self.driver.back()
# self.check_and_click_confirm_popup_appium()
# continue # 继续下一个任务
logging.info(f"设备 {self.device_id} 测量页面操作执行成功") logging.info(f"设备 {self.device_id} 测量页面操作执行成功")
@@ -259,41 +240,33 @@ class DeviceAutomation:
logging.info(f"设备 {self.device_id} 开始执行断面里程配置") logging.info(f"设备 {self.device_id} 开始执行断面里程配置")
if not self.section_mileage_config_page.section_mileage_config_page_manager(): if not self.section_mileage_config_page.section_mileage_config_page_manager():
logging.error(f"设备 {self.device_id} 断面里程配置执行失败") logging.error(f"设备 {self.device_id} 断面里程配置执行失败")
# continue # 继续下一个任务
# 任务完成后短暂等待 # 任务完成后短暂等待
logging.info(f"设备 {self.device_id}{task_count}个任务完成") logging.info(f"设备 {self.device_id}{task_count}个任务完成")
task_count += 1 task_count += 1
# # +++++++++++++white+++++++++++++++++ # # 执行打数据加转点
# if not self.check_station.run():
# logging.info(f"设备 {self.device_id} 已完成{task_count}个任务,结束打数据流程") # logging.error(f"设备 {self.device_id} 打数据加转点执行失败")
# if task_count == 0:
# logging.error(f"没有完成打数据的线路,结束任务")
# return False # return False
# 执行打数据加转点 # # 执行上传配置管理,传入当前断点名称
if not self.check_station.run(): # breakpoint_name = global_variable.GLOBAL_CURRENT_PROJECT_NAME
logging.error(f"设备 {self.device_id} 打数据加转点执行失败") # line_num = global_variable.GLOBAL_LINE_NUM
return False # if self.upload_config_page.upload_config_page_manager(self.results_dir, breakpoint_name, line_num):
# logging.info(f"设备 {self.device_id} 断点 '{breakpoint_name}' 上传成功")
# upload_success_count += 1
# else:
# logging.error(f"设备 {self.device_id} 断点 '{breakpoint_name}' 上传失败")
# for i in range(3):
# if self.upload_config_page.upload_config_page_manager(self.results_dir, breakpoint_name, line_num):
# logging.info(f"设备 {self.device_id} 断点 '{breakpoint_name}' 重试上传成功")
# upload_success_count += 1
# break
# else:
# logging.error(f"设备 {self.device_id} 断点 '{breakpoint_name}' 上传失败,第 {i+1} 次重试")
# 执行上传配置管理,传入当前断点名称 # return task_count > 0
breakpoint_name = global_variable.GLOBAL_CURRENT_PROJECT_NAME
line_num = global_variable.GLOBAL_LINE_NUM
if self.upload_config_page.upload_config_page_manager(self.results_dir, breakpoint_name, line_num):
logging.info(f"设备 {self.device_id} 断点 '{breakpoint_name}' 上传成功")
upload_success_count += 1
else:
logging.error(f"设备 {self.device_id} 断点 '{breakpoint_name}' 上传失败")
for i in range(3):
if self.upload_config_page.upload_config_page_manager(self.results_dir, breakpoint_name, line_num):
logging.info(f"设备 {self.device_id} 断点 '{breakpoint_name}' 重试上传成功")
upload_success_count += 1
break
else:
logging.error(f"设备 {self.device_id} 断点 '{breakpoint_name}' 上传失败,第 {i+1} 次重试")
return task_count > 0
except Exception as e: except Exception as e:
logging.error(f"设备 {self.device_id} 处理应用状态时出错: {str(e)}") logging.error(f"设备 {self.device_id} 处理应用状态时出错: {str(e)}")
@@ -301,6 +274,14 @@ class DeviceAutomation:
# 主执行逻辑 # 主执行逻辑
if __name__ == "__main__": if __name__ == "__main__":
parser = argparse.ArgumentParser(description='DeviceAutomation 脚本 - 执行设备自动化流程')
parser.add_argument('--user_name', type=str, default='', help='用户名')
parser.add_argument('--line_name', type=str, default='', help='项目/线路名称')
parser.add_argument('--line_num', type=str, default='', help='线路编码')
parser.add_argument('--account_id', type=int, default=0, help='账号ID')
args = parser.parse_args()
device_id = create_link.setup_adb_wireless() device_id = create_link.setup_adb_wireless()
automation = None automation = None
try: try:
@@ -308,12 +289,36 @@ if __name__ == "__main__":
logging.error("未能获取设备 ID无法继续执行自动化流程") logging.error("未能获取设备 ID无法继续执行自动化流程")
else: else:
automation = DeviceAutomation(device_id=device_id) automation = DeviceAutomation(device_id=device_id)
success = automation.run_automation()
# 如果传入了命令行参数,则构建 task_data 并传入
if args.user_name or args.line_name or args.line_num or args.account_id:
task_data = {
"id": args.account_id,
"user_name": args.user_name,
"line_num": args.line_num,
"line_name": args.line_name,
}
logging.info(f"使用命令行参数: {task_data}")
success = automation.run_automation(task_data=task_data)
else:
logging.info("未传入命令行参数,使用默认 task_data")
success = automation.run_automation()
if success: if success:
logging.info(f"设备 {automation.device_id} 自动化流程执行成功") logging.info(f"设备 {automation.device_id} 自动化流程执行成功")
print("自动化流程执行成功")
else: else:
logging.error(f"设备 {automation.device_id} 自动化流程执行失败") logging.error(f"设备 {automation.device_id} 自动化流程执行失败")
print("自动化流程执行失败")
# 保持脚本运行,不关闭连接
logging.info("自动化流程执行完成,保持连接状态...")
logging.info("按 Ctrl+C 退出并关闭连接")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
logging.info("用户中断,准备关闭连接...")
except Exception as e: except Exception as e:
logging.error(f"设备执行出错: {str(e)}") logging.error(f"设备执行出错: {str(e)}")
finally: finally:

1070
add_trasition.py Normal file

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 143 KiB

View File

@@ -110,11 +110,13 @@ class CheckStation:
return False return False
try: try:
# 查找并点击添加转点按钮 # 查找并点击添加转点按钮(双击确保点到)
add_transition_btn = self.wait.until( add_transition_btn = self.wait.until(
EC.element_to_be_clickable((AppiumBy.ID, "com.bjjw.cjgc:id/btn_add_ZPoint")) EC.element_to_be_clickable((AppiumBy.ID, "com.bjjw.cjgc:id/btn_add_ZPoint"))
) )
add_transition_btn.click() add_transition_btn.click()
time.sleep(0.3)
add_transition_btn.click()
logging.info("已点击添加转点按钮") logging.info("已点击添加转点按钮")
return True return True
except TimeoutException: except TimeoutException:

1042
check_upload.py Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -91,8 +91,8 @@ def get_breakpoint_list():
"id": 21, "id": 21,
"user_name": "czsczq115ykl", "user_name": "czsczq115ykl",
"name": "czsczq115ykl", "name": "czsczq115ykl",
"line_num": "L220076", "line_num": "L220179",
"line_name": "CZSCZQ-11-五工区-列衣隧道进口-D3K638+507-D3K638+607-山区", "line_name": "CZSCZQ-11-五工区-德达隧道6#斜井左线-DK632+707-DK632+705-山区",
"status": 3 "status": 3
}] }]
else: else:

View File

@@ -191,7 +191,24 @@ def setup_adb_wireless():
target_port = 4723 target_port = 4723
print(f"🚀 开始无线 ADB 建链(端口 {target_port}") print(f"🚀 开始无线 ADB 建链(端口 {target_port}")
# 获取USB连接的设备 # ===== 优先检查是否已有无线连接 =====
wireless_connections = check_wireless_connections(target_port)
if wireless_connections:
print(f"📡 发现 {len(wireless_connections)} 个现有无线连接")
for conn_id, ip, port in wireless_connections:
if port == target_port:
print(f"✅ 已存在目标端口 {target_port} 的无线连接: {conn_id}")
# 验证连接是否有效
verify_result = run_command("adb devices")
if conn_id in verify_result and "device" in verify_result.split(conn_id)[1][:10]:
print(f"✅ 连接验证通过")
# 启动 Appium如果未运行
start_appium()
return conn_id
else:
print(f"⚠️ 连接验证失败,准备重新建立")
# ===== 获取USB连接的设备 =====
devices_output = run_command("adb devices") devices_output = run_command("adb devices")
lines = devices_output.splitlines()[1:] lines = devices_output.splitlines()[1:]

View File

@@ -2,8 +2,8 @@
GLOBAL_DEVICE_ID = "" # 设备ID GLOBAL_DEVICE_ID = "" # 设备ID
GLOBAL_USERNAME = "czyuzongwen" # 用户名 GLOBAL_USERNAME = "czyuzongwen" # 用户名
GLOBAL_ACCOUNT_ID = "" # 账号ID GLOBAL_ACCOUNT_ID = "" # 账号ID
GLOBAL_CURRENT_PROJECT_NAME = "" # 当前测试项目名称 GLOBAL_CURRENT_PROJECT_NAME = "CZSCZQ-11-五工区-德达隧道6#斜井左线-DK632+707-DK632+705-山区" # 当前测试项目名称
GLOBAL_LINE_NUM = "" # 线路编码 GLOBAL_LINE_NUM = "L220179" # 线路编码
GLOBAL_BREAKPOINT_STATUS_CODES = [0,3] # 要获取的断点状态码列表 GLOBAL_BREAKPOINT_STATUS_CODES = [0,3] # 要获取的断点状态码列表
GLOBAL_UPLOAD_BREAKPOINT_LIST = [] GLOBAL_UPLOAD_BREAKPOINT_LIST = []
GLOBAL_UPLOAD_BREAKPOINT_DICT = {} GLOBAL_UPLOAD_BREAKPOINT_DICT = {}

View File

@@ -185,6 +185,104 @@ class LoginPage:
logging.error(f"登录过程中出错: {str(e)}") logging.error(f"登录过程中出错: {str(e)}")
return False return False
def login_get_username(self, username=None):
"""执行登录操作"""
try:
logging.info("正在执行登录操作...")
# 获取文本框中已有的用户名
username_field = self.wait.until(
EC.element_to_be_clickable((AppiumBy.ID, ids.LOGIN_USERNAME))
)
existing_username = username_field.text
# 日志记录获取到的已有用户名(若为空,也需明确记录,避免后续误解)
if existing_username.strip(): # 去除空格后判断是否有有效内容
logging.info(f"已获取文本框中的已有用户名: {existing_username}")
else:
logging.info("文本框中未检测到已有用户名(内容为空)")
# 将用户名写入全局变量中
global_variable.GLOBAL_USERNAME = existing_username # 关键:给全局变量赋值
# 1. 定位密码输入框
password_field = self.wait.until(
EC.element_to_be_clickable((AppiumBy.ID, ids.LOGIN_PASSWORD))
)
# 2. 清空密码框(如果需要)
try:
password_field.clear()
# time.sleep(0.5) # 等待清除完成
except:
# 如果clear方法不可用尝试其他方式
pass
accounts = apis.get_accounts_from_server("68ef0e02b0138d25e2ac9918")
# 检查accounts是否为None如果是则设为空列表
if accounts is None:
logging.warning("获取账户列表返回None设为空列表")
accounts = []
matches = [acc for acc in accounts if acc.get("username") == existing_username]
password = None
account_id = False
if matches:
password = matches[0].get("password")
# ✅ 关键:把 account_id 存入全局变量
account_id = matches[0].get("account_id", False)
# 只有 account_id 存在时才存全局
if account_id is not False:
global_variable.GLOBAL_ACCOUNT_ID = account_id
logging.info(f"匹配到账号信息username={existing_username}, account_id={account_id}")
else:
logging.warning(f"账号 {existing_username} 未返回 account_id已设为 False")
password_field.send_keys(password)
# 4. 可选:隐藏键盘
try:
self.driver.hide_keyboard()
except:
pass
# 点击登录按钮
max_retries = 3
retry_count = 0
while retry_count < max_retries:
login_btn = self.wait.until(
EC.element_to_be_clickable((AppiumBy.ID, ids.LOGIN_BTN))
)
login_btn.click()
logging.info(f"已点击登录按钮 (尝试 {retry_count + 1}/{max_retries})")
# 等待登录完成
time.sleep(3)
# 检查是否登录成功
if self.is_login_successful():
logging.info("登录成功")
return True
else:
logging.warning("登录后未检测到主页面元素,准备重试")
retry_count += 1
if retry_count < max_retries:
logging.info(f"等待2秒后重新尝试登录...")
time.sleep(2)
logging.error(f"登录失败,已尝试 {max_retries}")
return False
except Exception as e:
logging.error(f"登录过程中出错: {str(e)}")
return False
def is_login_successful(self): def is_login_successful(self):
"""检查登录是否成功""" """检查登录是否成功"""

View File

@@ -741,11 +741,13 @@ class SectionMileageConfigPage:
def add_transition_point(self): def add_transition_point(self):
"""添加转点""" """添加转点"""
try: try:
# 查找并点击添加转点按钮 # 查找并点击添加转点按钮(双击确保点到)
add_transition_btn = self.wait.until( add_transition_btn = self.wait.until(
EC.element_to_be_clickable((AppiumBy.ID, "com.bjjw.cjgc:id/btn_add_ZPoint")) EC.element_to_be_clickable((AppiumBy.ID, "com.bjjw.cjgc:id/btn_add_ZPoint"))
) )
add_transition_btn.click() add_transition_btn.click()
time.sleep(0.3)
add_transition_btn.click()
self.logger.info("已点击添加转点按钮") self.logger.info("已点击添加转点按钮")
return True return True
except TimeoutException: except TimeoutException:
@@ -981,7 +983,7 @@ class SectionMileageConfigPage:
try: try:
self.logger.info("检查线路弹出测量弹窗...") self.logger.info("检查线路弹出测量弹窗...")
# 直接尝试点击"继续测量"按钮 # 直接尝试点击"重新测量"按钮
remeasure_btn = WebDriverWait(self.driver, 2).until( remeasure_btn = WebDriverWait(self.driver, 2).until(
EC.element_to_be_clickable((AppiumBy.ID, "com.bjjw.cjgc:id/measure_remeasure_all_btn")) EC.element_to_be_clickable((AppiumBy.ID, "com.bjjw.cjgc:id/measure_remeasure_all_btn"))
) )
@@ -1087,26 +1089,7 @@ class SectionMileageConfigPage:
return False return False
self.logger.info("断面里程配置完成,待执行测量")
# if not self.check_station_page.run():
# self.logger.error("检查站页面运行失败")
# return False
# # 添加断点到列表
# if not self.add_breakpoint_to_tested_list():
# return False
# # 点击返回按钮
# if not self.click_back_button():
# return False
# # 测量结束。点击手机物理返回按钮,返回测量页面
# # 点击了手机独步导航栏返回键
# if not self.click_system_back_button():
# return False
self.logger.info("断面里程配置完成,正在执行测量")
return True return True
except Exception as e: except Exception as e: