Compare commits

..

6 Commits

Author SHA1 Message Date
Викторов Андрей Германович
adf5cfe2f8 Bump version: 1.1.8b5 → 1.1.8b6 2023-10-15 14:10:59 +03:00
Викторов Андрей Германович
6bb897a26f - fix init of conf_http 2023-10-15 14:01:39 +03:00
Викторов Андрей Германович
4edc0dcb4f - исправлена логика filter_value 2023-10-15 13:56:44 +03:00
Викторов Андрей Германович
89d261bd9c - исправление логики filter_scale 2023-10-15 13:53:11 +03:00
Викторов Андрей Германович
58288de1dd Bump version: 1.1.8b4 → 1.1.8b5 2023-10-15 13:37:31 +03:00
Викторов Андрей Германович
ec5aeab559 fix update extender 2023-10-15 13:37:24 +03:00
4 changed files with 118 additions and 80 deletions

View File

@@ -1,5 +1,5 @@
[bumpversion] [bumpversion]
current_version = 1.1.8b4 current_version = 1.1.8b6
parse = (?P<major>\d+)(\.(?P<minor>\d+))(\.(?P<patch>\d+))(?P<release>[bf]*)(?P<build>\d*) parse = (?P<major>\d+)(\.(?P<minor>\d+))(\.(?P<patch>\d+))(?P<release>[bf]*)(?P<build>\d*)
commit = True commit = True
tag = True tag = True

View File

@@ -164,7 +164,7 @@ class MegaD:
if allow_hosts is not None and DOMAIN in hass.data: if allow_hosts is not None and DOMAIN in hass.data:
allow_hosts = set(allow_hosts.split(";")) allow_hosts = set(allow_hosts.split(";"))
hass.data[DOMAIN][CONF_HTTP].allowed_hosts |= allow_hosts hass.data[DOMAIN][CONF_HTTP].allowed_hosts |= allow_hosts
hass.data[DOMAIN][CONF_HTTP].protected = protected hass.data[DOMAIN][CONF_HTTP].protected = protected
except Exception: except Exception:
self.lg.exception("while setting allowed hosts") self.lg.exception("while setting allowed hosts")
self.binary_sensors = [] self.binary_sensors = []
@@ -477,7 +477,7 @@ class MegaD:
return return
ret = {} ret = {}
for i, x in enumerate(values.split(";")): for i, x in enumerate(values.split(";")):
ret[f"{port}e{i}"] = x ret[f"{port}e{i}" if not self.new_naming else f"{port:02d}e{i:02d}"] = x
return ret return ret
async def _update_i2c(self, params): async def _update_i2c(self, params):

View File

@@ -15,5 +15,5 @@
"@andvikt" "@andvikt"
], ],
"issue_tracker": "https://github.com/andvikt/mega_hacs/issues", "issue_tracker": "https://github.com/andvikt/mega_hacs/issues",
"version": "v1.1.8b4" "version": "v1.1.8b6"
} }

View File

