Compare commits

..

8 Commits

Author SHA1 Message Date
Andrey
1aeaabfb3c fix errors 2021-02-28 14:50:47 +03:00
Andrey
a0bd8acac0 fix errors 2021-02-28 14:49:38 +03:00
andvikt
c48a3632d2 Update http.py 2021-02-28 13:04:00 +03:00
Andrey
e06ba65ead fix errors 2021-02-28 09:49:16 +03:00
Andrey
22720a27bd fix errors 2021-02-28 09:46:06 +03:00
Andrey
d0769b5b02 fix errors 2021-02-27 17:39:54 +03:00
Andrey
9ae093dd91 fix errors 2021-02-27 14:44:20 +03:00
Andrey
f88109c3a6 fix int(port) 2021-02-26 16:18:05 +03:00
10 changed files with 88 additions and 43 deletions

View File

@@ -20,7 +20,7 @@ from homeassistant.helpers.template import Template
from .const import EVENT_BINARY_SENSOR, DOMAIN, CONF_CUSTOM, CONF_SKIP, CONF_INVERT, CONF_RESPONSE_TEMPLATE from .const import EVENT_BINARY_SENSOR, DOMAIN, CONF_CUSTOM, CONF_SKIP, CONF_INVERT, CONF_RESPONSE_TEMPLATE
from .entities import MegaPushEntity from .entities import MegaPushEntity
from .hub import MegaD from .hub import MegaD
from .tools import int_ignore
lg = logging.getLogger(__name__) lg = logging.getLogger(__name__)
@@ -51,7 +51,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, asyn
devices = [] devices = []
customize = hass.data.get(DOMAIN, {}).get(CONF_CUSTOM, {}) customize = hass.data.get(DOMAIN, {}).get(CONF_CUSTOM, {})
for port, cfg in config_entry.data.get('binary_sensor', {}).items(): for port, cfg in config_entry.data.get('binary_sensor', {}).items():
port = int(port) port = int_ignore(port)
c = customize.get(mid, {}).get(port, {}) c = customize.get(mid, {}).get(port, {})
if c.get(CONF_SKIP, False): if c.get(CONF_SKIP, False):
continue continue
@@ -78,14 +78,15 @@ class MegaBinarySensor(BinarySensorEntity, MegaPushEntity):
@property @property
def is_on(self) -> bool: def is_on(self) -> bool:
val = self.mega.values.get(self.port, {}).get("value") \ val = self.mega.values.get(self.port, {})
or self.mega.values.get(self.port, {}).get('m') if isinstance(val, dict):
val = val.get("value", val.get('m'))
if val is None and self._state is not None: if val is None and self._state is not None:
return self._state == 'ON' return self._state == 'ON'
elif val is not None: elif val is not None:
if val in ['ON', 'OFF']: if val in ['ON', 'OFF', '1', '0']:
return val == 'ON' if not self.invert else val == 'OFF' return val in ['ON', '1'] if not self.invert else val in ['OFF', '0']
else: elif isinstance(val, int):
return val != 1 if not self.invert else val == 1 return val != 1 if not self.invert else val == 1
def _update(self, payload: dict): def _update(self, payload: dict):

View File

