1+ """Utilities for auto discovery of light models."""
2+
3+ from __future__ import annotations
4+ from collections import namedtuple
5+
6+ import logging
7+ import os
8+ from typing import NamedTuple , Optional
9+
10+ from .const import (
11+ CONF_CUSTOM_MODEL_DIRECTORY ,
12+ CONF_MANUFACTURER ,
13+ CONF_MODEL ,
14+ )
15+
16+ from homeassistant .components .hue .const import DOMAIN as HUE_DOMAIN
17+ from homeassistant .components .light import Light
18+ import homeassistant .helpers .entity_registry as er
19+ from homeassistant .helpers .typing import (
20+ HomeAssistantType ,
21+ )
22+
23+ from .light_model import LightModel
24+
25+ _LOGGER = logging .getLogger (__name__ )
26+
27+ async def get_light_model (
28+ hass : HomeAssistantType , entity_entry , config : dict
29+ ) -> Optional [LightModel ]:
30+ manufacturer = config .get (CONF_MANUFACTURER )
31+ model = config .get (CONF_MODEL )
32+ if (manufacturer is None or model is None ) and entity_entry :
33+ hue_model_info = await autodiscover_hue_model (hass , entity_entry )
34+ if hue_model_info :
35+ manufacturer = hue_model_info .manufacturer
36+ model = hue_model_info .model
37+
38+ if manufacturer is None or model is None :
39+ return None
40+
41+ custom_model_directory = config .get (CONF_CUSTOM_MODEL_DIRECTORY )
42+ if custom_model_directory :
43+ custom_model_directory = os .path .join (
44+ hass .config .config_dir , custom_model_directory
45+ )
46+
47+ return LightModel (manufacturer , model , custom_model_directory )
48+
49+
50+ async def autodiscover_hue_model (hass : HomeAssistantType , entity_entry ) -> Optional [HueModelInfo ]:
51+ # When Philips Hue model is enabled we can auto discover manufacturer and model from the bridge data
52+ if hass .data .get (HUE_DOMAIN ) is None or entity_entry .platform != "hue" :
53+ return
54+
55+ light = await find_hue_light (hass , entity_entry )
56+ if light is None :
57+ _LOGGER .error (
58+ "Cannot autodiscover model for '%s', not found in the hue bridge api" ,
59+ entity_entry .entity_id ,
60+ )
61+ return
62+
63+ _LOGGER .debug (
64+ "Auto discovered Hue model for entity %s: (manufacturer=%s, model=%s)" ,
65+ entity_entry .entity_id ,
66+ light .manufacturername ,
67+ light .modelid ,
68+ )
69+
70+ return HueModelInfo (light .manufacturername , light .modelid )
71+
72+ async def find_hue_light (
73+ hass : HomeAssistantType , entity_entry : er .RegistryEntry
74+ ) -> Light | None :
75+ """Find the light in the Hue bridge, we need to extract the model id."""
76+
77+ bridge = hass .data [HUE_DOMAIN ][entity_entry .config_entry_id ]
78+ lights = bridge .api .lights
79+ for light_id in lights :
80+ light = bridge .api .lights [light_id ]
81+ if light .uniqueid == entity_entry .unique_id :
82+ return light
83+
84+ return None
85+
86+ class HueModelInfo (NamedTuple ):
87+ manufacturer : str
88+ model : str
0 commit comments