forked from huangxin/ailai
程序正常退出(界面关闭后(投料启动前后),实现所有线程有序退出)
This commit is contained in:
152
EMV/EMV.py
152
EMV/EMV.py
@ -15,7 +15,7 @@ class RelayController:
|
||||
update_detect_image = Signal(np.ndarray)
|
||||
log_signal = Signal(int, str)
|
||||
|
||||
def __init__(self, host='192.168.0.18', port=50000):
|
||||
def __init__(self, host="192.168.0.18", port=50000):
|
||||
# ===================== 全局线程延时参数 =====================
|
||||
self.sensor1_loop_delay = 0.2 # SENSOR1 线程轮询间隔(秒)
|
||||
self.sensor1_error_delay = 1.0 # SENSOR1 出错时延时(秒)
|
||||
@ -25,7 +25,9 @@ class RelayController:
|
||||
self.sensor2_error_delay = 0.5 # SENSOR2 出错时延时(秒)
|
||||
self.sensor2_post_action_delay = 0.2 # SENSOR2 每次循环后延时(秒)
|
||||
# ===================== 全局动作延时参数 =====================
|
||||
self.delay_conveyor = 0.5 # 传送带开/关动作延时(一半时间,我在控制程序和线程都加了一样的延时)
|
||||
self.delay_conveyor = (
|
||||
0.5 # 传送带开/关动作延时(一半时间,我在控制程序和线程都加了一样的延时)
|
||||
)
|
||||
self.delay_pusher = 0.05 # 推板开/关动作延时
|
||||
self.delay_clamp = 0.5 # 夹爪动作延时
|
||||
self.delay_after_pusher = 3.0 # 推板推出后到重启传动带时间
|
||||
@ -39,25 +41,40 @@ class RelayController:
|
||||
self.host = host
|
||||
self.port = port
|
||||
|
||||
self.CONVEYOR1 = 'conveyor1'
|
||||
self.PUSHER = 'pusher'
|
||||
self.CONVEYOR2 = 'conveyor2'
|
||||
self.CLAMP = 'clamp'
|
||||
self.PUSHER1 = 'pusher1'
|
||||
self.SENSOR1 = 'sensor1'
|
||||
self.SENSOR2 = 'sensor2'
|
||||
self.CONVEYOR1 = "conveyor1"
|
||||
self.PUSHER = "pusher"
|
||||
self.CONVEYOR2 = "conveyor2"
|
||||
self.CLAMP = "clamp"
|
||||
self.PUSHER1 = "pusher1"
|
||||
self.SENSOR1 = "sensor1"
|
||||
self.SENSOR2 = "sensor2"
|
||||
|
||||
self.valve_commands = {
|
||||
self.CONVEYOR1: {'open': '00000000000601050000FF00', 'close': '000000000006010500000000'},
|
||||
self.PUSHER: {'open': '00000000000601050001FF00', 'close': '000000000006010500010000'},
|
||||
self.CONVEYOR2: {'open': '000100000006020620000012', 'close': '000100000006020620000001'},
|
||||
self.CLAMP: {'open': '00000000000601050003FF00', 'close': '000000000006010500030000'},
|
||||
self.PUSHER1: {'open': '00000000000601050004FF00', 'close': '000000000006010500040000'}
|
||||
self.CONVEYOR1: {
|
||||
"open": "00000000000601050000FF00",
|
||||
"close": "000000000006010500000000",
|
||||
},
|
||||
self.PUSHER: {
|
||||
"open": "00000000000601050001FF00",
|
||||
"close": "000000000006010500010000",
|
||||
},
|
||||
self.CONVEYOR2: {
|
||||
"open": "000100000006020620000012",
|
||||
"close": "000100000006020620000001",
|
||||
},
|
||||
self.CLAMP: {
|
||||
"open": "00000000000601050003FF00",
|
||||
"close": "000000000006010500030000",
|
||||
},
|
||||
self.PUSHER1: {
|
||||
"open": "00000000000601050004FF00",
|
||||
"close": "000000000006010500040000",
|
||||
},
|
||||
}
|
||||
|
||||
self.read_status_command = {
|
||||
'devices': '000000000006010100000008',
|
||||
'sensors': '000000000006010200000008'
|
||||
"devices": "000000000006010100000008",
|
||||
"sensors": "000000000006010200000008",
|
||||
}
|
||||
|
||||
self.device_bit_map = {
|
||||
@ -82,8 +99,8 @@ class RelayController:
|
||||
}
|
||||
|
||||
self.sensor_name_map = {
|
||||
self.SENSOR1: '位置传感器1',
|
||||
self.SENSOR2: '位置传感器2',
|
||||
self.SENSOR1: "位置传感器1",
|
||||
self.SENSOR2: "位置传感器2",
|
||||
}
|
||||
|
||||
# ===================== 状态控制变量 =====================
|
||||
@ -91,8 +108,8 @@ class RelayController:
|
||||
self._sensor1_thread = None
|
||||
self._sensor2_thread = None
|
||||
|
||||
self.required_codes = {'0101', '0103'} # 有效状态码(传感器1)
|
||||
self.required_codes_1 = {'0102', '0103'} # 有效状态码(传感器2)
|
||||
self.required_codes = {"0101", "0103"} # 有效状态码(传感器1)
|
||||
self.required_codes_1 = {"0102", "0103"} # 有效状态码(传感器2)
|
||||
|
||||
self.sensor1_triggered = False
|
||||
self.sensor1_last_time = 0
|
||||
@ -101,25 +118,33 @@ class RelayController:
|
||||
self.motor_stopped_by_sensor2 = False
|
||||
|
||||
# ===================== 基础通信方法 =====================
|
||||
def send_command(self, command_hex, retry_count=2, source='unknown'):
|
||||
def send_command(self, command_hex, retry_count=2, source="unknown"):
|
||||
if not self._running:
|
||||
return
|
||||
|
||||
byte_data = binascii.unhexlify(command_hex)
|
||||
for attempt in range(retry_count):
|
||||
if not self._running:
|
||||
return
|
||||
|
||||
try:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
||||
sock.settimeout(10)
|
||||
sock.connect((self.host, self.port))
|
||||
sock.send(byte_data)
|
||||
response = sock.recv(1024)
|
||||
hex_response = binascii.hexlify(response).decode('utf-8')
|
||||
#if source == 'sensor':
|
||||
#print(f"[传感器响应] {hex_response}")
|
||||
#elif source == 'device':
|
||||
#print(f"[设备控制响应] {hex_response}")
|
||||
#else:
|
||||
#print(f"[通信响应] {hex_response}")
|
||||
hex_response = binascii.hexlify(response).decode("utf-8")
|
||||
# if source == 'sensor':
|
||||
# print(f"[传感器响应] {hex_response}")
|
||||
# elif source == 'device':
|
||||
# print(f"[设备控制响应] {hex_response}")
|
||||
# else:
|
||||
# print(f"[通信响应] {hex_response}")
|
||||
return response
|
||||
except Exception as e:
|
||||
print(f"通信错误 ({source}): {e}, 尝试重连... ({attempt + 1}/{retry_count})")
|
||||
print(
|
||||
f"通信错误 ({source}): {e}, 尝试重连... ({attempt + 1}/{retry_count})"
|
||||
)
|
||||
time.sleep(5)
|
||||
self.trigger_alarm()
|
||||
return None
|
||||
@ -128,30 +153,38 @@ class RelayController:
|
||||
print("警告:连续多次通信失败,请检查设备连接!")
|
||||
|
||||
# ===================== 状态读取方法 =====================
|
||||
def get_all_device_status(self, command_type='devices'):
|
||||
def get_all_device_status(self, command_type="devices"):
|
||||
command = self.read_status_command.get(command_type)
|
||||
if not command:
|
||||
print(f"未知的读取类型: {command_type}")
|
||||
return {}
|
||||
|
||||
source = 'sensor' if command_type == 'sensors' else 'device'
|
||||
source = "sensor" if command_type == "sensors" else "device"
|
||||
response = self.send_command(command, source=source)
|
||||
status_dict = {}
|
||||
|
||||
if response and len(response) >= 10:
|
||||
status_byte = response[9]
|
||||
status_bin = f"{status_byte:08b}"[::-1]
|
||||
bit_map = self.device_bit_map if command_type == 'devices' else self.sensor_bit_map
|
||||
name_map = self.device_name_map if command_type == 'devices' else self.sensor_name_map
|
||||
bit_map = (
|
||||
self.device_bit_map
|
||||
if command_type == "devices"
|
||||
else self.sensor_bit_map
|
||||
)
|
||||
name_map = (
|
||||
self.device_name_map
|
||||
if command_type == "devices"
|
||||
else self.sensor_name_map
|
||||
)
|
||||
|
||||
for key, bit_index in bit_map.items():
|
||||
status_dict[key] = status_bin[bit_index] == '1'
|
||||
status_dict[key] = status_bin[bit_index] == "1"
|
||||
else:
|
||||
print(f"[{command_type}] 读取状态失败或响应无效")
|
||||
|
||||
return status_dict
|
||||
|
||||
def get_all_sensor_responses(self, command_type='sensors'):
|
||||
def get_all_sensor_responses(self, command_type="sensors"):
|
||||
"""
|
||||
获取所有传感器的原始 Modbus 响应字符串
|
||||
示例:{'sensor1': '00000000000401020101', 'sensor2': '00000000000401020100'}
|
||||
@ -161,12 +194,12 @@ class RelayController:
|
||||
print(f"未知的读取类型: {command_type}")
|
||||
return {}
|
||||
|
||||
source = 'sensor' if command_type == 'sensors' else 'device'
|
||||
source = "sensor" if command_type == "sensors" else "device"
|
||||
response = self.send_command(command, source=source)
|
||||
responses = {}
|
||||
|
||||
if response and len(response) >= 10:
|
||||
hex_response = binascii.hexlify(response).decode('utf-8')
|
||||
hex_response = binascii.hexlify(response).decode("utf-8")
|
||||
print(f"[原始响应][{command_type}] {hex_response}")
|
||||
|
||||
# 假设传感器数据从第 9 字节开始,长度为 2 字节
|
||||
@ -192,7 +225,7 @@ class RelayController:
|
||||
def is_valid_sensor_status(self, sensor_name):
|
||||
stable_count = 0
|
||||
for _ in range(int(self.sensor_stable_duration / self.sensor1_loop_delay)):
|
||||
responses = self.get_all_sensor_responses('sensors')
|
||||
responses = self.get_all_sensor_responses("sensors")
|
||||
response = responses.get(sensor_name)
|
||||
|
||||
if not response:
|
||||
@ -211,7 +244,7 @@ class RelayController:
|
||||
def is_valid_sensor_status_1(self, sensor_name):
|
||||
stable_count = 0
|
||||
for _ in range(int(self.sensor_stable_duration / self.sensor2_loop_delay)):
|
||||
responses = self.get_all_sensor_responses('sensors')
|
||||
responses = self.get_all_sensor_responses("sensors")
|
||||
response = responses.get(sensor_name)
|
||||
|
||||
if not response:
|
||||
@ -229,49 +262,57 @@ class RelayController:
|
||||
return False
|
||||
|
||||
# ===================== 动作控制方法 =====================
|
||||
def open(self, conveyor1=False, pusher=False, conveyor2=False, clamp=False, pusher1=False):
|
||||
def open(
|
||||
self, conveyor1=False, pusher=False, conveyor2=False, clamp=False, pusher1=False
|
||||
):
|
||||
status = self.get_all_device_status()
|
||||
if conveyor1 and not status.get(self.CONVEYOR1, False):
|
||||
self.send_command(self.valve_commands[self.CONVEYOR1]['open'])
|
||||
self.send_command(self.valve_commands[self.CONVEYOR1]["open"])
|
||||
time.sleep(self.delay_conveyor)
|
||||
if pusher and not status.get(self.PUSHER, False):
|
||||
self.send_command(self.valve_commands[self.PUSHER]['open'])
|
||||
self.send_command(self.valve_commands[self.PUSHER]["open"])
|
||||
time.sleep(self.delay_pusher)
|
||||
if conveyor2 and not status.get(self.CONVEYOR2, False):
|
||||
self.send_command(self.valve_commands[self.CONVEYOR2]['open'])
|
||||
self.send_command(self.valve_commands[self.CONVEYOR2]["open"])
|
||||
time.sleep(self.delay_conveyor)
|
||||
if clamp and not status.get(self.CLAMP, False):
|
||||
self.send_command(self.valve_commands[self.CLAMP]['open'])
|
||||
self.send_command(self.valve_commands[self.CLAMP]["open"])
|
||||
time.sleep(self.delay_clamp)
|
||||
if pusher1 and not status.get(self.PUSHER1, False):
|
||||
self.send_command(self.valve_commands[self.PUSHER1]['open'])
|
||||
self.send_command(self.valve_commands[self.PUSHER1]["open"])
|
||||
time.sleep(self.delay_pusher)
|
||||
|
||||
def close(self, conveyor1=False, pusher=False, conveyor2=False, clamp=False, pusher1=False):
|
||||
def close(
|
||||
self, conveyor1=False, pusher=False, conveyor2=False, clamp=False, pusher1=False
|
||||
):
|
||||
if conveyor1:
|
||||
self.send_command(self.valve_commands[self.CONVEYOR1]['close'])
|
||||
self.send_command(self.valve_commands[self.CONVEYOR1]["close"])
|
||||
time.sleep(self.delay_conveyor)
|
||||
if pusher:
|
||||
self.send_command(self.valve_commands[self.PUSHER]['close'])
|
||||
self.send_command(self.valve_commands[self.PUSHER]["close"])
|
||||
time.sleep(self.delay_pusher)
|
||||
if conveyor2:
|
||||
self.send_command(self.valve_commands[self.CONVEYOR2]['close'])
|
||||
self.send_command(self.valve_commands[self.CONVEYOR2]["close"])
|
||||
time.sleep(self.delay_conveyor)
|
||||
if clamp:
|
||||
self.send_command(self.valve_commands[self.CLAMP]['close'])
|
||||
self.send_command(self.valve_commands[self.CLAMP]["close"])
|
||||
time.sleep(self.delay_clamp)
|
||||
if pusher1:
|
||||
self.send_command(self.valve_commands[self.PUSHER1]['close'])
|
||||
self.send_command(self.valve_commands[self.PUSHER1]["close"])
|
||||
time.sleep(self.delay_pusher)
|
||||
|
||||
# ===================== 传感器处理线程 =====================
|
||||
def handle_sensor1(self):
|
||||
print("传感器线程1启动!!!")
|
||||
while self._running:
|
||||
try:
|
||||
if self.is_valid_sensor_status(self.SENSOR1):
|
||||
current_time = time.time()
|
||||
if not self.sensor1_triggered and (
|
||||
current_time - self.sensor1_last_time) > self.sensor1_debounce_time:
|
||||
if (
|
||||
not self.sensor1_triggered
|
||||
and (current_time - self.sensor1_last_time)
|
||||
> self.sensor1_debounce_time
|
||||
):
|
||||
self.sensor1_triggered = True
|
||||
self.sensor1_last_time = current_time
|
||||
# 1.停止包装机皮带电机:关闭 conveyor1
|
||||
@ -293,7 +334,7 @@ class RelayController:
|
||||
time.sleep(1)
|
||||
# 5. 状态检查(可选)
|
||||
status = self.get_all_device_status()
|
||||
if status.get('conveyor1') and not status.get('pusher'):
|
||||
if status.get("conveyor1") and not status.get("pusher"):
|
||||
print("流程完成1:皮带运行中,推板已收回")
|
||||
else:
|
||||
print("状态异常,请检查设备")
|
||||
@ -306,6 +347,7 @@ class RelayController:
|
||||
time.sleep(self.sensor1_error_delay)
|
||||
|
||||
def handle_sensor2(self):
|
||||
print("传感器线程12启动!!!")
|
||||
while self._running:
|
||||
try:
|
||||
if self.is_valid_sensor_status_1(self.SENSOR2):
|
||||
@ -357,7 +399,7 @@ class RelayController:
|
||||
self._sensor1_thread.start()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
controller = RelayController()
|
||||
controller.start()
|
||||
try:
|
||||
|
||||
Reference in New Issue
Block a user