mirror of
https://github.com/andvikt/mega_hacs.git
synced 2025-12-12 01:24:29 +05:00
Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d0659b84dc | ||
|
|
3cd38a57e0 | ||
|
|
261c628909 | ||
|
|
2af9cfbeaf | ||
|
|
60fad1f20f | ||
|
|
5c18e395da | ||
|
|
082c647110 | ||
|
|
21bc277b78 | ||
|
|
00e62ee83f | ||
|
|
b62406210c |
@@ -1,5 +1,5 @@
|
||||
[bumpversion]
|
||||
current_version = 1.1.7
|
||||
current_version = 1.1.8b4
|
||||
parse = (?P<major>\d+)(\.(?P<minor>\d+))(\.(?P<patch>\d+))(?P<release>[bf]*)(?P<build>\d*)
|
||||
commit = True
|
||||
tag = True
|
||||
|
||||
@@ -1,25 +1,57 @@
|
||||
"""The mega integration."""
|
||||
import asyncio
|
||||
import logging
|
||||
import typing
|
||||
from functools import partial
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.const import (
|
||||
CONF_NAME, CONF_DOMAIN,
|
||||
CONF_UNIT_OF_MEASUREMENT, CONF_VALUE_TEMPLATE, CONF_DEVICE_CLASS, CONF_PORT
|
||||
CONF_NAME,
|
||||
CONF_DOMAIN,
|
||||
CONF_UNIT_OF_MEASUREMENT,
|
||||
CONF_VALUE_TEMPLATE,
|
||||
CONF_DEVICE_CLASS,
|
||||
CONF_PORT,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant, ServiceCall
|
||||
from homeassistant.helpers.service import bind_hass
|
||||
from homeassistant.helpers import config_validation as cv
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from .const import DOMAIN, CONF_INVERT, CONF_RELOAD, PLATFORMS, CONF_PORTS, CONF_CUSTOM, CONF_SKIP, CONF_PORT_TO_SCAN, \
|
||||
CONF_MQTT_INPUTS, CONF_HTTP, CONF_RESPONSE_TEMPLATE, CONF_ACTION, CONF_GET_VALUE, CONF_ALLOW_HOSTS, \
|
||||
CONF_CONV_TEMPLATE, CONF_ALL, CONF_FORCE_D, CONF_DEF_RESPONSE, CONF_FORCE_I2C_SCAN, CONF_HEX_TO_FLOAT, \
|
||||
RGB_COMBINATIONS, CONF_WS28XX, CONF_ORDER, CONF_SMOOTH, CONF_LED, CONF_WHITE_SEP, CONF_CHIP, CONF_RANGE, \
|
||||
CONF_FILTER_VALUES, CONF_FILTER_SCALE, CONF_FILTER_LOW, CONF_FILTER_HIGH, CONF_FILL_NA, CONF_MEGA_ID, CONF_ADDR, \
|
||||
CONF_1WBUS
|
||||
from .const import (
|
||||
DOMAIN,
|
||||
CONF_INVERT,
|
||||
PLATFORMS,
|
||||
CONF_PORTS,
|
||||
CONF_CUSTOM,
|
||||
CONF_SKIP,
|
||||
CONF_HTTP,
|
||||
CONF_RESPONSE_TEMPLATE,
|
||||
CONF_ACTION,
|
||||
CONF_GET_VALUE,
|
||||
CONF_ALLOW_HOSTS,
|
||||
CONF_CONV_TEMPLATE,
|
||||
CONF_ALL,
|
||||
CONF_FORCE_D,
|
||||
CONF_DEF_RESPONSE,
|
||||
CONF_FORCE_I2C_SCAN,
|
||||
CONF_HEX_TO_FLOAT,
|
||||
RGB_COMBINATIONS,
|
||||
CONF_WS28XX,
|
||||
CONF_ORDER,
|
||||
CONF_SMOOTH,
|
||||
CONF_LED,
|
||||
CONF_WHITE_SEP,
|
||||
CONF_CHIP,
|
||||
CONF_RANGE,
|
||||
CONF_FILTER_VALUES,
|
||||
CONF_FILTER_SCALE,
|
||||
CONF_FILTER_LOW,
|
||||
CONF_FILTER_HIGH,
|
||||
CONF_FILL_NA,
|
||||
CONF_MEGA_ID,
|
||||
CONF_ADDR,
|
||||
CONF_1WBUS,
|
||||
)
|
||||
from .hub import MegaD
|
||||
from .config_flow import ConfigFlow
|
||||
from .http import MegaView
|
||||
@@ -28,58 +60,53 @@ _LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_port_n = vol.Any(int, str)
|
||||
|
||||
LED_LIGHT = \
|
||||
{
|
||||
str: vol.Any(
|
||||
{
|
||||
vol.Required(CONF_PORTS): vol.Any(
|
||||
vol.ExactSequence([_port_n, _port_n, _port_n]),
|
||||
vol.ExactSequence([_port_n, _port_n, _port_n, _port_n]),
|
||||
msg='ports must be [R, G, B] or [R, G, B, W] of integers 0..255'
|
||||
),
|
||||
vol.Optional(CONF_NAME): str,
|
||||
vol.Optional(CONF_WHITE_SEP, default=True): bool,
|
||||
vol.Optional(CONF_SMOOTH, default=1): cv.time_period_seconds,
|
||||
},
|
||||
{
|
||||
vol.Required(CONF_PORT): int,
|
||||
vol.Required(CONF_WS28XX): True,
|
||||
vol.Optional(CONF_CHIP, default=100): int,
|
||||
vol.Optional(CONF_ORDER, default='rgb'): vol.Any(*RGB_COMBINATIONS, msg=f'order must be one of {RGB_COMBINATIONS}'),
|
||||
vol.Optional(CONF_SMOOTH, default=1): cv.time_period_seconds,
|
||||
vol.Optional(CONF_NAME): str,
|
||||
},
|
||||
)
|
||||
}
|
||||
LED_LIGHT = {
|
||||
str: vol.Any(
|
||||
{
|
||||
vol.Required(CONF_PORTS): vol.Any(
|
||||
vol.ExactSequence([_port_n, _port_n, _port_n]),
|
||||
vol.ExactSequence([_port_n, _port_n, _port_n, _port_n]),
|
||||
msg="ports must be [R, G, B] or [R, G, B, W] of integers 0..255",
|
||||
),
|
||||
vol.Optional(CONF_NAME): str,
|
||||
vol.Optional(CONF_WHITE_SEP, default=True): bool,
|
||||
vol.Optional(CONF_SMOOTH, default=1): cv.time_period_seconds,
|
||||
},
|
||||
{
|
||||
vol.Required(CONF_PORT): int,
|
||||
vol.Required(CONF_WS28XX): True,
|
||||
vol.Optional(CONF_CHIP, default=100): int,
|
||||
vol.Optional(CONF_ORDER, default="rgb"): vol.Any(
|
||||
*RGB_COMBINATIONS, msg=f"order must be one of {RGB_COMBINATIONS}"
|
||||
),
|
||||
vol.Optional(CONF_SMOOTH, default=1): cv.time_period_seconds,
|
||||
vol.Optional(CONF_NAME): str,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
CUSTOMIZE_PORT = {
|
||||
vol.Optional(CONF_SKIP, description='исключить порт из сканирования', default=False): bool,
|
||||
vol.Optional(CONF_FILL_NA, default='last'): vol.Any(
|
||||
'last',
|
||||
'none'
|
||||
),
|
||||
vol.Optional(CONF_RANGE, description='диапазон диммирования'): [
|
||||
vol.Optional(
|
||||
CONF_SKIP, description="исключить порт из сканирования", default=False
|
||||
): bool,
|
||||
vol.Optional(CONF_FILL_NA, default="last"): vol.Any("last", "none"),
|
||||
vol.Optional(CONF_RANGE, description="диапазон диммирования"): [
|
||||
vol.Range(0, 255),
|
||||
vol.Range(0, 255),
|
||||
],
|
||||
vol.Optional(CONF_INVERT, default=False): bool,
|
||||
vol.Optional(CONF_NAME): vol.Any(str, {
|
||||
vol.Required(str): str
|
||||
}),
|
||||
vol.Optional(CONF_DOMAIN): vol.Any('light', 'switch'),
|
||||
vol.Optional(CONF_UNIT_OF_MEASUREMENT, description='единицы измерений, либо строка либо мепинг'):
|
||||
vol.Any(str, {
|
||||
vol.Required(str): str
|
||||
}),
|
||||
vol.Optional(CONF_DEVICE_CLASS):
|
||||
vol.Any(str, {
|
||||
vol.Required(str): str
|
||||
}),
|
||||
vol.Optional(CONF_NAME): vol.Any(str, {vol.Required(str): str}),
|
||||
vol.Optional(CONF_DOMAIN): vol.Any("light", "switch"),
|
||||
vol.Optional(
|
||||
CONF_UNIT_OF_MEASUREMENT,
|
||||
description="единицы измерений, либо строка либо мепинг",
|
||||
): vol.Any(str, {vol.Required(str): str}),
|
||||
vol.Optional(CONF_DEVICE_CLASS): vol.Any(str, {vol.Required(str): str}),
|
||||
vol.Optional(
|
||||
CONF_RESPONSE_TEMPLATE,
|
||||
description='шаблон ответа когда на этот порт приходит'
|
||||
'сообщение из меги '): cv.template,
|
||||
vol.Optional(CONF_ACTION): cv.script_action, # пока не реализовано
|
||||
description="шаблон ответа когда на этот порт приходит" "сообщение из меги ",
|
||||
): cv.template,
|
||||
vol.Optional(CONF_ACTION): cv.script_action, # пока не реализовано
|
||||
vol.Optional(CONF_GET_VALUE, default=True): bool,
|
||||
vol.Optional(CONF_CONV_TEMPLATE): cv.template,
|
||||
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
|
||||
@@ -96,43 +123,48 @@ CUSTOMIZE_PORT = {
|
||||
vol.Optional(CONF_DEVICE_CLASS): str,
|
||||
vol.Optional(CONF_UNIT_OF_MEASUREMENT): str,
|
||||
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
|
||||
}
|
||||
},
|
||||
}
|
||||
CUSTOMIZE_DS2413 = {
|
||||
vol.Optional(str.lower, description='адрес и индекс устройства'): CUSTOMIZE_PORT
|
||||
vol.Optional(str.lower, description="адрес и индекс устройства"): CUSTOMIZE_PORT
|
||||
}
|
||||
|
||||
|
||||
def extender(x):
|
||||
if isinstance(x, str) and 'e' in x:
|
||||
if isinstance(x, str) and "e" in x:
|
||||
return x
|
||||
else:
|
||||
raise ValueError('must has "e" in port name')
|
||||
|
||||
OWBUS = vol.Schema({
|
||||
vol.Required(CONF_PORT): vol.Any(vol.Coerce(int), vol.Coerce(str)),
|
||||
vol.Required(CONF_MEGA_ID): vol.Coerce(str),
|
||||
vol.Required(CONF_ADDR): [str],
|
||||
})
|
||||
|
||||
OWBUS = vol.Schema(
|
||||
{
|
||||
vol.Required(CONF_PORT): vol.Any(vol.Coerce(int), vol.Coerce(str)),
|
||||
vol.Required(CONF_MEGA_ID): vol.Coerce(str),
|
||||
vol.Required(CONF_ADDR): [str],
|
||||
}
|
||||
)
|
||||
|
||||
CONFIG_SCHEMA = vol.Schema(
|
||||
{
|
||||
DOMAIN: {
|
||||
vol.Optional(CONF_ALLOW_HOSTS): [str],
|
||||
vol.Optional('entities'): {
|
||||
vol.Optional(str): vol.Any(
|
||||
CUSTOMIZE_PORT,
|
||||
CUSTOMIZE_DS2413
|
||||
)},
|
||||
vol.Optional(vol.Any(str, int), description='id меги из веб-интерфейса'): {
|
||||
vol.Optional(CONF_FORCE_D, description='Принудительно слать d после срабатывания входа', default=False): bool,
|
||||
vol.Optional("entities"): {
|
||||
vol.Optional(str): vol.Any(CUSTOMIZE_PORT, CUSTOMIZE_DS2413)
|
||||
},
|
||||
vol.Optional(vol.Any(str, int), description="id меги из веб-интерфейса"): {
|
||||
vol.Optional(
|
||||
CONF_DEF_RESPONSE,
|
||||
description='Ответ по умолчанию',
|
||||
default=None
|
||||
CONF_FORCE_D,
|
||||
description="Принудительно слать d после срабатывания входа",
|
||||
default=False,
|
||||
): bool,
|
||||
vol.Optional(
|
||||
CONF_DEF_RESPONSE, description="Ответ по умолчанию", default=None
|
||||
): vol.Any(cv.template, None),
|
||||
vol.Optional(CONF_LED): LED_LIGHT,
|
||||
vol.Optional(vol.Any(int, extender), description='номер порта'): vol.Any(
|
||||
vol.Optional(
|
||||
vol.Any(int, extender), description="номер порта"
|
||||
): vol.Any(
|
||||
CUSTOMIZE_PORT,
|
||||
CUSTOMIZE_DS2413,
|
||||
),
|
||||
@@ -141,14 +173,14 @@ CONFIG_SCHEMA = vol.Schema(
|
||||
vol.Optional(CONF_FILTER_LOW): vol.Coerce(float),
|
||||
vol.Optional(CONF_FILTER_HIGH): vol.Coerce(float),
|
||||
},
|
||||
vol.Optional(CONF_1WBUS): [OWBUS]
|
||||
vol.Optional(CONF_1WBUS): [OWBUS],
|
||||
}
|
||||
},
|
||||
extra=vol.ALLOW_EXTRA,
|
||||
)
|
||||
|
||||
ALIVE_STATE = 'alive'
|
||||
DEF_ID = 'def'
|
||||
ALIVE_STATE = "alive"
|
||||
DEF_ID = "def"
|
||||
_POLL_TASKS = {}
|
||||
_hubs = {}
|
||||
_subs = {}
|
||||
@@ -162,29 +194,40 @@ async def async_setup(hass: HomeAssistant, config: dict):
|
||||
view.allowed_hosts |= set(config.get(DOMAIN, {}).get(CONF_ALLOW_HOSTS, []))
|
||||
hass.http.register_view(view)
|
||||
hass.services.async_register(
|
||||
DOMAIN, 'save', partial(_save_service, hass), schema=vol.Schema({
|
||||
vol.Optional('mega_id'): str
|
||||
})
|
||||
DOMAIN,
|
||||
"save",
|
||||
partial(_save_service, hass),
|
||||
schema=vol.Schema({vol.Optional("mega_id"): str}),
|
||||
)
|
||||
hass.services.async_register(
|
||||
DOMAIN, 'get_port', partial(_get_port, hass), schema=vol.Schema({
|
||||
vol.Optional('mega_id'): str,
|
||||
vol.Optional('port'): vol.Any(int, [int]),
|
||||
})
|
||||
DOMAIN,
|
||||
"get_port",
|
||||
partial(_get_port, hass),
|
||||
schema=vol.Schema(
|
||||
{
|
||||
vol.Optional("mega_id"): str,
|
||||
vol.Optional("port"): vol.Any(int, [int]),
|
||||
}
|
||||
),
|
||||
)
|
||||
hass.services.async_register(
|
||||
DOMAIN, 'run_cmd', partial(_run_cmd, hass), schema=vol.Schema({
|
||||
vol.Optional('port'): int,
|
||||
vol.Required('cmd'): str,
|
||||
vol.Optional('mega_id'): str,
|
||||
})
|
||||
DOMAIN,
|
||||
"run_cmd",
|
||||
partial(_run_cmd, hass),
|
||||
schema=vol.Schema(
|
||||
{
|
||||
vol.Optional("port"): int,
|
||||
vol.Required("cmd"): str,
|
||||
vol.Optional("mega_id"): str,
|
||||
}
|
||||
),
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
async def get_hub(hass, entry):
|
||||
id = entry.data.get('id', entry.entry_id)
|
||||
id = entry.data.get("id", entry.entry_id)
|
||||
data = dict(entry.data)
|
||||
data.update(entry.options or {})
|
||||
data.update(id=id)
|
||||
@@ -194,7 +237,7 @@ async def get_hub(hass, entry):
|
||||
|
||||
|
||||
async def _add_mega(hass: HomeAssistant, entry: ConfigEntry):
|
||||
id = entry.data.get('id', entry.entry_id)
|
||||
id = entry.data.get("id", entry.entry_id)
|
||||
hub = await get_hub(hass, entry)
|
||||
hub.fw = await hub.get_fw()
|
||||
hass.data[DOMAIN][id] = hub
|
||||
@@ -213,9 +256,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
|
||||
await hub.start()
|
||||
for platform in PLATFORMS:
|
||||
hass.async_create_task(
|
||||
hass.config_entries.async_forward_entry_setup(
|
||||
entry, platform
|
||||
)
|
||||
hass.config_entries.async_forward_entry_setup(entry, platform)
|
||||
)
|
||||
await hub.updater.async_refresh()
|
||||
return True
|
||||
@@ -237,11 +278,11 @@ async def updater(hass: HomeAssistant, entry: ConfigEntry):
|
||||
|
||||
async def async_remove_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
|
||||
"""Handle removal of an entry."""
|
||||
id = entry.data.get('id', entry.entry_id)
|
||||
id = entry.data.get("id", entry.entry_id)
|
||||
hub: MegaD = hass.data[DOMAIN].get(id)
|
||||
if hub is None:
|
||||
return True
|
||||
_LOGGER.debug(f'remove {id}')
|
||||
_LOGGER.debug(f"remove {id}")
|
||||
_hubs.pop(id, None)
|
||||
hass.data[DOMAIN].pop(id, None)
|
||||
hass.data[DOMAIN][CONF_ALL].pop(id, None)
|
||||
@@ -255,19 +296,24 @@ async def async_remove_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
|
||||
await hub.stop()
|
||||
return True
|
||||
|
||||
|
||||
async_unload_entry = async_remove_entry
|
||||
|
||||
|
||||
async def async_migrate_entry(hass, config_entry: ConfigEntry):
|
||||
"""Migrate old entry."""
|
||||
_LOGGER.debug("Migrating from version %s to version %s", config_entry.version, ConfigFlow.VERSION)
|
||||
_LOGGER.debug(
|
||||
"Migrating from version %s to version %s",
|
||||
config_entry.version,
|
||||
ConfigFlow.VERSION,
|
||||
)
|
||||
hub = await get_hub(hass, config_entry)
|
||||
new = dict(config_entry.data)
|
||||
await hub.start()
|
||||
cfg = await hub.get_config()
|
||||
await hub.stop()
|
||||
new.update(cfg)
|
||||
_LOGGER.debug(f'new config: %s', new)
|
||||
_LOGGER.debug(f"new config: %s", new)
|
||||
config_entry.data = new
|
||||
config_entry.version = ConfigFlow.VERSION
|
||||
|
||||
@@ -277,7 +323,7 @@ async def async_migrate_entry(hass, config_entry: ConfigEntry):
|
||||
|
||||
|
||||
async def _save_service(hass: HomeAssistant, call: ServiceCall):
|
||||
mega_id = call.data.get('mega_id')
|
||||
mega_id = call.data.get("mega_id")
|
||||
if mega_id:
|
||||
hub: MegaD = hass.data[DOMAIN][mega_id]
|
||||
await hub.save()
|
||||
@@ -289,8 +335,8 @@ async def _save_service(hass: HomeAssistant, call: ServiceCall):
|
||||
|
||||
@bind_hass
|
||||
async def _get_port(hass: HomeAssistant, call: ServiceCall):
|
||||
port = call.data.get('port')
|
||||
mega_id = call.data.get('mega_id')
|
||||
port = call.data.get("port")
|
||||
mega_id = call.data.get("mega_id")
|
||||
if mega_id:
|
||||
hub: MegaD = hass.data[DOMAIN][mega_id]
|
||||
if port is None:
|
||||
@@ -300,6 +346,7 @@ async def _get_port(hass: HomeAssistant, call: ServiceCall):
|
||||
elif isinstance(port, list):
|
||||
for x in port:
|
||||
await hub.get_port(x)
|
||||
hub.updater.async_set_updated_data(hub.values)
|
||||
else:
|
||||
for hub in hass.data[DOMAIN][CONF_ALL].values():
|
||||
if not isinstance(hub, MegaD):
|
||||
@@ -311,12 +358,13 @@ async def _get_port(hass: HomeAssistant, call: ServiceCall):
|
||||
elif isinstance(port, list):
|
||||
for x in port:
|
||||
await hub.get_port(x)
|
||||
hub.updater.async_set_updated_data(hub.values)
|
||||
|
||||
|
||||
@bind_hass
|
||||
async def _run_cmd(hass: HomeAssistant, call: ServiceCall):
|
||||
mega_id = call.data.get('mega_id')
|
||||
cmd = call.data.get('cmd')
|
||||
mega_id = call.data.get("mega_id")
|
||||
cmd = call.data.get("cmd")
|
||||
if mega_id:
|
||||
hub: MegaD = hass.data[DOMAIN][mega_id]
|
||||
await hub.request(cmd=cmd)
|
||||
|
||||
@@ -16,7 +16,9 @@ from homeassistant.components.light import (
|
||||
SUPPORT_BRIGHTNESS,
|
||||
LightEntity,
|
||||
SUPPORT_TRANSITION,
|
||||
SUPPORT_COLOR, ColorMode, LightEntityFeature,
|
||||
SUPPORT_COLOR,
|
||||
ColorMode,
|
||||
LightEntityFeature,
|
||||
# SUPPORT_WHITE_VALUE
|
||||
)
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
@@ -36,7 +38,15 @@ from .const import (
|
||||
CONF_SWITCH,
|
||||
DOMAIN,
|
||||
CONF_CUSTOM,
|
||||
CONF_SKIP, CONF_LED, CONF_WS28XX, CONF_PORTS, CONF_WHITE_SEP, CONF_SMOOTH, CONF_ORDER, CONF_CHIP, RGB,
|
||||
CONF_SKIP,
|
||||
CONF_LED,
|
||||
CONF_WS28XX,
|
||||
CONF_PORTS,
|
||||
CONF_WHITE_SEP,
|
||||
CONF_SMOOTH,
|
||||
CONF_ORDER,
|
||||
CONF_CHIP,
|
||||
RGB,
|
||||
)
|
||||
from .tools import int_ignore, map_reorder_rgb
|
||||
|
||||
@@ -64,13 +74,17 @@ PLATFORM_SCHEMA = LIGHT_SCHEMA.extend(
|
||||
|
||||
|
||||
async def async_setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
lg.warning('mega integration does not support yaml for lights, please use UI configuration')
|
||||
lg.warning(
|
||||
"mega integration does not support yaml for lights, please use UI configuration"
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, async_add_devices):
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant, config_entry: ConfigEntry, async_add_devices
|
||||
):
|
||||
mid = config_entry.data[CONF_ID]
|
||||
hub: MegaD = hass.data['mega'][mid]
|
||||
hub: MegaD = hass.data["mega"][mid]
|
||||
devices = []
|
||||
customize = hass.data.get(DOMAIN, {}).get(CONF_CUSTOM, {}).get(mid, {})
|
||||
skip = []
|
||||
@@ -78,23 +92,29 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, asyn
|
||||
for entity_id, conf in customize[CONF_LED].items():
|
||||
ports = conf.get(CONF_PORTS) or [conf.get(CONF_PORT)]
|
||||
skip.extend(ports)
|
||||
devices.append(MegaRGBW(
|
||||
mega=hub,
|
||||
port=ports,
|
||||
name=entity_id,
|
||||
customize=conf,
|
||||
id_suffix=entity_id,
|
||||
config_entry=config_entry
|
||||
))
|
||||
for port, cfg in config_entry.data.get('light', {}).items():
|
||||
devices.append(
|
||||
MegaRGBW(
|
||||
mega=hub,
|
||||
port=ports,
|
||||
name=entity_id,
|
||||
customize=conf,
|
||||
id_suffix=entity_id,
|
||||
config_entry=config_entry,
|
||||
)
|
||||
)
|
||||
for port, cfg in config_entry.data.get("light", {}).items():
|
||||
port = int_ignore(port)
|
||||
c = customize.get(port, {})
|
||||
if c.get(CONF_SKIP, False) or port in skip or c.get(CONF_DOMAIN, 'light') != 'light':
|
||||
if (
|
||||
c.get(CONF_SKIP, False)
|
||||
or port in skip
|
||||
or c.get(CONF_DOMAIN, "light") != "light"
|
||||
):
|
||||
continue
|
||||
for data in cfg:
|
||||
hub.lg.debug(f'add light on port %s with data %s', port, data)
|
||||
hub.lg.debug(f"add light on port %s with data %s", port, data)
|
||||
light = MegaLight(mega=hub, port=port, config_entry=config_entry, **data)
|
||||
if '<' in light.name:
|
||||
if "<" in light.name:
|
||||
continue
|
||||
devices.append(light)
|
||||
|
||||
@@ -102,17 +122,14 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, asyn
|
||||
|
||||
|
||||
class MegaLight(MegaOutPort, LightEntity):
|
||||
|
||||
@property
|
||||
def supported_features(self):
|
||||
return (
|
||||
(SUPPORT_BRIGHTNESS if self.dimmer else 0) |
|
||||
(SUPPORT_TRANSITION if self.dimmer else 0)
|
||||
return (SUPPORT_BRIGHTNESS if self.dimmer else 0) | (
|
||||
SUPPORT_TRANSITION if self.dimmer else 0
|
||||
)
|
||||
|
||||
|
||||
class MegaRGBW(LightEntity, BaseMegaEntity):
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self._is_on = None
|
||||
@@ -123,7 +140,7 @@ class MegaRGBW(LightEntity, BaseMegaEntity):
|
||||
self._task: asyncio.Task = None
|
||||
self._restore = None
|
||||
self.smooth: timedelta = self.customize[CONF_SMOOTH]
|
||||
self._color_order = self.customize.get(CONF_ORDER, 'rgb')
|
||||
self._color_order = self.customize.get(CONF_ORDER, "rgb")
|
||||
self._last_called: float = 0
|
||||
self._max_values = None
|
||||
|
||||
@@ -146,12 +163,11 @@ class MegaRGBW(LightEntity, BaseMegaEntity):
|
||||
def is_ws(self):
|
||||
return self.customize.get(CONF_WS28XX)
|
||||
|
||||
|
||||
@property
|
||||
def supported_color_modes(self) -> set[ColorMode] | set[str] | None:
|
||||
return {
|
||||
ColorMode.BRIGHTNESS,
|
||||
ColorMode.RGB if len(self.port) != 4 else ColorMode.RGBW
|
||||
ColorMode.RGB if len(self.port) != 4 else ColorMode.RGBW,
|
||||
}
|
||||
|
||||
@property
|
||||
@@ -164,7 +180,7 @@ class MegaRGBW(LightEntity, BaseMegaEntity):
|
||||
@property
|
||||
def white_value(self):
|
||||
# if self.supported_features & SUPPORT_WHITE_VALUE:
|
||||
return float(self.get_attribute('white_value', 0))
|
||||
return float(self.get_attribute("white_value", 0))
|
||||
|
||||
@property
|
||||
def rgb_color(self) -> tuple[int, int, int] | None:
|
||||
@@ -177,15 +193,15 @@ class MegaRGBW(LightEntity, BaseMegaEntity):
|
||||
|
||||
@property
|
||||
def brightness(self):
|
||||
return float(self.get_attribute('brightness', 0))
|
||||
return float(self.get_attribute("brightness", 0))
|
||||
|
||||
@property
|
||||
def hs_color(self):
|
||||
return self.get_attribute('hs_color', [0, 0])
|
||||
return self.get_attribute("hs_color", [0, 0])
|
||||
|
||||
@property
|
||||
def is_on(self):
|
||||
return self.get_attribute('is_on', False)
|
||||
return self.get_attribute("is_on", False)
|
||||
|
||||
@property
|
||||
def supported_features(self):
|
||||
@@ -195,7 +211,7 @@ class MegaRGBW(LightEntity, BaseMegaEntity):
|
||||
if not self.is_on:
|
||||
return [0 for x in range(len(self.port))] if not self.is_ws else [0] * 3
|
||||
rgb = colorsys.hsv_to_rgb(
|
||||
self.hs_color[0]/360, self.hs_color[1]/100, self.brightness / 255
|
||||
self.hs_color[0] / 360, self.hs_color[1] / 100, self.brightness / 255
|
||||
)
|
||||
rgb = [x for x in rgb]
|
||||
if self.white_value is not None:
|
||||
@@ -203,9 +219,7 @@ class MegaRGBW(LightEntity, BaseMegaEntity):
|
||||
if not self.customize.get(CONF_WHITE_SEP):
|
||||
white = white * (self.brightness / 255)
|
||||
rgb.append(white / 255)
|
||||
rgb = [
|
||||
round(x * self.max_values[i]) for i, x in enumerate(rgb)
|
||||
]
|
||||
rgb = [round(x * self.max_values[i]) for i, x in enumerate(rgb)]
|
||||
if self.is_ws:
|
||||
# восстанавливаем мэпинг
|
||||
rgb = map_reorder_rgb(rgb, RGB, self._color_order)
|
||||
@@ -215,7 +229,7 @@ class MegaRGBW(LightEntity, BaseMegaEntity):
|
||||
if (time.time() - self._last_called) < 0.1:
|
||||
return
|
||||
self._last_called = time.time()
|
||||
self.lg.debug(f'turn on %s with kwargs %s', self.entity_id, kwargs)
|
||||
self.lg.debug(f"turn on %s with kwargs %s", self.entity_id, kwargs)
|
||||
if self._restore is not None:
|
||||
self._restore.update(kwargs)
|
||||
kwargs = self._restore
|
||||
@@ -231,9 +245,9 @@ class MegaRGBW(LightEntity, BaseMegaEntity):
|
||||
return
|
||||
self._last_called = time.time()
|
||||
self._restore = {
|
||||
'hs_color': self.hs_color,
|
||||
'brightness': self.brightness,
|
||||
'white_value': self.white_value,
|
||||
"hs_color": self.hs_color,
|
||||
"brightness": self.brightness,
|
||||
"white_value": self.white_value,
|
||||
}
|
||||
_before = self.get_rgbw()
|
||||
self._is_on = False
|
||||
@@ -242,18 +256,22 @@ class MegaRGBW(LightEntity, BaseMegaEntity):
|
||||
self._task = asyncio.create_task(self.set_color(_before, **kwargs))
|
||||
|
||||
async def set_color(self, _before, **kwargs):
|
||||
transition = kwargs.get('transition')
|
||||
transition = kwargs.get("transition")
|
||||
update_state = transition is not None and transition > 3
|
||||
_after = None
|
||||
for item, value in kwargs.items():
|
||||
setattr(self, f'_{item}', value)
|
||||
_after = self.get_rgbw()
|
||||
self._rgb_color = tuple(_after[:3])
|
||||
setattr(self, f"_{item}", value)
|
||||
if item == "rgb_color":
|
||||
_after = map_reorder_rgb(value, RGB, self._color_order)
|
||||
self._hs_color = colorsys.rgb_to_hsv(*value)
|
||||
_after = _after or self.get_rgbw()
|
||||
self._rgb_color = map_reorder_rgb(tuple(_after[:3]), self._color_order, RGB)
|
||||
if transition is None:
|
||||
transition = self.smooth.total_seconds()
|
||||
ratio = self.calc_speed_ratio(_before, _after)
|
||||
transition = transition * ratio
|
||||
self.async_write_ha_state()
|
||||
ports = self.port if not self.is_ws else self.port*3
|
||||
ports = self.port if not self.is_ws else self.port * 3
|
||||
config = [(port, _before[i], _after[i]) for i, port in enumerate(ports)]
|
||||
try:
|
||||
await self.mega.smooth_dim(
|
||||
@@ -269,7 +287,7 @@ class MegaRGBW(LightEntity, BaseMegaEntity):
|
||||
except asyncio.CancelledError:
|
||||
return
|
||||
except:
|
||||
self.lg.exception('while dimming')
|
||||
self.lg.exception("while dimming")
|
||||
|
||||
async def async_will_remove_from_hass(self) -> None:
|
||||
await super().async_will_remove_from_hass()
|
||||
@@ -284,10 +302,10 @@ class MegaRGBW(LightEntity, BaseMegaEntity):
|
||||
w = None
|
||||
rgb = rgbw
|
||||
if self.is_ws:
|
||||
rgb = map_reorder_rgb(
|
||||
rgb, self._color_order, RGB
|
||||
)
|
||||
h, s, v = colorsys.rgb_to_hsv(*[x/self.max_values[i] for i, x in enumerate(rgb)])
|
||||
rgb = map_reorder_rgb(rgb, self._color_order, RGB)
|
||||
h, s, v = colorsys.rgb_to_hsv(
|
||||
*[x / self.max_values[i] for i, x in enumerate(rgb)]
|
||||
)
|
||||
h *= 360
|
||||
s *= 100
|
||||
v *= 255
|
||||
@@ -296,7 +314,7 @@ class MegaRGBW(LightEntity, BaseMegaEntity):
|
||||
self._brightness = v
|
||||
if w is not None:
|
||||
if not self.customize.get(CONF_WHITE_SEP):
|
||||
w = w/(self._brightness / 255)
|
||||
w = w / (self._brightness / 255)
|
||||
else:
|
||||
w = w
|
||||
w = w / (self.max_values[-1] / 255)
|
||||
@@ -321,7 +339,7 @@ class MegaRGBW(LightEntity, BaseMegaEntity):
|
||||
return
|
||||
data = data.get(x, None)
|
||||
if isinstance(data, dict):
|
||||
data = data.get('value')
|
||||
data = data.get("value")
|
||||
data = safe_int(data)
|
||||
if data is None:
|
||||
return
|
||||
@@ -338,4 +356,4 @@ class MegaRGBW(LightEntity, BaseMegaEntity):
|
||||
ret = r
|
||||
else:
|
||||
ret = max([r, ret])
|
||||
return ret
|
||||
return ret
|
||||
|
||||
@@ -15,5 +15,5 @@
|
||||
"@andvikt"
|
||||
],
|
||||
"issue_tracker": "https://github.com/andvikt/mega_hacs/issues",
|
||||
"version": "v1.1.7"
|
||||
"version": "v1.1.8b4"
|
||||
}
|
||||
Reference in New Issue
Block a user