From 20ae52ee423f1c0533621c4d40ae2372de2ef540 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9A=D0=B8=D1=80=D0=B8=D0=BB=D0=BA=D0=B8=D0=BD=20=D0=92?= =?UTF-8?q?=D0=BB=D0=B0=D0=B4=D0=B8=D0=BC=D0=B8=D1=80=20=D0=90=D0=BB=D0=B5?= =?UTF-8?q?=D0=BA=D1=81=D0=B5=D0=B5=D0=B2=D0=B8=D1=87?= Date: Wed, 8 Mar 2023 12:19:55 +0300 Subject: [PATCH] update for new hass, increase bt range --- custom_components/lelight/__init__.py | 11 +---- custom_components/lelight/config_flow.py | 46 ++------------------ custom_components/lelight/connector_bless.py | 5 ++- custom_components/lelight/light.py | 38 ++++------------ custom_components/lelight/manifest.json | 4 +- hacs.json | 2 +- 6 files changed, 20 insertions(+), 86 deletions(-) diff --git a/custom_components/lelight/__init__.py b/custom_components/lelight/__init__.py index dbaf88f..7b980ca 100644 --- a/custom_components/lelight/__init__.py +++ b/custom_components/lelight/__init__.py @@ -1,24 +1,15 @@ -from __future__ import annotations from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from .const import DOMAIN from .light import LeLight -import logging -_LOGGER = logging.getLogger(__name__) -# Перечисляем типы устройств, которое поддерживает интеграция PLATFORMS: list[str] = ["light"] async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: - # Создаем объект с подключением к сервису - - # host = hass.data[DOMAIN][config_entry.entry_id] - # - # sst1 = sst.SST(hass, entry.data["username"], entry.data["password"]) hass.data.setdefault(DOMAIN, {})[entry.entry_id] = LeLight(entry.data["host"]) - hass.config_entries.async_setup_platforms(entry, PLATFORMS) + await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) return True diff --git a/custom_components/lelight/config_flow.py b/custom_components/lelight/config_flow.py index a6e5c41..949d14e 100644 --- a/custom_components/lelight/config_flow.py +++ b/custom_components/lelight/config_flow.py @@ -1,43 +1,20 @@ -"""Config flow for Hello World integration.""" -from __future__ import annotations - -import logging +from logging import getLogger from typing import Any import voluptuous as vol - from homeassistant import config_entries, exceptions from homeassistant.core import HomeAssistant from .const import DOMAIN -logger = logging.getLogger("lelight") +logger = getLogger(DOMAIN) -# This is the schema that used to display the UI to the user. This simple -# schema has a single required host field, but it could include a number of fields -# such as username, password etc. See other components in the HA core code for -# further examples. -# Note the input displayed to the user will be translated. See the -# translations/.json file and strings.json. See here for further information: -# https://developers.home-assistant.io/docs/config_entries_config_flow_handler/#translations -# At the time of writing I found the translations created by the scaffold didn't -# quite work as documented and always gave me the "Lokalise key references" string -# (in square brackets), rather than the actual translated value. I did not attempt to -# figure this out or look further into it. DATA_SCHEMA = vol.Schema({"host": str}) async def validate_input(hass: HomeAssistant, data: dict) -> dict[str, Any]: - """Validate the user input allows us to connect. - Data has the keys from DATA_SCHEMA with values provided by the user. - """ - # Validate the data can be used to set up a connection. - - # This is a simple example to show an error in the UI for a short hostname - # The exceptions are defined at the end of this file, and are used in the - # `async_step_user` method below. - if len(data["host"]) < 3: - raise InvalidHost + if len(data["host"].strip()) != 8: + raise InvalidHost("Host name must be 8 characters long") return {"title": data["host"].strip()} @@ -46,20 +23,10 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Handle a config flow for Hello World.""" VERSION = 1 - # Pick one of the available connection classes in homeassistant/config_entries.py - # This tells HA if it should be asking for updates, or it'll be notified of updates - # automatically. This example uses PUSH, as the dummy hub will notify HA of - # changes. CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_PUSH async def async_step_user(self, user_input=None): """Handle the initial step.""" - # This goes through the steps to take the user through the setup process. - # Using this it is possible to update the UI and prompt for additional - # information. This example provides a single form (built from `DATA_SCHEMA`), - # and when that has some validated input, it calls `async_create_entry` to - # actually create the HA config entry. Note the "title" value is returned by - # `validate_input` above. errors = {} if user_input is not None: try: @@ -67,16 +34,11 @@ async def async_step_user(self, user_input=None): return self.async_create_entry(title=info["title"], data=user_input) except InvalidHost: - # The error string is set here, and should be translated. - # This example does not currently cover translations, see the - # comments on `DATA_SCHEMA` for further details. - # Set the error on the `host` field, not the entire form. errors["host"] = "cannot_connect" except Exception: # pylint: disable=broad-except logger.exception("Unexpected exception") errors["base"] = "unknown" - # If there is no user input or there were errors, show the form again, including any errors that were found with the input. return self.async_show_form( step_id="user", data_schema=DATA_SCHEMA, errors=errors ) diff --git a/custom_components/lelight/connector_bless.py b/custom_components/lelight/connector_bless.py index b847932..7e1a1af 100644 --- a/custom_components/lelight/connector_bless.py +++ b/custom_components/lelight/connector_bless.py @@ -7,17 +7,18 @@ from bless.backends.bluezdbus.server import BlessServerBlueZDBus from dbus_next import Variant +from .const import DOMAIN from .connector import BtBackend from .encoder import Message -logger = getLogger("lelight") +logger = getLogger(DOMAIN) class BlessServer(BlessServerBlueZDBus): async def setup(self): await super().setup() self.adv = BlueZLEAdvertisement(Type.BROADCAST, 1, self.app) - self.adv._tx_power = -35 + self.adv._tx_power = 35 self.app.advertisements = [self.adv] self.bus.export(self.adv.path, self.adv) diff --git a/custom_components/lelight/light.py b/custom_components/lelight/light.py index 696b4ce..9d7a3ed 100644 --- a/custom_components/lelight/light.py +++ b/custom_components/lelight/light.py @@ -1,27 +1,20 @@ -"""Platform for light integration.""" -from __future__ import annotations - -import logging +from logging import getLogger from typing import Any from homeassistant.components.light import ( ATTR_BRIGHTNESS, - ATTR_COLOR_TEMP, + ATTR_COLOR_TEMP_KELVIN, LightEntity, ColorMode, ) from homeassistant.helpers.entity import DeviceInfo -from homeassistant.util.color import ( - color_temperature_mired_to_kelvin, - color_temperature_kelvin_to_mired, -) from .connector import App from .connector_bless import BlessBackend from .const import DOMAIN from .encoder import Commands -logger = logging.getLogger("lelight") +logger = getLogger(DOMAIN) async def async_setup_entry(hass, config_entry, async_add_entities): @@ -36,8 +29,8 @@ def normalize_value(value: int, max: int, new_max: int) -> int: class LeLight(LightEntity): - min_mireds = color_temperature_kelvin_to_mired(6400) - max_mireds = color_temperature_kelvin_to_mired(3000) + min_color_temp_kelvin = 3000 + max_color_temp_kelvin = 6400 _attr_unique_id = "lelight_light" @@ -68,8 +61,8 @@ def brightness(self): return normalize_value(self._brightness, 1000, 255) @property - def color_temp(self) -> int | None: - return color_temperature_kelvin_to_mired(self._temp) + def color_temp_kelvin(self) -> int | None: + return self._temp @property def color_mode(self) -> ColorMode | None: @@ -78,26 +71,18 @@ def color_mode(self) -> ColorMode | None: def turn_on(self, **kwargs: Any) -> None: if not self._state: self.app.send(Commands.turn_on()) - # resp = requests.post(f"{self._host}/lamp?command=turn_on").json() logger.debug(f"lamp turn_on: {kwargs}") self._state = True if ATTR_BRIGHTNESS in kwargs: self._brightness = normalize_value(kwargs[ATTR_BRIGHTNESS], 255, 1000) - # resp = requests.post( - # f"{self._host}/lamp?command=bright&value={self._brightness}" - # ).json() # logger.info(f"lamp bright: {resp}") self.app.send(Commands.bright(self._brightness)) - if ATTR_COLOR_TEMP in kwargs: - self._temp = color_temperature_mired_to_kelvin(kwargs[ATTR_COLOR_TEMP]) - # resp = requests.post( - # f"{self._host}/lamp?command=temp&value={self._temp}" - # ).json() + if ATTR_COLOR_TEMP_KELVIN in kwargs: + self._temp = kwargs[ATTR_COLOR_TEMP_KELVIN] # logger.info(f"lamp temp: {resp}") self.app.send(Commands.temp(self._temp)) def turn_off(self, **kwargs: Any) -> None: - # resp = requests.post(f"{self._host}/lamp?command=turn_off").json() # logger.info(f"lamp turn_off: {resp}") self.app.send(Commands.turn_off()) self._state = False @@ -108,11 +93,6 @@ def update(self) -> None: This is the only method that should fetch new data for Home Assistant. """ pass - # data = requests.get(f"{self._host}/lamp").json() - # logger.info(f"lamp update: {data}") - # self._state = data["is_on"] - # self._brightness = data["brightness"] - # self._temp = data["temp"] @property def is_on(self) -> bool: diff --git a/custom_components/lelight/manifest.json b/custom_components/lelight/manifest.json index 432bac2..2456d8a 100644 --- a/custom_components/lelight/manifest.json +++ b/custom_components/lelight/manifest.json @@ -8,11 +8,11 @@ "@v1ack" ], "requirements": [ - "bless==0.2.4", + "bless==0.2.5", "dbus-next==0.2.3" ], "iot_class": "local_push", - "version": "0.1.1", + "version": "0.2.0", "config_flow": true, "loggers": [ "lelight" diff --git a/hacs.json b/hacs.json index b1bc7c6..36f1a43 100644 --- a/hacs.json +++ b/hacs.json @@ -1,5 +1,5 @@ { - "homeassistant": "2022.6.0", + "homeassistant": "2023.2.0", "name": "lelight", "render_readme": true }