feat: enhance MQTT integration checks in JackeryHome

- Added validation to ensure MQTT integration is configured before setting up the JackeryHome integration.
- Updated error handling in the configuration flow to provide user feedback if MQTT is not available.
- Improved logging for MQTT subscription processes and error handling in the data coordinator.
- Updated user interface strings to reflect the new requirements for MQTT integration.
This commit is contained in:
不求圣剑
2025-11-18 17:04:55 +08:00
parent e6afd02ff2
commit 0441a1ab38
5 changed files with 76 additions and 72 deletions

View File

@@ -4,6 +4,7 @@ import logging
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.const import Platform
from homeassistant.components import mqtt
_LOGGER = logging.getLogger(__name__)
@@ -15,6 +16,17 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up JackeryHome from a config entry."""
_LOGGER.info("Setting up JackeryHome integration")
# 检查 MQTT 集成是否已配置和可用
if not await mqtt.async_wait_for_mqtt_client(hass):
_LOGGER.error(
"MQTT integration is not available or not configured. "
"Please set up the MQTT integration first: "
"Settings -> Devices & Services -> Add Integration -> MQTT"
)
return False
_LOGGER.info("MQTT integration is available and ready")
# 初始化存储结构
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = {

View File

@@ -7,6 +7,7 @@ import voluptuous as vol
from homeassistant import config_entries
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResult
from homeassistant.components import mqtt
from . import DOMAIN
@@ -19,14 +20,6 @@ DATA_SCHEMA = vol.Schema(
"topic_prefix",
default="homeassistant/sensor"
): str,
vol.Required(
"mqtt_broker",
default="192.168.1.100"
): str,
vol.Optional(
"mqtt_port",
default=1883
): int,
}
)
@@ -46,21 +39,14 @@ class JackeryHomeConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
errors = {}
if user_input is not None:
# 验证 MQTT broker 地址
mqtt_broker = user_input.get("mqtt_broker", "").strip()
if not mqtt_broker:
errors["base"] = "mqtt_broker_required"
# 验证端口范围
try:
mqtt_port = int(user_input.get("mqtt_port", 1883))
if mqtt_port < 1 or mqtt_port > 65535:
errors["base"] = "invalid_port"
except (ValueError, TypeError):
errors["base"] = "invalid_port"
if not errors:
_LOGGER.info(f"Creating JackeryHome config entry with topic_prefix: {user_input.get('topic_prefix', 'homeassistant/sensor')}")
# 检查 MQTT 集成是否已配置
if not await mqtt.async_wait_for_mqtt_client(self.hass):
errors["base"] = "mqtt_not_configured"
else:
_LOGGER.info(
f"Creating JackeryHome config entry with topic_prefix: "
f"{user_input.get('topic_prefix', 'homeassistant/sensor')}"
)
return self.async_create_entry(
title="JackeryHome",

View File

@@ -170,38 +170,45 @@ class JackeryDataCoordinator:
if self._subscribed:
return
# 订阅 LWT topic
@callback
def lwt_message_received(msg):
"""处理 LWT 消息."""
self._handle_lwt_message(msg)
try:
# 订阅 LWT topic
@callback
def lwt_message_received(msg):
"""处理 LWT 消息."""
self._handle_lwt_message(msg)
await ha_mqtt.async_subscribe(
self.hass,
self._gw_lwt_topic,
lwt_message_received,
1
)
_LOGGER.info(f"Coordinator subscribed to LWT topic: {self._gw_lwt_topic}")
await ha_mqtt.async_subscribe(
self.hass,
self._gw_lwt_topic,
lwt_message_received,
1
)
_LOGGER.info(f"Coordinator subscribed to LWT topic: {self._gw_lwt_topic}")
# 订阅数据响应 topic
@callback
def data_message_received(msg):
"""处理数据响应消息."""
self._handle_data_message(msg)
# 订阅数据响应 topic
@callback
def data_message_received(msg):
"""处理数据响应消息."""
self._handle_data_message(msg)
await ha_mqtt.async_subscribe(
self.hass,
self._data_topic,
data_message_received,
1
)
_LOGGER.info(f"Coordinator subscribed to data topic: {self._data_topic}")
await ha_mqtt.async_subscribe(
self.hass,
self._data_topic,
data_message_received,
1
)
_LOGGER.info(f"Coordinator subscribed to data topic: {self._data_topic}")
self._subscribed = True
self._subscribed = True
# 启动定时请求任务
self._data_task = asyncio.create_task(self._periodic_data_request())
# 启动定时请求任务
self._data_task = asyncio.create_task(self._periodic_data_request())
except Exception as e:
_LOGGER.error(
f"Failed to start coordinator. MQTT may not be connected: {e}. "
"Please check your MQTT integration settings."
)
async def async_stop(self) -> None:
"""停止协调器:取消定时任务."""
@@ -350,7 +357,9 @@ class JackeryDataCoordinator:
)
except Exception as mqtt_error:
_LOGGER.warning(
f"MQTT not ready: {mqtt_error}. Will retry in {REQUEST_INTERVAL} seconds..."
f"MQTT publish failed: {mqtt_error}. "
f"Please check MQTT broker connection. "
f"Will retry in {REQUEST_INTERVAL} seconds..."
)
await asyncio.sleep(REQUEST_INTERVAL)

View File

@@ -3,22 +3,20 @@
"step": {
"user": {
"title": "配置 JackeryHome",
"description": "设置 MQTT 连接参数以接收能源监控数据",
"description": "设置您的 JackeryHome 能源监控集成。注意:必须先配置 MQTT 集成。",
"data": {
"topic_prefix": "MQTT 主题前缀",
"mqtt_broker": "MQTT Broker 地址",
"mqtt_port": "MQTT 端口"
"topic_prefix": "MQTT 主题前缀"
}
}
},
"error": {
"already_configured": "该集成已配置",
"mqtt_broker_required": "MQTT Broker 地址不能为空",
"invalid_port": "端口号必须在 1-65535 范围内"
"mqtt_not_configured": "MQTT 集成未配置或不可用。请先设置 MQTT 集成:设置 -> 设备与服务 -> 添加集成 -> MQTT",
"single_instance_allowed": "只允许一个此集成的实例"
},
"abort": {
"already_configured": "该集成已配置",
"single_instance_allowed": "该集成已配置"
"single_instance_allowed": "只允许一个此集成的实例"
}
}
}

View File

@@ -3,21 +3,20 @@
"step": {
"user": {
"title": "配置 JackeryHome",
"description": "设置 MQTT 连接参数以接收能源监控数据",
"description": "设置您的 JackeryHome 能源监控集成。注意:必须先配置 MQTT 集成。",
"data": {
"topic_prefix": "MQTT 主题前缀",
"mqtt_broker": "MQTT Broker 地址",
"mqtt_port": "MQTT 端口"
"topic_prefix": "MQTT 主题前缀"
}
}
},
"error": {
"already_configured": "该集成已配置",
"mqtt_broker_required": "MQTT Broker 地址不能为空",
"invalid_port": "端口号必须在 1-65535 范围内"
"mqtt_not_configured": "MQTT 集成未配置或不可用。请先设置 MQTT 集成:设置 -> 设备与服务 -> 添加集成 -> MQTT",
"single_instance_allowed": "只允许一个此集成的实例"
},
"abort": {
"already_configured": "该集成已配置"
"already_configured": "该集成已配置",
"single_instance_allowed": "只允许一个此集成的实例"
}
}
}