Compare commits

...

10 Commits

Author SHA1 Message Date
Andrey
0c43e61c59 make fake http response 2021-02-18 11:11:30 +03:00
Andrey
0a71be693e fix bugs 2021-02-18 11:00:41 +03:00
Andrey
8146148d0c fix bugs 2021-02-18 10:46:17 +03:00
Andrey
e0eaafd0fa fix bugs 2021-02-18 10:40:09 +03:00
Andrey
51f3eb3b19 fix bugs 2021-02-18 10:23:27 +03:00
Andrey
1716651497 fix bugs 2021-02-18 10:12:01 +03:00
Andrey
a87e8139a7 fix bugs 2021-02-18 09:53:30 +03:00
Andrey
358d29f8fd fix bugs 2021-02-18 09:27:40 +03:00
Andrey
fcce9dcfc1 fix bugs 2021-02-17 22:01:33 +03:00
Andrey
4fe2469a01 fix bugs 2021-02-17 19:10:58 +03:00
5 changed files with 47 additions and 35 deletions

View File

@@ -24,7 +24,7 @@ from .http import MegaView
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
CUSTOMIZE_PORT = vol.Schema({ CUSTOMIZE_PORT = {
vol.Optional(CONF_SKIP, description='исключить порт из сканирования', default=False): bool, vol.Optional(CONF_SKIP, description='исключить порт из сканирования', default=False): bool,
vol.Optional(CONF_INVERT, default=False): bool, vol.Optional(CONF_INVERT, default=False): bool,
vol.Optional(CONF_NAME): vol.Any(str, { vol.Optional(CONF_NAME): vol.Any(str, {
@@ -42,16 +42,15 @@ CUSTOMIZE_PORT = vol.Schema({
vol.Optional(CONF_ACTION): cv.script_action, # пока не реализовано vol.Optional(CONF_ACTION): cv.script_action, # пока не реализовано
vol.Optional(CONF_GET_VALUE, default=True): bool, vol.Optional(CONF_GET_VALUE, default=True): bool,
vol.Optional(CONF_CONV_TEMPLATE): cv.template vol.Optional(CONF_CONV_TEMPLATE): cv.template
}) }
CUSTOMIZE_DS2413 = vol.Schema({ CUSTOMIZE_DS2413 = {
vol.Optional(str.lower, description='адрес и индекс устройства'): CUSTOMIZE_PORT vol.Optional(str.lower, description='адрес и индекс устройства'): CUSTOMIZE_PORT
}) }
CONFIG_SCHEMA = vol.Schema( CONFIG_SCHEMA = vol.Schema(
{ {
DOMAIN: { DOMAIN: {
vol.Optional(CONF_ALLOW_HOSTS): [str], vol.Optional(CONF_ALLOW_HOSTS): [str],
# vol.Optional(CONF_FORCE_D, description='Принудительно слать d после срабатывания входа', default=False): bool,
vol.Required(str, description='id меги из веб-интерфейса'): { vol.Required(str, description='id меги из веб-интерфейса'): {
vol.Optional(CONF_FORCE_D, description='Принудительно слать d после срабатывания входа', default=False): bool, vol.Optional(CONF_FORCE_D, description='Принудительно слать d после срабатывания входа', default=False): bool,
vol.Optional(int, description='номер порта'): vol.Any( vol.Optional(int, description='номер порта'): vol.Any(

View File

@@ -48,6 +48,9 @@ class BaseMegaEntity(CoordinatorEntity, RestoreEntity):
index=None, index=None,
): ):
super().__init__(mega.updater) super().__init__(mega.updater)
self.http_cmd = http_cmd
self._state: State = None self._state: State = None
self.port = port self.port = port
self.config_entry = config_entry self.config_entry = config_entry
@@ -60,9 +63,10 @@ class BaseMegaEntity(CoordinatorEntity, RestoreEntity):
self._name = name or f"{mega.id}_{port}" + \ self._name = name or f"{mega.id}_{port}" + \
(f"_{id_suffix}" if id_suffix else "") (f"_{id_suffix}" if id_suffix else "")
self._customize: dict = None self._customize: dict = None
self.http_cmd = http_cmd
self.index = index self.index = index
self.addr = addr self.addr = addr
if self.http_cmd == 'ds2413':
self.mega.ds2413_ports |= {self.port}
@property @property
def customize(self): def customize(self):
@@ -125,7 +129,8 @@ class BaseMegaEntity(CoordinatorEntity, RestoreEntity):
_task_set_ev_on = asyncio.create_task(_set_events_on()) _task_set_ev_on = asyncio.create_task(_set_events_on())
async def get_state(self): async def get_state(self):
if self.mega.mqtt is None: self.lg.debug(f'state is %s', self.state)
if not self.mega.mqtt_inputs:
self.async_write_ha_state() self.async_write_ha_state()
@@ -249,18 +254,21 @@ class MegaOutPort(MegaPushEntity):
elif val is not None: elif val is not None:
val = val.get("value") val = val.get("value")
if self.index and self.addr: if self.index and self.addr:
_val = val.get(self.addr) if not isinstance(val, dict):
if not isinstance(val, str): self.mega.lg.warning(f'{self.entity_id}: {val} is not a dict')
self.mega.lg.warning(f'{self} has wrong state: {val}') return
_val = val.get(self.addr, val.get(self.addr.lower(), val.get(self.addr.upper())))
if not isinstance(_val, str):
self.mega.lg.warning(f'{self.entity_id}: can not get {self.addr} from {val}, recieved {_val}')
return return
_val = _val.split('/') _val = _val.split('/')
if len(_val) >= 2: if len(_val) >= 2:
val = val[self.index] val = _val[self.index]
else: else:
self.mega.lg.warning(f'{self} has wrong state: {val}') self.mega.lg.warning(f'{self.entity_id}: {_val} has wrong length')
return return
elif self.index and self.addr is None: elif self.index and self.addr is None:
self.mega.lg.warning(f'{self} does not has addr') self.mega.lg.warning(f'{self.entity_id} does not has addr')
return return
if not self.invert: if not self.invert:
@@ -284,10 +292,10 @@ class MegaOutPort(MegaPushEntity):
cmd = brightness cmd = brightness
else: else:
cmd = 1 if not self.invert else 0 cmd = 1 if not self.invert else 0
cmd = {"cmd": f"{self.cmd_port}:{cmd}"} _cmd = {"cmd": f"{self.cmd_port}:{cmd}"}
if self.addr: if self.addr:
cmd['addr'] = self.addr _cmd['addr'] = self.addr
await self.mega.request(**cmd) await self.mega.request(**_cmd)
if self.index is not None: if self.index is not None:
# обновление текущего стейта для ds2413 # обновление текущего стейта для ds2413
await self.mega.get_port( await self.mega.get_port(
@@ -303,10 +311,10 @@ class MegaOutPort(MegaPushEntity):
async def async_turn_off(self, **kwargs) -> None: async def async_turn_off(self, **kwargs) -> None:
cmd = "0" if not self.invert else "1" cmd = "0" if not self.invert else "1"
cmd = {"cmd": f"{self.cmd_port}:{cmd}"} _cmd = {"cmd": f"{self.cmd_port}:{cmd}"}
if self.addr: if self.addr:
cmd['addr'] = self.addr _cmd['addr'] = self.addr
await self.mega.request(**cmd) await self.mega.request(**_cmd)
if self.index is not None: if self.index is not None:
# обновление текущего стейта для ds2413 # обновление текущего стейта для ds2413
await self.mega.get_port( await self.mega.get_port(

View File

@@ -78,7 +78,8 @@ class MegaView(HomeAssistantView):
template.hass = hass template.hass = hass
ret = template.async_render(data) ret = template.async_render(data)
_LOGGER.debug('response %s', ret) _LOGGER.debug('response %s', ret)
ret = Response(body=ret or 'd', content_type='text/plain', headers={'Server': 's', 'Date': 'n'}) ret = Response(body='', content_type='text/plain', headers={'Server': 's', 'Date': 'n'})
await hub.request(cmd=ret)
return ret return ret
async def later_update(self, hub): async def later_update(self, hub):

View File

@@ -101,6 +101,7 @@ class MegaD:
self.cnd = asyncio.Condition() self.cnd = asyncio.Condition()
self.online = True self.online = True
self.entities: typing.List[BaseMegaEntity] = [] self.entities: typing.List[BaseMegaEntity] = []
self.ds2413_ports = set()
self.poll_interval = scan_interval self.poll_interval = scan_interval
self.subs = None self.subs = None
self.lg: logging.Logger = lg.getChild(self.id) self.lg: logging.Logger = lg.getChild(self.id)
@@ -191,25 +192,25 @@ class MegaD:
) )
self.online = True self.online = True
async def _get_ds2413(self):
"""
обновление ds2413 устройств
:return:
"""
for x in self.ds2413_ports:
self.lg.debug(f'poll ds2413 for %s', x)
await self.get_port(
port=x,
force_http=True,
http_cmd='list',
conv=False
)
async def poll(self): async def poll(self):
""" """
Polling ports Polling ports
""" """
self.lg.debug('poll') self.lg.debug('poll')
ds2413_polled = []
for x in self.entities:
# обновление ds2413 устройств
if x.http_cmd == 'ds2413':
self.lg.debug(f'poll ds2413 for {x.entity_id}')
if x.port in ds2413_polled:
continue
await self.get_port(
port=x.port,
force_http=True,
http_cmd='list',
conv=False
)
ds2413_polled.append(x.port)
if self.mqtt is None: if self.mqtt is None:
await self.get_all_ports() await self.get_all_ports()
await self.get_sensors(only_list=True) await self.get_sensors(only_list=True)
@@ -219,6 +220,7 @@ class MegaD:
await self.get_sensors() await self.get_sensors()
else: else:
await self.get_port(self.port_to_scan) await self.get_port(self.port_to_scan)
await self._get_ds2413()
return self.values return self.values
async def get_mqtt_id(self): async def get_mqtt_id(self):
@@ -313,6 +315,8 @@ class MegaD:
if not self.mqtt_inputs: if not self.mqtt_inputs:
ret = await self.request(cmd='all') ret = await self.request(cmd='all')
for port, x in enumerate(ret.split(';')): for port, x in enumerate(ret.split(';')):
if port in self.ds2413_ports:
continue
if check_skip and not port in self.ports: if check_skip and not port in self.ports:
continue continue
ret = self.parse_response(x) ret = self.parse_response(x)

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": "v0.4.1b3" "version": "v0.4.1b7"
} }