Files
huojv/utils/mouse.py
2025-10-29 10:49:38 +08:00

76 lines
2.4 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
# 初始化串口
serial.ser = serial.Serial(
config_group['serial_port'],
config_group['serial_baudrate']
)
# 初始化鼠标
mouse = ch9329Comm.mouse.DataComm(
config_group['camera_width'],
config_group['camera_height']
)
print(f"✅ 串口已打开: {config_group['serial_port']} {config_group['serial_baudrate']}")
print(f"✅ 鼠标已初始化: {config_group['camera_width']}x{config_group['camera_height']}")
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