Initial commit: 上传完整代码

This commit is contained in:
2026-06-19 20:47:06 +08:00
commit 78b5898da2
71 changed files with 8767 additions and 0 deletions
+389
View File
@@ -0,0 +1,389 @@
import os
import math
import time
import threading
import subprocess
import re
import json
from config import *
from PySide6.QtCore import *
from PySide6.QtNetwork import QUdpSocket, QHostAddress
import socket, struct
from PySide6.QtCore import QTimer
class ScannerState:
STOP = 'stop'
MOVING_UP = 'moving_up'
MOVING_DOWN = 'moving_down'
STOP_AT_UPPER = 'stop_at_upper'
STOP_AT_BOTTOM = 'stop_at_bottom'
STOP_AT_ORIGIN = 'stop_at_origin'
UNKNOWN = 'unknown'
valid_states = [STOP, MOVING_UP, MOVING_DOWN,
STOP_AT_UPPER, STOP_AT_BOTTOM,
STOP_AT_ORIGIN, UNKNOWN]
class Scanner:
def __init__(self, id):
self.id = id
self.config = {}
self.state = ScannerState.UNKNOWN
self.running = False
self.last_update_time = 0
self.location = 0
self.velocity = 0
self.daq_info = {}
self.last_moving_time = 0
self.last_idle_time = 0
self.run_flag = False
self.read_config()
self.ip = self.config.get("ip", "192.168.100.21")
def read_config(self):
try:
config = {}
path = "/home/admin/.config/cpy/scanner.json"
if not os.path.exists(path):
return
with open(path, "r") as f:
config = json.load(f)
self.config = config[f"scanner{self.id}"]
except Exception as e:
print(e)
class MotorManager(QObject):
update_location = Signal(int,int)
update_direction = Signal(int,str)
update_estimates = Signal(int, float, float)
update_online_status = Signal(int, int)
update_setting_velocity = Signal(int, float)
update_duration = Signal(int,float)
update_state = Signal(int, int)
update_work_mode = Signal(str)
# 定义ID_MT1、ID_MT2两个常量为0x01, 0x02
ID_MT1 = 0x01
ID_MT2 = 0x02
UDP_STATUS_PORT = 11200
UDP_CMD_PORT = 11300
def __init__(self, bus_id = 1):
super().__init__()
self.scanners = [Scanner(self.ID_MT1),
Scanner(self.ID_MT2)]
self.mqtt_client = None
self.read_config()
self.work_mode = "fast"
print(self.config)
self.light_status = None
self.last_light_on_time = 0
self.start_scan_time = 0
self.online_status_update_time = 0
self.moto_info_update_time = 0
self.udp_socket = QUdpSocket(self)
self.udp_socket.bind(QHostAddress.Any, self.UDP_STATUS_PORT)
self.udp_socket.readyRead.connect(self.udp_data_handle)
self.timer = QTimer(self)
self.timer.setInterval(100)
self.timer.timeout.connect(self.timer_callback)
self.timer.start()
def scanner(self, index):
return self.scanners[index - 1]
def send_udp_cmd(self, index, cmd):
try:
ip = self.scanner(index).ip
self.udp_socket.writeDatagram(json.dumps(cmd).encode(), QHostAddress(ip), self.UDP_CMD_PORT)
print("send to", ip, cmd)
except Exception as e:
print(e)
def start_scanning(self, index, count = 1, period = 6000):
if self.scanner(index).run_flag == True:
return
print("scanner", index, self.scanner(index).run_flag)
self.scanner(index).run_flag = True
self.scanner(index).running = True
self.send_udp_cmd(index, {"cmd": "start", "count": count, "period": period})
def stop_scanning(self, index):
self.scanner(index).running = False
self.send_udp_cmd(index, {"cmd": "stop"})
def stop_scanning_emer(self, index):
self.scanner(index).running = False
self.send_udp_cmd(index, {"cmd": "emer_stop"})
def reset_scanning(self, index):
self.scanner(index).running = False
self.send_udp_cmd(index, {"cmd": "reset"})
def update_motor_info(self):
try:
if time.time() > self.moto_info_update_time + 0.300:
state_map = {
ScannerState.STOP_AT_BOTTOM: 3,
ScannerState.STOP_AT_UPPER: 1,
ScannerState.STOP_AT_ORIGIN: 0,
ScannerState.MOVING_UP: 2,
ScannerState.MOVING_DOWN: 2,
}
try:
state = state_map[self.scanner(self.ID_MT1).state]
self.update_location.emit(self.ID_MT1, state)
self.update_estimates.emit(self.ID_MT1, self.scanner(self.ID_MT1).location, self.scanner(self.ID_MT1).velocity)
# print(self.scanner(self.ID_MT1).location, self.scanner(self.ID_MT1).velocity)
except Exception as e:
pass
try:
state = state_map[self.scanner(self.ID_MT2).state]
self.update_location.emit(self.ID_MT2, state)
self.update_estimates.emit(self.ID_MT2, self.scanner(self.ID_MT2).location, self.scanner(self.ID_MT2).velocity)
# print(self.scanner(self.ID_MT2).location, self.scanner(self.ID_MT2).velocity)
except Exception as e:
pass
self.moto_info_update_time = time.time()
except Exception as e:
print(e)
self.moto_info_update_time = time.time()
def update_online_state(self):
try:
if time.time() > self.online_status_update_time + 1:
online_state = {
self.ID_MT1: time.time() < self.scanner(self.ID_MT1).last_update_time + 1,
self.ID_MT2: time.time() < self.scanner(self.ID_MT2).last_update_time + 1,
}
self.update_online_status.emit(self.ID_MT1, online_state[self.ID_MT1])
self.update_online_status.emit(self.ID_MT2, online_state[self.ID_MT2])
self.online_status_update_time = time.time()
# print("online state:", online_state)
except Exception as e:
print(e)
self.online_status_update_time = time.time()
@Slot(bytes)
def udp_data_handle(self):
while self.udp_socket.hasPendingDatagrams():
datagram, addr, port = self.udp_socket.readDatagram(self.udp_socket.pendingDatagramSize())
datagram = bytes(datagram.data())
# print(f"Received datagram: {datagram} from {addr}:{port}")
try:
data = json.loads(datagram.decode())
# print(f"Parsed JSON data: {data}")
index = int(data['id'][0])
self.scanner(index).state = data['state']
self.scanner(index).location = data['pos']
self.scanner(index).velocity = data['speed']
self.scanner(index).run_flag = data['run_flag']
self.scanner(index).last_update_time = time.time()
if 'daq_temp' in data:
self.scanner(index).daq_info['temp'] = data['daq_temp']
if 'daq_online' in data:
self.scanner(index).daq_info['online'] = data['daq_online']
if self.scanner(index).state in [ScannerState.MOVING_UP, ScannerState.MOVING_DOWN]:
self.scanner(index).last_moving_time = time.time()
elif self.scanner(index).state in [ScannerState.STOP_AT_BOTTOM, ScannerState.STOP_AT_UPPER, ScannerState.STOP_AT_ORIGIN]:
self.scanner(index).last_idle_time = time.time()
except json.JSONDecodeError as e:
print(f"JSON decode error: {e}")
def scanner_idle_time(self, index):
return time.time() - self.scanner(index).last_moving_time
def scan(self):
# print(self.scanner(self.ID_MT1).running, self.scanner(self.ID_MT2).running)
# print(self.scanner(self.ID_MT1).last_moving_time, self.scanner(self.ID_MT2).last_moving_time)
# print(time.time(), "\n")
if self.work_mode == "normal" and self.scan_count <= 0:
idle_time = 60.0 * 1
self.scan_count = 8
if self.scanner_idle_time(self.ID_MT1) > idle_time and self.scanner_idle_time(self.ID_MT2) > idle_time:
self.scan_count = 8
elif self.work_mode == "slow" and self.scan_count <= 0:
idle_time = 60.0 * 5
if self.scanner_idle_time(self.ID_MT1) > idle_time and self.scanner_idle_time(self.ID_MT2) > idle_time:
self.scan_count = 8
elif self.work_mode == "fast":
self.scan_count = 8
if self.scan_count <= 0:
return
if time.time() - self.start_scan_time < 2.0:
return
if self.scanner(self.ID_MT1).running and (not self.scanner(self.ID_MT2).running):
if time.time() > self.scanner(self.ID_MT1).last_moving_time + 3.0:
self.start_scanning(self.ID_MT1)
print("start_scanning(self.ID_MT1)")
self.scan_count -= 2
self.start_scan_time = time.time()
elif (not self.scanner(self.ID_MT1).running) and self.scanner(self.ID_MT2).running:
if time.time() > self.scanner(self.ID_MT2).last_moving_time + 3.0:
self.start_scanning(self.ID_MT2)
self.scan_count -= 2
self.start_scan_time = time.time()
elif self.scanner(self.ID_MT1).running and self.scanner(self.ID_MT2).running:
idle_time = 3.0
if self.work_mode == "normal":
idle_time = 18.0
if self.scanner_idle_time(self.ID_MT1) > idle_time and self.scanner_idle_time(self.ID_MT2) > 1.0:
self.start_scanning(self.ID_MT1)
self.scan_count -= 1
self.start_scan_time = time.time()
elif self.scanner_idle_time(self.ID_MT1) > 1.0 and self.scanner_idle_time(self.ID_MT2) > idle_time:
self.start_scanning(self.ID_MT2)
self.scan_count -= 1
self.start_scan_time = time.time()
def update_daq_info(self):
try:
daq_index = self.daq_index
if time.time() - self.daq_info_update_time < 1.0:
return
packet = {
'id' : daq_index,
'type' : "daq_info",
'status' : self.scanner(daq_index).daq_info
}
self.udp_socket.writeDatagram(json.dumps(packet).encode(), QHostAddress("127.0.0.1"), 50009)
self.daq_info_update_time = time.time()
if daq_index == self.ID_MT1:
self.daq_index = self.ID_MT2
else:
self.daq_index = self.ID_MT1
except Exception as e:
self.daq_index = self.ID_MT1
self.daq_info_update_time = time.time()
print(f"Error reading DAQ: {e}")
def timer_callback(self):
self.update_online_state()
self.update_motor_info()
self.update_daq_info()
self.scan()
def write_config(self):
with open("/home/admin/.config/cpy/config.json", "w") as f:
json.dump(self.config, f)
def default_config(self):
config = {
}
self.config = config
return config
def read_config(self):
config = {}
path = "/home/admin/.config/cpy/config.json"
if not os.path.exists(path):
self.default_config()
return self.config
with open(path, "r") as f:
config = json.load(f)
self.config = config
return config
def start(self, motor_index):
if motor_index & self.ID_MT1:
self.scanner(self.ID_MT1).running = True
if self.scanner_idle_time(self.ID_MT1) > 3.0:
self.scanner(self.ID_MT1).last_moving_time = 0.0
if motor_index & self.ID_MT2:
self.scanner(self.ID_MT2).running = True
if self.scanner_idle_time(self.ID_MT2) > 3.0:
self.scanner(self.ID_MT2).last_moving_time = 0.0
def emergency_stop(self, motor_index):
if motor_index & self.ID_MT1:
self.stop_scanning_emer(self.ID_MT1)
if motor_index & self.ID_MT2:
self.stop_scanning_emer(self.ID_MT2)
def stop(self, motor_index):
if motor_index & self.ID_MT1:
self.stop_scanning(self.ID_MT1)
if motor_index & self.ID_MT2:
self.stop_scanning(self.ID_MT2)
def destroy(self):
pass
@Slot(int, str, str)
def set_globaldev_value(self, motor_index, key, value):
print("set_globaldev_value", motor_index, key, value)
if motor_index == 3 and key == "sports_mode":
self.work_mode = value
print("self.work_mode =",self.work_mode)
self.update_work_mode.emit(self.work_mode)
if motor_index == 3 and key == "switch":
try:
val = int(value)
except ValueError:
print("set_globaldev_value ValueError", motor_index, key, value)
return
if val == 0:
self.reset_scanning(self.ID_MT1)
self.reset_scanning(self.ID_MT2)
@Slot(int, str, int)
def set_value(self, motor_index, key, value):
if key == "profileVelocity":
return
if key == "emergency_stop":
self.emergency_stop(motor_index)
elif key == "switch":
if value == 1:
self.start(motor_index)
else:
if motor_index == 3:
self.reset_scanning(self.ID_MT1)
self.reset_scanning(self.ID_MT2)
else:
self.stop(motor_index)
@@ -0,0 +1,390 @@
import os
import math
import time
import threading
import subprocess
import re
import json
from config import *
from PySide6.QtCore import *
from PySide6.QtNetwork import QUdpSocket, QHostAddress
import socket, struct
from PySide6.QtCore import QTimer
class ScannerState:
STOP = 'stop'
MOVING_UP = 'moving_up'
MOVING_DOWN = 'moving_down'
STOP_AT_UPPER = 'stop_at_upper'
STOP_AT_BOTTOM = 'stop_at_bottom'
STOP_AT_ORIGIN = 'stop_at_origin'
UNKNOWN = 'unknown'
valid_states = [STOP, MOVING_UP, MOVING_DOWN,
STOP_AT_UPPER, STOP_AT_BOTTOM,
STOP_AT_ORIGIN, UNKNOWN]
class Scanner:
def __init__(self, id):
self.id = id
self.config = {}
self.state = ScannerState.UNKNOWN
self.running = False
self.last_update_time = 0
self.location = 0
self.velocity = 0
self.daq_info = {}
self.last_moving_time = 0
self.last_idle_time = 0
self.run_flag = False
self.read_config()
self.ip = self.config.get("ip", "192.168.100.21")
def read_config(self):
try:
config = {}
path = "/home/admin/.config/cpy/scanner.json"
if not os.path.exists(path):
return
with open(path, "r") as f:
config = json.load(f)
self.config = config[f"scanner{self.id}"]
except Exception as e:
print(e)
class MotorManager(QObject):
update_location = Signal(int,int)
update_direction = Signal(int,str)
update_estimates = Signal(int, float, float)
update_online_status = Signal(int, int)
update_setting_velocity = Signal(int, float)
update_duration = Signal(int,float)
update_state = Signal(int, int)
update_work_mode = Signal(str)
# 定义ID_MT1、ID_MT2两个常量为0x01, 0x02
ID_MT1 = 0x01
ID_MT2 = 0x02
UDP_STATUS_PORT = 11200
UDP_CMD_PORT = 11300
def __init__(self, bus_id = 1):
super().__init__()
self.scanners = [Scanner(self.ID_MT1),
Scanner(self.ID_MT2)]
self.mqtt_client = None
self.read_config()
self.work_mode = "fast"
print(self.config)
self.light_status = None
self.last_light_on_time = 0
self.start_scan_time = 0
self.online_status_update_time = 0
self.moto_info_update_time = 0
self.udp_socket = QUdpSocket(self)
self.udp_socket.bind(QHostAddress.Any, self.UDP_STATUS_PORT)
self.udp_socket.readyRead.connect(self.udp_data_handle)
self.timer = QTimer(self)
self.timer.setInterval(100)
self.timer.timeout.connect(self.timer_callback)
self.timer.start()
def scanner(self, index):
return self.scanners[index - 1]
def send_udp_cmd(self, index, cmd):
try:
ip = self.scanner(index).ip
self.udp_socket.writeDatagram(json.dumps(cmd).encode(), QHostAddress(ip), self.UDP_CMD_PORT)
print("send to", ip, cmd)
except Exception as e:
print(e)
def start_scanning(self, index, count = 1, period = 6000):
if self.scanner(index).run_flag == True:
return
print("scanner", index, self.scanner(index).run_flag)
self.scanner(index).run_flag = True
self.scanner(index).running = True
self.send_udp_cmd(index, {"cmd": "start", "count": count, "period": period})
def stop_scanning(self, index):
self.scanner(index).running = False
self.send_udp_cmd(index, {"cmd": "stop"})
def stop_scanning_emer(self, index):
self.scanner(index).running = False
self.send_udp_cmd(index, {"cmd": "emer_stop"})
def reset_scanning(self, index):
self.scanner(index).running = False
self.send_udp_cmd(index, {"cmd": "reset"})
def update_motor_info(self):
try:
if time.time() > self.moto_info_update_time + 0.300:
state_map = {
ScannerState.STOP_AT_BOTTOM: 3,
ScannerState.STOP_AT_UPPER: 1,
ScannerState.STOP_AT_ORIGIN: 0,
ScannerState.MOVING_UP: 2,
ScannerState.MOVING_DOWN: 2,
}
try:
state = state_map[self.scanner(self.ID_MT1).state]
self.update_location.emit(self.ID_MT1, state)
self.update_estimates.emit(self.ID_MT1, self.scanner(self.ID_MT1).location, self.scanner(self.ID_MT1).velocity)
# print(self.scanner(self.ID_MT1).location, self.scanner(self.ID_MT1).velocity)
except Exception as e:
pass
try:
state = state_map[self.scanner(self.ID_MT2).state]
self.update_location.emit(self.ID_MT2, state)
self.update_estimates.emit(self.ID_MT2, self.scanner(self.ID_MT2).location, self.scanner(self.ID_MT2).velocity)
# print(self.scanner(self.ID_MT2).location, self.scanner(self.ID_MT2).velocity)
except Exception as e:
pass
self.moto_info_update_time = time.time()
except Exception as e:
print(e)
self.moto_info_update_time = time.time()
def update_online_state(self):
try:
if time.time() > self.online_status_update_time + 1:
online_state = {
self.ID_MT1: time.time() < self.scanner(self.ID_MT1).last_update_time + 1,
self.ID_MT2: time.time() < self.scanner(self.ID_MT2).last_update_time + 1,
}
self.update_online_status.emit(self.ID_MT1, online_state[self.ID_MT1])
self.update_online_status.emit(self.ID_MT2, online_state[self.ID_MT2])
self.online_status_update_time = time.time()
# print("online state:", online_state)
except Exception as e:
print(e)
self.online_status_update_time = time.time()
@Slot(bytes)
def udp_data_handle(self):
while self.udp_socket.hasPendingDatagrams():
datagram, addr, port = self.udp_socket.readDatagram(self.udp_socket.pendingDatagramSize())
datagram = bytes(datagram.data())
# print(f"Received datagram: {datagram} from {addr}:{port}")
try:
data = json.loads(datagram.decode())
# print(f"Parsed JSON data: {data}")
index = int(data['id'][0])
self.scanner(index).state = data['state']
self.scanner(index).location = data['pos']
self.scanner(index).velocity = data['speed']
self.scanner(index).run_flag = data['run_flag']
self.scanner(index).last_update_time = time.time()
if 'daq_temp' in data:
self.scanner(index).daq_info['temp'] = data['daq_temp']
if 'daq_online' in data:
self.scanner(index).daq_info['online'] = data['daq_online']
if self.scanner(index).state in [ScannerState.MOVING_UP, ScannerState.MOVING_DOWN]:
self.scanner(index).last_moving_time = time.time()
elif self.scanner(index).state in [ScannerState.STOP_AT_BOTTOM, ScannerState.STOP_AT_UPPER, ScannerState.STOP_AT_ORIGIN]:
self.scanner(index).last_idle_time = time.time()
except json.JSONDecodeError as e:
print(f"JSON decode error: {e}")
def scanner_idle_time(self, index):
return time.time() - self.scanner(index).last_moving_time
def scan(self):
# print(self.scanner(self.ID_MT1).running, self.scanner(self.ID_MT2).running)
# print(self.scanner(self.ID_MT1).last_moving_time, self.scanner(self.ID_MT2).last_moving_time)
# print(time.time(), "\n")
if self.work_mode == "normal" and self.scan_count <= 0:
idle_time = 60.0 * 1
if self.scanner_idle_time(self.ID_MT1) > idle_time and self.scanner_idle_time(self.ID_MT2) > idle_time:
self.scan_count = 8
elif self.work_mode == "slow" and self.scan_count <= 0:
idle_time = 60.0 * 5
if self.scanner_idle_time(self.ID_MT1) > idle_time and self.scanner_idle_time(self.ID_MT2) > idle_time:
self.scan_count = 8
elif self.work_mode == "fast":
self.scan_count = 8
if self.scan_count <= 0:
return
if time.time() - self.start_scan_time < 2.0:
return
if self.scanner(self.ID_MT1).running and (not self.scanner(self.ID_MT2).running):
if time.time() > self.scanner(self.ID_MT1).last_moving_time + 3.0:
self.start_scanning(self.ID_MT1)
print("start_scanning(self.ID_MT1)")
self.scan_count -= 2
self.start_scan_time = time.time()
elif (not self.scanner(self.ID_MT1).running) and self.scanner(self.ID_MT2).running:
if time.time() > self.scanner(self.ID_MT2).last_moving_time + 3.0:
self.start_scanning(self.ID_MT2)
self.scan_count -= 2
self.start_scan_time = time.time()
elif self.scanner(self.ID_MT1).running and self.scanner(self.ID_MT2).running:
idle_time = 3.0
if self.scanner_idle_time(self.ID_MT1) > idle_time and self.scanner_idle_time(self.ID_MT2) > idle_time:
self.start_scanning(self.ID_MT1)
self.scan_count -= 1
self.start_scan_time = time.time()
elif (self.scanner_idle_time(self.ID_MT1) > 1.0) and (self.scanner_idle_time(self.ID_MT2) > 1.0):
if self.scanner_idle_time(self.ID_MT1) > self.scanner_idle_time(self.ID_MT2):
self.start_scanning(self.ID_MT1)
self.scan_count -= 1
self.start_scan_time = time.time()
else:
self.start_scanning(self.ID_MT2)
self.scan_count -= 1
self.start_scan_time = time.time()
def update_daq_info(self):
try:
daq_index = self.daq_index
if time.time() - self.daq_info_update_time < 1.0:
return
packet = {
'id' : daq_index,
'type' : "daq_info",
'status' : self.scanner(daq_index).daq_info
}
self.udp_socket.writeDatagram(json.dumps(packet).encode(), QHostAddress("127.0.0.1"), 50009)
self.daq_info_update_time = time.time()
if daq_index == self.ID_MT1:
self.daq_index = self.ID_MT2
else:
self.daq_index = self.ID_MT1
except Exception as e:
self.daq_index = self.ID_MT1
self.daq_info_update_time = time.time()
print(f"Error reading DAQ: {e}")
def timer_callback(self):
self.update_online_state()
self.update_motor_info()
self.update_daq_info()
self.scan()
def write_config(self):
with open("/home/admin/.config/cpy/config.json", "w") as f:
json.dump(self.config, f)
def default_config(self):
config = {
}
self.config = config
return config
def read_config(self):
config = {}
path = "/home/admin/.config/cpy/config.json"
if not os.path.exists(path):
self.default_config()
return self.config
with open(path, "r") as f:
config = json.load(f)
self.config = config
return config
def start(self, motor_index):
if motor_index & self.ID_MT1:
self.scanner(self.ID_MT1).running = True
if self.scanner_idle_time(self.ID_MT1) > 3.0:
self.scanner(self.ID_MT1).last_moving_time = 0.0
if motor_index & self.ID_MT2:
self.scanner(self.ID_MT2).running = True
if self.scanner_idle_time(self.ID_MT2) > 3.0:
self.scanner(self.ID_MT2).last_moving_time = 0.0
def emergency_stop(self, motor_index):
if motor_index & self.ID_MT1:
self.stop_scanning_emer(self.ID_MT1)
if motor_index & self.ID_MT2:
self.stop_scanning_emer(self.ID_MT2)
def stop(self, motor_index):
if motor_index & self.ID_MT1:
self.stop_scanning(self.ID_MT1)
if motor_index & self.ID_MT2:
self.stop_scanning(self.ID_MT2)
def destroy(self):
pass
@Slot(int, str, str)
def set_globaldev_value(self, motor_index, key, value):
print("set_globaldev_value", motor_index, key, value)
if motor_index == 3 and key == "sports_mode":
self.work_mode = value
print("self.work_mode =",self.work_mode)
self.update_work_mode.emit(self.work_mode)
if motor_index == 3 and key == "switch":
try:
val = int(value)
except ValueError:
print("set_globaldev_value ValueError", motor_index, key, value)
return
if val == 0:
self.reset_scanning(self.ID_MT1)
self.reset_scanning(self.ID_MT2)
@Slot(int, str, int)
def set_value(self, motor_index, key, value):
if key == "profileVelocity":
return
if key == "emergency_stop":
self.emergency_stop(motor_index)
elif key == "switch":
if value == 1:
self.start(motor_index)
else:
if motor_index == 3:
self.reset_scanning(self.ID_MT1)
self.reset_scanning(self.ID_MT2)
else:
self.stop(motor_index)
+12
View File
@@ -0,0 +1,12 @@
BROKER = "127.0.0.1"
PORT = 1883
USER = "test"
PWD = "test"
PIN_CTRL_XRAY_1 = 22
PIN_CTRL_XRAY_2 = 27
PIN_CTRL_MOTOR = 18
PIN_CTRL_DAQ = 17
# BROKER = "127.0.0.1"
# PORT = 1883
# USER = "tgzz"
# PWD = "Tgzz2025"
+107
View File
@@ -0,0 +1,107 @@
from PySide6.QtCore import *
class DataCenter(QObject):
plcAlive = Signal(bool)
dataReady = Signal(int, dict)
readFinished = Signal()
def __init__(self, parent=None):
super().__init__(parent)
self.settings = QSettings("TGZZ", "TGX") # 设置存储位置
self.device_object = {
"scanner1":{
"motor":{
"online": False,
"position": 0,
"direction": 0,
"duration": 0,
"location": 0,
"velocity": 0,
"setting_velocity": 0,
"usage_duration": 15,
"useful_life": 365,
"failure_status": 1,
"failure_info": ""
}
},
"scanner2":{
"motor":{
"online": False,
"position": 0,
"direction": 0,
"duration": 0,
"location": 0,
"velocity": 0,
"setting_velocity": 0,
"usage_duration": 15,
"useful_life": 365,
"failure_status": 1,
"failure_info": ""
}
},
"global_dev":{
"device":{
"sports_mode": "fast"
}
}
}
@Slot(str)
def update_motor_sports_mode(self, sports_mode):
self.device_object["global_dev"]["device"]["sports_mode"] = sports_mode
print("self.device_object global_dev=",self.device_object["global_dev"])
self.dataReady.emit(3, self.device_object["global_dev"]["device"]) # 更新全局设备数据
@Slot(int, int)
def update_online_status(self, motor_index, status):
result = False
if status == 1:
result = True
else:
result = False
self.device_object[f"scanner{motor_index}"]["motor"]["online"] = result
self.dataReady.emit(motor_index, self.device_object[f"scanner{motor_index}"]["motor"])
@Slot(int, float, float)
def update_motor_estimates(self, node_index, position, velocity):
motor_index = node_index
self.device_object[f"scanner{motor_index}"]["motor"]["position"] = position
self.device_object[f"scanner{motor_index}"]["motor"]["velocity"] = velocity
self.dataReady.emit(motor_index, self.device_object[f"scanner{motor_index}"]["motor"])
# print(f"motor{motor_index}, position:{position}, velocity:{velocity}")
@Slot(int, int)
def update_motor_location(self, motor_index, location):
self.device_object[f"scanner{motor_index}"]["motor"]["location"] = location
self.dataReady.emit(motor_index, self.device_object[f"scanner{motor_index}"]["motor"])
# print(f"motor{motor_index}, location:{location}")
@Slot(int, str)
def update_motor_direction(self, motor_index, direction):
print(f"motor{motor_index}, direction:{direction}")
self.device_object[f"scanner{motor_index}"]["motor"]["direction"] = direction
self.dataReady.emit(motor_index, self.device_object[f"scanner{motor_index}"]["motor"])
@Slot(int, float)
def update_motor_duration(self, motor_index, duration):
self.device_object[f"scanner{motor_index}"]["motor"]["duration"] = duration
self.dataReady.emit(motor_index, self.device_object[f"scanner{motor_index}"]["motor"])
@Slot(int,float)
def update_motor_setting_velocity(self, motor_index, setting_velocity):
if motor_index == 0:
self.device_object["scanner1"]["motor"]["setting_velocity"] = setting_velocity
self.device_object["scanner2"]["motor"]["setting_velocity"] = setting_velocity
else:
self.device_object[f"scanner{motor_index}"]["motor"]["setting_velocity"] = setting_velocity
self.dataReady.emit(motor_index, self.device_object[f"scanner{motor_index}"]["motor"])
@Slot(int,int)
def update_motor_state(self, motor_index, state):
self.device_object[f"scanner{motor_index}"]["motor"]["state"] = state
self.dataReady.emit(motor_index, self.device_object[f"scanner{motor_index}"]["motor"])
+102
View File
@@ -0,0 +1,102 @@
# Draw.io 使用指南:绘制UML状态图并保存本地
## 一、进入绘制界面
1. 打开 [draw.io](https://app.diagrams.net/)
2. 选择「Create New Diagram」(创建新图表)
3. 选择存储位置:点击「Device」(设备)→ 暂时不保存
4. 选择模板:点击「Blank Diagram」(空白图表)→ 点击「Create」
## 二、绘制UML状态图
### 1. 启用UML状态图工具
在左侧工具栏找到并点击「More Shapes」(更多形状):
- 展开「Software」(软件)→ 勾选「UML」
- 特别勾选「UML State Machine」(UML状态机)
- 点击「Apply」(应用)
### 2. 绘制基本元素
#### 初始状态
- 从左侧「UML State Machine」工具栏拖拽「Initial State」(实心圆)到画布
#### 普通状态
- 拖拽「State」(圆角矩形)到画布
- 双击状态框输入状态名称(如:`scanner1_scanning`)
- 右键点击状态 → 「Edit Style」(编辑样式)可修改颜色、边框等
#### 状态转换
- 从左侧工具栏拖拽「Transition」(带箭头的线)到画布
- 连接两个状态(起点状态 → 终点状态)
- 双击箭头输入触发事件(如:`scanner1_complete`)
#### 终止状态
- 从左侧工具栏拖拽「Final State」(同心圆)到画布(如果需要)
### 3. 高级设置
#### 转换条件
- 右键点击转换箭头 → 「Edit」(编辑)→ 「Add Condition」(添加条件)
- 输入条件(如:`if position == upper_limit`)
#### 状态动作
- 双击状态 → 进入编辑模式
- 输入格式:`状态名称\n/进入动作\n退出动作`
- 示例:`scanner1_scanning\n/on_scanner1_scanning_start()\non_scanner1_scanning_stop()`
#### 并行区域(可选)
- 使用「Composite State」(复合状态)创建嵌套区域
- 用于表示并发执行的状态
## 三、保存到本地
### 1. 保存为.drawio格式(可编辑)
- 点击顶部菜单栏「File」(文件)→ 「Save As」(另存为)
- 选择「Device」(设备)
- 选择保存位置(推荐保存到 `motor_service` 目录)
- 输入文件名(如:`scanner_state_machine.drawio`)
- 点击「Save」(保存)
### 2. 导出为图片格式(用于查看)
- 点击顶部菜单栏「File」(文件)→ 「Export As」(导出为)→ 「PNG」
- 设置图片参数:
- 「Include a border」(包含边框):可选
- 「Zoom」(缩放):100%
- 「Transparent Background」(透明背景):可选
- 点击「Export」(导出)
- 选择保存位置和文件名(如:`scanner_state_machine.png`)
- 点击「Save」(保存)
### 3. 导出为PDF格式(用于文档)
- 点击顶部菜单栏「File」(文件)→ 「Export As」(导出为)→ 「PDF」
- 设置PDF参数后点击「Export」(导出)
## 四、绘制示例(扫描器状态图)
按照之前的设计指南,绘制以下状态:
- 初始状态
- `all_stopped`
- `scanner1_scanning`
- `scanner1_waiting`
- `scanner2_scanning`
- `scanner2_waiting`
并添加以下转换:
- 初始状态 → `all_stopped`
- `all_stopped` → `scanner1_scanning`(触发:`start_scanner1`)
- `all_stopped` → `scanner2_scanning`(触发:`start_scanner2`)
- `scanner1_scanning` → `scanner1_waiting`(触发:`scanner1_complete`)
- `scanner2_scanning` → `scanner2_waiting`(触发:`scanner2_complete`)
- `scanner1_waiting` → `scanner2_scanning`(触发:`start_scanner2`)
- `scanner2_waiting` → `scanner1_scanning`(触发:`start_scanner1`)
- 所有状态 → `all_stopped`(触发:`stop_all` 或 `emer_stop_all`)
## 五、注意事项
1. 定期保存:绘制过程中可按 Ctrl+S(Windows)或 Command+S(Mac)快速保存
2. 命名规范:使用有意义的状态名称和事件名称
3. 布局清晰:使用「Arrange」(排列)菜单调整状态布局
4. 颜色区分:使用不同颜色表示不同类型的状态(如:运行状态用绿色,停止状态用红色)
绘制完成后,将 `.drawio` 文件保存到 `motor_service` 目录,然后告诉我,我将根据您的状态图实现代码。
+76
View File
@@ -0,0 +1,76 @@
from mqtt_client import MQTTClient
from data_center import DataCenter
from Manager.mwmotor_manager import MotorManager
import sys
import os
import time
import signal
from PySide6.QtCore import *
class Application(QCoreApplication):
def __init__(self, argv):
super().__init__(argv)
self.motor_manager = None
self.mqtt_client = None
self._signal_received = False
# 创建定时器检查信号
self.timer = QTimer()
self.timer.timeout.connect(self.check_signals)
self.timer.start(100) # 每100ms检查一次
def check_signals(self):
if self._signal_received:
self.timer.stop()
self.cleanup()
def cleanup(self):
print("\n正在清理资源...")
# 停止电机
if self.motor_manager:
self.motor_manager.emergency_stop(MotorManager.ID_MT1 | MotorManager.ID_MT2)
time.sleep(0.2)
self.motor_manager.destroy()
time.sleep(0.2)
# 断开MQTT连接
if self.mqtt_client:
self.mqtt_client.quit()
print("资源清理完成,程序退出")
self.quit()
def signal_handler(signum, frame):
app._signal_received = True
def exec_cmd(cmd):
print("exec:", cmd)
out = os.popen(cmd)
print(out.readlines())
if __name__ == "__main__":
app = Application(sys.argv)
# 注册信号处理
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
exec_cmd("sudo pinctrl set 17 op pn dl")
app.motor_manager = MotorManager()
app.mqtt_client = MQTTClient()
data_center = DataCenter()
app.motor_manager.mqtt_client = app.mqtt_client
app.motor_manager.update_online_status.connect(data_center.update_online_status)
app.motor_manager.update_setting_velocity.connect(data_center.update_motor_setting_velocity)
app.motor_manager.update_location.connect(data_center.update_motor_location)
app.motor_manager.update_estimates.connect(data_center.update_motor_estimates)
app.motor_manager.update_direction.connect(data_center.update_motor_direction)
app.motor_manager.update_duration.connect(data_center.update_motor_duration)
app.motor_manager.update_state.connect(data_center.update_motor_state)
app.motor_manager.update_work_mode.connect(data_center.update_motor_sports_mode)
data_center.dataReady.connect(app.mqtt_client.send_motor_status)
app.mqtt_client.write_motor_data.connect(app.motor_manager.set_value)
app.mqtt_client.write_motor_globaldev_data.connect(app.motor_manager.set_globaldev_value)
sys.exit(app.exec())
+178
View File
@@ -0,0 +1,178 @@
import paho.mqtt.client as mqtt
import json
from datetime import datetime
import time
import socket
from threading import Timer
from config import *
from PySide6.QtCore import *
from PySide6.QtCore import QTimer
from typing import Dict, Any, List, Optional
#from PySide6.QtNetWork import *
# 定义主题常量
TOPICFIRST = "v1/cpy/"
TOPICDEVICE = "/device"
TOPICSTATUS = "/devstatus"
TOPICCAL = "/calculation"
TOPICCTRL = "/control"
TOPICPRODUCT = "/product"
TOPICCOLLECT = "/collect"
startTime = time.time()
# 定义MQTT主题
DEVICE_STATUS_TOPIC = "device/status"
DEVICE_CONTROL_TOPIC = "device/control"
SERVICE_STATUS_TOPIC = "service/status"
DEVICE_API_TOPIC = "api/devices/response"
class MQTTClient(QObject):
write_motor_data = Signal(int, str, int)
write_motor_globaldev_data = Signal(int, str, str)
def __init__(self ):
super().__init__()
self.mqtt_client = mqtt.Client(client_id = 'scanner_service_' + self.random_string(6)) # 创建本地客户端
self.mqtt_client.username_pw_set(USER, PWD)
# 设置回调函数
self.mqtt_client.on_connect = self.on_connect
self.mqtt_client.on_message = self.on_message
self.mqtt_client.on_disconnect = self.on_disconnect
self.is_connected = False
self.conn_timer = QTimer(self)
self.conn_timer.setInterval(1000)
self.conn_timer.timeout.connect(self.connTimerHandler)
self.conn_timer.start()
def random_string(self, length=6):
"""生成随机字符串"""
import random
import string
return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
def checkLocalServer(self):
host = '127.0.0.1'
port = 1883
timeout = 1
print(f"Starting to check if {host}:{port} is available")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
try:
result = sock.connect_ex((host, port))
if result == 0:
print(f"Successfully connected to {host}:{port}")
return True
else:
print(f"Failed to connect to {host}:{port}, error code: {result}")
return False
except Exception as e:
print(f"An exception occurred while connecting to {host}:{port}: {e}")
return False
finally:
sock.close()
def connTimerHandler(self):
print("mqtt connect timer")
self.conn_timer.stop()
if self.checkLocalServer():
self.mqtt_client.connect(BROKER, PORT) # 连接本地 MQTT 服务器
self.mqtt_client.loop_start() # 开始循环以处理网络流量
else:
print("local mqtt brokeris not ready")
self.conn_timer.start()
def quit(self):
self.mqtt_client.loop_stop() # 停止循环
self.mqtt_client.disconnect()
def on_connect(self, client, userdata, flags, rc):
"""连接成功时调用"""
print(f"Connected to MQTT broker with result code {rc}")
client.subscribe(DEVICE_CONTROL_TOPIC) # 订阅命令主题
self.is_connected = True
def on_disconnect(self, client, userdata, rc):
self.is_connected = False
print("MQTT 已断开连接")
def on_message(self, client, userdata, msg):
"""处理接收到的消息"""
if not 'MTO' in msg.payload.decode():
return
print(f"Message received on topic: {msg.topic} Message: {msg.payload.decode()}")
# 解析 JSON
try:
json_obj = json.loads(msg.payload.decode())
if msg.topic == DEVICE_CONTROL_TOPIC:
self.handle_message(json_obj)
except json.JSONDecodeError:
print("Failed to decode JSON")
def handle_message(self, json_obj):
"""处理接收到的 JSON 消息"""
motor_index = -1
device_code = json_obj.get("device_code")
device_id = json_obj.get("device_id")
device_address = int(json_obj.get("device_address", 0))
command = json_obj.get("command")
if not 'MTO' in device_code:
return
print("device_code", device_code, "device_id", device_id, "device_address", device_address, "command", command)
if device_code == "1#MTO" or device_code == "2#MTO" or device_code == "3#MTO":
value = json_obj.get("value")
if device_address == 1:
print("motor",device_address, command, value)
self.write_motor_data.emit(1, command, value)
elif device_address == 2:
print("motor",device_address, command, value)
self.write_motor_data.emit(2, command, value)
if device_address == 3:
print("motor",device_address, command, value)
self.write_motor_globaldev_data.emit(3, command, str(value))
def publish_msg(self, topic, msg):
if isinstance(msg, dict):
msg = json.dumps(msg)
# print("publish_msg", topic, msg)
self.mqtt_client.publish(topic, msg, qos=0)
def pusblish_service_status(self):
global startTime
runningTime = time.time() - startTime
message = {
"service_name" : "motor_service",
"status": {
"available": True,
"running_time": runningTime
}
}
self.publish_msg(SERVICE_STATUS_TOPIC, message)
def send_motor_status(self, motor_index, status):
device_id = ""
device_code = ""
# print("send_motor_status", motor_index, status)
device_code = f"{motor_index}#MTO"
self.publish_msg(DEVICE_STATUS_TOPIC, {
"device_code": device_code, # 添加设备编码
"status": status,
"timestamp": datetime.now().isoformat()
})
if hasattr(self, 'last_status_update'):
if time.time() - self.last_status_update < 3.0:
return
self.last_status_update = time.time()
self.pusblish_service_status()
def publish_cpy(self, topicname, data):
topic = TOPICFIRST + self.device_id + topicname # 构建完整的主题名称
json_data = json.dumps(data) # 将数据转换为 JSON 字符串
self.mqtt_client.publish(topic, json_data) # 发布数据到本地
+154
View File
@@ -0,0 +1,154 @@
aiocoap==0.4.9
altgraph==0.17.3
astroid==3.0.1
autograd==1.6.2
autopep8==2.0.4
bleak==0.20.2
bleak-winrt==1.2.0
blinker==1.7.0
certifi==2023.7.22
cffi==1.15.1
charset-normalizer==3.2.0
click==8.1.3
clr-loader==0.2.5
colorama==0.4.6
colorlog==6.7.0
comtypes==1.4.7
contourpy==1.1.0
CPU-temperature-monitor==0.2
crcmod==1.7
cycler==0.11.0
dill==0.3.7
docopt==0.6.2
docstring-to-markdown==0.13
et-xmlfile==1.1.0
flake8==6.1.0
Flask==3.0.0
Flask-Cors==4.0.0
fonttools==4.40.0
future==0.18.3
greenlet==2.0.2
httpserver==1.1.0
idna==3.4
importlib-metadata==6.7.0
influxdb==5.3.1
influxdb-client==1.36.1
iso8601==2.0.0
isort==5.12.0
isqdeployer==0.0.45
isqtools==0.1.5
itsdangerous==2.1.2
jedi==0.19.1
Jinja2==3.1.2
joblib==1.3.2
kiwisolver==1.4.4
kneed==0.8.5
Markdown==3.5.1
markdown-it-py==3.0.0
MarkupSafe==2.1.3
matlab==0.1
matlabengine==24.1
matplotlib==3.7.1
mccabe==0.7.0
mdurl==0.1.2
MouseInfo==0.1.3
mplcursors==0.5.2
msgpack==1.0.5
mysql-connector-python==8.2.0
numpy==1.25.0
opencv-python==4.10.0.84
opencv-python-headless==4.10.0.84
openpyxl==3.1.2
packaging==23.1
paho-mqtt==1.6.1
pandas==2.1.3
parso==0.8.3
pefile==2023.2.7
Pillow==10.0.0
platformdirs==3.7.0
pluggy==1.3.0
protobuf==4.21.12
psutil==5.9.5
pyasn1==0.6.0
PyAutoGUI==0.9.54
pycodestyle==2.11.1
pycparser==2.21
pycryptodome==3.16.0
pydocstyle==6.3.0
pyflakes==3.1.0
PyGetWindow==0.0.9
Pygments==2.15.1
pyinstaller==6.2.0
pyinstaller-hooks-contrib==2023.3
pylint==3.0.2
pymodbus==3.6.4
PyMsgBox==1.0.9
PyMySQL==1.1.0
pyparsing==3.1.0
pyperclip==1.9.0
pypiwin32==223
pyqt5-plugins==5.15.9.2.3
PyQt5-Qt5==5.15.2
PyQt5-sip==12.13.0
pyqt5-tools==5.15.9.3.3
PyQt6==6.6.0
PyQt6-Charts==6.6.0
PyQt6-Charts-Qt6==6.6.2
PyQt6-QScintilla==2.14.1
PyQt6-Qt6==6.6.0
PyQt6-sip==13.6.0
PyQt6-WebEngine==6.6.0
PyQt6-WebEngine-Qt6==6.6.0
PyQtChart==5.15.6
PyQtChart-Qt5==5.15.2
pyqtgraph==0.13.3
PyRect==0.2.0
pyscard==2.0.9
PyScreeze==0.1.30
pyserial==3.5
pytesseract==0.3.10
python-can==4.3.1
python-dateutil==2.8.2
python-dotenv==1.0.0
python-lsp-jsonrpc==1.1.2
python-lsp-server==1.9.0
pythonnet==3.0.1
pytoolconfig==1.2.6
pytweening==1.2.0
pytz==2023.3
pywin32==306
pywin32-ctypes==0.2.1
PyYAML==6.0
QCustomPlot_PyQt5==2.1.1.1
qt5-applications==5.15.2.2.3
qt5-tools==5.15.2.1.3
qt6-applications==6.4.3.2.3
qt6-tools==6.4.3.1.3
reactivex==4.0.4
requests==2.28.2
rich==13.6.0
rope==1.11.0
scikit-learn==1.3.2
scipy==1.11.1
SCons==4.8.0
serial==0.0.97
six==1.16.0
snowballstemmer==2.2.0
SQLAlchemy==2.0.19
threadpoolctl==3.2.0
tkinterdnd2==0.4.2
tomli==2.0.1
tomlkit==0.12.3
typing_extensions==4.7.1
tzdata==2023.3
ujson==5.8.0
urllib3==1.26.18
watchdog==3.0.0
Werkzeug==3.0.1
whatthepatch==1.0.5
WMI==1.5.1
wrapt==1.17.2
xlwings==0.31.1
yapf==0.40.1
zipp==3.15.0
transitions==0.9.0
+18
View File
@@ -0,0 +1,18 @@
[Unit]
Description=Scanner Service
After=emqx.service
Wants=network-online.target
[Service]
Type=simple
User=root
Group=root
WorkingDirectory=/home/admin/CPY/CPY_AdminPlatform_V3.5/scanner_service
ExecStart=/home/admin/CPY/venv/bin/python /home/admin/CPY/CPY_AdminPlatform_V3.5/scanner_service/main.py
Restart=always
RestartSec=10s
StartLimitBurst=5
Environment=PYTHONUNBUFFERED=1
[Install]
WantedBy=multi-user.target
+165
View File
@@ -0,0 +1,165 @@
# 状态机设计指南
## 一、状态图绘制指南
### 1. 状态图包含要素
为了确保状态图能准确转换为代码,请包含以下要素:
| 要素 | 说明 | 示例 |
|------|------|------|
| **状态名称** | 清晰描述系统状态 | `scanner1_scanning` |
| **状态转换** | 状态间的变化路径 | `scanner1_scanning → scanner1_waiting` |
| **触发事件** | 导致转换的信号 | `scanner1_complete` |
| **转换条件** | 转换发生的条件 | `if position == upper_limit` |
| **执行动作** | 转换时执行的操作 | `on_scanner1_scanning_start()` |
| **初始状态** | 系统初始状态 | `all_stopped` |
### 2. 状态图绘制工具推荐
- **在线工具**:
- [draw.io](https://app.diagrams.net/) - 免费、功能强大
- [Lucidchart](https://www.lucidchart.com/) - 专业UML绘图
- [PlantUML](https://plantuml.com/state-diagram) - 文本描述生成图形
- **本地工具**:
- Microsoft Visio
- StarUML
- Visual Studio Code 插件 (如 PlantUML)
### 3. 绘制示例(PlantUML语法)
```plantuml
@startuml
skinparam state {
StartColor red
EndColor silver
BackgroundColor beige
BorderColor gray
FontName Helvetica
}
[*] --> all_stopped
state all_stopped {
}
state scanner1_scanning {
}
state scanner1_waiting {
}
state scanner2_scanning {
}
state scanner2_waiting {
}
all_stopped --> scanner1_scanning : start_scanner1
transition all_stopped --> scanner2_scanning : start_scanner2
scanner1_scanning --> scanner1_waiting : scanner1_complete
scanner2_scanning --> scanner2_waiting : scanner2_complete
scanner1_waiting --> scanner2_scanning : start_scanner2
scanner2_waiting --> scanner1_scanning : start_scanner1
scanner1_scanning --> all_stopped : stop_all
scanner1_waiting --> all_stopped : stop_all
scanner2_scanning --> all_stopped : stop_all
scanner2_waiting --> all_stopped : stop_all
@enduml
```
## 二、代码实现对应关系
### 1. 状态映射
| 状态图要素 | 代码实现 |
|------------|----------|
| 状态 | `self.states = ['state1', 'state2', ...]` |
| 转换 | `self.transitions = [{'trigger': 'event', 'source': 'from_state', 'dest': 'to_state'}]` |
| 初始状态 | `Machine(initial='initial_state')` |
| 动作 | `self.on_enter_state_name(action_function)` |
### 2. 事件处理
```python
# 状态转换定义
self.transitions = [
{'trigger': 'start_scanner1', 'source': 'all_stopped', 'dest': 'scanner1_scanning'},
{'trigger': 'scanner1_complete', 'source': 'scanner1_scanning', 'dest': 'scanner1_waiting'},
# 更多转换...
]
# 状态进入动作
self.on_enter_scanner1_scanning(self.on_scanner1_scanning_start)
# 动作实现
def on_scanner1_scanning_start(self):
"""1号扫描开始时的回调"""
self.start_scanning(self.ID_MT1)
```
## 三、交付要求
请提供:
1. **状态图文件**:支持格式包括 PNG、JPG、SVG 或 PlantUML 文本
2. **状态说明文档**:
- 每个状态的含义
- 每个事件的触发条件
- 每个动作的具体功能
3. **特殊需求说明**:
- 超时处理
- 错误恢复机制
- 并发控制要求
## 四、示例状态图与代码对应
### 状态图
```
[*] → all_stopped
all_stopped → scanner1_scanning : start_scanner1
scanner1_scanning → scanner1_waiting : scanner1_complete
scanner1_waiting → scanner2_scanning : start_scanner2
scanner2_scanning → scanner2_waiting : scanner2_complete
scanner2_waiting → scanner1_scanning : start_scanner1
```
### 对应代码
```python
from transitions import Machine
class MotorManager:
def __init__(self):
# 定义状态
self.states = ['all_stopped', 'scanner1_scanning', 'scanner1_waiting', 'scanner2_scanning', 'scanner2_waiting']
# 定义转换
self.transitions = [
{'trigger': 'start_scanner1', 'source': ['all_stopped', 'scanner2_waiting'], 'dest': 'scanner1_scanning'},
{'trigger': 'scanner1_complete', 'source': 'scanner1_scanning', 'dest': 'scanner1_waiting'},
{'trigger': 'start_scanner2', 'source': ['all_stopped', 'scanner1_waiting'], 'dest': 'scanner2_scanning'},
{'trigger': 'scanner2_complete', 'source': 'scanner2_scanning', 'dest': 'scanner2_waiting'},
]
# 初始化状态机
self.machine = Machine(model=self, states=self.states, transitions=self.transitions, initial='all_stopped')
# 添加回调
self.on_enter_scanner1_scanning(self.on_scanner1_scanning_start)
self.on_enter_scanner2_scanning(self.on_scanner2_scanning_start)
def on_scanner1_scanning_start(self):
print("1号扫描器开始扫描")
def on_scanner2_scanning_start(self):
print("2号扫描器开始扫描")
```
---
请完成状态图绘制后,将文件保存到 `y:\CPY\CPY_AdminPlatform_V3.5\motor_service\` 目录下,然后告知我开始实现代码。