332 lines
12 KiB
Python
332 lines
12 KiB
Python
import math
|
|
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 *
|
|
import threading
|
|
|
|
logging.basicConfig(level=logging.INFO)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
class SensorService:
|
|
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
|
|
|
|
# 订阅MQTT主题
|
|
self.mqtt_client.subscribe(DEVICE_CONTROL_TOPIC, self.handle_control_message)
|
|
|
|
# 设备列表
|
|
self.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
|
|
self.lock = threading.Lock()
|
|
|
|
def handle_control_message(self, topic, payload):
|
|
"""异步处理设备控制消息"""
|
|
if topic == DEVICE_CONTROL_TOPIC:
|
|
dev_code = payload.get("device_code")
|
|
if "ALU" 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_control_message, newpayload)
|
|
|
|
def _process_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 = 0x30
|
|
if not device_code:
|
|
logger.error("控制消息缺少device_code")
|
|
return
|
|
|
|
# 使用设备管理器控制设备
|
|
with self.lock:
|
|
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
|
|
logger.info("Modbus连接成功")
|
|
|
|
while not self.mqtt_client.is_connected:
|
|
logger.info("waiting for mqtt conn...")
|
|
time.sleep(1)
|
|
|
|
logger.info("Modbus和MQTT连接成功,开始定时读取和发布数据...")
|
|
|
|
self.devices = config.get("devices", [])
|
|
|
|
if not self.devices or len(self.devices) == 0:
|
|
logger.error("未找到HVS设备,程序退出")
|
|
return
|
|
|
|
logger.info(f"找到 {len(self.devices)} 个sensor设备")
|
|
|
|
logger.info(f"sensor_devices: {json.dumps(self.devices, ensure_ascii=False)}")
|
|
|
|
# 主循环
|
|
while self.exit_flag == False:
|
|
# 计算当前时间
|
|
current_time = time.time()
|
|
|
|
logger.info(f"loop... {current_time}")
|
|
|
|
# 定期发布服务状态 (每10秒)
|
|
if current_time - self.last_service_status_time >= 3:
|
|
logger.debug("publish service status")
|
|
self._publish_service_status(current_time)
|
|
|
|
|
|
# 读取并发布所有HVS设备数据
|
|
self.read_and_publish_devices_data()
|
|
|
|
# 等待指定间隔
|
|
time.sleep(config.get("poll_interval", 1))
|
|
|
|
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": "powerbus_service",
|
|
"status": {
|
|
"available": True,
|
|
"running_time": running_time
|
|
}
|
|
}
|
|
|
|
# 发布消息
|
|
self.mqtt_client.publish(SERVICE_STATUS_TOPIC, service_message)
|
|
logger.info(f"成功发布服务状态到 {SERVICE_STATUS_TOPIC}: {service_message}")
|
|
self.last_service_status_time = current_time
|
|
|
|
# float get_temperature(float Rt)
|
|
# {
|
|
# const float Rp = 50000.0; ///< 10K NTC
|
|
# const float T2 = (273.15+25.0); ///< 10K NTC
|
|
# const float Bx = 3950.0; ///< 10K NTC
|
|
# const float Ka = 273.15; ///< 10K NTC
|
|
|
|
# float Temp = 0.0f;
|
|
# Temp = Rt / Rp;
|
|
# Temp = log(Temp);
|
|
# Temp /=Bx;
|
|
# Temp += (1 / T2);
|
|
# Temp = 1 / Temp;
|
|
# Temp -= Ka;
|
|
# return Temp;
|
|
# }
|
|
|
|
def wsu_get_temperature(self, Rt):
|
|
"""计算WSU温度"""
|
|
Rp = 50000.0
|
|
T2 = (273.15+25.0)
|
|
Bx = 3950.0
|
|
Ka = 273.15
|
|
|
|
Temp = 0.0
|
|
Temp = Rt / Rp
|
|
Temp = math.log10(Temp)
|
|
Temp /=Bx
|
|
Temp += (1 / T2)
|
|
Temp = 1 / Temp
|
|
Temp -= Ka
|
|
return Temp
|
|
|
|
def wsu_get_flow_rate_g1(self, freq):
|
|
"""计算WSU流量"""
|
|
if freq == 0:
|
|
return 0.0
|
|
return 50 * 1000.0 * 60 * 10 / 660 / freq
|
|
|
|
def wsu_get_flow_rate_g2(self, freq, factor):
|
|
"""计算WSU流量"""
|
|
if freq == 0:
|
|
return 0.0
|
|
|
|
return freq * 60 / factor
|
|
|
|
def handle_wsu_data(self, device, regs):
|
|
"""处理WSU数据"""
|
|
|
|
if not regs or len(regs) < 2:
|
|
return 0, 0
|
|
|
|
generation = device.get("generation", "0")
|
|
flow_rate = regs[0]
|
|
water_temp = regs[1]
|
|
|
|
if generation == "0" and regs[1] < 500:
|
|
flow_rate = flow_rate / 1000.0
|
|
water_temp = water_temp / 10.0
|
|
elif generation == "1" and regs[1] >= 500:
|
|
flow_rate = self.wsu_get_flow_rate_g1(flow_rate)
|
|
water_temp = self.wsu_get_temperature(water_temp * 2)
|
|
elif generation == "2":
|
|
factor = device.get("factor", 6000)
|
|
flow_rate = self.wsu_get_flow_rate_g2(flow_rate, factor)
|
|
water_temp = self.wsu_get_temperature(water_temp * 2)
|
|
|
|
return flow_rate, water_temp
|
|
|
|
def read_and_publish_devices_data(self):
|
|
"""读取并发布所有设备数据"""
|
|
# 确保Modbus连接正常
|
|
if not self.modbus_client._ensure_connection():
|
|
logger.error(f"无法连接到Modbus设备")
|
|
return
|
|
|
|
for device in self.devices:
|
|
try:
|
|
slave_id = int(device.get('address'))
|
|
logger.info(f"开始读取设备 {device.get('code')} (从站ID: {slave_id}) 数据")
|
|
|
|
if device.get('type', '') == 'WSU':
|
|
# 读取输入寄存器
|
|
with self.lock:
|
|
regs = self.modbus_client.read_holding_registers(
|
|
slave_id=slave_id,
|
|
address=0,
|
|
count=2
|
|
)
|
|
if regs is None:
|
|
device["error_count"] = device.get("error_count", 10) + 1
|
|
else:
|
|
device["error_count"] = 0
|
|
|
|
flow_rate, water_temp = self.handle_wsu_data(device, regs)
|
|
|
|
device.update({
|
|
"status" : {
|
|
"online": device.get("error_count", 10) < 3,
|
|
"flow_rate": flow_rate,
|
|
"water_temp": water_temp
|
|
}
|
|
})
|
|
elif device.get('type', '') == 'OSU':
|
|
# 读取输入寄存器
|
|
with self.lock:
|
|
regs = self.modbus_client.read_holding_registers(
|
|
slave_id=slave_id,
|
|
address=0,
|
|
count=2
|
|
)
|
|
if regs is None:
|
|
device["error_count"] = device.get("error_count", 10) + 1
|
|
else:
|
|
device["error_count"] = 0
|
|
device.update({
|
|
"status" : {
|
|
"online": device.get("error_count", 10) < 3,
|
|
"oil_temp": regs[1] / 10.0 if regs and len(regs) > 1 else None,
|
|
"oil_level": regs[0] if regs and len(regs) > 0 else None,
|
|
}
|
|
})
|
|
elif device.get('type', '') == 'ALU':
|
|
# 读取线圈
|
|
with self.lock:
|
|
coils = self.modbus_client.read_coils(
|
|
slave_id=slave_id,
|
|
address=0,
|
|
count=1
|
|
)
|
|
if coils is None:
|
|
device["error_count"] = device.get("error_count", 10) + 1
|
|
else:
|
|
device["error_count"] = 0
|
|
device.update({
|
|
"status" : {
|
|
"online": device.get("error_count", 10) < 3,
|
|
"status": coils[0] if coils and len(coils) > 0 else None,
|
|
}
|
|
})
|
|
if regs is None:
|
|
logger.error(f"读取失败")
|
|
else:
|
|
logger.info(f"读取成功")
|
|
# 短暂延迟,避免总线冲突
|
|
time.sleep(0.1)
|
|
|
|
except Exception as e:
|
|
logger.error(f"处理设备 {device.get('code')} 数据失败: {e}")
|
|
|
|
# 准备发布的数据
|
|
data = []
|
|
for device in self.devices:
|
|
data.append({
|
|
"device_code": device.get('code'),
|
|
"timestamp": datetime.now().isoformat(),
|
|
"status": device.get("status", {})
|
|
})
|
|
|
|
# 发布数据
|
|
self.mqtt_client.publish(DEVICE_STATUS_TOPIC, data)
|
|
logger.info(f"成功发布设备数据: {json.dumps(data, ensure_ascii=False)}")
|