first commit

This commit is contained in:
2025-07-29 13:16:30 +08:00
commit dca51db4eb
145 changed files with 721268 additions and 0 deletions

77
EMV/ALL_test.py Normal file
View File

@ -0,0 +1,77 @@
from EMV import RelayController
import time
relay_controller = RelayController() # 实例化控制器
def test_device(device_name, action):
"""
测试指定设备的开/关操作,并读取传感器状态
:param device_name: str设备名conveyor1, conveyor2, pusher, clamp
:param action: str操作open, close
"""
device_map = {
'conveyor1': {
'open': lambda: relay_controller.open(conveyor1=True),
'close': lambda: relay_controller.close(conveyor1=True)
},
'conveyor2': {
'open': lambda: relay_controller.open(conveyor2=True),
'close': lambda: relay_controller.close(conveyor2=True)
},
'pusher': {
'open': lambda: relay_controller.open(pusher=True),
'close': lambda: relay_controller.close(pusher=True)
},
'pusher1': {
'open': lambda: relay_controller.open(pusher1=True),
'close': lambda: relay_controller.close(pusher1=True)
},
'clamp': {
'open': lambda: relay_controller.open(clamp=True),
'close': lambda: relay_controller.close(clamp=True)
}
}
if device_name not in device_map:
print(f"❌ 未知设备: {device_name}")
return
if action not in ['open', 'close']:
print(f"❌ 未知操作: {action}")
return
print(f"\n🧪 正在测试设备: {device_name},操作: {action}")
device_map[device_name][action]()
# 可选:等待一段时间后读取传感器状态
time.sleep(1)
print("📊 当前传感器状态:")
status = relay_controller.get_all_sensor_responses(command_type='sensors')
print(status)
# ✅ 示例调用(你可以取消注释你想测试的部分)
if __name__ == "__main__":
#test_device('conveyor1', 'open')
#test_device('conveyor1', 'close')
#已完成测试
#test_device('conveyor2', 'open')
test_device('conveyor2', 'close')
'''
test_device('conveyor2', 'close')
sensors = relay_controller.get_all_device_status('sensors')
sensor2_value = sensors.get(relay_controller.SENSOR2, False)
print(sensor2_value)
'''
#test_device('pusher', 'open')
#time.sleep(0.1)
#test_device('pusher', 'close')
#test_device('pusher1', 'open')
#time.sleep(0.1)
#test_device('pusher1', 'close')
# 已完成测试
#test_device('clamp', 'open')
#test_device('clamp', 'close')

401
EMV/EMV.py Normal file
View File

