fix: improve MQTT connection handling in JackeryHome sensor

- Added a delay at startup to ensure MQTT connection is established before sending data requests.
- Implemented error handling for MQTT connection issues, logging warnings and continuing the periodic data request process.
- Enhanced logging for task cancellation to provide clearer feedback on sensor operation.
This commit is contained in:
不求圣剑
2025-11-18 16:47:15 +08:00
parent fa44eb31a8
commit c94fb0d0c8

View File

@@ -418,6 +418,10 @@ class JackeryHomeSensor(SensorEntity):
async def _periodic_data_request(self) -> None: async def _periodic_data_request(self) -> None:
"""Periodically send data request to device/data-get topic.""" """Periodically send data request to device/data-get topic."""
# 启动时等待一段时间,确保 MQTT 连接已建立
_LOGGER.info(f"Starting periodic data request for {self._sensor_id}, waiting for MQTT connection...")
await asyncio.sleep(2)
while True: while True:
try: try:
# 如果还没有设备序列号,等待一段时间再重试 # 如果还没有设备序列号,等待一段时间再重试
@@ -428,24 +432,36 @@ class JackeryHomeSensor(SensorEntity):
await asyncio.sleep(REQUEST_INTERVAL) await asyncio.sleep(REQUEST_INTERVAL)
continue continue
# 构造并发送 data_get 格式的请求 # 检查 MQTT 是否可用
request_data = self._construct_data_get_request() try:
await ha_mqtt.async_publish( # 构造并发送 data_get 格式的请求
self.hass, request_data = self._construct_data_get_request()
self._data_get_topic, await ha_mqtt.async_publish(
json.dumps(request_data, ensure_ascii=False), self.hass,
1, self._data_get_topic,
False json.dumps(request_data, ensure_ascii=False),
) 1,
_LOGGER.debug( False
f"Sent data_get request for {self._sensor_id} " )
f"(meter_sn: {self._meter_sn}) to {self._data_get_topic}" _LOGGER.debug(
) f"Sent data_get request for {self._sensor_id} "
f"(meter_sn: {self._meter_sn}) to {self._data_get_topic}"
)
except Exception as mqtt_error:
# MQTT 连接错误,记录警告但继续运行
_LOGGER.warning(
f"MQTT not ready for {self._sensor_id}: {mqtt_error}. "
f"Will retry in {REQUEST_INTERVAL} seconds..."
)
await asyncio.sleep(REQUEST_INTERVAL) await asyncio.sleep(REQUEST_INTERVAL)
except asyncio.CancelledError:
# 任务被取消时正常退出
_LOGGER.info(f"Periodic data request task cancelled for {self._sensor_id}")
raise
except Exception as e: except Exception as e:
_LOGGER.error(f"Error in periodic data request for {self._sensor_id}: {e}") _LOGGER.error(f"Unexpected error in periodic data request for {self._sensor_id}: {e}")
await asyncio.sleep(REQUEST_INTERVAL) await asyncio.sleep(REQUEST_INTERVAL)
async def async_will_remove_from_hass(self) -> None: async def async_will_remove_from_hass(self) -> None: