Compare commits
6
Commits
5948dbaaf5
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8d0f57763a | ||
|
|
bb9e546ccf | ||
|
|
3f8a6bd509 | ||
|
|
17233eb947 | ||
|
|
f3526e46f1 | ||
|
|
e7cbafa6eb |
@@ -39,4 +39,4 @@ try:
|
|||||||
with open(CONFIG_FILE, "r") as f:
|
with open(CONFIG_FILE, "r") as f:
|
||||||
config = json.load(f)
|
config = json.load(f)
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
config = {}
|
config = {}
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import json
|
||||||
|
|
||||||
|
# MQTT配置
|
||||||
|
BROKER = "127.0.0.1"
|
||||||
|
MQTT_PORT = 1883
|
||||||
|
USER = "test"
|
||||||
|
PWD = "test"
|
||||||
|
|
||||||
|
# Modbus配置
|
||||||
|
TIMEOUT = 0.5
|
||||||
|
BYTESIZE = 8
|
||||||
|
PARITY = 'N'
|
||||||
|
STOPBITS = 1
|
||||||
|
|
||||||
|
# 读取间隔(秒)
|
||||||
|
READ_INTERVAL = 0.5
|
||||||
|
|
||||||
|
# MQTT主题
|
||||||
|
DEVICE_STATUS_TOPIC = "device/status"
|
||||||
|
DEVICE_CONTROL_TOPIC = "device/control"
|
||||||
|
DEVICE_HVS_CONTROL_TOPIC = "device/hvs/control"
|
||||||
|
DEVICE_API_TOPIC = "api/devices/hvs/response"
|
||||||
|
SERVICE_STATUS_TOPIC = "service/status"
|
||||||
|
|
||||||
|
# 寄存器配置 - 根据实际设备修改
|
||||||
|
INPUT_REGISTERS = {
|
||||||
|
"start_address": 0,
|
||||||
|
"count": 2
|
||||||
|
}
|
||||||
|
|
||||||
|
COIL_REGISTERS = {
|
||||||
|
"start_address": 0,
|
||||||
|
"count": 4
|
||||||
|
}
|
||||||
|
|
||||||
|
CONFIG_FILE = "/home/admin/.config/cpy/hvs.json"
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(CONFIG_FILE, "r") as f:
|
||||||
|
config = json.load(f)
|
||||||
|
except FileNotFoundError:
|
||||||
|
config = {}
|
||||||
@@ -0,0 +1,301 @@
|
|||||||
|
import time
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from datetime import datetime
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
from modbus_client import ModbusClient
|
||||||
|
from mqtt_client import mqtt_client
|
||||||
|
from config import *
|
||||||
|
from tcp_io_module import TcpIoModule
|
||||||
|
import threading
|
||||||
|
import socket
|
||||||
|
|
||||||
|
logging.basicConfig(level=logging.INFO)
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
UDP_PORT = 62000
|
||||||
|
|
||||||
|
class HvService:
|
||||||
|
def __init__(self):
|
||||||
|
# 记录服务启动时间
|
||||||
|
self.start_time = time.time()
|
||||||
|
|
||||||
|
# 创建线程池用于异步发布消息
|
||||||
|
self.executor = ThreadPoolExecutor(max_workers=5)
|
||||||
|
|
||||||
|
# 初始化Modbus客户端
|
||||||
|
self.modbus_client = ModbusClient()
|
||||||
|
|
||||||
|
# 初始化MQTT客户端
|
||||||
|
self.mqtt_client = mqtt_client
|
||||||
|
|
||||||
|
# 设备列表
|
||||||
|
self.hvs_devices = []
|
||||||
|
|
||||||
|
# 上次发布服务状态的时间
|
||||||
|
self.last_service_status_time = 0
|
||||||
|
|
||||||
|
self.filament_info = [None, None]
|
||||||
|
self.xray_on = [False, False]
|
||||||
|
self.last_hvs_update_time = 0
|
||||||
|
|
||||||
|
self.exit_flag = False
|
||||||
|
self.loop_thread = None
|
||||||
|
|
||||||
|
# UDP socket,监听62000端口
|
||||||
|
self.udp_socket = None
|
||||||
|
self.udp_thread = None
|
||||||
|
|
||||||
|
def handle_hvs_control_message(self, topic, payload):
|
||||||
|
"""异步处理设备控制消息"""
|
||||||
|
if topic == DEVICE_HVS_CONTROL_TOPIC:
|
||||||
|
print(f"handle_hvs_control_message: {topic, payload}")
|
||||||
|
self.executor.submit(self._process_hvs_control_message, payload)
|
||||||
|
elif topic == DEVICE_CONTROL_TOPIC:
|
||||||
|
dev_code = payload.get("device_code")
|
||||||
|
if "HVS" in dev_code :
|
||||||
|
print(f"handle_hvs_control_message: {topic, payload}")
|
||||||
|
dev_id = int(dev_code.split('#')[0])
|
||||||
|
command = payload.get("command")
|
||||||
|
if command == "set_status":
|
||||||
|
value = 1 if payload.get('status') else 0
|
||||||
|
newpayload = {
|
||||||
|
"command" : 'hv_switch',
|
||||||
|
'device_id' : dev_id,
|
||||||
|
'device_code' : dev_code,
|
||||||
|
'value' : value
|
||||||
|
}
|
||||||
|
self.executor.submit(self._process_hvs_control_message, newpayload)
|
||||||
|
|
||||||
|
def _process_hvs_control_message(self, payload):
|
||||||
|
"""处理设备控制消息"""
|
||||||
|
try:
|
||||||
|
logger.info(f"接收到控制消息: {payload}")
|
||||||
|
command = payload.get("command")
|
||||||
|
value = payload.get("value")
|
||||||
|
device_code = payload.get("device_code")
|
||||||
|
slave_id = 1 # payload.get("device_id")
|
||||||
|
if not device_code:
|
||||||
|
logger.error("控制消息缺少device_code")
|
||||||
|
return
|
||||||
|
|
||||||
|
# 使用设备管理器控制设备
|
||||||
|
if command == "hv_switch":
|
||||||
|
if value == 1:
|
||||||
|
self.modbus_client.write_coil(slave_id, 0x00, True)
|
||||||
|
self.modbus_client.write_coil(slave_id, 0x01, True)
|
||||||
|
self.modbus_client.write_holding_register(slave_id, 0x00, 6000)
|
||||||
|
else:
|
||||||
|
self.modbus_client.write_coil(slave_id, 0x01, False)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"处理控制消息失败: {e}")
|
||||||
|
|
||||||
|
def start(self):
|
||||||
|
# 创建线程
|
||||||
|
self.loop_thread = threading.Thread(target=self.loop)
|
||||||
|
self.loop_thread.daemon = True
|
||||||
|
self.loop_thread.start()
|
||||||
|
|
||||||
|
# 启动UDP监听线程
|
||||||
|
self.udp_thread = threading.Thread(target=self._udp_listen)
|
||||||
|
self.udp_thread.daemon = True
|
||||||
|
self.udp_thread.start()
|
||||||
|
|
||||||
|
def stop(self):
|
||||||
|
if not self.loop_thread:
|
||||||
|
return
|
||||||
|
"""停止服务"""
|
||||||
|
self.exit_flag = True
|
||||||
|
self.loop_thread.join()
|
||||||
|
if self.udp_thread:
|
||||||
|
self.udp_thread.join()
|
||||||
|
self.executor.shutdown(wait=True)
|
||||||
|
|
||||||
|
def _udp_listen(self):
|
||||||
|
"""UDP监听线程,监听62000端口"""
|
||||||
|
self.udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||||
|
self.udp_socket.bind(("0.0.0.0", UDP_PORT))
|
||||||
|
self.udp_socket.settimeout(1.0)
|
||||||
|
logger.info(f"UDP监听已启动,端口: {UDP_PORT}")
|
||||||
|
while not self.exit_flag:
|
||||||
|
try:
|
||||||
|
data, addr = self.udp_socket.recvfrom(4096)
|
||||||
|
self.handle_udp_message(data, addr)
|
||||||
|
except socket.timeout:
|
||||||
|
continue
|
||||||
|
except OSError as e:
|
||||||
|
if not self.exit_flag:
|
||||||
|
logger.error(f"UDP接收数据失败: {e}")
|
||||||
|
self.udp_socket.close()
|
||||||
|
|
||||||
|
def handle_udp_message(self, data, addr):
|
||||||
|
"""处理UDP消息(留空,由外部实现)"""
|
||||||
|
try:
|
||||||
|
info = json.loads(data.decode())
|
||||||
|
#logger.info(f"收到UDP消息: {info}")
|
||||||
|
if 'id' in info:
|
||||||
|
id = int(info['id'][0])
|
||||||
|
self.filament_info[id - 1] = info
|
||||||
|
if 'work_state' in info:
|
||||||
|
self.xray_on[id - 1] = info['work_state'] == 2
|
||||||
|
self.last_hvs_update_time = time.time()
|
||||||
|
if "osu" in info:
|
||||||
|
osu = info['osu']
|
||||||
|
self.publish_osu_info(f"{id}#OSU", osu['temp'], osu['level'])
|
||||||
|
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
logger.error("UDP消息不是JSON格式")
|
||||||
|
|
||||||
|
def loop(self):
|
||||||
|
"""启动服务"""
|
||||||
|
try:
|
||||||
|
# 连接Modbus
|
||||||
|
if not self.modbus_client.connect():
|
||||||
|
logger.error("Modbus连接失败,程序退出")
|
||||||
|
return
|
||||||
|
print("Modbus连接成功")
|
||||||
|
|
||||||
|
# 订阅MQTT主题
|
||||||
|
self.mqtt_client.subscribe(DEVICE_CONTROL_TOPIC, self.handle_hvs_control_message)
|
||||||
|
self.mqtt_client.subscribe(DEVICE_HVS_CONTROL_TOPIC, self.handle_hvs_control_message)
|
||||||
|
|
||||||
|
while not self.mqtt_client.is_connected:
|
||||||
|
time.sleep(1)
|
||||||
|
logger.info("waiting for mqtt conn...")
|
||||||
|
|
||||||
|
logger.info("Modbus和MQTT连接成功,开始定时读取和发布数据...")
|
||||||
|
|
||||||
|
self.hvs_devices = config.get("devices", [])
|
||||||
|
|
||||||
|
if not self.hvs_devices or len(self.hvs_devices) == 0:
|
||||||
|
logger.error("未找到HVS设备,程序退出")
|
||||||
|
return
|
||||||
|
|
||||||
|
logger.info(f"找到 {len(self.hvs_devices)} 个HVS设备")
|
||||||
|
|
||||||
|
logger.info(f"hvs_devices: {json.dumps(self.hvs_devices, ensure_ascii=False)}")
|
||||||
|
|
||||||
|
# 主循环
|
||||||
|
while self.exit_flag == False:
|
||||||
|
# 计算当前时间
|
||||||
|
current_time = time.time()
|
||||||
|
|
||||||
|
# 定期发布服务状态 (每10秒)
|
||||||
|
if current_time - self.last_service_status_time >= 3:
|
||||||
|
self._publish_service_status(current_time)
|
||||||
|
# continue
|
||||||
|
# 读取并发布所有HVS设备数据
|
||||||
|
self.read_and_publish_devices_data()
|
||||||
|
|
||||||
|
# 等待指定间隔
|
||||||
|
time.sleep(READ_INTERVAL)
|
||||||
|
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
logger.info("程序收到中断信号,正在退出...")
|
||||||
|
finally:
|
||||||
|
# 清理资源
|
||||||
|
self.modbus_client.disconnect()
|
||||||
|
logger.info("程序已退出")
|
||||||
|
|
||||||
|
def publish_osu_info(self, dev_code, temp, level):
|
||||||
|
"""发布OSU信息"""
|
||||||
|
data = {
|
||||||
|
"device_id": None,
|
||||||
|
"device_code": dev_code,
|
||||||
|
"timestamp": datetime.now().isoformat(),
|
||||||
|
"status": {
|
||||||
|
"online": True,
|
||||||
|
"oil_temp": temp / 10.0,
|
||||||
|
"oil_level": level,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.mqtt_client.publish(DEVICE_STATUS_TOPIC, data)
|
||||||
|
|
||||||
|
def _publish_service_status(self, current_time):
|
||||||
|
"""发布服务状态"""
|
||||||
|
# 计算运行时间
|
||||||
|
running_time = current_time - self.start_time
|
||||||
|
|
||||||
|
# 准备服务状态消息
|
||||||
|
service_message = {
|
||||||
|
"service_name": "modbus_service",
|
||||||
|
"status": {
|
||||||
|
"available": True,
|
||||||
|
"running_time": running_time
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# 发布消息
|
||||||
|
self.mqtt_client.publish(SERVICE_STATUS_TOPIC, service_message)
|
||||||
|
logger.debug(f"成功发布服务状态到 {SERVICE_STATUS_TOPIC}: {service_message}")
|
||||||
|
self.last_service_status_time = current_time
|
||||||
|
|
||||||
|
def read_and_publish_devices_data(self):
|
||||||
|
"""读取并发布所有设备数据"""
|
||||||
|
# 确保Modbus连接正常
|
||||||
|
if not self.modbus_client._ensure_connection():
|
||||||
|
logger.error(f"无法连接到Modbus设备,跳过读取设备 {hvs_device.get('code')}")
|
||||||
|
return
|
||||||
|
|
||||||
|
for hvs_device in self.hvs_devices:
|
||||||
|
try:
|
||||||
|
slave_id = int(hvs_device.get('address'))
|
||||||
|
logger.info(f"开始读取设备 {hvs_device.get('code')} (从站ID: {slave_id}) 数据")
|
||||||
|
|
||||||
|
|
||||||
|
# 读取输入寄存器
|
||||||
|
input_regs = self.modbus_client.read_input_registers(
|
||||||
|
slave_id=1,
|
||||||
|
address=INPUT_REGISTERS["start_address"],
|
||||||
|
count=INPUT_REGISTERS["count"]
|
||||||
|
)
|
||||||
|
print("------------------input_regs:", input_regs)
|
||||||
|
if input_regs is None:
|
||||||
|
hvs_device["error_count"] = hvs_device.get("error_count", 10) + 1
|
||||||
|
else:
|
||||||
|
hvs_device["error_count"] = 0
|
||||||
|
|
||||||
|
# 短暂延迟,避免总线冲突
|
||||||
|
time.sleep(0.1)
|
||||||
|
|
||||||
|
# 读取线圈
|
||||||
|
discrete = self.modbus_client.read_discrete(
|
||||||
|
slave_id=1,
|
||||||
|
address=COIL_REGISTERS["start_address"],
|
||||||
|
count=COIL_REGISTERS["count"]
|
||||||
|
)
|
||||||
|
print("discrete:", discrete)
|
||||||
|
if discrete is None:
|
||||||
|
hvs_device["error_count"] = hvs_device.get("error_count", 10) + 1
|
||||||
|
else:
|
||||||
|
hvs_device["error_count"] = 0
|
||||||
|
|
||||||
|
# 设备间添加延迟,避免总线冲突
|
||||||
|
time.sleep(0.1)
|
||||||
|
|
||||||
|
# 准备发布的数据
|
||||||
|
|
||||||
|
data = {
|
||||||
|
"device_id": hvs_device.get('id'),
|
||||||
|
"device_code": hvs_device.get('code'),
|
||||||
|
"timestamp": datetime.now().isoformat(),
|
||||||
|
"status": {
|
||||||
|
"online": hvs_device.get("error_count", 10) < 5,
|
||||||
|
"voltage": input_regs[0] / 100.0 if input_regs and len(input_regs) > 0 else None,
|
||||||
|
"current": self.filament_info[slave_id-1]['xray_current'] / 1000.0 if self.filament_info[slave_id-1] is not None else None,
|
||||||
|
"current_filament": self.filament_info[slave_id-1]['filament_current'] / 1000.0 if self.filament_info[slave_id-1] is not None else None,
|
||||||
|
"internal_temperature": self.filament_info[slave_id-1]['temp'] / 10.0 if self.filament_info[slave_id-1] is not None else None,
|
||||||
|
"fault_status": discrete[3] if discrete and len(discrete) > 3 else None,
|
||||||
|
"switch_status": discrete[1] if discrete and len(discrete) > 3 else None,
|
||||||
|
"xray_status": self.xray_on[slave_id-1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
# 发布数据
|
||||||
|
self.mqtt_client.publish(DEVICE_STATUS_TOPIC, data)
|
||||||
|
if hvs_device.get("error_count", 10) > 5:
|
||||||
|
logger.error(f"设备 {hvs_device.get('code')} 数据发布失败,错误次数超过5次")
|
||||||
|
else:
|
||||||
|
logger.info(f"成功发布设备数据: {data}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"处理设备 {hvs_device.get('code')} 数据失败: {e}")
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Hvs Service
|
||||||
|
After=emqx.service
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=root
|
||||||
|
Group=root
|
||||||
|
WorkingDirectory=/home/admin/CPY/CPY_AdminPlatform_V3.5/hvs_service
|
||||||
|
ExecStart=/home/admin/CPY/venv/bin/python /home/admin/CPY/CPY_AdminPlatform_V3.5/hvs_service/main.py
|
||||||
|
Restart=always
|
||||||
|
RestartSec=10s
|
||||||
|
StartLimitBurst=5
|
||||||
|
Environment=PYTHONUNBUFFERED=1
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import time
|
||||||
|
import os
|
||||||
|
|
||||||
|
from config import *
|
||||||
|
from tcp_io_module import TcpIoModule
|
||||||
|
from hvs import HvService
|
||||||
|
from mqtt_client import mqtt_client
|
||||||
|
|
||||||
|
# pinctrl set 26 op pn dl
|
||||||
|
|
||||||
|
def main():
|
||||||
|
#通过pinctrl打开电源
|
||||||
|
os.system("pinctrl set 26 op pn dl")
|
||||||
|
|
||||||
|
io_module = TcpIoModule(host='192.168.8.211', port=502)
|
||||||
|
io_module.start()
|
||||||
|
|
||||||
|
hv_service = HvService()
|
||||||
|
hv_service.start()
|
||||||
|
|
||||||
|
light_state = False
|
||||||
|
light_new_state = False
|
||||||
|
|
||||||
|
light_state_update_time = 0.0
|
||||||
|
xray_off_time = 0.0
|
||||||
|
last_valve_time = time.time()
|
||||||
|
|
||||||
|
if 'valve' in config:
|
||||||
|
valve_off_time = config['valve'][0]
|
||||||
|
valve_on_time = config['valve'][1]
|
||||||
|
else:
|
||||||
|
valve_off_time = 60.0
|
||||||
|
valve_on_time = 1.0
|
||||||
|
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
if time.time() - hv_service.last_hvs_update_time > 5.0:
|
||||||
|
hv_service.xray_on = [False, False]
|
||||||
|
if hv_service.xray_on[0] or hv_service.xray_on[1]:
|
||||||
|
light_new_state = True
|
||||||
|
else:
|
||||||
|
if light_new_state == True:
|
||||||
|
xray_off_time = time.time()
|
||||||
|
light_new_state = False
|
||||||
|
|
||||||
|
if light_state != light_new_state and time.time() - light_state_update_time > 2 and time.time() - xray_off_time > 2:
|
||||||
|
# if light_new_state == False:
|
||||||
|
# if time.time() - xray_off_time > 12.0:
|
||||||
|
# light_state = light_new_state
|
||||||
|
# else:
|
||||||
|
# light_state = light_new_state
|
||||||
|
light_state = light_new_state
|
||||||
|
io_module.control_light(8, light_state)
|
||||||
|
mqtt_client.control_xray_light(light_state)
|
||||||
|
light_state_update_time = time.time()
|
||||||
|
|
||||||
|
time.sleep(0.1)
|
||||||
|
|
||||||
|
if time.time() - last_valve_time > valve_off_time:
|
||||||
|
io_module.control_valve(11, True)
|
||||||
|
time.sleep(valve_on_time)
|
||||||
|
io_module.control_valve(11, False)
|
||||||
|
last_valve_time = time.time()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print("程序收到中断信号,正在退出...")
|
||||||
|
io_module.control_valve(11, False)
|
||||||
|
io_module.stop()
|
||||||
|
hv_service.stop()
|
||||||
|
mqtt_client.stop()
|
||||||
|
break
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
|
|
||||||
@@ -0,0 +1,326 @@
|
|||||||
|
import logging
|
||||||
|
import threading
|
||||||
|
from pymodbus.client import ModbusSerialClient
|
||||||
|
from pymodbus.exceptions import ModbusException, ConnectionException
|
||||||
|
import time
|
||||||
|
from config import *
|
||||||
|
|
||||||
|
logging.basicConfig(level=logging.INFO)
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
RETRIES = 2
|
||||||
|
RECONNECT_INTERVAL = 0.1 # 优化重连间隔时间(秒)
|
||||||
|
|
||||||
|
class ModbusClient:
|
||||||
|
def __init__(self):
|
||||||
|
self.client = None
|
||||||
|
#使用普通锁
|
||||||
|
self.serial_lock = threading.Lock()
|
||||||
|
|
||||||
|
try:
|
||||||
|
port = config.get("interface", {}).get("port", "/dev/ttyModbus")
|
||||||
|
if port:
|
||||||
|
self.port = port
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
try:
|
||||||
|
baudrate = config.get("interface", {}).get("baudrate", 115200)
|
||||||
|
if baudrate:
|
||||||
|
self.baudrate = baudrate
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def acquire_lock(self):
|
||||||
|
self.serial_lock.acquire()
|
||||||
|
|
||||||
|
def release_lock(self):
|
||||||
|
self.serial_lock.release()
|
||||||
|
|
||||||
|
def connect(self):
|
||||||
|
"""建立Modbus RTU连接"""
|
||||||
|
try:
|
||||||
|
# 连接操作也需要写锁保护
|
||||||
|
self.acquire_lock()
|
||||||
|
if self.client:
|
||||||
|
try:
|
||||||
|
self.client.close()
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
self.client = None
|
||||||
|
try:
|
||||||
|
self.client = ModbusSerialClient(
|
||||||
|
port=self.port,
|
||||||
|
baudrate=self.baudrate,
|
||||||
|
bytesize=BYTESIZE,
|
||||||
|
parity=PARITY,
|
||||||
|
stopbits=STOPBITS,
|
||||||
|
timeout=TIMEOUT
|
||||||
|
)
|
||||||
|
|
||||||
|
if self.client.connect():
|
||||||
|
logger.info(f"成功连接到Modbus串口: {self.port}")
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
logger.error(f"Modbus串口连接失败: {self.port}")
|
||||||
|
return False
|
||||||
|
finally:
|
||||||
|
self.release_lock()
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Modbus连接异常: {str(e)}")
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
def disconnect(self):
|
||||||
|
"""断开Modbus连接"""
|
||||||
|
try:
|
||||||
|
self.acquire_lock()
|
||||||
|
try:
|
||||||
|
if self.client:
|
||||||
|
self.client.close()
|
||||||
|
logger.info("已断开Modbus连接")
|
||||||
|
finally:
|
||||||
|
self.client = None
|
||||||
|
self.release_lock()
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"断开连接异常: {str(e)}")
|
||||||
|
|
||||||
|
|
||||||
|
def read_input_registers(self, slave_id, address, count):
|
||||||
|
"""读取输入寄存器,包含重试机制和线程锁保护"""
|
||||||
|
|
||||||
|
# 先确保连接正常,减少锁内操作
|
||||||
|
if self.client is None or not self.client.is_socket_open():
|
||||||
|
logger.error(f"无法确保Modbus连接,无法读取输入寄存器 (从站{slave_id}, 地址{address})")
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 只在实际读写操作时使用锁,减少锁持有时间
|
||||||
|
self.acquire_lock()
|
||||||
|
try:
|
||||||
|
response = self.client.read_input_registers(
|
||||||
|
address=address,
|
||||||
|
count=count,
|
||||||
|
device_id=slave_id
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
self.release_lock()
|
||||||
|
|
||||||
|
# 检查响应
|
||||||
|
if response.isError():
|
||||||
|
logger.error(f"读取输入寄存器错误: 从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES}, 错误: {response}")
|
||||||
|
# 非致命错误不立即重连,仅在最后一次尝试失败后重连
|
||||||
|
|
||||||
|
logger.debug(f"成功读取输入寄存器: 从站{slave_id}, 地址{address}, 值: {response.registers}")
|
||||||
|
return response.registers
|
||||||
|
except ModbusException as e:
|
||||||
|
logger.error(f"Modbus协议错误: {str(e)} (从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES})")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"读取输入寄存器异常: {str(e)} (从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES})")
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
def read_coils(self, slave_id, address, count):
|
||||||
|
"""读取线圈状态,包含重试机制和线程锁保护"""
|
||||||
|
|
||||||
|
# 先确保连接正常,减少锁内操作
|
||||||
|
if self.client is None or not self.client.is_socket_open():
|
||||||
|
logger.error(f"无法确保Modbus连接,无法读取线圈 (从站{slave_id}, 地址{address})")
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 只在实际读写操作时使用锁,减少锁持有时间
|
||||||
|
self.acquire_lock()
|
||||||
|
try:
|
||||||
|
response = self.client.read_coils(
|
||||||
|
address=address,
|
||||||
|
count=count,
|
||||||
|
device_id=slave_id
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
self.release_lock()
|
||||||
|
|
||||||
|
# 检查响应
|
||||||
|
if response.isError():
|
||||||
|
logger.error(f"读取线圈错误: 从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES}, 错误: {response}")
|
||||||
|
|
||||||
|
logger.debug(f"成功读取线圈: 从站{slave_id}, 地址{address}, 值: {response.bits[:count]}")
|
||||||
|
return response.bits[:count]
|
||||||
|
except ModbusException as e:
|
||||||
|
logger.error(f"Modbus协议错误: {str(e)} (从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES})")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"读取线圈异常: {str(e)} (从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES})")
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
def read_discrete(self, slave_id, address, count):
|
||||||
|
"""读取离散输入状态,包含重试机制和线程锁保护"""
|
||||||
|
# 先确保连接正常,减少锁内操作
|
||||||
|
if self.client is None or not self.client.is_socket_open():
|
||||||
|
logger.error(f"无法确保Modbus连接,无法读取离散输入 (从站{slave_id}, 地址{address})")
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 只在实际读写操作时使用锁,减少锁持有时间
|
||||||
|
self.acquire_lock()
|
||||||
|
try:
|
||||||
|
response = self.client.read_discrete_inputs(
|
||||||
|
address=address,
|
||||||
|
count=count,
|
||||||
|
device_id=slave_id
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
self.release_lock()
|
||||||
|
|
||||||
|
# 检查响应
|
||||||
|
if response.isError():
|
||||||
|
logger.error(f"读取离散输入错误: 从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES}, 错误: {response}")
|
||||||
|
|
||||||
|
logger.debug(f"成功读取离散输入: 从站{slave_id}, 地址{address}, 值: {response.bits[:count]}")
|
||||||
|
return response.bits[:count]
|
||||||
|
except ModbusException as e:
|
||||||
|
logger.error(f"Modbus协议错误: {str(e)} (从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES})")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"读取离散输入异常: {str(e)} (从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES})")
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _ensure_connection(self) -> bool:
|
||||||
|
"""确保Modbus连接正常
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: 连接是否正常
|
||||||
|
"""
|
||||||
|
self.acquire_lock()
|
||||||
|
try:
|
||||||
|
if self.client and self.client.is_socket_open():
|
||||||
|
return True
|
||||||
|
return self.connect()
|
||||||
|
finally:
|
||||||
|
self.release_lock()
|
||||||
|
|
||||||
|
def write_coil(self, slave_id: int, address: int, value: bool) -> bool:
|
||||||
|
"""写入线圈状态,带重试机制和线程锁保护
|
||||||
|
|
||||||
|
Args:
|
||||||
|
slave_id: 从站地址
|
||||||
|
address: 线圈地址
|
||||||
|
value: 线圈状态(True/False)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: 写入是否成功
|
||||||
|
"""
|
||||||
|
# 先确保连接正常,减少锁内操作
|
||||||
|
if not self._ensure_connection():
|
||||||
|
logger.error(f"无法确保Modbus连接,无法写入线圈 (从站{slave_id}, 地址{address})")
|
||||||
|
return False
|
||||||
|
|
||||||
|
for attempt in range(RETRIES):
|
||||||
|
try:
|
||||||
|
# 只在实际写操作时使用锁,减少锁持有时间
|
||||||
|
self.acquire_lock()
|
||||||
|
response = None
|
||||||
|
try:
|
||||||
|
logger.debug(f"发送写入线圈请求: 从站{slave_id}, 地址{address}, 状态{value}")
|
||||||
|
response = self.client.write_coil(address, value, device_id=slave_id)
|
||||||
|
finally:
|
||||||
|
self.release_lock()
|
||||||
|
|
||||||
|
if response:
|
||||||
|
# 检查响应
|
||||||
|
if response.isError():
|
||||||
|
logger.error(f"写入线圈错误响应: 从站{slave_id}, 地址{address} (尝试{attempt+1}/{RETRIES})")
|
||||||
|
# 非致命错误不立即重连,仅在最后一次尝试失败后重连
|
||||||
|
if attempt < RETRIES - 1:
|
||||||
|
time.sleep(0.05) # 使用更短的延迟
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
logger.debug(f"接收到写入线圈响应: 长度{len(response.encode())}字节, 内容{response.encode().hex()}")
|
||||||
|
|
||||||
|
# 快速释放锁,减少其他操作等待时间
|
||||||
|
|
||||||
|
logger.info(f"成功写入线圈 {address}: {value} (尝试{attempt+1}/{RETRIES})")
|
||||||
|
return True
|
||||||
|
except ConnectionException as e:
|
||||||
|
logger.error(f"连接中断错误: {str(e)} (从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES})")
|
||||||
|
self.connected = False # 修正变量名
|
||||||
|
if attempt < RETRIES - 1:
|
||||||
|
time.sleep(0.05)
|
||||||
|
except ModbusException as e:
|
||||||
|
logger.error(f"Modbus协议错误: {str(e)} (从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES})")
|
||||||
|
|
||||||
|
if attempt < RETRIES - 1:
|
||||||
|
time.sleep(0.05)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"写入线圈未知错误: {str(e)} (从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES})")
|
||||||
|
|
||||||
|
if attempt < RETRIES - 1:
|
||||||
|
time.sleep(0.05)
|
||||||
|
|
||||||
|
logger.error(f"所有{RETRIES}次写入线圈尝试均失败: 从站{slave_id}, 地址{address}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def write_holding_register(self, slave_id: int, address: int, value: int) -> bool:
|
||||||
|
"""写入保持寄存器,带重试机制和线程锁保护
|
||||||
|
|
||||||
|
Args:
|
||||||
|
slave_id: 从站地址
|
||||||
|
address: �保持寄存器地址
|
||||||
|
value: 保持寄存器值
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: 写入是否成功
|
||||||
|
"""
|
||||||
|
# 先确保连接正常,减少锁内操作
|
||||||
|
if not self._ensure_connection():
|
||||||
|
logger.error(f"无法确保Modbus连接,无法写入保持寄存器 (从站{slave_id}, 地址{address})")
|
||||||
|
return False
|
||||||
|
|
||||||
|
for attempt in range(RETRIES):
|
||||||
|
try:
|
||||||
|
# 只在实际写操作时使用锁,减少锁持有时间
|
||||||
|
self.acquire_lock()
|
||||||
|
response = None
|
||||||
|
try:
|
||||||
|
logger.debug(f"发送写入保持寄存器请求: 从站{slave_id}, 地址{address}, 值{value}")
|
||||||
|
response = self.client.write_register(address, value, device_id=slave_id)
|
||||||
|
finally:
|
||||||
|
self.release_lock()
|
||||||
|
|
||||||
|
if response:
|
||||||
|
# 检查响应
|
||||||
|
if response.isError():
|
||||||
|
logger.error(f"写入保持寄存器错误响应: 从站{slave_id}, 地址{address} (尝试{attempt+1}/{RETRIES})")
|
||||||
|
# 非致命错误不立即重连,仅在最后一次尝试失败后重连
|
||||||
|
if attempt < RETRIES - 1:
|
||||||
|
time.sleep(0.05) # 使用更短的延迟
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
logger.debug(f"接收到写入保持寄存器响应: 长度{len(response.encode())}字节, 内容{response.encode().hex()}")
|
||||||
|
|
||||||
|
# 快速释放锁,减少其他操作等待时间
|
||||||
|
|
||||||
|
logger.info(f"成功写入保持寄存器 {address}: {value} (尝试{attempt+1}/{RETRIES})")
|
||||||
|
return True
|
||||||
|
except ConnectionException as e:
|
||||||
|
logger.error(f"连接中断错误: {str(e)} (从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES})")
|
||||||
|
self.connected = False # 修正变量名
|
||||||
|
if attempt < RETRIES - 1:
|
||||||
|
time.sleep(0.05)
|
||||||
|
except ModbusException as e:
|
||||||
|
logger.error(f"Modbus协议错误: {str(e)} (从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES})")
|
||||||
|
|
||||||
|
if attempt < RETRIES - 1:
|
||||||
|
time.sleep(0.05)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"写入保持寄存器未知错误: {str(e)} (从站{slave_id}, 地址{address}, 尝试{attempt+1}/{RETRIES})")
|
||||||
|
|
||||||
|
if attempt < RETRIES - 1:
|
||||||
|
time.sleep(0.05)
|
||||||
|
|
||||||
|
logger.error(f"所有{RETRIES}次写入保持寄存器尝试均失败: 从站{slave_id}, 地址{address}")
|
||||||
|
return False
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
import paho.mqtt.client as mqtt
|
||||||
|
import json
|
||||||
|
import socket
|
||||||
|
import logging
|
||||||
|
from datetime import datetime
|
||||||
|
import time
|
||||||
|
import socket
|
||||||
|
from threading import Timer
|
||||||
|
from config import *
|
||||||
|
from typing import Dict, Any, List, Optional, Callable
|
||||||
|
import requests
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
class MQTTClient():
|
||||||
|
def __init__(self, broker: str, port: int = 1883, client_id: str = None):
|
||||||
|
self.client = mqtt.Client(client_id = 'hv_service_' + self.random_string(6)) # 创建本地客户端
|
||||||
|
self.client.username_pw_set(USER,PWD)
|
||||||
|
self.broker = broker
|
||||||
|
self.port = port
|
||||||
|
self.callbacks: Dict[str, Callable] = {}
|
||||||
|
self.received_messages = {}
|
||||||
|
self.message_events = {}
|
||||||
|
|
||||||
|
self.is_connected = False
|
||||||
|
|
||||||
|
# 设置回调函数
|
||||||
|
self.client.on_connect = self._on_connect
|
||||||
|
self.client.on_message = self._on_message
|
||||||
|
self.client.on_disconnect = self._on_disconnect
|
||||||
|
|
||||||
|
Timer(1, self.connTimerHandler).start()
|
||||||
|
|
||||||
|
def random_string(self, length=6):
|
||||||
|
"""生成随机字符串"""
|
||||||
|
import random
|
||||||
|
import string
|
||||||
|
return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
|
||||||
|
|
||||||
|
def stop(self):
|
||||||
|
"""停止服务"""
|
||||||
|
self.client.loop_stop()
|
||||||
|
self.client.disconnect()
|
||||||
|
|
||||||
|
def checkLocalServer(self):
|
||||||
|
host = '127.0.0.1'
|
||||||
|
port = 1883
|
||||||
|
timeout = 1
|
||||||
|
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
|
sock.settimeout(timeout)
|
||||||
|
try:
|
||||||
|
result = sock.connect_ex((host, port))
|
||||||
|
if result == 0:
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
return False
|
||||||
|
except Exception as e:
|
||||||
|
print(e)
|
||||||
|
return False
|
||||||
|
finally:
|
||||||
|
sock.close()
|
||||||
|
|
||||||
|
def connTimerHandler(self):
|
||||||
|
print("mqtt conn timer handler")
|
||||||
|
if self.checkLocalServer():
|
||||||
|
self.client.connect(BROKER, MQTT_PORT) # 连接本地 MQTT 服务器
|
||||||
|
self.client.loop_start() # 开始循环以处理网络流量
|
||||||
|
else:
|
||||||
|
print("local mqtt brokeris not ready")
|
||||||
|
|
||||||
|
Timer(1, self.connTimerHandler).start()
|
||||||
|
|
||||||
|
def connect(self):
|
||||||
|
"""连接到MQTT代理并处理连接错误"""
|
||||||
|
try:
|
||||||
|
self.client.connect(self.broker, self.port)
|
||||||
|
self.client.loop_start()
|
||||||
|
logger.info(f"成功连接到MQTT代理: {self.broker}:{self.port}")
|
||||||
|
return True
|
||||||
|
except socket.gaierror:
|
||||||
|
logger.error(f"MQTT代理地址解析失败: {self.broker}")
|
||||||
|
except ConnectionRefusedError:
|
||||||
|
logger.error(f"MQTT代理拒绝连接: {self.broker}:{self.port}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"MQTT连接失败: {str(e)}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def disconnect(self):
|
||||||
|
"""断开MQTT连接"""
|
||||||
|
self.client.loop_stop()
|
||||||
|
self.client.disconnect()
|
||||||
|
|
||||||
|
def subscribe(self, topic: str, callback: Callable):
|
||||||
|
"""订阅主题并设置回调函数"""
|
||||||
|
self.callbacks[topic] = callback
|
||||||
|
|
||||||
|
def publish(self, topic: str, message: Dict[str, Any]):
|
||||||
|
"""发布消息到指定主题"""
|
||||||
|
payload = json.dumps(message)
|
||||||
|
self.client.publish(topic, payload)
|
||||||
|
|
||||||
|
|
||||||
|
def control_xray_light(self, value):
|
||||||
|
msg = {
|
||||||
|
"device_code" : "1#ALU",
|
||||||
|
"command" : "set_status",
|
||||||
|
"status" : value
|
||||||
|
}
|
||||||
|
# print("publish", DEVICE_CONTROL_TOPIC, msg)
|
||||||
|
self.publish(DEVICE_CONTROL_TOPIC, msg) # 发布数据到本地
|
||||||
|
|
||||||
|
def _on_connect(self, client, userdata, flags, rc):
|
||||||
|
"""连接回调"""
|
||||||
|
print(f"已连接到MQTT代理: {self.broker}")
|
||||||
|
for topic in self.callbacks:
|
||||||
|
self.client.subscribe(topic)
|
||||||
|
self.is_connected = True
|
||||||
|
|
||||||
|
def _on_message(self, client, userdata, msg):
|
||||||
|
"""消息接收回调"""
|
||||||
|
print("mqtt msg:", msg.topic, msg.payload)
|
||||||
|
topic = msg.topic
|
||||||
|
try:
|
||||||
|
payload = json.loads(msg.payload.decode())
|
||||||
|
if topic in self.callbacks:
|
||||||
|
self.callbacks[topic](topic, payload)
|
||||||
|
|
||||||
|
# 存储接收到的消息
|
||||||
|
self.received_messages[topic] = msg
|
||||||
|
|
||||||
|
# 触发等待事件
|
||||||
|
if topic in self.message_events:
|
||||||
|
event = self.message_events.pop(topic)
|
||||||
|
event.set()
|
||||||
|
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
print(f"无法解析消息: {msg.payload}")
|
||||||
|
|
||||||
|
def _on_disconnect(self, client, userdata, rc):
|
||||||
|
"""断开连接回调"""
|
||||||
|
print(f"已断开与MQTT代理的连接: {self.broker}")
|
||||||
|
self.is_connected= False
|
||||||
|
|
||||||
|
def wait_for_message(self, topic: str, timeout: float = 5.0) -> Optional[mqtt.MQTTMessage]:
|
||||||
|
"""等待接收指定主题的消息
|
||||||
|
|
||||||
|
Args:
|
||||||
|
topic: 要等待的主题
|
||||||
|
timeout: 超时时间(秒)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
接收到的消息对象,如果超时则返回None
|
||||||
|
"""
|
||||||
|
import threading
|
||||||
|
|
||||||
|
# 检查是否已经有缓存的消息
|
||||||
|
if topic in self.received_messages:
|
||||||
|
return self.received_messages.pop(topic)
|
||||||
|
|
||||||
|
# 创建事件对象
|
||||||
|
event = threading.Event()
|
||||||
|
self.message_events[topic] = event
|
||||||
|
|
||||||
|
# 等待事件触发或超时
|
||||||
|
event.wait(timeout)
|
||||||
|
|
||||||
|
# 移除事件对象
|
||||||
|
if topic in self.message_events:
|
||||||
|
self.message_events.pop(topic)
|
||||||
|
|
||||||
|
# 返回接收到的消息
|
||||||
|
return self.received_messages.pop(topic, None)
|
||||||
|
|
||||||
|
|
||||||
|
mqtt_client = MQTTClient(broker=BROKER, port=MQTT_PORT)
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
pymodbus>=3.5.0
|
||||||
|
paho-mqtt>=2.1.0
|
||||||
@@ -0,0 +1,216 @@
|
|||||||
|
import time
|
||||||
|
import threading
|
||||||
|
from pymodbus.client import ModbusTcpClient
|
||||||
|
class TcpIoModule():
|
||||||
|
def __init__(self, host='localhost', port=502, timeout=3, retry_interval=1, max_retries=0):
|
||||||
|
|
||||||
|
"""
|
||||||
|
初始化TCP IO模块
|
||||||
|
:param host: 服务器IP地址
|
||||||
|
:param port: 服务器端口
|
||||||
|
:param timeout: 超时时间(秒)
|
||||||
|
:param retry_interval: 重连间隔(秒)
|
||||||
|
:param max_retries: 最大重连次数,0表示无限重试
|
||||||
|
"""
|
||||||
|
self.host = host
|
||||||
|
self.port = port
|
||||||
|
self.timeout = timeout
|
||||||
|
self.retry_interval = retry_interval
|
||||||
|
self.max_retries = max_retries
|
||||||
|
self.client = None
|
||||||
|
self.is_connected = False
|
||||||
|
self.is_running = False
|
||||||
|
self.read_thread = None
|
||||||
|
self.register_values = {}
|
||||||
|
self.reconnect_count = 0
|
||||||
|
self.reconnect_lock = threading.Lock()
|
||||||
|
self.button_states = [False] * 10
|
||||||
|
|
||||||
|
def _connect(self):
|
||||||
|
"""
|
||||||
|
连接到Modbus服务器
|
||||||
|
:return: 是否连接成功
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
if self.client:
|
||||||
|
self.client.close()
|
||||||
|
self.client = ModbusTcpClient(host=self.host, port=self.port, timeout=self.timeout)
|
||||||
|
self.is_connected = self.client.connect()
|
||||||
|
if self.is_connected:
|
||||||
|
print(f"成功连接到Modbus服务器: {self.host}:{self.port}")
|
||||||
|
self.reconnect_count = 0
|
||||||
|
else:
|
||||||
|
print(f"连接Modbus服务器失败: {self.host}:{self.port}")
|
||||||
|
return self.is_connected
|
||||||
|
except Exception as e:
|
||||||
|
print(f"连接失败: {e}")
|
||||||
|
self.is_connected = False
|
||||||
|
return False
|
||||||
|
|
||||||
|
def start(self):
|
||||||
|
"""
|
||||||
|
启动Modbus客户端,开始读取寄存器
|
||||||
|
:return: 是否启动成功
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
self.is_running = True
|
||||||
|
self.read_thread = threading.Thread(target=self._read_data_loop)
|
||||||
|
self.read_thread.daemon = True
|
||||||
|
self.read_thread.start()
|
||||||
|
return True
|
||||||
|
|
||||||
|
def stop(self):
|
||||||
|
"""
|
||||||
|
停止Modbus客户端
|
||||||
|
"""
|
||||||
|
self.is_running = False
|
||||||
|
if self.read_thread and self.read_thread.is_alive():
|
||||||
|
self.read_thread.join(timeout=1.0)
|
||||||
|
if self.client:
|
||||||
|
self.client.close()
|
||||||
|
self.is_connected = False
|
||||||
|
print("Modbus客户端已停止")
|
||||||
|
|
||||||
|
def _read_data_loop(self):
|
||||||
|
"""
|
||||||
|
循环读取寄存器的内部方法
|
||||||
|
"""
|
||||||
|
while self.is_running:
|
||||||
|
if not self.is_connected:
|
||||||
|
# 连接断开,尝试重连
|
||||||
|
with self.reconnect_lock:
|
||||||
|
if not self.is_connected and self._auto_reconnect():
|
||||||
|
print("连成功")
|
||||||
|
time.sleep(0.5)
|
||||||
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 这里实现读取寄存器的逻辑
|
||||||
|
self.read_data()
|
||||||
|
time.sleep(0.1) # 每秒读取一次
|
||||||
|
except Exception as e:
|
||||||
|
print(f"读取寄存器出错: {e}")
|
||||||
|
# 读取错误可能是连接问题,标记为断开以便重连
|
||||||
|
self.is_connected = False
|
||||||
|
time.sleep(0.5)
|
||||||
|
|
||||||
|
def _auto_reconnect(self):
|
||||||
|
"""
|
||||||
|
自动重连机制
|
||||||
|
:return: 是否重连成功
|
||||||
|
"""
|
||||||
|
# 只尝试一次重连,避免长时间持有锁
|
||||||
|
if self.is_running and (self.max_retries == 0 or self.reconnect_count < self.max_retries):
|
||||||
|
self.reconnect_count += 1
|
||||||
|
|
||||||
|
if self._connect():
|
||||||
|
return True
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
def read_data(self):
|
||||||
|
"""
|
||||||
|
读取寄存器的方法
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# 读取输入寄存器,起始地址为0,读取10个寄存器
|
||||||
|
response = self.client.read_discrete_inputs(address=0, count= 4)
|
||||||
|
if not response.isError():
|
||||||
|
for idx, bit in enumerate(response.bits):
|
||||||
|
if idx == 3:
|
||||||
|
# 检测下降沿:从抬起(True)变为按下(False)
|
||||||
|
previous_state = self.button_states[idx]
|
||||||
|
current_state = bit
|
||||||
|
|
||||||
|
# 更新当前状态
|
||||||
|
self.button_states[idx] = current_state
|
||||||
|
|
||||||
|
# 下降沿检测
|
||||||
|
if previous_state == True and current_state == False:
|
||||||
|
self.control_stop()
|
||||||
|
print("=================control_stop")
|
||||||
|
|
||||||
|
else:
|
||||||
|
if bit:
|
||||||
|
print(f"寄存器 {idx} 的值是 {bit}")
|
||||||
|
self.button_states[idx] = True
|
||||||
|
|
||||||
|
elif self.button_states[idx]:
|
||||||
|
self.button_states[idx] = False
|
||||||
|
if idx == 0:
|
||||||
|
self.control_start()
|
||||||
|
print("=================control_start")
|
||||||
|
elif idx == 1:
|
||||||
|
self.control_pause()
|
||||||
|
print("=================control_pause")
|
||||||
|
elif idx == 2:
|
||||||
|
self.control_reset()
|
||||||
|
print("=================control_reset")
|
||||||
|
|
||||||
|
else:
|
||||||
|
print(f"读取寄存器出错: {response}")
|
||||||
|
self.is_connected = False
|
||||||
|
except Exception as e:
|
||||||
|
print(f"读取寄存器出错: {e}")
|
||||||
|
self.is_connected = False
|
||||||
|
|
||||||
|
def control_start(self):
|
||||||
|
self.control_light(9, True)
|
||||||
|
"""
|
||||||
|
控制设备启动
|
||||||
|
"""
|
||||||
|
|
||||||
|
def control_pause(self):
|
||||||
|
self.control_light(9, False)
|
||||||
|
"""
|
||||||
|
控制设备暂停
|
||||||
|
"""
|
||||||
|
|
||||||
|
def control_reset(self):
|
||||||
|
"""
|
||||||
|
控制设备复位
|
||||||
|
"""
|
||||||
|
|
||||||
|
def control_stop(self):
|
||||||
|
self.control_light(9, False)
|
||||||
|
"""
|
||||||
|
控制设备停止
|
||||||
|
"""
|
||||||
|
|
||||||
|
def control_light(self, index, value):
|
||||||
|
try:
|
||||||
|
self.client.write_coil(index, value)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"写入线圈出错: {e}")
|
||||||
|
self.is_connected = False
|
||||||
|
|
||||||
|
def control_valve(self, index, value):
|
||||||
|
try:
|
||||||
|
self.client.write_coil(index, value)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"写入线圈出错: {e}")
|
||||||
|
self.is_connected = False
|
||||||
|
|
||||||
|
def get_register_value(self, register_address):
|
||||||
|
"""
|
||||||
|
获取指定寄存器的值
|
||||||
|
:param register_address: 寄存器地址
|
||||||
|
:return: 寄存器值或None(如果不存在)
|
||||||
|
"""
|
||||||
|
return self.register_values.get(register_address)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
# 示例用法
|
||||||
|
modbus_client = TcpIoModule(host='192.168.8.211', port=502)
|
||||||
|
if modbus_client.start():
|
||||||
|
print("Modbus客户端已启动")
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
time.sleep(1)
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print("停止Modbus客户端")
|
||||||
|
modbus_client.stop()
|
||||||
|
else:
|
||||||
|
print("Modbus客户端启动失败")
|
||||||
|
|
||||||
@@ -245,6 +245,9 @@ class SensorService:
|
|||||||
|
|
||||||
for device in self.devices:
|
for device in self.devices:
|
||||||
try:
|
try:
|
||||||
|
enabled = device.get("enabled", False)
|
||||||
|
if not enabled:
|
||||||
|
continue
|
||||||
slave_id = int(device.get('address'))
|
slave_id = int(device.get('address'))
|
||||||
logger.info(f"开始读取设备 {device.get('code')} (从站ID: {slave_id}) 数据")
|
logger.info(f"开始读取设备 {device.get('code')} (从站ID: {slave_id}) 数据")
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import threading
|
|||||||
import subprocess
|
import subprocess
|
||||||
import re
|
import re
|
||||||
import json
|
import json
|
||||||
|
from copy import deepcopy
|
||||||
from config import *
|
from config import *
|
||||||
from PySide6.QtCore import *
|
from PySide6.QtCore import *
|
||||||
from PySide6.QtNetwork import QUdpSocket, QHostAddress
|
from PySide6.QtNetwork import QUdpSocket, QHostAddress
|
||||||
@@ -210,6 +211,11 @@ class MotorManager(QObject):
|
|||||||
self.scanner(index).daq_info['online'] = data['daq_online']
|
self.scanner(index).daq_info['online'] = data['daq_online']
|
||||||
if 'daq_power' in data:
|
if 'daq_power' in data:
|
||||||
self.scanner(index).daq_info['power'] = data['daq_power']
|
self.scanner(index).daq_info['power'] = data['daq_power']
|
||||||
|
if 'filament_info' in data:
|
||||||
|
filament_info = deepcopy(data['filament_info'])
|
||||||
|
filament_info['id'] = data['id']
|
||||||
|
self.udp_socket.writeDatagram(QByteArray(json.dumps(filament_info).encode()) ,
|
||||||
|
QHostAddress("127.0.0.1"), 62000)
|
||||||
|
|
||||||
if 'motor_power' in data:
|
if 'motor_power' in data:
|
||||||
self.scanner(index).motor_power = data['motor_power']
|
self.scanner(index).motor_power = data['motor_power']
|
||||||
|
|||||||
Reference in New Issue
Block a user