@ -0,0 +1,401 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import binascii
import time
import threading
import logging
from PySide6.QtCore import Signal, QObject
import numpy as np
class RelayController:
need_origin_signal = Signal(str)
take_no_photo_sigal = Signal()
update_detect_image = Signal(np.ndarray)
log_signal = Signal(int, str)
def __init__(self, host='192.168.0.18', port=50000):
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.valve_commands = {
self.CONVEYOR1: {'open': '00000000000601050000FF00', 'close': '000000000006010500000000'},
self.PUSHER: {'open': '00000000000601050001FF00', 'close': '000000000006010500010000'},
#self.CONVEYOR2: {'open': '00000000000601050002FF00', 'close': '000000000006010500020000'},
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'
}
self.device_bit_map = {
self.CONVEYOR1: 0,
self.PUSHER: 1,
self.CONVEYOR2: 2,
self.CLAMP: 3,
self.PUSHER1: 4,
}
self.sensor_bit_map = {
self.SENSOR1: 0,
self.SENSOR2: 1,#
}
self.device_name_map = {
self.CONVEYOR1: "传送带1",
self.PUSHER: "推板开",
self.CONVEYOR2: "传送带2",
self.CLAMP: "机械臂夹爪",
self.PUSHER1: "推板关",
}
self.sensor_name_map = {
self.SENSOR1: '位置传感器1',
self.SENSOR2: '位置传感器2',
}
# 传感器状态变量
self._running = False
self._sensor1_thread = None
self._sensor2_thread = None
# 配置项
self.required_codes = {'0101', '0103'} # 有效状态码
self.required_codes_1 = { '0102', '0103'} # 有效状态码(需要修改)
self.stable_duration = 1.0 # 稳定检测时间(秒)
self.max_attempts = 3 # 连续检测次数
self.poll_interval = 0.2 # 检测间隔
# 状态锁和防抖
self.sensor1_triggered = False
self.sensor1_last_time = 0
self.sensor1_debounce = 2.0
# 传感器2状态变量
self.sensor2_ready = True
self.motor_stopped_by_sensor2 = False
def send_command(self, command_hex, retry_count=2, source='unknown'):
byte_data = binascii.unhexlify(command_hex)
for attempt in range(retry_count):
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}")
return response
except Exception as e:
print(f"通信错误 ({source}): {e}, 尝试重连... ({attempt + 1}/{retry_count})")
time.sleep(5)
self.trigger_alarm()
return None
def trigger_alarm(self):
print("警告:连续多次通信失败,请检查设备连接!")
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'
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
for key, bit_index in bit_map.items():
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'):
"""
获取所有传感器的原始 Modbus 响应字符串
示例:{'sensor1': '00000000000401020101', 'sensor2': '00000000000401020100'}
"""
command = self.read_status_command.get(command_type)
if not command:
print(f"未知的读取类型: {command_type}")
return {}
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')
print(f"[原始响应][{command_type}] {hex_response}")
# 假设传感器数据从第 9 字节开始,长度为 2 字节
for name, bit_index in self.sensor_bit_map.items():
offset = 9 + (bit_index // 8)
bit_pos = bit_index % 8
byte = response[offset]
status = (byte >> bit_pos) & 1
responses[name] = hex_response
else:
print(f"[{command_type}] 无法获取响应数据")
return responses
def parse_status_code(self, response):
"""
从 Modbus 响应字符串中提取状态码(后两位)
示例00000000000401020101 -> '01'
"""
if isinstance(response, str) and len(response) >= 18:
return response[16:20]
return None
def is_valid_sensor_status(self, sensor_name: object) -> object:
"""
检查传感器是否在稳定时间内连续返回有效状态码01 或 03
"""
stable_count = 0
for _ in range(int(self.stable_duration / self.poll_interval)):
responses = self.get_all_sensor_responses('sensors')
response = responses.get(sensor_name)
if not response:
print(f"[警告] 无法获取 {sensor_name} 的响应,尝试重试...")
stable_count = 0
else:
status_code = self.parse_status_code(response)
if status_code in self.required_codes:
stable_count += 1
if stable_count >= self.max_attempts:
return True
else:
stable_count = 0
print(f"[警告] {sensor_name} 状态码无效: {status_code}")
time.sleep(self.poll_interval)
return False
def is_valid_sensor_status_1(self, sensor_name: object) -> object:
"""
检查传感器是否在稳定时间内连续返回有效状态码01 或 03
"""
stable_count = 0
for _ in range(int(self.stable_duration / self.poll_interval)):
responses = self.get_all_sensor_responses('sensors')
response = responses.get(sensor_name)
if not response:
print(f"[警告] 无法获取 {sensor_name} 的响应,尝试重试...")
stable_count = 0
else:
status_code = self.parse_status_code(response)
if status_code in self.required_codes_1:
stable_count += 1
if stable_count >= self.max_attempts:
return True
else:
stable_count = 0
print(f"[警告] {sensor_name} 状态码无效: {status_code}")
time.sleep(self.poll_interval)
return 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):
print("打开传送带1")
self.send_command(self.valve_commands[self.CONVEYOR1]['open'], source='device')
time.sleep(1)
if pusher and not status.get(self.PUSHER, False):
print("打开推板")
self.send_command(self.valve_commands[self.PUSHER]['open'], source='device')
time.sleep(0.05)
if conveyor2 and not status.get(self.CONVEYOR2, False):
print("打开传送带2")
self.send_command(self.valve_commands[self.CONVEYOR2]['open'], source='device')
time.sleep(1)
if clamp and not status.get(self.CLAMP, False):
print("启动机械臂抓夹")
self.send_command(self.valve_commands[self.CLAMP]['open'], source='device')
time.sleep(0.5)
if pusher1 and not status.get(self.PUSHER1, False):
print("关闭推板")
self.send_command(self.valve_commands[self.PUSHER1]['open'], source='device')
time.sleep(0.05)
def close(self, conveyor1=False, pusher=False, conveyor2=False, clamp=False, pusher1=False):
status = self.get_all_device_status()
if conveyor1 :
#if conveyor1 and status.get(self.CONVEYOR1, True):
print("关闭传送带1")
self.send_command(self.valve_commands[self.CONVEYOR1]['close'], source='device')
time.sleep(1)
if pusher :
#if pusher and status.get(self.PUSHER, True):
print("关闭推板")
self.send_command(self.valve_commands[self.PUSHER]['close'], source='device')
time.sleep(0.05)
if conveyor2 :
#if conveyor2 and status.get(self.CONVEYOR2, True):
print("关闭传送带2")
self.send_command(self.valve_commands[self.CONVEYOR2]['close'], source='device')
time.sleep(1)
if clamp :
#if clamp and status.get(self.CLAMP, True):
print("停止机械臂抓夹")
self.send_command(self.valve_commands[self.CLAMP]['close'], source='device')
time.sleep(0.5)
if pusher1 :
#if pusher and status.get(self.PUSHER1, True):
print("关闭推板_1")
self.send_command(self.valve_commands[self.PUSHER1]['close'], source='device')
time.sleep(0.05)
def handle_sensor1(self):
while self._running:
try:
# 检查传感器是否返回有效状态码01 或 03
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:
print("✅ SENSOR1 检测到有效信号,开始执行推料流程")
# 标记已触发,防止重复执行
self.sensor1_triggered = True
self.sensor1_last_time = current_time
# 1. 停止包装机皮带电机(关闭)
self.close(conveyor1=True)
time.sleep(0.5)
# 2. 推板开启
self.open(pusher=True)
time.sleep(0.1)
self.close(pusher=True)
# 2结束
time.sleep(3) # 保持 3 秒
# 3. 包装机皮带电机开启
self.open(conveyor1=True)
time.sleep(0.5)
# 4. 推板关闭
#self.close(pusher=True)
self.open(pusher1=True)
time.sleep(0.1)
self.close(pusher1=True)
time.sleep(1)
# 5. 状态检查(可选)
status = self.get_all_device_status()
if status.get('conveyor1') and not status.get('pusher'):
print("🟢流程完成1皮带运行中推板已收回")
else:
print("⚠️ 状态异常,请检查设备")
# 流程结束,重置触发标志
self.sensor1_triggered = False
# 如果传感器无效,确保触发标志可重置(可选)
time.sleep(0.2)
except Exception as e:
print(f"SENSOR1 处理错误: {e}")
self.sensor1_triggered = False
time.sleep(1)
#传感器2检测到料包 → 立即停止 conveyor2」这个逻辑 放在传感器线程中处理
def handle_sensor2(self):
while self._running:
try:
# 检测传感器2状态
#self.sensor2_ready = None
if self.is_valid_sensor_status_1(self.SENSOR2):
print("✅ SENSOR2 检测到有效信号,开始执行关闭滚筒电机流程")
if not self.sensor2_ready:
#self.log_signal.emit(logging.INFO, "🟢 传感器2检测到料包到位立即停止 conveyor2")
# ✅ 立即停止电机(不管机器人是否在抓取)
self.close(conveyor2=True)
print("执行关闭")
self.motor_stopped_by_sensor2 = True # 标记为传感器2触发停止
self.sensor2_ready = True
else:
if self.sensor2_ready and self.motor_stopped_by_sensor2:
#self.log_signal.emit(logging.INFO, "🟡 传感器2未检测到料包准备重新启动 conveyor2")
# ✅ 重新启动 conveyor2可选
self.open(conveyor2=True)
self.motor_stopped_by_sensor2 = False
self.sensor2_ready = False
time.sleep(0.5)
except Exception as e:
self.log_signal.emit(logging.ERROR, f"🔴 SENSOR2 处理错误: {e}")
time.sleep(1)
def start(self):
if self._running:
print("线程已经在运行")
return
print("启动传感器线程")
self._running = True
self._sensor1_thread = threading.Thread(target=self.handle_sensor1, daemon=True)
self._sensor2_thread = threading.Thread(target=self.handle_sensor2, daemon=True)
self._sensor1_thread.start()
self._sensor2_thread.start()
def stop(self):
if not self._running:
print("线程未在运行")
return
print("停止传感器线程")
self._running = False
if self._sensor1_thread:
self._sensor1_thread.join()
if self._sensor2_thread:
self._sensor2_thread.join()
print("传感器线程已终止。")
def start_sensor1_only(self):
if self._running:
print("传感器线程已经在运行")
return
print("启动传感器1监听线程...")
self._running = True
self._sensor1_thread = threading.Thread(target=self.handle_sensor1, daemon=True)
self._sensor1_thread.start()
if __name__ == '__main__':
controller = RelayController()
controller.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
controller.stop()

