|
4 | 4 |
|
5 | 5 | import asyncio |
6 | 6 | import logging |
| 7 | +from collections import defaultdict |
7 | 8 | from pathlib import Path |
8 | 9 | from typing import Any, Dict |
9 | 10 |
|
| 11 | +from homeassistant.components.homeassistant import exposed_entities |
10 | 12 | from homeassistant.core import HomeAssistant |
| 13 | +from homeassistant.helpers import area_registry as ar, entity_registry as er |
11 | 14 |
|
12 | 15 | _LOGGER = logging.getLogger(__name__) |
13 | 16 |
|
|
19 | 22 | CONFIG_FILES = [ |
20 | 23 | "base.yaml", |
21 | 24 | "lists.yaml", |
| 25 | + "auto_lists.yaml", |
22 | 26 | "expansion.yaml", |
23 | 27 | "intents.yaml", |
24 | 28 | "local_control.yaml", |
25 | 29 | ] |
26 | 30 |
|
| 31 | +DOMAIN_TO_LIST = { |
| 32 | + "light": "light_names", |
| 33 | + "climate": "climate_names", |
| 34 | + "fan": "fan_names", |
| 35 | + "media_player": "media_player_names", |
| 36 | + "cover": "cover_names", |
| 37 | + "switch": "switch_names", |
| 38 | + "vacuum": "vacuum_names", |
| 39 | + "camera": "camera_names", |
| 40 | + "lock": "lock_names", |
| 41 | + "valve": "valve_names", |
| 42 | + "sensor": "sensor_names", |
| 43 | + "device_tracker": "tracker_names", |
| 44 | +} |
| 45 | + |
| 46 | +AUTO_LISTS_PATH = Path(__file__).parent / "config" / "auto_lists.yaml" |
| 47 | + |
27 | 48 |
|
28 | 49 | def _get_fallback_config() -> dict[str, Any]: |
29 | 50 | """获取备用配置(仅当配置读取失败时使用).""" |
@@ -51,6 +72,102 @@ def _deep_merge(base: Dict, override: Dict) -> Dict: |
51 | 72 | return result |
52 | 73 |
|
53 | 74 |
|
| 75 | +def _normalize_list_value(value: str) -> str: |
| 76 | + """Normalize values for list deduplication.""" |
| 77 | + return " ".join(value.strip().split()).casefold() |
| 78 | + |
| 79 | + |
| 80 | +def _append_unique_value(target: list[str], seen: set[str], value: str | None) -> None: |
| 81 | + """Append value if non-empty and unique.""" |
| 82 | + if not value: |
| 83 | + return |
| 84 | + |
| 85 | + value = value.strip() |
| 86 | + if not value: |
| 87 | + return |
| 88 | + |
| 89 | + normalized = _normalize_list_value(value) |
| 90 | + if normalized in seen: |
| 91 | + return |
| 92 | + |
| 93 | + seen.add(normalized) |
| 94 | + target.append(value) |
| 95 | + |
| 96 | + |
| 97 | +def _build_auto_lists_config(hass: HomeAssistant) -> dict[str, Any]: |
| 98 | + """Build auto-generated lists from HA areas and entities.""" |
| 99 | + area_reg = ar.async_get(hass) |
| 100 | + entity_reg = er.async_get(hass) |
| 101 | + |
| 102 | + lists: dict[str, list[str]] = defaultdict(list) |
| 103 | + seen: dict[str, set[str]] = defaultdict(set) |
| 104 | + |
| 105 | + for area in area_reg.areas.values(): |
| 106 | + _append_unique_value(lists["area_names"], seen["area_names"], area.name) |
| 107 | + |
| 108 | + for entity_id in hass.states.async_entity_ids(): |
| 109 | + state = hass.states.get(entity_id) |
| 110 | + if state is None: |
| 111 | + continue |
| 112 | + |
| 113 | + if not exposed_entities.async_should_expose(hass, "conversation", entity_id): |
| 114 | + continue |
| 115 | + |
| 116 | + domain = entity_id.split(".", 1)[0] |
| 117 | + list_name = DOMAIN_TO_LIST.get(domain) |
| 118 | + if list_name is None: |
| 119 | + continue |
| 120 | + |
| 121 | + _append_unique_value(lists[list_name], seen[list_name], state.name) |
| 122 | + |
| 123 | + registry_entry = entity_reg.async_get(entity_id) |
| 124 | + if registry_entry is not None: |
| 125 | + _append_unique_value(lists[list_name], seen[list_name], registry_entry.original_name) |
| 126 | + _append_unique_value(lists[list_name], seen[list_name], registry_entry.name) |
| 127 | + |
| 128 | + return { |
| 129 | + "lists": { |
| 130 | + key: {"values": values} |
| 131 | + for key, values in sorted(lists.items()) |
| 132 | + if values |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + |
| 137 | +def _sync_auto_lists_config_sync(hass: HomeAssistant) -> bool: |
| 138 | + """Write auto-generated list config if content changed.""" |
| 139 | + import yaml # type: ignore[import] |
| 140 | + |
| 141 | + data = _build_auto_lists_config(hass) |
| 142 | + serialized = ( |
| 143 | + "# This file is auto-generated by AI Hub.\n" |
| 144 | + "# It supplements lists.yaml with Home Assistant areas and entity names.\n" |
| 145 | + "# Manual edits may be overwritten.\n\n" |
| 146 | + + yaml.safe_dump(data, allow_unicode=True, sort_keys=False) |
| 147 | + ) |
| 148 | + |
| 149 | + if AUTO_LISTS_PATH.exists(): |
| 150 | + current = AUTO_LISTS_PATH.read_text(encoding="utf-8") |
| 151 | + if current == serialized: |
| 152 | + return False |
| 153 | + |
| 154 | + AUTO_LISTS_PATH.parent.mkdir(parents=True, exist_ok=True) |
| 155 | + AUTO_LISTS_PATH.write_text(serialized, encoding="utf-8") |
| 156 | + return True |
| 157 | + |
| 158 | + |
| 159 | +async def async_sync_intent_lists(hass: HomeAssistant) -> bool: |
| 160 | + """Sync HA areas and entity names into auto-generated lists.yaml overlay.""" |
| 161 | + global _INTENTS_CONFIG, _CONFIG_LOADED |
| 162 | + |
| 163 | + changed = await hass.async_add_executor_job(_sync_auto_lists_config_sync, hass) |
| 164 | + if changed: |
| 165 | + _INTENTS_CONFIG = None |
| 166 | + _CONFIG_LOADED = False |
| 167 | + _LOGGER.debug("Auto intent lists updated from Home Assistant registry") |
| 168 | + return changed |
| 169 | + |
| 170 | + |
54 | 171 | def _load_intents_config_sync() -> dict[str, Any]: |
55 | 172 | """同步加载配置 - 支持多文件合并.""" |
56 | 173 | import yaml # type: ignore[import] |
|
0 commit comments