Skip to content

Commit 20ae52e

Browse files
committed
update for new hass, increase bt range
1 parent efb9eca commit 20ae52e

File tree

6 files changed

+20
-86
lines changed

6 files changed

+20
-86
lines changed

custom_components/lelight/__init__.py

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,15 @@
1-
from __future__ import annotations
21
from homeassistant.config_entries import ConfigEntry
32
from homeassistant.core import HomeAssistant
43

54
from .const import DOMAIN
65
from .light import LeLight
7-
import logging
86

9-
_LOGGER = logging.getLogger(__name__)
10-
# Перечисляем типы устройств, которое поддерживает интеграция
117
PLATFORMS: list[str] = ["light"]
128

139

1410
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
15-
# Создаем объект с подключением к сервису
16-
17-
# host = hass.data[DOMAIN][config_entry.entry_id]
18-
#
19-
# sst1 = sst.SST(hass, entry.data["username"], entry.data["password"])
2011
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = LeLight(entry.data["host"])
21-
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
12+
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
2213
return True
2314

2415

custom_components/lelight/config_flow.py

Lines changed: 4 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,20 @@
1-
"""Config flow for Hello World integration."""
2-
from __future__ import annotations
3-
4-
import logging
1+
from logging import getLogger
52
from typing import Any
63

74
import voluptuous as vol
8-
95
from homeassistant import config_entries, exceptions
106
from homeassistant.core import HomeAssistant
117

128
from .const import DOMAIN
139

14-
logger = logging.getLogger("lelight")
10+
logger = getLogger(DOMAIN)
1511

16-
# This is the schema that used to display the UI to the user. This simple
17-
# schema has a single required host field, but it could include a number of fields
18-
# such as username, password etc. See other components in the HA core code for
19-
# further examples.
20-
# Note the input displayed to the user will be translated. See the
21-
# translations/<lang>.json file and strings.json. See here for further information:
22-
# https://developers.home-assistant.io/docs/config_entries_config_flow_handler/#translations
23-
# At the time of writing I found the translations created by the scaffold didn't
24-
# quite work as documented and always gave me the "Lokalise key references" string
25-
# (in square brackets), rather than the actual translated value. I did not attempt to
26-
# figure this out or look further into it.
2712
DATA_SCHEMA = vol.Schema({"host": str})
2813

2914

3015
async def validate_input(hass: HomeAssistant, data: dict) -> dict[str, Any]:
31-
"""Validate the user input allows us to connect.
32-
Data has the keys from DATA_SCHEMA with values provided by the user.
33-
"""
34-
# Validate the data can be used to set up a connection.
35-
36-
# This is a simple example to show an error in the UI for a short hostname
37-
# The exceptions are defined at the end of this file, and are used in the
38-
# `async_step_user` method below.
39-
if len(data["host"]) < 3:
40-
raise InvalidHost
16+
if len(data["host"].strip()) != 8:
17+
raise InvalidHost("Host name must be 8 characters long")
4118

4219
return {"title": data["host"].strip()}
4320

@@ -46,37 +23,22 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
4623
"""Handle a config flow for Hello World."""
4724

4825
VERSION = 1
49-
# Pick one of the available connection classes in homeassistant/config_entries.py
50-
# This tells HA if it should be asking for updates, or it'll be notified of updates
51-
# automatically. This example uses PUSH, as the dummy hub will notify HA of
52-
# changes.
5326
CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_PUSH
5427

5528
async def async_step_user(self, user_input=None):
5629
"""Handle the initial step."""
57-
# This goes through the steps to take the user through the setup process.
58-
# Using this it is possible to update the UI and prompt for additional
59-
# information. This example provides a single form (built from `DATA_SCHEMA`),
60-
# and when that has some validated input, it calls `async_create_entry` to
61-
# actually create the HA config entry. Note the "title" value is returned by
62-
# `validate_input` above.
6330
errors = {}
6431
if user_input is not None:
6532
try:
6633
info = await validate_input(self.hass, user_input)
6734

6835
return self.async_create_entry(title=info["title"], data=user_input)
6936
except InvalidHost:
70-
# The error string is set here, and should be translated.
71-
# This example does not currently cover translations, see the
72-
# comments on `DATA_SCHEMA` for further details.
73-
# Set the error on the `host` field, not the entire form.
7437
errors["host"] = "cannot_connect"
7538
except Exception: # pylint: disable=broad-except
7639
logger.exception("Unexpected exception")
7740
errors["base"] = "unknown"
7841

79-
# If there is no user input or there were errors, show the form again, including any errors that were found with the input.
8042
return self.async_show_form(
8143
step_id="user", data_schema=DATA_SCHEMA, errors=errors
8244
)

custom_components/lelight/connector_bless.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,18 @@
77
from bless.backends.bluezdbus.server import BlessServerBlueZDBus
88
from dbus_next import Variant
99

10+
from .const import DOMAIN
1011
from .connector import BtBackend
1112
from .encoder import Message
1213