274
EMV/EMV_reneer.py Normal file
View File

@ -0,0 +1,274 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import binascii
import time
import threading
class RelayController:
def __init__(self, host='192.168.0.18', port=50000):
self.host = host
self.port = port
# 控件映射
self.CONVEYOR1 = 'conveyor1'
self.PUSHER = 'pusher'
self.CONVEYOR2 = 'conveyor2'
self.CLAMP = 'clamp'
self.SENSOR1 = 'sensor1'
self.SENSOR2 = 'sensor2'
self.valve_commands = {
self.CONVEYOR1: {'open': '00000000000601050000FF00', 'close': '000000000006010500000000'},
self.PUSHER: {'open': '00000000000601050001FF00', 'close': '000000000006010500010000'},
self.CONVEYOR2: {'open': '00000000000601050002FF00', 'close': '000000000006010500020000'},
self.CLAMP: {'open': '00000000000601050003FF00', 'close': '000000000006010500030000'}
}
self.read_status_command = {
'devices': '000000000006010100000008',
'sensors': '000000000006010200000008'
}
self.device_bit_map = {
self.CONVEYOR1: 0,
self.PUSHER: 1,
self.CONVEYOR2: 2,
self.CLAMP: 3,
}
self.sensor_bit_map = {
self.SENSOR1: 0,
self.SENSOR2: 1,
}
self.device_name_map = {
self.CONVEYOR1: "传送带1",
self.PUSHER: "推板",
self.CONVEYOR2: "传送带2",
self.CLAMP: "机械臂"
}
self.sensor_name_map = {
self.SENSOR1: '位置传感器1',
self.SENSOR2: '位置传感器2',
}
self._running = False
self._sensor1_thread = None
self._sensor2_thread = None
def send_command_old(self, command_hex):
byte_data = binascii.unhexlify(command_hex)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
try:
sock.connect((self.host, self.port))
sock.send(byte_data)
response = sock.recv(1024)
print(f"收到响应: {binascii.hexlify(response)}")
return response
except Exception as e:
print(f"通信错误: {e}")
return None
def start_sensor1_only(self):
if self._running:
print("线程已经在运行")
return
print("启动传感器1监听线程")
self._running = True
self._sensor1_thread = threading.Thread(target=self.handle_sensor1, daemon=True)
self._sensor1_thread.start()
def send_command(self, command_hex, retry_count=5, source='unknown'):
byte_data = binascii.unhexlify(command_hex)
for attempt in range(retry_count):
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')
# 根据 source 区分响应来源
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})")
if attempt == retry_count - 1:
self.trigger_alarm()
time.sleep(5)
return None
def trigger_alarm(self):
"""当通信错误超过最大重试次数时触发报警"""
print("警告:连续多次通信失败,请检查设备连接!")
# 这里可以添加更多的报警措施,如发送邮件、短信或声音警报等
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'
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
for key, bit_index in bit_map.items():
status_dict[key] = status_bin[bit_index] == '1'
else:
print(f"[{command_type}] 读取状态失败或响应无效")
return status_dict
def get_device_status_old(self, name, command_type='devices'):
return self.get_all_device_status(command_type).get(name, None)
def get_device_status(self, name, command_type='devices', stable_duration=1.0, max_attempts=3):
"""
获取指定设备/传感器的状态,只有在连续稳定检测到信号后才返回 True。
参数:
name (str): 设备/传感器名称,如 SENSOR1
command_type (str): 类型,'devices''sensors'
stable_duration (float): 信号需要稳定的持续时间(秒)
max_attempts (int): 最大尝试次数(用于稳定性判断)
返回:
bool or None: 稳定检测到信号返回 True否则返回 False 或 None失败
"""
stable_count = 0
interval = 0.2 # 每隔多久检查一次
for _ in range(int(stable_duration / interval)):
statuses = self.get_all_device_status(command_type)
status = statuses.get(name)
if status is True:
stable_count += 1
if stable_count >= max_attempts:
return True
elif status is False:
return False
else:
# None 表示读取失败
print(f"[警告] 读取 {name} 状态失败,尝试重试...")
stable_count = 0
time.sleep(interval)
return False # 默认返回 False避免误触发
def open(self, conveyor1=False, pusher=False, conveyor2=False, clamp=False):
status = self.get_all_device_status()
if conveyor1 and not status.get(self.CONVEYOR1, False):
print("打开传送带1")
self.send_command(self.valve_commands[self.CONVEYOR1]['open'], source='device')
time.sleep(1)
if pusher and not status.get(self.PUSHER, False):
print("打开推板")
self.send_command(self.valve_commands[self.PUSHER]['open'], source='device')
time.sleep(0.05)
if conveyor2 and not status.get(self.CONVEYOR2, False):
print("打开传送带2")
self.send_command(self.valve_commands[self.CONVEYOR2]['open'], source='device')
time.sleep(1)
if clamp and not status.get(self.CLAMP, False):
print("启动机械臂抓夹")
self.send_command(self.valve_commands[self.CLAMP]['open'], source='device')
time.sleep(0.5)
def close(self, conveyor1=False, pusher=False, conveyor2=False, clamp=False):
status = self.get_all_device_status()
if conveyor1 and status.get(self.CONVEYOR1, True):
print("关闭传送带1")
self.send_command(self.valve_commands[self.CONVEYOR1]['close'], source='device')
time.sleep(1)
if pusher and status.get(self.PUSHER, True):
print("关闭推板")
self.send_command(self.valve_commands[self.PUSHER]['close'], source='device')
time.sleep(0.05)
if conveyor2 and status.get(self.CONVEYOR2, True):
print("关闭传送带2")
self.send_command(self.valve_commands[self.CONVEYOR2]['close'], source='device')
time.sleep(1)
if clamp and status.get(self.CLAMP, True):
print("停止机械臂抓夹")
self.send_command(self.valve_commands[self.CLAMP]['close'], source='device')
time.sleep(0.5)
def handle_sensor1(self):
while self._running:
try:
if self.get_device_status(self.SENSOR1, 'sensors'):
print("SENSOR1 检测到信号,执行流程")
self.close(conveyor1=True)
time.sleep(2)
self.open(pusher=True)
time.sleep(5)
self.close(pusher=True)
time.sleep(2)
self.open(conveyor1=True)
time.sleep(0.5)
except Exception as e:
print(f"SENSOR1 处理错误: {e}")
def handle_sensor2(self):
while self._running:
try:
if self.get_device_status(self.SENSOR2, 'sensors'):
print("SENSOR2 检测到信号,执行流程")
self.close(conveyor2=True)
time.sleep(2)
self.open(clamp=True)
time.sleep(2)
self.open(conveyor2=True)
time.sleep(0.5)
except Exception as e:
print(f"SENSOR2 处理错误: {e}")
def start(self):
if self._running:
print("线程已经在运行")
return
print("启动传感器线程")
self._running = True
self._sensor1_thread = threading.Thread(target=self.handle_sensor1, daemon=True)
self._sensor2_thread = threading.Thread(target=self.handle_sensor2, daemon=True)
self._sensor1_thread.start()
self._sensor2_thread.start()
def stop(self):
if not self._running:
print("线程未在运行")
return
print("停止传感器线程")
self._running = False # 设置标志位为 False
if self._sensor1_thread is not None:
self._sensor1_thread.join() # 等待线程结束
if self._sensor2_thread is not None:
self._sensor2_thread.join()
print("传感器线程已终止。")

