242 lines
9.8 KiB
Python
Executable File
242 lines
9.8 KiB
Python
Executable File
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
|
|
|
|
logging.basicConfig(level=logging.INFO)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
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.xray_on = [False, False]
|
|
self.last_hvs_update_time = 0
|
|
|
|
self.exit_flag = False
|
|
self.loop_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 = 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)
|
|
else:
|
|
self.modbus_client.write_coil(slave_id, 0x00, 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()
|
|
|
|
def stop(self):
|
|
if not self.loop_thread:
|
|
return
|
|
"""停止服务"""
|
|
self.exit_flag = True
|
|
self.loop_thread.join()
|
|
self.executor.shutdown(wait=True)
|
|
|
|
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_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=slave_id,
|
|
address=INPUT_REGISTERS["start_address"],
|
|
count=INPUT_REGISTERS["count"]
|
|
)
|
|
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)
|
|
|
|
# 读取线圈
|
|
coils = self.modbus_client.read_coils(
|
|
slave_id=slave_id,
|
|
address=COIL_REGISTERS["start_address"],
|
|
count=COIL_REGISTERS["count"]
|
|
)
|
|
if coils is None:
|
|
hvs_device["error_count"] = hvs_device.get("error_count", 10) + 1
|
|
else:
|
|
hvs_device["error_count"] = 0
|
|
|
|
if coils is not None:
|
|
# print("coils:", coils)
|
|
if coils[2]:
|
|
self.xray_on[slave_id - 1] = True
|
|
else:
|
|
self.xray_on[slave_id - 1] = False
|
|
# print(f"slave_id: {slave_id}, xray_on: {self.xray_on[slave_id - 1]}")
|
|
self.last_hvs_update_time = time.time()
|
|
|
|
# 设备间添加延迟,避免总线冲突
|
|
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": input_regs[1] / 1000.0 if input_regs and len(input_regs) > 1 else None,
|
|
"current_filament": input_regs[2] / 1000.0 if input_regs and len(input_regs) > 2 else None,
|
|
"internal_temperature": input_regs[3] / 100.0 if input_regs and len(input_regs) > 3 else None,
|
|
"fault_status": input_regs[4] if input_regs and len(input_regs) > 4 else None,
|
|
"switch_status": coils[0] if coils and len(coils) > 0 else None,
|
|
"xray_status": coils[2] if coils and len(coils) > 2 else None
|
|
}
|
|
}
|
|
# 发布数据
|
|
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}") |