修改驱动启用;两个大块逻辑。

This commit is contained in:
2026-03-13 18:01:36 +08:00
parent aa4d4c7d7c
commit b80f553009
10 changed files with 391 additions and 250 deletions

View File

@@ -16,6 +16,89 @@ import globals.global_variable as global_variable
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s: %(message)s")
class DriverManager:
_driver = None
_wait = None
_device_id = None
@classmethod
def get_driver(cls):
# 如果驱动不存在,或者 session 失效,则初始化/重连
if cls._device_id is None:
cls._device_id = get_device_id()
if grant_appium_permissions(cls._device_id):
logging.info(f"设备 {cls._device_id} 授予Appium权限成功")
else:
logging.warning(f"设备 {cls._device_id} 授予Appium权限失败")
if not check_server_status(4723):
start_appium_server()
if cls._driver is None:
cls._driver, cls._wait = init_appium_driver(cls._device_id)
elif not check_session_valid(cls._driver, cls._device_id):
logging.info("检测到 Session 失效,正在重连...")
cls._driver, cls._wait = reconnect_driver(cls._device_id, cls._driver)
return cls._driver, cls._wait, cls._device_id
@classmethod
def quit_driver(cls, device_id):
if cls._driver:
safe_quit_driver(cls._driver, device_id)
cls._driver = None
cls._wait = None
cls._device_id = None
def get_device_id() -> str:
"""
获取设备ID优先使用已连接设备否则使用全局配置
"""
try:
# 检查已连接设备
result = subprocess.run(
["adb", "devices"],
capture_output=True,
text=True,
timeout=10
)
target_port = "4723"
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]
# 检查是否为无线设备且端口为4723
if ':' in device_id:
ip_port = device_id.split(':')
if len(ip_port) == 2 and ip_port[1] == target_port:
logging.info(f"找到目标无线设备(端口{target_port}): {device_id}")
global_variable.GLOBAL_DEVICE_ID = device_id
return device_id
# 如果没有找到端口4723的设备找其他无线设备
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]
# 检查是否为无线设备(任何端口)
if ':' in device_id and device_id.split(':')[-1].isdigit():
logging.info(f"未找到端口{target_port}的设备,使用其他无线设备: {device_id}")
global_variable.GLOBAL_DEVICE_ID = device_id
return device_id
# 如果没有任何无线设备,找有线设备
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
logging.error("未找到任何可用设备")
return None
except Exception as e:
logging.warning(f"设备检测失败: {e}")
return None
def init_appium_driver(device_id, app_package="com.bjjw.cjgc", app_activity=".activity.LoginActivity"):
"""
初始化Appium驱动的全局函数
@@ -599,27 +682,40 @@ def safe_quit_driver(driver, device_id=None):
if not hasattr(driver, 'quit'):
logging.warning(f"{device_str}驱动对象类型无效不具有quit方法: {type(driver).__name__}")
return
max_quit_attempts = 3
for attempt in range(max_quit_attempts):
try:
logging.info(f"{device_str}尝试关闭驱动 (尝试 {attempt + 1}/{max_quit_attempts})")
driver.quit()
logging.info(f"{device_str}驱动已成功关闭")
return
except InvalidSessionIdException:
# 会话已经失效,不需要重试
logging.info(f"{device_str}会话已经失效,无需关闭")
return
except Exception as e:
logging.error(f"{device_str}关闭驱动时出错 (尝试 {attempt + 1}/{max_quit_attempts}): {str(e)}")
if attempt < max_quit_attempts - 1:
# 等待一段时间后重试
wait_time = 2
logging.info(f"{device_str}将在 {wait_time} 秒后重试")
time.sleep(wait_time)
else:
logging.critical(f"{device_str}尝试多次关闭驱动失败,可能导致资源泄漏")
try:
logging.info(f"{device_str}尝试关闭驱动 (尝试)")
driver.quit()
logging.info(f"{device_str}驱动已成功关闭")
return
except InvalidSessionIdException:
# 会话已经失效,不需要重试
logging.info(f"{device_str}会话已经失效,无需关闭")
return
except Exception as e:
logging.error(f"{device_str}关闭驱动时出错 : {str(e)}")
return
# max_quit_attempts = 3
# for attempt in range(max_quit_attempts):
# try:
# logging.info(f"{device_str}尝试关闭驱动 (尝试 {attempt + 1}/{max_quit_attempts})")
# driver.quit()
# logging.info(f"{device_str}驱动已成功关闭")
# return
# except InvalidSessionIdException:
# # 会话已经失效,不需要重试
# logging.info(f"{device_str}会话已经失效,无需关闭")
# return
# except Exception as e:
# logging.error(f"{device_str}关闭驱动时出错 (尝试 {attempt + 1}/{max_quit_attempts}): {str(e)}")
# if attempt < max_quit_attempts - 1:
# # 等待一段时间后重试
# wait_time = 2
# logging.info(f"{device_str}将在 {wait_time} 秒后重试")
# time.sleep(wait_time)
# else:
# logging.critical(f"{device_str}尝试多次关闭驱动失败,可能导致资源泄漏")
def check_app_status(driver, package_name="com.bjjw.cjgc", activity=".activity.LoginActivity"):
"""