Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

v2.1 - Refactor integrations #132

Merged
merged 11 commits into from
May 2, 2024
Merged
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
# Changelog

## 2.1.0

Major refactor:

- Code cleanup
- Fix thread safe issues
- Fix typos
- Improve performance
- Add util for translations
- Removed service of update configuration

New components:

- Consider Away Interval - Number
- Update API Interval - Number
- Update Entities Interval - Number
- Log Incoming Messages - Switch

## 2.0.32

- Ignore interfaces that were removed
Expand Down
88 changes: 68 additions & 20 deletions custom_components/edgeos/__init__.py
Original file line number Diff line number Diff line change
@@ -1,60 +1,108 @@
"""
Init.
This component provides support for EdgeOS based devices.
For more details about this component, please refer to the documentation at
https://github.com/elad-bar/ha-EdgeOS
"""
import logging
import sys

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EVENT_HOMEASSISTANT_START
from homeassistant.core import HomeAssistant

from .component.helpers import async_set_ha, clear_ha, get_ha
from .configuration.helpers.const import DOMAIN
from .common.consts import DEFAULT_NAME, DOMAIN
from .common.entity_descriptions import PLATFORMS
from .managers.config_manager import ConfigManager
from .managers.coordinator import Coordinator
from .managers.password_manager import PasswordManager
from .models.exceptions import LoginError

_LOGGER = logging.getLogger(__name__)


async def async_setup(hass, config):
async def async_setup(_hass, _config):
return True


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up a component."""
"""Set up a EdgeOS component."""
initialized = False

try:
_LOGGER.debug(f"Starting async_setup_entry of {DOMAIN}")
entry.add_update_listener(async_options_updated)
_LOGGER.debug("Setting up")
entry_config = {key: entry.data[key] for key in entry.data}

await async_set_ha(hass, entry)
_LOGGER.debug("Starting up password manager")
await PasswordManager.decrypt(hass, entry_config, entry.entry_id)

initialized = True
_LOGGER.debug("Starting up configuration manager")
config_manager = ConfigManager(hass, entry)
await config_manager.initialize(entry_config)

is_initialized = config_manager.is_initialized

if is_initialized:
_LOGGER.debug("Starting up coordinator")
coordinator = Coordinator(hass, config_manager)

hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coordinator

if hass.is_running:
_LOGGER.debug("Initializing coordinator")
await coordinator.initialize()

else:
_LOGGER.debug("Registering listener for HA started event")
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_START, coordinator.on_home_assistant_start
)

_LOGGER.info("Finished loading integration")

initialized = is_initialized

_LOGGER.debug(f"Setup status: {is_initialized}")

except LoginError:
_LOGGER.info(f"Failed to login {DEFAULT_NAME} API, cannot log integration")

except Exception as ex:
exc_type, exc_obj, tb = sys.exc_info()
line_number = tb.tb_lineno

_LOGGER.error(f"Failed to load integration, error: {ex}, line: {line_number}")
_LOGGER.error(
f"Failed to load {DEFAULT_NAME}, error: {ex}, line: {line_number}"
)

return initialized


async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Unload a config entry."""
ha = get_ha(hass, entry.entry_id)
_LOGGER.info(f"Unloading {DOMAIN} integration, Entry ID: {entry.entry_id}")

coordinator: Coordinator = hass.data[DOMAIN][entry.entry_id]

if ha is not None:
await ha.async_remove(entry)
await coordinator.terminate()

clear_ha(hass, entry.entry_id)
for platform in PLATFORMS:
await hass.config_entries.async_forward_entry_unload(entry, platform)

del hass.data[DOMAIN][entry.entry_id]

return True


async def async_options_updated(hass: HomeAssistant, entry: ConfigEntry):
"""Triggered by config entry options updates."""
_LOGGER.info(f"async_options_updated, Entry: {entry.as_dict()} ")
async def async_remove_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Unload a config entry."""
_LOGGER.info(f"Removing {DOMAIN} integration, Entry ID: {entry.entry_id}")

entry_id = entry.entry_id

coordinator: Coordinator = hass.data[DOMAIN][entry_id]

await coordinator.config_manager.remove(entry_id)

ha = get_ha(hass, entry.entry_id)
result = await async_unload_entry(hass, entry)

if ha is not None:
await ha.async_update_entry(entry)
return result
64 changes: 44 additions & 20 deletions custom_components/edgeos/binary_sensor.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,58 @@
"""
Support for binary sensors.
"""
from __future__ import annotations

import logging

from .core.components.binary_sensor import CoreBinarySensor
from .core.helpers.setup_base_entry import async_setup_base_entry
from homeassistant.components.binary_sensor import BinarySensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_ICON, Platform
from homeassistant.core import HomeAssistant

from .common.base_entity import IntegrationBaseEntity, async_setup_base_entry
from .common.consts import ATTR_ATTRIBUTES, ATTR_IS_ON
from .common.entity_descriptions import IntegrationBinarySensorEntityDescription
from .common.enums import DeviceTypes
from .managers.coordinator import Coordinator

_LOGGER = logging.getLogger(__name__)


async def async_setup_entry(hass, config_entry, async_add_devices):
"""Set up the component."""
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities
):
await async_setup_base_entry(
hass,
config_entry,
async_add_devices,
CoreBinarySensor.get_domain(),
CoreBinarySensor.get_component,
entry,
Platform.BINARY_SENSOR,
IntegrationBinarySensorEntity,
async_add_entities,
)


async def async_unload_entry(hass, config_entry):
_LOGGER.info(
f"Unload entry for {CoreBinarySensor.get_domain()} domain: {config_entry}"
)
class IntegrationBinarySensorEntity(IntegrationBaseEntity, BinarySensorEntity):
"""Representation of a sensor."""

def __init__(
self,
hass: HomeAssistant,
entity_description: IntegrationBinarySensorEntityDescription,
coordinator: Coordinator,
device_type: DeviceTypes,
item_id: str | None,
):
super().__init__(hass, entity_description, coordinator, device_type, item_id)

self._attr_device_class = entity_description.device_class

def update_component(self, data):
"""Fetch new state parameters for the sensor."""
if data is not None:
is_on = data.get(ATTR_IS_ON)
attributes = data.get(ATTR_ATTRIBUTES)
icon = data.get(ATTR_ICON)

return True
self._attr_is_on = is_on
self._attr_extra_state_attributes = attributes

if icon is not None:
self._attr_icon = icon

async def async_remove_entry(hass, entry) -> None:
_LOGGER.info(f"Remove entry for {CoreBinarySensor.get_domain()} entry: {entry}")
else:
self._attr_is_on = None
Loading
Loading