MassageRobot_Dobot/Restart_Speaker.py
2025-05-29 16:47:49 +08:00

48 lines
1.6 KiB
Python
Executable File
Raw Permalink 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 serial
import serial.tools.list_ports
import time
import sys
class USB_board:
def __init__(self, port=None, baudrate=115200, timeout=1):
# 自动查找 ESP32 端口
if port is None:
port = self.find_esp32_port()
self.ser = serial.Serial(port, baudrate, timeout=timeout)
time.sleep(2) # 等待 ESP32 初始化
def find_esp32_port(self):
"""自动查找 ESP32 的串口端口"""
ports = list(serial.tools.list_ports.comports())
for port in ports:
if "USB" in port.description: # 根据描述过滤端口(可以使用具体的描述或 VID/PID
return port.device
raise Exception("ESP32 串口未找到")
def send_command(self, command):
"""发送命令到 ESP32"""
if self.ser.isOpen():
self.ser.write((command + '\n').encode()) # 发送命令并换行
time.sleep(0.3) # 等待 ESP32 响应
response = self.ser.read(self.ser.in_waiting).decode() # 读取 ESP32 的响应
return response
else:
raise ConnectionError("Serial port not open")
def close(self):
"""关闭串口连接"""
if self.ser.isOpen():
self.ser.close()
if __name__ == "__main__":
USB_board = USB_board() # 自动找到 ESP32 端口
try:
command = "restart"
response = USB_board.send_command(command)
print("ESP32 响应:", response)
finally:
print("Restart Complete.")
print("Closing Program.")
USB_board.close() # 关闭连接