Skip to content

Commit

Permalink
refactor: more idiomatic python syntax
Browse files Browse the repository at this point in the history
  • Loading branch information
andersevenrud committed Dec 31, 2022
1 parent 74d755b commit e7b0d56
Show file tree
Hide file tree
Showing 8 changed files with 69 additions and 84 deletions.
16 changes: 5 additions & 11 deletions custom_components/nexa_bridge_x/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,6 @@
from homeassistant.config_entries import ConfigEntry
from .const import DOMAIN
from .entities import NexaBinarySensorEntity
import logging

_LOGGER = logging.getLogger(__name__)


async def async_setup_entry(
Expand All @@ -23,14 +20,11 @@ async def async_setup_entry(
) -> None:
"""Set up all detected binary sensors"""
coordinator = hass.data[DOMAIN][entry.entry_id].coordinator
entities = []

for node in coordinator.data.nodes:
if node.is_binary_sensor():
_LOGGER.info("Found binary sensor %s: %s", node.id, node.name)
entities.append(
NexaBinarySensorEntity(coordinator, node, "switchBinary")
)
entities = (
NexaBinarySensorEntity(coordinator, node, "switchBinary")
for node in coordinator.data.nodes
if node.is_binary_sensor()
)

if entities:
async_add_entities(entities)
9 changes: 9 additions & 0 deletions custom_components/nexa_bridge_x/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,15 @@
"luminance"
]

ENERGY_ATTRS = [
"total_kilowatt_hours",
"current_wattage",
"current_kilowatt_hours",
"today_kilowatt_hours",
"yesterday_kilowatt_hours",
"month_kilowatt_hours"
]