28
EMV/EMV_test_sensor.py Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
from EMV import RelayController # 请根据你的实际模块名修改
def run_real_sensor_monitor():
# 创建控制器实例
controller = RelayController()
try:
print("启动传感器1监听线程...")
controller.start_sensor1_only() # 只启动传感器1的监听线程
print("开始监听真实传感器1信号按 Ctrl+C 停止...")
# 主线程可以继续做其他事情,或者只是等待
while True:
time.sleep(1) # 保持主线程运行
except KeyboardInterrupt:
print("\n检测到中断信号,正在停止传感器监听...")
finally:
controller.stop()
print("程序已安全退出。")
if __name__ == '__main__':
run_real_sensor_monitor()

Binary file not shown.

20
EMV/code_statue.py Normal file
View File

@ -0,0 +1,20 @@
def parse_coil_status_response(response_hex):
"""
解析 Modbus 功能码 0x01 的响应(读线圈状态)
:param response_hex: 十六进制字符串,如 '00000000000401010101'
:return: dict表示每个 bit 的状态True/False
"""
if len(response_hex) < 18:
return {"error": "响应数据过短"}
data_part = response_hex[14:18] # 提取 0101 部分
status_byte = int(data_part[2:4], 16) # 取出 01 → 十进制 1
# 每个 bit 对应一个设备bit0 是最低位
status = {f"device_{i}": (status_byte >> i) & 0x01 == 1 for i in range(8)}
return status
# 示例使用
response = "00000000000401010103"
status = parse_coil_status_response(response)
print("设备状态:", status)

