fix: improve MQTT topic resubscription and error handling in JackeryHome sensor

- Refactored the error handling logic to use an asynchronous function for resubscribing to MQTT topics after an error occurs.
- Added detailed logging for LWT message processing and device serial number updates.
- Ensured that the periodic data request task is initiated after resubscribing to the necessary topics.
This commit is contained in:
不求圣剑
2025-11-18 15:41:46 +08:00
parent 2d22a25006
commit 1179018be7

View File

@@ -336,6 +336,31 @@ def data_message_received(msg):
except Exception as e: except Exception as e:
_LOGGER.error(f"Error processing data message for {self._sensor_id}: {e}") _LOGGER.error(f"Error processing data message for {self._sensor_id}: {e}")
# 在回调函数中不能直接使用 await需要通过 async_create_task 执行异步操作
async def _resubscribe_topics():
"""重新订阅 MQTT 主题的异步函数"""
# 定义 LWT 消息处理回调
@callback
def lwt_message_received(msg):
"""Handle LWT messages to get device serial number."""
try:
payload = msg.payload
if isinstance(payload, bytes):
payload = payload.decode("utf-8")
_LOGGER.debug(f"Received LWT message: {payload}")
try:
data = json.loads(payload)
if isinstance(data, dict) and "gw_sn" in data:
self._device_sn = data["gw_sn"]
_LOGGER.info(f"Device serial number updated: {self._device_sn}")
except json.JSONDecodeError:
_LOGGER.warning(f"Failed to parse LWT message: {payload}")
except Exception as e:
_LOGGER.error(f"Error processing LWT message: {e}")
# 订阅 LWT topic 以获取设备序列号 # 订阅 LWT topic 以获取设备序列号
await ha_mqtt.async_subscribe( await ha_mqtt.async_subscribe(
self.hass, self.hass,
@@ -358,6 +383,8 @@ def data_message_received(msg):
# 启动定时器每隔5秒向 device/data-get 发送数据获取请求 # 启动定时器每隔5秒向 device/data-get 发送数据获取请求
self._data_task = asyncio.create_task(self._periodic_data_request()) self._data_task = asyncio.create_task(self._periodic_data_request())
self.hass.async_create_task(_resubscribe_topics())
def _construct_data_get_request(self) -> dict: def _construct_data_get_request(self) -> dict:
"""构造 data_get 格式的请求数据.""" """构造 data_get 格式的请求数据."""