Home Assistant Unofficial Reference 2024.12.1
scene.py
Go to the documentation of this file.
1 """Support for LIFX Cloud scenes."""
2 
3 from __future__ import annotations
4 
5 import asyncio
6 from http import HTTPStatus
7 import logging
8 from typing import Any
9 
10 import aiohttp
11 from aiohttp.hdrs import AUTHORIZATION
12 import voluptuous as vol
13 
14 from homeassistant.components.scene import Scene
15 from homeassistant.const import CONF_PLATFORM, CONF_TIMEOUT, CONF_TOKEN
16 from homeassistant.core import HomeAssistant
17 from homeassistant.helpers.aiohttp_client import async_get_clientsession
19 from homeassistant.helpers.entity_platform import AddEntitiesCallback
20 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
21 
22 _LOGGER = logging.getLogger(__name__)
23 
24 DEFAULT_TIMEOUT = 10
25 
26 PLATFORM_SCHEMA = vol.Schema(
27  {
28  vol.Required(CONF_PLATFORM): "lifx_cloud",
29  vol.Required(CONF_TOKEN): cv.string,
30  vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int,
31  }
32 )
33 
34 
36  hass: HomeAssistant,
37  config: ConfigType,
38  async_add_entities: AddEntitiesCallback,
39  discovery_info: DiscoveryInfoType | None = None,
40 ) -> None:
41  """Set up the scenes stored in the LIFX Cloud."""
42  token = config.get(CONF_TOKEN)
43  timeout = config.get(CONF_TIMEOUT)
44 
45  headers: dict[str, str] = {AUTHORIZATION: f"Bearer {token}"}
46 
47  url = "https://api.lifx.com/v1/scenes"
48 
49  try:
50  httpsession = async_get_clientsession(hass)
51  async with asyncio.timeout(timeout):
52  scenes_resp = await httpsession.get(url, headers=headers)
53 
54  except (TimeoutError, aiohttp.ClientError):
55  _LOGGER.exception("Error on %s", url)
56  return
57 
58  status = scenes_resp.status
59  if status == HTTPStatus.OK:
60  data = await scenes_resp.json()
61  devices = [LifxCloudScene(hass, headers, timeout, scene) for scene in data]
62  async_add_entities(devices)
63  return
64  if status == HTTPStatus.UNAUTHORIZED:
65  _LOGGER.error("Unauthorized (bad token?) on %s", url)
66  return
67 
68  _LOGGER.error("HTTP error %d on %s", scenes_resp.status, url)
69 
70 
72  """Representation of a LIFX Cloud scene."""
73 
74  def __init__(self, hass, headers, timeout, scene_data):
75  """Initialize the scene."""
76  self.hasshasshass = hass
77  self._headers_headers = headers
78  self._timeout_timeout = timeout
79  self._name_name = scene_data["name"]
80  self._uuid_uuid = scene_data["uuid"]
81 
82  @property
83  def name(self):
84  """Return the name of the scene."""
85  return self._name_name
86 
87  async def async_activate(self, **kwargs: Any) -> None:
88  """Activate the scene."""
89  url = f"https://api.lifx.com/v1/scenes/scene_id:{self._uuid}/activate"
90 
91  try:
92  httpsession = async_get_clientsession(self.hasshasshass)
93  async with asyncio.timeout(self._timeout_timeout):
94  await httpsession.put(url, headers=self._headers_headers)
95 
96  except (TimeoutError, aiohttp.ClientError):
97  _LOGGER.exception("Error on %s", url)
def __init__(self, hass, headers, timeout, scene_data)
Definition: scene.py:74
None async_setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback async_add_entities, DiscoveryInfoType|None discovery_info=None)
Definition: scene.py:40
aiohttp.ClientSession async_get_clientsession(HomeAssistant hass, bool verify_ssl=True, socket.AddressFamily family=socket.AF_UNSPEC, ssl_util.SSLCipherList ssl_cipher=ssl_util.SSLCipherList.PYTHON_DEFAULT)