修复代码, 现在可以正常接收平台心跳包并返回设备状态
This commit is contained in:
@@ -10,6 +10,7 @@ LoRa协议处理模块
|
||||
import logging
|
||||
import time
|
||||
import random
|
||||
import os
|
||||
from ..base import ProtocolHandler
|
||||
|
||||
# 配置日志
|
||||
@@ -29,6 +30,7 @@ class LoRaHandler(ProtocolHandler):
|
||||
"""
|
||||
super().__init__(config)
|
||||
self.initialized = False
|
||||
self.last_config_mtime = None # 上次配置文件修改时间
|
||||
logger.info("初始化LoRa协议处理器")
|
||||
|
||||
def initialize(self):
|
||||
@@ -41,43 +43,46 @@ class LoRaHandler(ProtocolHandler):
|
||||
|
||||
# 如果启用模拟模式,初始化设备管理器
|
||||
if self.config.simulation_enabled:
|
||||
from internal.simulation import DeviceManager, AreaController, NormalDevice
|
||||
self.device_manager = DeviceManager()
|
||||
|
||||
# 根据配置创建模拟区域主控设备
|
||||
controllers = {}
|
||||
for controller_config in self.config.simulation_controllers:
|
||||
controller = AreaController(
|
||||
device_id=controller_config['id'],
|
||||
lora_address=controller_config['lora_address'],
|
||||
status=controller_config.get('status', 'stopped')
|
||||
)
|
||||
self.device_manager.add_controller(controller)
|
||||
controllers[controller.device_id] = controller
|
||||
|
||||
# 根据配置创建模拟普通设备,并关联到区域主控
|
||||
for device_config in self.config.simulation_devices:
|
||||
device = NormalDevice(
|
||||
device_id=device_config['id'],
|
||||
device_type=device_config['type'],
|
||||
rs485_bus=device_config['rs485_bus'],
|
||||
rs485_address=device_config['rs485_address'],
|
||||
controller_id=device_config['controller_id'],
|
||||
status=device_config.get('status', 'stopped')
|
||||
)
|
||||
self.device_manager.add_device(device)
|
||||
|
||||
# 将设备添加到对应的区域主控中
|
||||
controller_id = device_config['controller_id']
|
||||
if controller_id in controllers:
|
||||
controllers[controller_id].add_device(device)
|
||||
|
||||
logger.info(f"模拟模式已启用,创建了 {len(controllers)} 个区域主控和 {len(self.config.simulation_devices)} 个普通设备")
|
||||
self._initialize_simulation()
|
||||
else:
|
||||
logger.info("真实模式,需要连接LoRa硬件")
|
||||
|
||||
logger.info("LoRa协议处理器初始化完成")
|
||||
|
||||
def _initialize_simulation(self):
|
||||
"""初始化模拟模式"""
|
||||
from internal.simulation import DeviceManager, AreaController, NormalDevice
|
||||
|
||||
# 如果设备管理器尚未创建,则创建它
|
||||
if not hasattr(self, 'device_manager') or self.device_manager is None:
|
||||
self.device_manager = DeviceManager()
|
||||
|
||||
# 检查是否需要重新加载配置(在模拟模式下)
|
||||
self._check_and_reload_config()
|
||||
|
||||
# 重新初始化设备(根据最新的配置)
|
||||
self.device_manager.reinitialize_devices(
|
||||
self.config.simulation_controllers,
|
||||
self.config.simulation_devices
|
||||
)
|
||||
|
||||
def _check_and_reload_config(self):
|
||||
"""检查并重新加载配置文件(仅在模拟模式下)"""
|
||||
if not self.config.simulation_enabled:
|
||||
return
|
||||
|
||||
try:
|
||||
# 获取配置文件的修改时间
|
||||
current_mtime = os.path.getmtime(self.config.config_path)
|
||||
|
||||
# 如果是第一次检查或者文件已被修改,则重新加载配置
|
||||
if self.last_config_mtime is None or current_mtime > self.last_config_mtime:
|
||||
logger.info("检测到配置文件发生变化,重新加载配置")
|
||||
self.config.reload_config()
|
||||
self.last_config_mtime = current_mtime
|
||||
except Exception as e:
|
||||
logger.error(f"检查配置文件修改时间时发生错误: {e}")
|
||||
|
||||
def send_command(self, command, data):
|
||||
"""
|
||||
通过LoRa发送命令到设备
|
||||
@@ -100,6 +105,8 @@ class LoRaHandler(ProtocolHandler):
|
||||
|
||||
# 如果启用模拟模式,直接处理命令
|
||||
if self.config.simulation_enabled and self.device_manager:
|
||||
# 在模拟模式下,每次都检查配置文件是否有更新
|
||||
self._check_and_reload_config()
|
||||
result = self._handle_simulated_command(command, data)
|
||||
logger.info(f"模拟命令处理结果: {result}")
|
||||
return result
|
||||
|
||||
@@ -93,6 +93,8 @@ class WebSocketClient:
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"发送消息失败: {e}")
|
||||
# 连接可能已断开,更新状态
|
||||
self.connected = False
|
||||
return False
|
||||
|
||||
async def listen(self):
|
||||
@@ -125,18 +127,26 @@ class WebSocketClient:
|
||||
logger.error(f"监听平台消息时发生错误: {e}")
|
||||
self.connected = False
|
||||
|
||||
async def send_heartbeat(self):
|
||||
"""发送心跳消息"""
|
||||
if not self.connected:
|
||||
return False
|
||||
async def reconnect(self):
|
||||
"""尝试重新连接到平台"""
|
||||
logger.info("尝试重新连接到平台...")
|
||||
reconnect_delay = 5 # 初始重连延迟(秒)
|
||||
max_delay = 60 # 最大重连延迟(秒)
|
||||
|
||||
heartbeat_msg = {
|
||||
"type": "heartbeat",
|
||||
"device_id": self.device_id,
|
||||
"timestamp": datetime.utcnow().isoformat() + 'Z'
|
||||
}
|
||||
|
||||
return await self.send_message(heartbeat_msg)
|
||||
while self.running and not self.connected:
|
||||
try:
|
||||
await self.connect()
|
||||
if self.connected:
|
||||
logger.info("重新连接成功")
|
||||
return True
|
||||
else:
|
||||
logger.warning(f"重新连接失败,{reconnect_delay}秒后重试...")
|
||||
await asyncio.sleep(reconnect_delay)
|
||||
# 指数退避,但不超过最大延迟
|
||||
reconnect_delay = min(reconnect_delay * 2, max_delay)
|
||||
except Exception as e:
|
||||
logger.error(f"重新连接时发生错误: {e}")
|
||||
await asyncio.sleep(reconnect_delay)
|
||||
|
||||
def is_connected(self):
|
||||
"""检查是否已连接"""
|
||||
|
||||
Reference in New Issue
Block a user