Skip to content

Commit

Permalink
update for new hass, increase bt range
Browse files Browse the repository at this point in the history
  • Loading branch information
v1ack committed Mar 8, 2023
1 parent efb9eca commit 20ae52e
Show file tree
Hide file tree
Showing 6 changed files with 20 additions and 86 deletions.
11 changes: 1 addition & 10 deletions custom_components/lelight/__init__.py
Original file line number Diff line number Diff line change
@@ -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


Expand Down
46 changes: 4 additions & 42 deletions custom_components/lelight/config_flow.py
Original file line number Diff line number Diff line change
@@ -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/<lang>.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()}

Expand All @@ -46,37 +23,22 @@ 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:
info = await validate_input(self.hass, user_input)

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
)
Expand Down
5 changes: 3 additions & 2 deletions custom_components/lelight/connector_bless.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
38 changes: 9 additions & 29 deletions custom_components/lelight/light.py
Original file line number Diff line number Diff line change
@@ -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):
Expand All @@ -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"

Expand Down Expand Up @@ -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:
Expand All @@ -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
Expand All @@ -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:
Expand Down
4 changes: 2 additions & 2 deletions custom_components/lelight/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
2 changes: 1 addition & 1 deletion hacs.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"homeassistant": "2022.6.0",
"homeassistant": "2023.2.0",
"name": "lelight",
"render_readme": true
}

0 comments on commit 20ae52e

Please sign in to comment.