@@ -63,7 +63,7 @@ async def validate_input(hass: core.HomeAssistant, data):
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for mega.""" """Handle a config flow for mega."""
VERSION = 12 VERSION = 15
CONNECTION_CLASS = config_entries.CONN_CLASS_ASSUMED CONNECTION_CLASS = config_entries.CONN_CLASS_ASSUMED
async def async_step_user(self, user_input=None): async def async_step_user(self, user_input=None):

View File

@@ -1,6 +1,19 @@
from dataclasses import dataclass, field from dataclasses import dataclass, field
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
inputs = [
'eact',
'inta',
'misc',
]
selectors = [
'pty',
'm',
'gr',
'd',
'ety',
]
@dataclass(frozen=True, eq=True) @dataclass(frozen=True, eq=True)
class Config: class Config:
@@ -8,21 +21,16 @@ class Config:
m: str = None m: str = None
gr: str = None gr: str = None
d: str = None d: str = None
inta: str = field(compare=False, hash=False, default=None)
ety: str = None ety: str = None
inta: str = field(compare=False, hash=False, default=None)
misc: str = field(compare=False, hash=False, default=None) misc: str = field(compare=False, hash=False, default=None)
eact: str = field(compare=False, hash=False, default=None)
def parse_config(page: str): def parse_config(page: str):
page = BeautifulSoup(page, features="lxml") page = BeautifulSoup(page, features="lxml")
ret = {} ret = {}
for x in [ for x in selectors:
'pty',
'm',
'gr',
'd',
'ety',
]:
v = page.find('select', attrs={'name': x}) v = page.find('select', attrs={'name': x})
if v is None: if v is None:
continue continue
@@ -31,12 +39,10 @@ def parse_config(page: str):
if v: if v:
v = v['value'] v = v['value']
ret[x] = v ret[x] = v
v = page.find('input', attrs={'name': 'inta'}) for x in inputs:
if v: v = page.find('input', attrs={'name': x})
ret['inta'] = v['value'] if v:
v = page.find('input', attrs={'name': 'misc'}) ret[x] = v['value']
if v:
ret['misc'] = v.get('checked', False)
return Config(**ret) return Config(**ret)

View File

@@ -247,8 +247,8 @@ class MegaOutPort(MegaPushEntity):
val = 0 val = 0
if val == 0: if val == 0:
return self._brightness return self._brightness
else: elif isinstance(val, (int, float)):
return val return int(val / self.dimmer_scale)
elif val is not None: elif val is not None:
val = val.get("value") val = val.get("value")
if val is None: if val is None:
@@ -269,7 +269,8 @@ class MegaOutPort(MegaPushEntity):
return return
if self.dimmer: if self.dimmer:
val = safe_int(val) val = safe_int(val)
return val > 0 if not self.invert else val == 0 if val is not None:
return val > 0 if not self.invert else val == 0
else: else:
return val == 'ON' if not self.invert else val == 'OFF' return val == 'ON' if not self.invert else val == 'OFF'
elif val is not None: elif val is not None:
@@ -358,8 +359,10 @@ class MegaOutPort(MegaPushEntity):
def safe_int(v): def safe_int(v):
if v in ['ON', 'OFF']: if v == 'ON':
return None return 1
elif v == 'OFF':
return 0
try: try:
return int(v) return int(v)
except (ValueError, TypeError): except (ValueError, TypeError):

View File

@@ -15,7 +15,11 @@ from .tools import make_ints
from . import hub as h from . import hub as h
_LOGGER = logging.getLogger(__name__).getChild('http') _LOGGER = logging.getLogger(__name__).getChild('http')
ext = {f'ext{x}' for x in range(16)}
def is_ext(data: typing.Dict[str, typing.Any]):
for x in data:
if x.startswith('ext'):
return True
class MegaView(HomeAssistantView): class MegaView(HomeAssistantView):
@@ -95,17 +99,27 @@ class MegaView(HomeAssistantView):
data['mega_id'] = hub.id data['mega_id'] = hub.id
ret = 'd' if hub.force_d else '' ret = 'd' if hub.force_d else ''
if port is not None: if port is not None:
if set(data).issubset(ext): if is_ext(data):
ret = '' # пока ответ всегда пустой, неясно какая будет реакция на непустой ответ ret = '' # пока ответ всегда пустой, неясно какая будет реакция на непустой ответ
for e in ext: if port in hub.extenders:
if e in data: pt_orig = port
idx = e[-1] else:
pt = f'{port}e{idx}' pt_orig = hub.ext_in.get(port)
data['value'] = 'ON' if data[e] == '1' else 'OFF' if pt_orig is None:
hub.lg.warning(f'can not find extender for int port {port}')
return Response(status=200)
for e, v in data.items():
if e.startswith('ext'):
idx = e[3:]
pt = f'{pt_orig}e{idx}'
data['pt_orig'] = pt_orig
data['value'] = 'ON' if v == '1' else 'OFF'
data['m'] = 1 if data[e] == '0' else 0 # имитация поведения обычного входа, чтобы события обрабатывались аналогично data['m'] = 1 if data[e] == '0' else 0 # имитация поведения обычного входа, чтобы события обрабатывались аналогично
hub.values[pt] = data hub.values[pt] = data
for cb in self.callbacks[hub.id][pt]: for cb in self.callbacks[hub.id][pt]:
cb(data) cb(data)
if pt in hub.ext_act:
await hub.request(cmd=hub.ext_act[pt])
else: else:
hub.values[port] = data hub.values[port] = data
for cb in self.callbacks[hub.id][port]: for cb in self.callbacks[hub.id][port]:

View File

@@ -24,7 +24,7 @@ from .const import (
) )
from .entities import set_events_off, BaseMegaEntity, MegaOutPort from .entities import set_events_off, BaseMegaEntity, MegaOutPort
from .exceptions import CannotConnect, NoPort from .exceptions import CannotConnect, NoPort
from .tools import make_ints from .tools import make_ints, int_ignore
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\.]+)')
@@ -81,6 +81,8 @@ class MegaD:
protected=True, protected=True,
restore_on_restart=False, restore_on_restart=False,
extenders=None, extenders=None,
ext_in=None,
ext_act=None,
**kwargs, **kwargs,
): ):
"""Initialize.""" """Initialize."""
@@ -96,6 +98,8 @@ class MegaD:
else: else:
self.http = None self.http = None
self.extenders = extenders or [] self.extenders = extenders or []
self.ext_in = ext_in or {}
self.ext_act = ext_act or {}
self.poll_outs = poll_outs self.poll_outs = poll_outs
self.update_all = update_all if update_all is not None else True self.update_all = update_all if update_all is not None else True
self.nports = nports self.nports = nports
@@ -394,7 +398,7 @@ class MegaD:
if port == 'cmd': if port == 'cmd':
return return
try: try:
port = int(port) port = int_ignore(port)
except: except:
self.lg.warning('can not process %s', msg) self.lg.warning('can not process %s', msg)
return return
@@ -423,7 +427,7 @@ class MegaD:
asyncio.run_coroutine_threadsafe(self._notify(port, value), self.loop) asyncio.run_coroutine_threadsafe(self._notify(port, value), self.loop)
def subscribe(self, port, callback): def subscribe(self, port, callback):
port = int(port) port = int_ignore(port)
self.lg.debug( self.lg.debug(
f'subscribe %s %s', port, callback f'subscribe %s %s', port, callback
) )
@@ -514,6 +518,8 @@ class MegaD:
ret = defaultdict(lambda: defaultdict(list)) ret = defaultdict(lambda: defaultdict(list))
ret['mqtt_id'] = await self.get_mqtt_id() ret['mqtt_id'] = await self.get_mqtt_id()
ret['extenders'] = extenders = [] ret['extenders'] = extenders = []
ret['ext_in'] = ext_int = {}
ret['ext_acts'] = ext_acts = {}
async for port, cfg in self.scan_ports(nports): async for port, cfg in self.scan_ports(nports):
if cfg.pty == "0": if cfg.pty == "0":
ret['binary_sensor'][port].append({}) ret['binary_sensor'][port].append({})
@@ -533,15 +539,19 @@ class MegaD:
]) ])
elif cfg == MCP230: elif cfg == MCP230:
extenders.append(port) extenders.append(port)
ext_int[int(cfg.inta)] = port
values = await self.request(pt=port, cmd='get') values = await self.request(pt=port, cmd='get')
values = values.split(';') values = values.split(';')
for n in range(len(values)): for n in range(len(values)):
ext_page = await self.request(pt=port, ext=n) ext_page = await self.request(pt=port, ext=n)
ext_cfg = parse_config(ext_page) ext_cfg = parse_config(ext_page)
pt = f'{port}e{n}'
if ext_cfg.ety == '1': if ext_cfg.ety == '1':
ret['light'][f'{port}e{n}'].append({}) ret['light'][pt].append({})
elif ext_cfg.ety == '0': elif ext_cfg.ety == '0':
ret['binary_sensor'][f'{port}e{n}'].append({}) if ext_cfg.eact:
ext_acts[pt] = ext_cfg.eact
ret['binary_sensor'][pt].append({})
elif cfg == PCA9685: elif cfg == PCA9685:
extenders.append(port) extenders.append(port)
values = await self.request(pt=port, cmd='get') values = await self.request(pt=port, cmd='get')

View File

@@ -26,6 +26,7 @@ from .const import (
CONF_CUSTOM, CONF_CUSTOM,
CONF_SKIP, CONF_SKIP,
) )
from .tools import int_ignore
lg = logging.getLogger(__name__) lg = logging.getLogger(__name__)
@@ -61,7 +62,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, asyn
devices = [] devices = []
customize = hass.data.get(DOMAIN, {}).get(CONF_CUSTOM, {}) customize = hass.data.get(DOMAIN, {}).get(CONF_CUSTOM, {})
for port, cfg in config_entry.data.get('light', {}).items(): for port, cfg in config_entry.data.get('light', {}).items():
port = int(port) port = int_ignore(port)
c = customize.get(mid, {}).get(port, {}) c = customize.get(mid, {}).get(port, {})
if c.get(CONF_SKIP, False) or c.get(CONF_DOMAIN, 'light') != 'light': if c.get(CONF_SKIP, False) or c.get(CONF_DOMAIN, 'light') != 'light':
continue continue

View File

@@ -22,6 +22,8 @@ from .const import CONF_KEY, TEMP, HUM, W1, W1BUS, CONF_CONV_TEMPLATE
from .hub import MegaD from .hub import MegaD
import re import re
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\.]+)')
@@ -81,7 +83,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, asyn
hub: MegaD = hass.data['mega'][mid] hub: MegaD = hass.data['mega'][mid]
devices = [] devices = []
for port, cfg in config_entry.data.get('sensor', {}).items(): for port, cfg in config_entry.data.get('sensor', {}).items():
port = int(port) port = int_ignore(port)
for data in cfg: for data in cfg:
hub.lg.debug(f'add sensor on port %s with data %s', port, data) hub.lg.debug(f'add sensor on port %s with data %s', port, data)
sensor = Mega1WSensor( sensor = Mega1WSensor(

View File

@@ -18,6 +18,7 @@ from homeassistant.core import HomeAssistant
from . import hub as h from . import hub as h
from .entities import MegaOutPort from .entities import MegaOutPort
from .const import CONF_DIMMER, CONF_SWITCH, DOMAIN, CONF_CUSTOM, CONF_SKIP from .const import CONF_DIMMER, CONF_SWITCH, DOMAIN, CONF_CUSTOM, CONF_SKIP
from .tools import int_ignore
_LOGGER = lg = logging.getLogger(__name__) _LOGGER = lg = logging.getLogger(__name__)
@@ -50,7 +51,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, asyn
customize = hass.data.get(DOMAIN, {}).get(CONF_CUSTOM, {}) customize = hass.data.get(DOMAIN, {}).get(CONF_CUSTOM, {})
for port, cfg in config_entry.data.get('light', {}).items(): for port, cfg in config_entry.data.get('light', {}).items():
port = int(port) port = int_ignore(port)
c = customize.get(mid, {}).get(port, {}) c = customize.get(mid, {}).get(port, {})
if c.get(CONF_SKIP, False) or c.get(CONF_DOMAIN, 'light') != 'switch': if c.get(CONF_SKIP, False) or c.get(CONF_DOMAIN, 'light') != 'switch':
continue continue

View File

@@ -10,4 +10,11 @@ def make_ints(d: dict):
if 'm' not in d: if 'm' not in d:
d['m'] = 0 d['m'] = 0
if 'click' not in d: if 'click' not in d:
d['click'] = 0 d['click'] = 0
def int_ignore(x):
try:
return int(x)
except (TypeError, ValueError):
return x