mirror of
https://github.com/andvikt/mega_hacs.git
synced 2025-12-12 01:24:29 +05:00
Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
db52d93ee4 | ||
|
|
a38de65071 | ||
|
|
6d1aa47e4f | ||
|
|
cc122cf98b | ||
|
|
a6ff177577 |
14
.github/workflows/hassfest.yaml
vendored
Normal file
14
.github/workflows/hassfest.yaml
vendored
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
name: Validate with hassfest
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
pull_request:
|
||||||
|
schedule:
|
||||||
|
- cron: "0 0 * * *"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
validate:
|
||||||
|
runs-on: "ubuntu-latest"
|
||||||
|
steps:
|
||||||
|
- uses: "actions/checkout@v2"
|
||||||
|
- uses: home-assistant/actions/hassfest@master
|
||||||
17
.github/workflows/validate.yaml
vendored
Normal file
17
.github/workflows/validate.yaml
vendored
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
name: Validate
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
pull_request:
|
||||||
|
schedule:
|
||||||
|
- cron: "0 0 * * *"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
validate:
|
||||||
|
runs-on: "ubuntu-latest"
|
||||||
|
steps:
|
||||||
|
- uses: "actions/checkout@v2"
|
||||||
|
- name: HACS validation
|
||||||
|
uses: "hacs/action@main"
|
||||||
|
with:
|
||||||
|
category: "integration"
|
||||||
@@ -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(
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
"domain": "mega",
|
"domain": "mega",
|
||||||
"name": "mega",
|
"name": "mega",
|
||||||
"config_flow": true,
|
"config_flow": true,
|
||||||
"documentation": "https://www.home-assistant.io/integrations/mega",
|
"documentation": "https://www.home-assistant.io/integrations/mega_hacs",
|
||||||
"requirements": [
|
"requirements": [
|
||||||
"beautifulsoup4",
|
"beautifulsoup4",
|
||||||
"lxml"
|
"lxml"
|
||||||
@@ -15,5 +15,6 @@
|
|||||||
],
|
],
|
||||||
"codeowners": [
|
"codeowners": [
|
||||||
"@andvikt"
|
"@andvikt"
|
||||||
]
|
],
|
||||||
|
"issue_tracker": "https://github.com/andvikt/mega_hacs/issues"
|
||||||
}
|
}
|
||||||
@@ -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
|
||||||
|
|||||||
5
install.sh
Normal file
5
install.sh
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
git clone https://github.com/andvikt/mega_hacs.git
|
||||||
|
mkdir custom_components
|
||||||
|
cp mega_hacs/custom_components/mega custom_components/mega
|
||||||
|
rm -fR mega_hacs
|
||||||
19
readme.md
19
readme.md
@@ -13,15 +13,18 @@
|
|||||||
## Устройства
|
## Устройства
|
||||||
Поддерживаются устройства: light, switch, binary_sensor, sensor. light может работать как диммер
|
Поддерживаются устройства: light, switch, binary_sensor, sensor. light может работать как диммер
|
||||||
## Установка
|
## Установка
|
||||||
В папке config/custom_components выполнить:
|
Рекомендованнй способ - через [HACS](https://hacs.xyz/docs/installation/installation).
|
||||||
```shell
|
После установки HACS, нужно перейти в меню hacs -> integrations, далее в верхнем правом углу
|
||||||
git clone https://github.com/andvikt/mega.git
|
нажать три точки, где будет `Custom repositories`, открыть, нажать add и добавить `https://github.com/andvikt/mega_hacs.git`
|
||||||
```
|
|
||||||
Обновление:
|
Альтернативный способ установки:
|
||||||
```shell
|
```shell
|
||||||
git pull
|
# из папки с конфигом
|
||||||
```
|
wget -q -O - https://raw.githubusercontent.com/andvikt/mega_hacs/master/install.sh | bash -
|
||||||
|
```
|
||||||
Перезагрузить HA
|
Перезагрузить HA
|
||||||
|
|
||||||
|
Для обновления повторить
|
||||||
## Зависимости
|
## Зависимости
|
||||||
Перед использованием необходимо настроить интеграцию mqtt в HomeAssistant
|
Перед использованием необходимо настроить интеграцию mqtt в HomeAssistant
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user