13-
logger = getLogger("lelight")
14+
logger = getLogger(DOMAIN)
1415

1516

1617
class BlessServer(BlessServerBlueZDBus):
1718
async def setup(self):
1819
await super().setup()
1920
self.adv = BlueZLEAdvertisement(Type.BROADCAST, 1, self.app)
20-
self.adv._tx_power = -35
21+
self.adv._tx_power = 35
2122

2223
self.app.advertisements = [self.adv]
2324
self.bus.export(self.adv.path, self.adv)

custom_components/lelight/light.py

Lines changed: 9 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,20 @@
1-
"""Platform for light integration."""
2-
from __future__ import annotations
3-
4-
import logging
1+
from logging import getLogger
52
from typing import Any
63

74
from homeassistant.components.light import (
85
ATTR_BRIGHTNESS,
9-
ATTR_COLOR_TEMP,
6+
ATTR_COLOR_TEMP_KELVIN,
107
LightEntity,
118
ColorMode,
129
)
1310
from homeassistant.helpers.entity import DeviceInfo
14-
from homeassistant.util.color import (
15-
color_temperature_mired_to_kelvin,
16-
color_temperature_kelvin_to_mired,
17-
)
1811

1912
from .connector import App
2013
from .connector_bless import BlessBackend
2114
from .const import DOMAIN
2215
from .encoder import Commands
2316

24-
logger = logging.getLogger("lelight")
17+
logger = getLogger(DOMAIN)
2518

2619

2720
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:
3629

3730

3831
class LeLight(LightEntity):
39-
min_mireds = color_temperature_kelvin_to_mired(6400)
40-
max_mireds = color_temperature_kelvin_to_mired(3000)
32+
min_color_temp_kelvin = 3000
33+
max_color_temp_kelvin = 6400
4134

4235
_attr_unique_id = "lelight_light"
4336

@@ -68,8 +61,8 @@ def brightness(self):
6861
return normalize_value(self._brightness, 1000, 255)
6962

7063
@property
71-
def color_temp(self) -> int | None:
72-
return color_temperature_kelvin_to_mired(self._temp)
64+
def color_temp_kelvin(self) -> int | None:
65+
return self._temp
7366

7467
@property
7568
def color_mode(self) -> ColorMode | None:
@@ -78,26 +71,18 @@ def color_mode(self) -> ColorMode | None:
7871
def turn_on(self, **kwargs: Any) -> None:
7972
if not self._state:
8073
self.app.send(Commands.turn_on())
81-
# resp = requests.post(f"{self._host}/lamp?command=turn_on").json()
8274
logger.debug(f"lamp turn_on: {kwargs}")
8375
self._state = True
8476
if ATTR_BRIGHTNESS in kwargs:
8577
self._brightness = normalize_value(kwargs[ATTR_BRIGHTNESS], 255, 1000)
86-
# resp = requests.post(
87-
# f"{self._host}/lamp?command=bright&value={self._brightness}"
88-
# ).json()
8978
# logger.info(f"lamp bright: {resp}")
9079
self.app.send(Commands.bright(self._brightness))
91-
if ATTR_COLOR_TEMP in kwargs:
92-
self._temp = color_temperature_mired_to_kelvin(kwargs[ATTR_COLOR_TEMP])
93-
# resp = requests.post(
94-
# f"{self._host}/lamp?command=temp&value={self._temp}"
95-
# ).json()
80+
if ATTR_COLOR_TEMP_KELVIN in kwargs:
81+
self._temp = kwargs[ATTR_COLOR_TEMP_KELVIN]
9682
# logger.info(f"lamp temp: {resp}")
9783
self.app.send(Commands.temp(self._temp))
9884

9985
def turn_off(self, **kwargs: Any) -> None:
100-
# resp = requests.post(f"{self._host}/lamp?command=turn_off").json()
10186
# logger.info(f"lamp turn_off: {resp}")
10287
self.app.send(Commands.turn_off())
10388
self._state = False
@@ -108,11 +93,6 @@ def update(self) -> None:
10893
This is the only method that should fetch new data for Home Assistant.
10994
"""
11095
pass
111-
# data = requests.get(f"{self._host}/lamp").json()
112-
# logger.info(f"lamp update: {data}")
113-
# self._state = data["is_on"]
114-
# self._brightness = data["brightness"]
115-
# self._temp = data["temp"]
11696

11797
@property
11898
def is_on(self) -> bool:

custom_components/lelight/manifest.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,11 @@
88
"@v1ack"
99
],
1010
"requirements": [
11-
"bless==0.2.4",
11+
"bless==0.2.5",
1212
"dbus-next==0.2.3"
1313
],
1414
"iot_class": "local_push",
15-
"version": "0.1.1",
15+
"version": "0.2.0",
1616
"config_flow": true,
1717
"loggers": [
1818
"lelight"

hacs.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
2-
"homeassistant": "2022.6.0",
2+
"homeassistant": "2023.2.0",
33
"name": "lelight",
44
"render_readme": true
55
}

0 commit comments

Comments
 (0)