from appium.options.android import UiAutomator2Options
import logging
from selenium import webdriver

def app_setup_driver(platformName, platformVersion, deviceName, appPackage, appActivity, udid):

    desired_caps = {
        'platformName': platformName,  # 被测手机是安卓
        'platformVersion': platformVersion,  # 手机安卓版本，如果是鸿蒙系统，依次尝试 12、11、10 这些版本号
        'deviceName': deviceName,  # 设备名，安卓手机可以随意填写
        'appPackage': appPackage,  # 启动APP Package名称
        'appActivity': appActivity,  # 启动Activity名称
        'unicodeKeyboard': True,  # 自动化需要输入中文时填True
        'resetKeyboard': True,  # 执行完程序恢复原来输入法
        'noReset': True,  # 不要重置App
        'newCommandTimeout': 6000,
        'automationName': 'UiAutomator2',
        'skipUnlock': True,
        'autoGrantPermissions': True,
        'udid':udid
    }
    logging.info(f"desired_caps参数：{desired_caps}")

    try:
        logging.info("正在初始化 Appium 驱动程序...")
        driver = webdriver.Remote('http://localhost:4723/wd/hub',
                                  options=UiAutomator2Options().load_capabilities(desired_caps))
        logging.info("Appium 驱动程序初始化成功。")
        return driver
    except Exception as e:
        logging.error(f"初始化驱动程序失败: {e}")
        raise

def swipe_up(app_driver):
    # 获取屏幕尺寸
    size = app_driver.get_window_size()
    start_x = size['width'] // 2
    start_y = int(size['height'] * 0.2)  # 起始y坐标，屏幕高度的20%
    end_x = start_x
    end_y = int(size['height'] * 0.8)  # 结束y坐标，屏幕高度的80%

    # 执行滑动操作
    app_driver.swipe(start_x, start_y, end_x, end_y, duration=500)

from PIL import Image
import numpy as np
import os
import logging

# 配置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


def compare_brightness(light_down_path, light_on_path, threshold=50):
    """
    对比两张图片的亮度，返回亮度是否增加的布尔值。
    light_on_path：传入暗色的图片
    light_down_path：传入亮色的图片
    """
    try:
        image1 = Image.open(light_down_path).convert('L')  # 转换为灰度图像
        image2 = Image.open(light_on_path).convert('L')  # 转换为灰度图像

        # 将图像转换为numpy数组
        array1 = np.array(image1)
        array2 = np.array(image2)

        # 计算平均亮度
        avg_brightness1 = np.mean(array1)
        avg_brightness2 = np.mean(array2)

        logging.info(f"关闭灯光时的平均亮度: {avg_brightness1}")
        logging.info(f"打开灯光时的平均亮度: {avg_brightness2}")

        # 判断亮度是否增加，考虑阈值
        brightness_increase = avg_brightness2 - avg_brightness1
        logging.info(f"亮度变化量: {brightness_increase}")

        return brightness_increase > threshold
    except Exception as e:
        logging.error(f"对比亮度时发生错误: {e}", exc_info=True)
        return False

# if __name__ == '__main__':
#     logging.info("开始对比亮度")
#
#     image1_path = r'D:\GithubData\自动化\ubains-module-test\预定系统\Base\暗图.jpg'
#     image2_path = r'D:\GithubData\自动化\ubains-module-test\预定系统\Base\亮图.jpg'
#
#     # 检查图片路径是否存在
#     if not os.path.exists(image1_path):
#         logging.error(f"图片 {image1_path} 不存在")
#         exit(1)
#     if not os.path.exists(image2_path):
#         logging.error(f"图片 {image2_path} 不存在")
#         exit(1)
#
#     # 对比两张截图的亮度
#     result = compare_brightness(image1_path, image2_path)
#     logging.info(f"亮度比较结果: {result}")
#
#     if result:
#         logging.info("灯光已成功打开")
#     else:
#         logging.error("灯光未成功打开")

import cv2
import numpy as np

def compare_images_feature_matching(image1_path, image2_path):
    """
    使用特征匹配对比两张图片的相似度。
    """
    try:
        image1 = cv2.imread(image1_path, cv2.IMREAD_GRAYSCALE)
        image2 = cv2.imread(image2_path, cv2.IMREAD_GRAYSCALE)

        # 初始化ORB检测器
        orb = cv2.ORB_create()

        # 查找关键点和描述符
        kp1, des1 = orb.detectAndCompute(image1, None)
        kp2, des2 = orb.detectAndCompute(image2, None)

        # BFMatcher对象
        bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)

        # 匹配描述符
        matches = bf.match(des1, des2)

        # 按距离排序
        matches = sorted(matches, key=lambda x: x.distance)

        # 计算匹配点的数量
        num_matches = len(matches)
        logging.info(f"匹配点数量: {num_matches}")

        # 判断匹配点数量是否在可接受范围内
        return num_matches > 10  # 可以根据需要调整阈值
    except Exception as e:
        logging.error(f"对比图片时发生错误: {e}", exc_info=True)
        return False


if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
    logging.info("开始对比图片")

    image1_path = r'D:\GithubData\自动化\ubains-module-test\预定系统\Base\暗图.jpg'
    image2_path = r'D:\GithubData\自动化\ubains-module-test\预定系统\Base\亮图.jpg'

    if not os.path.exists(image1_path):
        logging.error(f"图片 {image1_path} 不存在")
        exit(1)
    if not os.path.exists(image2_path):
        logging.error(f"图片 {image2_path} 不存在")
        exit(1)

    # 对比两张截图的相似度
    if compare_images_feature_matching(image1_path, image2_path):
        logging.info("图片相同")
    else:
        logging.error("图片不同")

def capture_frame_from_rtsp(rtsp_url, output_path):
    """
    从RTSP流中捕获一帧并保存为图像文件。
    """
    try:
        # 打开RTSP流
        cap = cv2.VideoCapture(rtsp_url)

        if not cap.isOpened():
            logging.error("无法打开RTSP流")
            return False

        # 读取一帧
        ret, frame = cap.read()

        if not ret:
            logging.error("无法从RTSP流中读取帧")
            cap.release()
            return False

        # 保存帧为图像文件
        cv2.imwrite(output_path, frame)
        logging.info(f"帧已保存到 {output_path}")

        # 释放资源
        cap.release()
        return True
    except Exception as e:
        logging.error(f"捕获帧时发生错误: {e}", exc_info=True)
        return False


if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
    logging.info("开始捕获RTSP流中的帧")

    rtsp_url = "rtsp://admin:huawei@123@192.168.4.15/LiveMedia/ch1/Media2"  # 替换为你的RTSP流地址
    output_path = "captured_frame.jpg"  # 保存帧的路径

    if capture_frame_from_rtsp(rtsp_url, output_path):
        logging.info("帧捕获成功")
    else:
        logging.error("帧捕获失败")