feat: add device by homeid

This commit is contained in:
sususweet
2025-09-30 15:06:27 +08:00
parent bbf4d168e7
commit 8b93c58654
6 changed files with 111 additions and 14 deletions

View File

@@ -41,7 +41,8 @@ from .const import (
CONF_SN8,
CONF_SN,
CONF_MODEL_NUMBER,
CONF_SERVERS, STORAGE_PATH, CONF_MANUFACTURER_CODE
CONF_SERVERS, STORAGE_PATH, CONF_MANUFACTURER_CODE,
CONF_SELECTED_HOMES
)
# 账号型:登录云端、获取设备列表,并为每台设备建立协调器(无本地控制)
from .const import CONF_PASSWORD as CONF_PASSWORD_KEY, CONF_SERVER as CONF_SERVER_KEY
@@ -169,7 +170,26 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry):
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN].setdefault("accounts", {})
bucket = {"device_list": {}, "coordinator_map": {}}
# 获取用户选择的家庭ID列表
selected_homes = config_entry.data.get(CONF_SELECTED_HOMES, [])
MideaLogger.debug(f"Selected homes from config: {selected_homes}")
MideaLogger.debug(f"Available homes keys: {list(homes.keys())}")
if not selected_homes:
# 如果没有选择,默认使用所有家庭
home_ids = list(homes.keys())
else:
# 只处理用户选择的家庭,确保类型匹配
home_ids = []
for selected_home in selected_homes:
# 尝试匹配字符串和数字类型的home_id
if selected_home in homes:
home_ids.append(selected_home)
elif str(selected_home) in homes:
home_ids.append(str(selected_home))
elif int(selected_home) in homes:
home_ids.append(int(selected_home))
MideaLogger.debug(f"Final home_ids to process: {home_ids}")
for home_id in home_ids:
appliances = await cloud.list_appliances(home_id)

View File

@@ -8,11 +8,14 @@ from homeassistant.core import callback
from homeassistant.const import (
CONF_TYPE,
)
import homeassistant.helpers.config_validation as cv
from .const import (
CONF_ACCOUNT,
CONF_PASSWORD,
DOMAIN,
CONF_SERVER, CONF_SERVERS
CONF_SERVER, CONF_SERVERS,
CONF_HOMES,
CONF_SELECTED_HOMES
)
from .core.cloud import get_midea_cloud
@@ -20,6 +23,8 @@ _LOGGER = logging.getLogger(__name__)
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
_session = None
_cloud = None
_homes = None
@staticmethod
@callback
@@ -41,15 +46,19 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
if await cloud.login():
await self.async_set_unique_id(user_input[CONF_ACCOUNT])
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=user_input[CONF_ACCOUNT],
data={
CONF_TYPE: CONF_ACCOUNT,
CONF_ACCOUNT: user_input[CONF_ACCOUNT],
CONF_PASSWORD: user_input[CONF_PASSWORD],
CONF_SERVER: user_input[CONF_SERVER]
},
)
# 保存云实例和用户输入,用于后续步骤
self._cloud = cloud
self._user_input = user_input
# 获取家庭列表
homes = await cloud.list_home()
if homes and len(homes) > 0:
_LOGGER.debug(f"Found homes: {homes}")
self._homes = homes
return await self.async_step_select_homes()
else:
errors["base"] = "no_homes"
else:
errors["base"] = "login_failed"
except Exception as e:
@@ -65,6 +74,55 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
errors=errors,
)
async def async_step_select_homes(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult:
"""家庭选择步骤"""
errors: dict[str, str] = {}
if user_input is not None:
selected_homes = user_input.get(CONF_SELECTED_HOMES, [])
if not selected_homes:
errors["base"] = "no_homes_selected"
else:
# 创建配置条目
return self.async_create_entry(
title=self._user_input[CONF_ACCOUNT],
data={
CONF_TYPE: CONF_ACCOUNT,
CONF_ACCOUNT: self._user_input[CONF_ACCOUNT],
CONF_PASSWORD: self._user_input[CONF_PASSWORD],
CONF_SERVER: self._user_input[CONF_SERVER],
CONF_SELECTED_HOMES: selected_homes
},
)
# 构建家庭选择选项
home_options = {}
for home_id, home_info in self._homes.items():
_LOGGER.debug(f"Processing home_id: {home_id}, home_info: {home_info}, type: {type(home_info)}")
# 确保home_id是字符串因为multi_select需要字符串键
home_id_str = str(home_id)
if isinstance(home_info, dict):
home_name = home_info.get("name", f"家庭 {home_id}")
else:
# 如果home_info是字符串直接使用
home_name = str(home_info) if home_info else f"家庭 {home_id}"
home_options[home_id_str] = home_name
# 默认全选
default_selected = list(home_options.keys())
_LOGGER.debug(f"Home options: {home_options}")
_LOGGER.debug(f"Default selected: {default_selected}")
return self.async_show_form(
step_id="select_homes",
data_schema=vol.Schema({
vol.Required(CONF_SELECTED_HOMES, default=default_selected): vol.All(
cv.multi_select(home_options)
)
}),
errors=errors,
)
class OptionsFlowHandler(config_entries.OptionsFlow):
def __init__(self, config_entry: config_entries.ConfigEntry):

View File

@@ -19,3 +19,5 @@ CONF_SERVERS = {
1: "MSmartHome",
2: "美的美居",
}
CONF_HOMES = "homes"
CONF_SELECTED_HOMES = "selected_homes"

View File

@@ -162,7 +162,6 @@ class MideaEntity(CoordinatorEntity[MideaDataUpdateCoordinator], Entity):
"""Set boolean attribute via coordinator, no-op if key is None."""
if attribute_key is None:
return
MideaLogger.error(f"self._rationale: {self._rationale}, {int(turn_on)}")
await self.async_set_attribute(attribute_key, self._rationale[int(turn_on)])
def _list_get_selected(self, key_of_list: list, rationale: Rationale = Rationale.EQUALLY):

View File

@@ -2,6 +2,8 @@
"config": {
"error": {
"no_home": "No available home",
"no_homes": "No available homes",
"no_homes_selected": "Please select at least one home",
"account_invalid": "Failed to authenticate on Midea cloud, the password may be changed",
"invalid_input": "Illegal input, IP address or 'auto' needed",
"login_failed": "Failed to login, wrong account or password",
@@ -38,6 +40,13 @@
"data": {
"ip_address": "IP address('auto' for discovery automatic)"
}
},
"select_homes": {
"title": "Select Homes",
"description": "Select the homes to add devices from, all selected by default",
"data": {
"selected_homes": "Select Homes"
}
}
}
},

View File

@@ -2,6 +2,8 @@
"config": {
"error": {
"no_home": "未找到可用家庭",
"no_homes": "未找到可用家庭",
"no_homes_selected": "请至少选择一个家庭",
"account_invalid": "登录美的云服务器失败,是否已修改过密码",
"invalid_input": "无效的输入请输入有效IP地址或auto",
"login_failed": "无法登录到选择的美的云服务器,请检查用户名或密码",
@@ -38,6 +40,13 @@
"data": {
"ip_address": "设备地址(输入auto自动搜索设备)"
}
},
"select_homes": {
"title": "选择家庭",
"description": "选择要添加设备的家庭,默认全选",
"data": {
"selected_homes": "选择家庭"
}
}
}
},