SENSOR_MAP = {
"switchLevel": {
"name": "Level",
Expand Down
15 changes: 11 additions & 4 deletions custom_components/nexa_bridge_x/entities.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@
)
from .const import (DOMAIN, SENSOR_MAP, ENERGY_MAP)
from .nexa import NexaNode
import logging

_LOGGER = logging.getLogger(__name__)


def create_friendly_name(suffix: str, node: NexaNode) -> str:
Expand Down Expand Up @@ -66,6 +69,7 @@ class NexaDimmerEntity(NexaEntity, LightEntity):
_attr_supported_color_modes = {ColorMode.ONOFF, ColorMode.BRIGHTNESS}

def __init__(self, coordinator: DataUpdateCoordinator, node: NexaNode):
_LOGGER.info("Found light %s: %s", node.id, node.name)
super().__init__(coordinator)
self.id = node.id
self.switch_to_state = None
Expand Down Expand Up @@ -123,6 +127,7 @@ class NexaSwitchEntity(NexaEntity, SwitchEntity):
"""Entity for swtich"""

def __init__(self, coordinator: DataUpdateCoordinator, node: NexaNode):
_LOGGER.info("Found switch %s: %s", node.id, node.name)
super().__init__(coordinator)
self.id = node.id
self._attr_name = create_friendly_name("Switch", node)
Expand Down Expand Up @@ -162,6 +167,7 @@ def __init__(
node: NexaNode,
key: str
):
_LOGGER.info("Found %s sensor %s: %s", key, node.id, node.name)
super().__init__(coordinator)
self.id = node.id
self.key = key
Expand Down Expand Up @@ -200,12 +206,11 @@ class NexaBinarySensorEntity(NexaEntity, BinarySensorEntity):
def __init__(
self,
coordinator: DataUpdateCoordinator,
node: NexaNode,
key: str
node: NexaNode
):
_LOGGER.info("Found binary sensor %s: %s", node.id, node.name)
super().__init__(coordinator)
self.id = node.id
self.key = key
self._attr_is_on = None
self._attr_name = create_friendly_name("Binary Sensor", node)
self._attr_unique_id = f"binary_sensor_{node.id}"
Expand All @@ -214,7 +219,7 @@ def __init__(
def _handle_coordinator_update(self) -> None:
node = self.coordinator.get_node_by_id(self.id)
if node:
self._attr_is_on = node.get_value(self.key)
self._attr_is_on = node.get_value("switchBinary")
self._attr_name = create_friendly_name("Binary Sensor", node)
self.async_write_ha_state()

Expand All @@ -223,6 +228,7 @@ class NexaEnergyEntity(NexaEntity, SensorEntity):
"""Entity for global energy usage"""

def __init__(self, coordinator: DataUpdateCoordinator, attr: str):
_LOGGER.info("Found energy information: %s", attr)
super().__init__(coordinator)
self.id = attr
self._attr_native_value = None
Expand Down Expand Up @@ -261,6 +267,7 @@ def __init__(
coordinator: DataUpdateCoordinator,
node: NexaNode
):
_LOGGER.info("Found media player %s: %s", node.id, node.name)
super().__init__(coordinator)
self.id = node.id
self._attr_native_value = None
Expand Down
14 changes: 5 additions & 9 deletions custom_components/nexa_bridge_x/light.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,6 @@
from homeassistant.config_entries import ConfigEntry
from .const import DOMAIN
from .entities import NexaDimmerEntity
import logging

_LOGGER = logging.getLogger(__name__)


async def async_setup_entry(
Expand All @@ -23,12 +20,11 @@ async def async_setup_entry(
) -> None:
"""Set up all detected lights"""
coordinator = hass.data[DOMAIN][entry.entry_id].coordinator
entities = []

for node in coordinator.data.nodes:
if node.is_light():
_LOGGER.info("Found light %s: %s", node.id, node.name)
entities.append(NexaDimmerEntity(coordinator, node))
entities = (
NexaDimmerEntity(coordinator, node)
for node in coordinator.data.nodes
if node.is_light()
)

if entities:
async_add_entities(entities)
16 changes: 5 additions & 11 deletions custom_components/nexa_bridge_x/media_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,6 @@
from homeassistant.config_entries import ConfigEntry
from .const import DOMAIN
from .entities import NexaMediaPlayerEntity
import logging

_LOGGER = logging.getLogger(__name__)


async def async_setup_entry(
Expand All @@ -23,14 +20,11 @@ async def async_setup_entry(
) -> None:
"""Set up all detected media players"""
coordinator = hass.data[DOMAIN][entry.entry_id].coordinator
entities = []

for node in coordinator.data.nodes:
if node.is_binary_sensor():
_LOGGER.info("Found media player %s: %s", node.id, node.name)
entities.append(
NexaMediaPlayerEntity(coordinator, node)
)
entities = (
NexaMediaPlayerEntity(coordinator, node)
for node in coordinator.data.nodes
if node.is_media_player()
)

if entities:
async_add_entities(entities)
23 changes: 8 additions & 15 deletions custom_components/nexa_bridge_x/nexa.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@
NexaCallData = Any


def is_capable_of(node: NexaNode, items: list(str)):
"""Check if given capability is available"""
return any(cap for cap in items if cap in node.capabilities)


class NexaApiError(Exception):
"""Base error"""

Expand Down Expand Up @@ -289,27 +294,15 @@ def is_light(self) -> bool:

def is_sensor(self) -> bool:
"""If this is a sensor"""
for cap in NODE_SENSOR_CAPABILITIES:
if cap in self.capabilities:
return True

return False
return is_capable_of(self, NODE_SENSOR_CAPABILITIES)

def is_binary_sensor(self) -> bool:
"""If this is a binary sensor"""
for cap in NODE_BINARY_CAPABILITIES:
if cap in self.capabilities:
return True

return False
return is_capable_of(self, NODE_BINARY_CAPABILITIES)

def is_media_player(self) -> bool:
"""If this is a media player"""
for cap in NODE_MEDIA_CAPABILITIES:
if cap in self.capabilities:
return True

return False
return is_capable_of(self, NODE_MEDIA_CAPABILITIES)


class NexaData:
Expand Down
46 changes: 21 additions & 25 deletions custom_components/nexa_bridge_x/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,15 @@
License: MIT
"""
from __future__ import annotations
from itertools import chain
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.config_entries import ConfigEntry
from .const import DOMAIN
from .const import (DOMAIN, ENERGY_ATTRS)
from .entities import (
NexaSensorEntity,
NexaEnergyEntity
)
import logging

_LOGGER = logging.getLogger(__name__)


async def async_setup_entry(
Expand All @@ -27,24 +25,22 @@ async def async_setup_entry(
"""Set up all detected sensors"""
coordinator = hass.data[DOMAIN][entry.entry_id].coordinator

entities = [
NexaEnergyEntity(coordinator, "total_kilowatt_hours"),
NexaEnergyEntity(coordinator, "current_wattage"),
NexaEnergyEntity(coordinator, "today_kilowatt_hours"),
NexaEnergyEntity(coordinator, "current_kilowatt_hours"),
NexaEnergyEntity(coordinator, "yesterday_kilowatt_hours"),
NexaEnergyEntity(coordinator, "month_kilowatt_hours"),
]

for node in coordinator.data.nodes:
if node.is_sensor():
for name in node.get_sensor_capabilities():
_LOGGER.info("Found sensor %s: %s - %s",
node.id,
node.name,
name)

entities.append(NexaSensorEntity(coordinator, node, name))

if entities:
async_add_entities(entities)
found_sensors = filter(
lambda node: node.is_sensor(),
coordinator.data.nodes
)

energy_entities = (
NexaEnergyEntity(coordinator, attr)
for attr in (ENERGY_ATTRS)
)

sensor_entities = (
NexaSensorEntity(coordinator, node, name)
for node in found_sensors
for name in node.get_sensor_capabilities()
)

entities = chain(energy_entities, sensor_entities)

async_add_entities(entities)
14 changes: 5 additions & 9 deletions custom_components/nexa_bridge_x/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,6 @@
from homeassistant.config_entries import ConfigEntry
from .const import DOMAIN
from .entities import NexaSwitchEntity
import logging

_LOGGER = logging.getLogger(__name__)


async def async_setup_entry(
Expand All @@ -23,12 +20,11 @@ async def async_setup_entry(
) -> None:
"""Set up all detected switches"""
coordinator = hass.data[DOMAIN][entry.entry_id].coordinator
entities = []

for node in coordinator.data.nodes:
if node.is_switch():
_LOGGER.info("Found switch %s: %s", node.id, node.name)
entities.append(NexaSwitchEntity(coordinator, node))
entities = (
NexaSwitchEntity(coordinator, node)
for node in coordinator.data.nodes
if node.is_switch()
)

if entities:
async_add_entities(entities)

0 comments on commit e7b0d56

Please sign in to comment.