@@ -4,7 +4,9 @@ import voluptuous as vol
import struct import struct
from homeassistant.components.sensor import ( from homeassistant.components.sensor import (
PLATFORM_SCHEMA as SENSOR_SCHEMA, SensorEntity, SensorDeviceClass PLATFORM_SCHEMA as SENSOR_SCHEMA,
SensorEntity,
SensorDeviceClass,
) )
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ( from homeassistant.const import (
@@ -12,35 +14,46 @@ from homeassistant.const import (
CONF_PORT, CONF_PORT,
CONF_UNIQUE_ID, CONF_UNIQUE_ID,
CONF_ID, CONF_ID,
CONF_TYPE, CONF_UNIT_OF_MEASUREMENT, CONF_VALUE_TEMPLATE, CONF_TYPE,
CONF_UNIT_OF_MEASUREMENT,
CONF_VALUE_TEMPLATE,
CONF_DEVICE_CLASS, CONF_DEVICE_CLASS,
) )
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.template import Template from homeassistant.helpers.template import Template
from .entities import MegaPushEntity from .entities import MegaPushEntity
from .const import CONF_KEY, TEMP, HUM, W1, W1BUS, CONF_CONV_TEMPLATE, CONF_HEX_TO_FLOAT, DOMAIN, CONF_CUSTOM, \ from .const import (
CONF_SKIP, CONF_FILTER_VALUES, CONF_FILTER_SCALE, CONF_FILTER_LOW, CONF_FILTER_HIGH, CONF_FILL_NA CONF_KEY,
TEMP,
HUM,
W1,
W1BUS,
CONF_CONV_TEMPLATE,
CONF_HEX_TO_FLOAT,
DOMAIN,
CONF_CUSTOM,
CONF_SKIP,
CONF_FILTER_VALUES,
CONF_FILTER_SCALE,
CONF_FILTER_LOW,
CONF_FILTER_HIGH,
CONF_FILL_NA,
)
from .hub import MegaD from .hub import MegaD
import re import re
from .tools import int_ignore from .tools import int_ignore
lg = logging.getLogger(__name__) lg = logging.getLogger(__name__)
TEMP_PATT = re.compile(r'temp:([01234567890\.]+)') TEMP_PATT = re.compile(r"temp:([01234567890\.]+)")
HUM_PATT = re.compile(r'hum:([01234567890\.]+)') HUM_PATT = re.compile(r"hum:([01234567890\.]+)")
PATTERNS = { PATTERNS = {
TEMP: TEMP_PATT, TEMP: TEMP_PATT,
HUM: HUM_PATT, HUM: HUM_PATT,
} }
UNITS = { UNITS = {TEMP: "°C", HUM: "%"}
TEMP: '°C', CLASSES = {TEMP: SensorDeviceClass.TEMPERATURE, HUM: SensorDeviceClass.HUMIDITY}
HUM: '%'
}
CLASSES = {
TEMP: SensorDeviceClass.TEMPERATURE,
HUM: SensorDeviceClass.HUMIDITY
}
# Validation of the user's configuration # Validation of the user's configuration
_ITEM = { _ITEM = {
vol.Required(CONF_PORT): int, vol.Required(CONF_PORT): int,
@@ -50,18 +63,18 @@ _ITEM = {
W1, W1,
W1BUS, W1BUS,
), ),
vol.Optional(CONF_KEY, default=''): str, vol.Optional(CONF_KEY, default=""): str,
} }
PLATFORM_SCHEMA = SENSOR_SCHEMA.extend( PLATFORM_SCHEMA = SENSOR_SCHEMA.extend(
{ {vol.Optional(str, description="mega id"): [_ITEM]},
vol.Optional(str, description="mega id"): [_ITEM]
},
extra=vol.ALLOW_EXTRA, extra=vol.ALLOW_EXTRA,
) )
async def async_setup_platform(hass, config, add_entities, discovery_info=None): async def async_setup_platform(hass, config, add_entities, discovery_info=None):
lg.warning('mega integration does not support yaml for sensors, please use UI configuration') lg.warning(
"mega integration does not support yaml for sensors, please use UI configuration"
)
return True return True
@@ -72,19 +85,23 @@ def _make_entity(config_entry, mid: str, port: int, conf: dict):
mega_id=mid, mega_id=mid,
port=port, port=port,
patt=PATTERNS.get(key), patt=PATTERNS.get(key),
unit_of_measurement=UNITS.get(key, UNITS[TEMP]), # TODO: make other units, make options in config flow unit_of_measurement=UNITS.get(
key, UNITS[TEMP]
), # TODO: make other units, make options in config flow
device_class=CLASSES.get(key, CLASSES[TEMP]), device_class=CLASSES.get(key, CLASSES[TEMP]),
id_suffix=key, id_suffix=key,
config_entry=config_entry config_entry=config_entry,
) )
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] mid = config_entry.data[CONF_ID]
hub: MegaD = hass.data['mega'][mid] hub: MegaD = hass.data["mega"][mid]
devices = [] devices = []
customize = hass.data.get(DOMAIN, {}).get(CONF_CUSTOM, {}).get(mid, {}) customize = hass.data.get(DOMAIN, {}).get(CONF_CUSTOM, {}).get(mid, {})
for tp in ['sensor', 'i2c']: for tp in ["sensor", "i2c"]:
for port, cfg in config_entry.data.get(tp, {}).items(): for port, cfg in config_entry.data.get(tp, {}).items():
port = int_ignore(port) port = int_ignore(port)
c = customize.get(port, {}) c = customize.get(port, {})
@@ -92,14 +109,19 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, asyn
hub.skip_ports |= {port} hub.skip_ports |= {port}
continue continue
for data in cfg: for data in cfg:
hub.lg.debug(f'add sensor on port %s with data %s, constructor: %s', port, data, _constructors[tp]) hub.lg.debug(
f"add sensor on port %s with data %s, constructor: %s",
port,
data,
_constructors[tp],
)
sensor = _constructors[tp]( sensor = _constructors[tp](
mega=hub, mega=hub,
port=port, port=port,
config_entry=config_entry, config_entry=config_entry,
**data, **data,
) )
if '<' in sensor.name: if "<" in sensor.name:
continue continue
devices.append(sensor) devices.append(sensor)
@@ -107,64 +129,76 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, asyn
class FilterBadValues(MegaPushEntity, SensorEntity): class FilterBadValues(MegaPushEntity, SensorEntity):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
self._prev_value = None self._prev_value = None
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
def filter_value(self, value): def filter_value(self, value):
if value is None:
return
try: try:
if value \ if (
in self.filter_values \ value in self.filter_values
or (self.filter_low is not None and value < self.filter_low) \ or (self.filter_low is not None and value < self.filter_low)
or (self.filter_high is not None and value > self.filter_high) \ or (self.filter_high is not None and value > self.filter_high)
or ( or (
self._prev_value is not None self._prev_value is not None
and self.filter_scale is not None and self.filter_scale is not None
and abs(value)
> 2 # при переходе через 0 каждое небольшое изменение будет иметь слишком большой эффект
and ( and (
abs(value - self._prev_value) / self._prev_value > self.filter_scale abs((value - self._prev_value) / self._prev_value)
> self.filter_scale
) )
)
): ):
if self.fill_na == 'last': if self.fill_na == "last":
value = self._prev_value value = self._prev_value
else: else:
value = None value = None
self._prev_value = value self._prev_value = value
return value return value
except Exception as exc: except Exception as exc:
lg.exception(f'while parsing value') lg.exception(f"while parsing value")
return None return None
@property @property
def filter_values(self): def filter_values(self):
return self.customize.get(CONF_FILTER_VALUES, self.mega.customize.get(CONF_FILTER_VALUES, [])) return self.customize.get(
CONF_FILTER_VALUES, self.mega.customize.get(CONF_FILTER_VALUES, [])
)
@property @property
def filter_scale(self): def filter_scale(self):
return self.customize.get(CONF_FILTER_SCALE, self.mega.customize.get(CONF_FILTER_SCALE, None)) return self.customize.get(
CONF_FILTER_SCALE, self.mega.customize.get(CONF_FILTER_SCALE, None)
)
@property @property
def filter_low(self): def filter_low(self):
return self.customize.get(CONF_FILTER_LOW, self.mega.customize.get(CONF_FILTER_LOW, None)) return self.customize.get(
CONF_FILTER_LOW, self.mega.customize.get(CONF_FILTER_LOW, None)
)
@property @property
def filter_high(self): def filter_high(self):
return self.customize.get(CONF_FILTER_HIGH, self.mega.customize.get(CONF_FILTER_HIGH, None)) return self.customize.get(
CONF_FILTER_HIGH, self.mega.customize.get(CONF_FILTER_HIGH, None)
)
@property @property
def fill_na(self): def fill_na(self):
return self.customize.get(CONF_FILL_NA, 'last') return self.customize.get(CONF_FILL_NA, "last")
class MegaI2C(FilterBadValues): class MegaI2C(FilterBadValues):
def __init__( def __init__(
self, self,
*args, *args,
device_class: str, device_class: str,
params: dict, params: dict,
unit_of_measurement: str = None, unit_of_measurement: str = None,
**kwargs **kwargs,
): ):
self._device_class = device_class self._device_class = device_class
self._params = tuple(params.items()) self._params = tuple(params.items())
@@ -183,9 +217,11 @@ class MegaI2C(FilterBadValues):
@property @property
def extra_state_attributes(self): def extra_state_attributes(self):
attrs = super().extra_state_attributes or {} attrs = super().extra_state_attributes or {}
attrs.update({ attrs.update(
'i2c_id': self.id_suffix, {
}) "i2c_id": self.id_suffix,
}
)
return attrs return attrs
@property @property
@@ -202,22 +238,24 @@ class MegaI2C(FilterBadValues):
ret = self.mega.values.get(self._params) ret = self.mega.values.get(self._params)
if self.customize.get(CONF_HEX_TO_FLOAT): if self.customize.get(CONF_HEX_TO_FLOAT):
try: try:
ret = struct.unpack('!f', bytes.fromhex(ret))[0] ret = struct.unpack("!f", bytes.fromhex(ret))[0]
except: except:
self.lg.warning(f'could not convert {ret} form hex to float') self.lg.warning(f"could not convert {ret} form hex to float")
tmpl: Template = self.customize.get(CONF_CONV_TEMPLATE, self.customize.get(CONF_VALUE_TEMPLATE)) tmpl: Template = self.customize.get(
CONF_CONV_TEMPLATE, self.customize.get(CONF_VALUE_TEMPLATE)
)
try: try:
ret = float(ret) ret = float(ret)
if tmpl is not None and self.hass is not None: if tmpl is not None and self.hass is not None:
tmpl.hass = self.hass tmpl.hass = self.hass
ret = tmpl.async_render({'value': ret}) ret = tmpl.async_render({"value": ret})
except: except:
ret = ret ret = ret
ret = self.filter_value(ret) ret = self.filter_value(ret)
if ret is not None: if ret is not None:
return str(ret) return str(ret)
except Exception: except Exception:
lg.exception('while getting value') lg.exception("while getting value")
return None return None
@property @property
@@ -226,14 +264,8 @@ class MegaI2C(FilterBadValues):
class Mega1WSensor(FilterBadValues): class Mega1WSensor(FilterBadValues):
def __init__( def __init__(
self, self, unit_of_measurement=None, device_class=None, key=None, *args, **kwargs
unit_of_measurement=None,
device_class=None,
key=None,
*args,
**kwargs
): ):
""" """
1-wire sensor entity 1-wire sensor entity
@@ -264,7 +296,7 @@ class Mega1WSensor(FilterBadValues):
@property @property
def unique_id(self): def unique_id(self):
if self.key: if self.key:
return super().unique_id + f'_{self.key}' return super().unique_id + f"_{self.key}"
else: else:
return super().unique_id return super().unique_id
@@ -284,23 +316,27 @@ class Mega1WSensor(FilterBadValues):
def native_value(self): def native_value(self):
try: try:
ret = None ret = None
if not hasattr(self, 'key'): if not hasattr(self, "key"):
return None return None
if self.key: if self.key:
try: try:
ret = self.mega.values.get(self.port, {}) ret = self.mega.values.get(self.port, {})
if isinstance(ret, dict): if isinstance(ret, dict):
ret = ret.get('value', {}) ret = ret.get("value", {})
if isinstance(ret, dict): if isinstance(ret, dict):
ret = ret.get(self.key) ret = ret.get(self.key)
except: except:
self.lg.error(self.mega.values.get(self.port, {}).get('value', {})) self.lg.error(self.mega.values.get(self.port, {}).get("value", {}))
return return
else: else:
ret = self.mega.values.get(self.port, {}).get('value') ret = self.mega.values.get(self.port, {}).get("value")
if ret is None and self.fill_na == 'fill_na' and self.prev_value is not None: if (
ret is None
and self.fill_na == "fill_na"
and self.prev_value is not None
):
ret = self.prev_value ret = self.prev_value
elif ret is None and self.fill_na == 'fill_na' and self._state is not None: elif ret is None and self.fill_na == "fill_na" and self._state is not None:
ret = self._state.state ret = self._state.state
try: try:
ret = float(ret) ret = float(ret)
@@ -310,15 +346,17 @@ class Mega1WSensor(FilterBadValues):
ret = self.prev_value ret = self.prev_value
if self.customize.get(CONF_HEX_TO_FLOAT): if self.customize.get(CONF_HEX_TO_FLOAT):
try: try:
ret = struct.unpack('!f', bytes.fromhex(ret))[0] ret = struct.unpack("!f", bytes.fromhex(ret))[0]
except: except:
self.lg.warning(f'could not convert {ret} form hex to float') self.lg.warning(f"could not convert {ret} form hex to float")
tmpl: Template = self.customize.get(CONF_CONV_TEMPLATE, self.customize.get(CONF_VALUE_TEMPLATE)) tmpl: Template = self.customize.get(
CONF_CONV_TEMPLATE, self.customize.get(CONF_VALUE_TEMPLATE)
)
try: try:
ret = float(ret) ret = float(ret)
if tmpl is not None and self.hass is not None: if tmpl is not None and self.hass is not None:
tmpl.hass = self.hass tmpl.hass = self.hass
ret = tmpl.async_render({'value': ret}) ret = tmpl.async_render({"value": ret})
except: except:
pass pass
ret = self.filter_value(ret) ret = self.filter_value(ret)
@@ -326,7 +364,7 @@ class Mega1WSensor(FilterBadValues):
if ret is not None: if ret is not None:
return str(ret) return str(ret)
except Exception: except Exception:
lg.exception('while parsing state') lg.exception("while parsing state")
return None return None
@property @property
@@ -342,6 +380,6 @@ class Mega1WSensor(FilterBadValues):
_constructors = { _constructors = {
'sensor': Mega1WSensor, "sensor": Mega1WSensor,
'i2c': MegaI2C, "i2c": MegaI2C,
} }