mirror of
https://github.com/andvikt/mega_hacs.git
synced 2025-12-11 17:14:28 +05:00
fix updater
This commit is contained in:
@@ -11,7 +11,7 @@ from homeassistant.helpers.entity_component import EntityComponent
|
|||||||
from homeassistant.helpers.service import bind_hass
|
from homeassistant.helpers.service import bind_hass
|
||||||
from homeassistant.components import mqtt
|
from homeassistant.components import mqtt
|
||||||
from homeassistant.config_entries import ConfigEntry
|
from homeassistant.config_entries import ConfigEntry
|
||||||
from .const import DOMAIN, CONF_INVERT
|
from .const import DOMAIN, CONF_INVERT, CONF_RELOAD
|
||||||
from .hub import MegaD
|
from .hub import MegaD
|
||||||
|
|
||||||
|
|
||||||
@@ -60,6 +60,8 @@ async def async_setup(hass: HomeAssistant, config: dict):
|
|||||||
hass.services.async_register(
|
hass.services.async_register(
|
||||||
DOMAIN, 'save', _save_service,
|
DOMAIN, 'save', _save_service,
|
||||||
)
|
)
|
||||||
|
for id, hub in hass.data[DOMAIN].__items__():
|
||||||
|
_POLL_TASKS[id] = asyncio.create_task(hub.poll())
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
@@ -73,22 +75,25 @@ async def _add_mega(hass: HomeAssistant, id, data: dict):
|
|||||||
raise Exception("not authentificated")
|
raise Exception("not authentificated")
|
||||||
mid = await hub.get_mqtt_id()
|
mid = await hub.get_mqtt_id()
|
||||||
hub.mqtt_id = mid
|
hub.mqtt_id = mid
|
||||||
_POLL_TASKS[id] = asyncio.create_task(hub.poll())
|
|
||||||
return hub
|
return hub
|
||||||
|
|
||||||
|
|
||||||
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
|
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
|
||||||
print(entry.entry_id)
|
print(entry.entry_id)
|
||||||
id = entry.data.get('id', entry.entry_id)
|
id = entry.data.get('id', entry.entry_id)
|
||||||
hub = await _add_mega(hass, id, dict(entry.data))
|
data = dict(entry.data)
|
||||||
|
data.update(entry.options or {})
|
||||||
|
hub = await _add_mega(hass, id, data)
|
||||||
_hubs[entry.entry_id] = hub
|
_hubs[entry.entry_id] = hub
|
||||||
_subs[entry.entry_id] = entry.add_update_listener(update)
|
_subs[entry.entry_id] = entry.add_update_listener(update)
|
||||||
|
|
||||||
for platform in PLATFORMS:
|
for platform in PLATFORMS:
|
||||||
hass.async_create_task(
|
hass.async_create_task(
|
||||||
hass.config_entries.async_forward_entry_setup(
|
hass.config_entries.async_forward_entry_setup(
|
||||||
entry, platform
|
entry, platform
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
_POLL_TASKS[id] = asyncio.create_task(hub.poll())
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
@@ -96,9 +101,9 @@ async def update(hass: HomeAssistant, entry: ConfigEntry):
|
|||||||
hub: MegaD = hass.data[DOMAIN][entry.data[CONF_ID]]
|
hub: MegaD = hass.data[DOMAIN][entry.data[CONF_ID]]
|
||||||
hub.poll_interval = entry.options[CONF_SCAN_INTERVAL]
|
hub.poll_interval = entry.options[CONF_SCAN_INTERVAL]
|
||||||
hub.port_to_scan = entry.options[CONF_PORT_TO_SCAN]
|
hub.port_to_scan = entry.options[CONF_PORT_TO_SCAN]
|
||||||
# hub.inverted = map(lambda x: x.strip(), (
|
if entry.options[CONF_RELOAD]:
|
||||||
# entry.options.get(CONF_INVERT, '').split(',')
|
await async_remove_entry(hass, entry)
|
||||||
# )
|
await async_setup_entry(hass, entry)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
@@ -111,7 +116,6 @@ async def async_remove_entry(hass, entry) -> None:
|
|||||||
_hubs.pop(entry.entry_id)
|
_hubs.pop(entry.entry_id)
|
||||||
unsub = _subs.pop(entry.entry_id)
|
unsub = _subs.pop(entry.entry_id)
|
||||||
unsub()
|
unsub()
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
@bind_hass
|
@bind_hass
|
||||||
@@ -119,8 +123,3 @@ async def _save_service(hass: HomeAssistant, mega_id='def'):
|
|||||||
hub: MegaD = hass.data[DOMAIN][mega_id]
|
hub: MegaD = hass.data[DOMAIN][mega_id]
|
||||||
await hub.save()
|
await hub.save()
|
||||||
|
|
||||||
|
|
||||||
async def _is_alive(cond: asyncio.Condition, msg):
|
|
||||||
async with cond:
|
|
||||||
cond.notify_all()
|
|
||||||
|
|
||||||
|
|||||||
@@ -104,8 +104,7 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
|
|||||||
vol.Optional(CONF_SCAN_INTERVAL, default=e[CONF_SCAN_INTERVAL]): int,
|
vol.Optional(CONF_SCAN_INTERVAL, default=e[CONF_SCAN_INTERVAL]): int,
|
||||||
vol.Optional(CONF_PORT_TO_SCAN, default=e.get(CONF_PORT_TO_SCAN, 0)): int,
|
vol.Optional(CONF_PORT_TO_SCAN, default=e.get(CONF_PORT_TO_SCAN, 0)): int,
|
||||||
vol.Optional(CONF_RELOAD, default=False): bool,
|
vol.Optional(CONF_RELOAD, default=False): bool,
|
||||||
vol.Optional(CONF_INVERT): vol.Set(),
|
# vol.Optional(CONF_INVERT, default=''): str,
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
print(ret)
|
|
||||||
return ret
|
return ret
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
|
from datetime import datetime
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
|
|
||||||
import aiohttp
|
import aiohttp
|
||||||
@@ -22,12 +23,12 @@ class MegaD:
|
|||||||
host: str,
|
host: str,
|
||||||
password: str,
|
password: str,
|
||||||
mqtt: mqtt.MQTT,
|
mqtt: mqtt.MQTT,
|
||||||
lg:logging.Logger,
|
lg: logging.Logger,
|
||||||
id: str,
|
id: str,
|
||||||
mqtt_id: str = None,
|
mqtt_id: str = None,
|
||||||
scan_interval=60,
|
scan_interval=60,
|
||||||
port_to_scan=0,
|
port_to_scan=0,
|
||||||
inverted:typing.List[int] = None,
|
inverted: typing.List[int] = None,
|
||||||
**kwargs,
|
**kwargs,
|
||||||
):
|
):
|
||||||
"""Initialize."""
|
"""Initialize."""
|
||||||
@@ -47,6 +48,7 @@ class MegaD:
|
|||||||
self.sensors = []
|
self.sensors = []
|
||||||
self.port_to_scan = port_to_scan
|
self.port_to_scan = port_to_scan
|
||||||
self.inverted = inverted or []
|
self.inverted = inverted or []
|
||||||
|
self.last_update = datetime.now()
|
||||||
if not mqtt_id:
|
if not mqtt_id:
|
||||||
_id = host.split(".")[-1]
|
_id = host.split(".")[-1]
|
||||||
self.mqtt_id = f"megad/{_id}"
|
self.mqtt_id = f"megad/{_id}"
|
||||||
@@ -59,10 +61,11 @@ class MegaD:
|
|||||||
self.entities.append(ent)
|
self.entities.append(ent)
|
||||||
|
|
||||||
async def get_sensors(self):
|
async def get_sensors(self):
|
||||||
|
self.lg.debug(self.sensors)
|
||||||
_ports = {x.port for x in self.sensors}
|
_ports = {x.port for x in self.sensors}
|
||||||
for x in _ports:
|
for x in _ports:
|
||||||
await self.get_port(x)
|
await self.get_port(x)
|
||||||
await asyncio.sleep(self.poll_interval)
|
await asyncio.sleep(0.1)
|
||||||
|
|
||||||
async def poll(self):
|
async def poll(self):
|
||||||
"""
|
"""
|
||||||
@@ -70,36 +73,37 @@ class MegaD:
|
|||||||
offline
|
offline
|
||||||
"""
|
"""
|
||||||
self._loop = asyncio.get_event_loop()
|
self._loop = asyncio.get_event_loop()
|
||||||
if self.sensors:
|
|
||||||
await self.subscribe(self.sensors[0].port, callback=self._notify)
|
|
||||||
else:
|
|
||||||
await self.subscribe(self.port_to_scan, callback=self._notify)
|
|
||||||
while True:
|
|
||||||
async with self.is_alive:
|
|
||||||
if len(self.sensors) > 0:
|
|
||||||
await self.get_sensors()
|
|
||||||
else:
|
|
||||||
await self.get_port(self.port_to_scan)
|
|
||||||
|
|
||||||
try:
|
while True:
|
||||||
await asyncio.wait_for(self.is_alive.wait(), timeout=5)
|
if len(self.sensors) > 0:
|
||||||
self.hass.states.async_set(
|
await self.get_sensors()
|
||||||
f'mega.{self.id}',
|
else:
|
||||||
'online',
|
await self.get_port(self.port_to_scan)
|
||||||
)
|
|
||||||
self.online = True
|
await asyncio.sleep(1)
|
||||||
except asyncio.TimeoutError:
|
if (datetime.now() - self.last_update).total_seconds() > self.poll_interval:
|
||||||
self.online = False
|
await self.get_port(self.port_to_scan)
|
||||||
|
await asyncio.sleep(1)
|
||||||
|
if (datetime.now() - self.last_update).total_seconds() > self.poll_interval:
|
||||||
|
self.lg.warning('mega is offline')
|
||||||
self.hass.states.async_set(
|
self.hass.states.async_set(
|
||||||
f'mega.{self.id}',
|
f'mega.{self.id}',
|
||||||
'offline',
|
'offline',
|
||||||
)
|
)
|
||||||
for x in self.entities:
|
self.online = False
|
||||||
try:
|
else:
|
||||||
await x.async_update_ha_state()
|
self.hass.states.async_set(
|
||||||
except RuntimeError:
|
f'mega.{self.id}',
|
||||||
pass
|
'online',
|
||||||
await asyncio.sleep(self.poll_interval)
|
)
|
||||||
|
self.online = True
|
||||||
|
|
||||||
|
for x in self.entities:
|
||||||
|
try:
|
||||||
|
await x.async_update_ha_state()
|
||||||
|
except RuntimeError:
|
||||||
|
pass
|
||||||
|
await asyncio.sleep(self.poll_interval - 1)
|
||||||
|
|
||||||
async def _async_notify(self):
|
async def _async_notify(self):
|
||||||
async with self.is_alive:
|
async with self.is_alive:
|
||||||
@@ -187,6 +191,7 @@ class MegaD:
|
|||||||
self.lg.debug(
|
self.lg.debug(
|
||||||
'process incomming message: %s', msg
|
'process incomming message: %s', msg
|
||||||
)
|
)
|
||||||
|
self.last_update = datetime.now()
|
||||||
return callback(msg)
|
return callback(msg)
|
||||||
|
|
||||||
self.lg.debug(
|
self.lg.debug(
|
||||||
|
|||||||
@@ -107,6 +107,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, asyn
|
|||||||
CONF_KEY: key,
|
CONF_KEY: key,
|
||||||
})
|
})
|
||||||
devices.append(sensor)
|
devices.append(sensor)
|
||||||
|
hub.sensors.append(sensor)
|
||||||
|
|
||||||
async_add_devices(devices)
|
async_add_devices(devices)
|
||||||
|
|
||||||
@@ -135,11 +136,6 @@ class Mega1WSensor(BaseMegaEntity):
|
|||||||
self._device_class = device_class
|
self._device_class = device_class
|
||||||
self._unit_of_measurement = unit_of_measurement
|
self._unit_of_measurement = unit_of_measurement
|
||||||
|
|
||||||
async def async_added_to_hass(self) -> None:
|
|
||||||
|
|
||||||
await super(Mega1WSensor, self).async_added_to_hass()
|
|
||||||
self.mega.sensors.append(self)
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def unit_of_measurement(self):
|
def unit_of_measurement(self):
|
||||||
return self._unit_of_measurement
|
return self._unit_of_measurement
|
||||||
|
|||||||
Reference in New Issue
Block a user