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, 1000) 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}")