Files
huojv/utils/mouse.py
2025-11-06 09:48:32 +08:00

90 lines
3.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import random
import time
import ch9329Comm
import serial
# 全局变量由main.py初始化
serial.ser = None
mouse = None
def init_mouse_keyboard(config_group):
"""初始化鼠标和串口"""
global serial, mouse
from utils.logger import logger
# 初始化串口
try:
logger.info(f"🔧 正在打开串口: {config_group['serial_port']} @ {config_group['serial_baudrate']}")
serial.ser = serial.Serial(
config_group['serial_port'],
config_group['serial_baudrate'],
timeout=1
)
logger.info(f"✅ 串口已打开: {config_group['serial_port']} @ {config_group['serial_baudrate']}")
except Exception as e:
logger.error(f"❌ 串口打开失败: {e}")
raise
# 初始化鼠标
try:
logger.info(f"🔧 正在初始化鼠标: {config_group['camera_width']}x{config_group['camera_height']}")
mouse = ch9329Comm.mouse.DataComm(
config_group['camera_width'],
config_group['camera_height']
)
logger.info(f"✅ 鼠标已初始化: {config_group['camera_width']}x{config_group['camera_height']}")
except Exception as e:
logger.error(f"❌ 鼠标初始化失败: {e}")
raise
def bezier_point(t, p0, p1, p2, p3):
"""计算三次贝塞尔曲线上的点"""
x = (1-t)**3 * p0[0] + 3*(1-t)**2*t*p1[0] + 3*(1-t)*t**2*p2[0] + t**3*p3[0]
y = (1-t)**3 * p0[1] + 3*(1-t)**2*t*p1[1] + 3*(1-t)*t**2*p2[1] + t**3*p3[1]
return (x, y)
def move_mouse_bezier(mouse, start, end, duration=1, steps=120):
"""
用贝塞尔曲线模拟鼠标移动(安全版)
"""
x1, y1 = start
x2, y2 = end
# 控制点(轻微随机)
ctrl1 = (x1 + (x2 - x1) * random.uniform(0.2, 0.4) + random.randint(-20, 20),
y1 + (y2 - y1) * random.uniform(0.1, 0.4) + random.randint(-20, 20))
ctrl2 = (x1 + (x2 - x1) * random.uniform(0.6, 0.8) + random.randint(-20, 20),
y1 + (y2 - y1) * random.uniform(0.6, 0.9) + random.randint(-20, 20))
# 生成轨迹
points = [bezier_point(t, (x1, y1), ctrl1, ctrl2, (x2, y2)) for t in [i/steps for i in range(steps+1)]]
delay = duration / steps
for (x, y) in points:
# 坐标裁剪,防止越界或负数
x_safe = max(0, min(1919, int(x)))
y_safe = max(0, min(1079, int(y)))
mouse.send_data_absolute(x_safe, y_safe)
time.sleep(delay * random.uniform(0.6, 1.0))
# 最后一步确保到达终点
x2_safe = max(0, min(1919, int(x2)))
y2_safe = max(0, min(1079, int(y2)))
mouse.send_data_absolute(x2_safe, y2_safe)
class Mouse_guiji():
def __init__(self):
self.point=(0,0)
def send_data_absolute(self, x, y, may=0):
move_mouse_bezier(mouse, self.point, (x,y), duration=1, steps=120)
if may == 1: # 点击左
mouse.click()
elif may == 2:
mouse.click1() # 点击右
self.point=(x,y)
# mouse_gui 将在main.py中初始化
mouse_gui = None