2
EMV/test.py Normal file
View File

@ -0,0 +1,2 @@

88
EMV/test_EMV.py Normal file
View File

@ -0,0 +1,88 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import logging
from threading import Thread
from unittest.mock import patch
# 假设你的 RelayController 类在名为 EMV 的模块中
from EMV import RelayController # 替换为你的模块名
# 设置日志格式
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def simulate_sensor(controller, sensor_name, active=True, duration=10):
"""
模拟指定传感器在一段时间内处于激活状态。
:param controller: RelayController 实例
:param sensor_name: 要模拟的传感器名(如 controller.SENSOR2
:param active: 是否激活传感器信号
:param duration: 模拟运行时间(秒)
"""
logging.info(f"🧪 开始模拟传感器:{controller.sensor_name_map.get(sensor_name, sensor_name)}")
original_method = controller.get_all_device_status
def mock_get_all_device_status(command_type='devices'):
if command_type == 'sensors':
all_status = original_method(command_type)
all_status[sensor_name] = active
return all_status
return original_method(command_type)
# 确定目标函数
target_func = None
if sensor_name == controller.SENSOR1:
target_func = controller.handle_sensor1
elif sensor_name == controller.SENSOR2:
target_func = controller.handle_sensor2
else:
raise ValueError("不支持的传感器名称")
# 设置 _running 为 True确保线程能进入循环
controller._running = True
# 启动线程
sensor_thread = Thread(target=target_func, daemon=True)
sensor_thread.start()
logging.info(f"{controller.sensor_name_map[sensor_name]} 监听线程已启动")
try:
# Patch get_all_device_status 方法
with patch.object(controller, 'get_all_device_status', mock_get_all_device_status):
logging.info(f"🟢 模拟 {controller.sensor_name_map[sensor_name]} 有信号输入,持续 {duration}")
time.sleep(duration)
except Exception as e:
logging.error(f"🔴 模拟过程中发生错误: {e}")
finally:
# 停止控制器
controller._running = False
logging.info("🛑 停止控制器主循环")
# 等待线程退出
sensor_thread.join(timeout=2)
if sensor_thread.is_alive():
logging.warning("⚠️ 传感器线程未能及时退出")
else:
logging.info("✅ 传感器线程已安全退出")
if __name__ == '__main__':
# 创建控制器实例
relay_controller = RelayController()
# 打印当前配置的传感器名称映射(方便调试)
logging.info("🔧 当前传感器配置:")
for key, val in relay_controller.sensor_name_map.items():
logging.info(f" {key}: {val}")
try:
# 模拟 SENSOR2 有信号输入,运行 10 秒
logging.info("🧪 开始模拟传感器2")#修改这里
simulate_sensor(relay_controller, relay_controller.SENSOR1, active=True, duration=10)#
# 可选:模拟 SENSOR1
# logging.info("🧪 开始模拟传感器1")
# simulate_sensor(relay_controller, relay_controller.SENSOR1, active=True, duration=10)
except KeyboardInterrupt:
logging.info("🛑 用户中断模拟")
finally:
logging.info("🏁 模拟结束")