Code cleanup

This commit is contained in:
tomaae 2020-12-25 20:28:36 +01:00
parent 4e6b29b1aa
commit 88c79bcada
4 changed files with 156 additions and 188 deletions

View file

@ -1,6 +1,7 @@
"""Support for the Mikrotik Router binary sensor service.""" """Support for the Mikrotik Router binary sensor service."""
import logging import logging
from typing import Any, Dict, Optional
from homeassistant.components.binary_sensor import ( from homeassistant.components.binary_sensor import (
BinarySensorEntity, BinarySensorEntity,
@ -210,18 +211,18 @@ class MikrotikControllerBinarySensor(BinarySensorEntity):
self._attrs = {ATTR_ATTRIBUTION: ATTRIBUTION} self._attrs = {ATTR_ATTRIBUTION: ATTRIBUTION}
@property @property
def name(self): def name(self) -> str:
"""Return the name.""" """Return the name."""
return f"{self._inst} {self._type[ATTR_LABEL]}" return f"{self._inst} {self._type[ATTR_LABEL]}"
@property @property
def device_state_attributes(self): def device_state_attributes(self) -> Dict[str, Any]:
"""Return the state attributes.""" """Return the state attributes."""
return self._attrs return self._attrs
@property @property
def unique_id(self): def unique_id(self) -> str:
"""Return a unique_id for this entity.""" """Return a unique id for this entity."""
return f"{self._inst.lower()}-{self._sensor.lower()}" return f"{self._inst.lower()}-{self._sensor.lower()}"
@property @property
@ -230,8 +231,8 @@ class MikrotikControllerBinarySensor(BinarySensorEntity):
return self._ctrl.connected() return self._ctrl.connected()
@property @property
def device_info(self): def device_info(self) -> Dict[str, Any]:
"""Return a port description for device registry.""" """Return a description for device registry."""
info = { info = {
"manufacturer": self._ctrl.data["resource"]["platform"], "manufacturer": self._ctrl.data["resource"]["platform"],
"model": self._ctrl.data["resource"]["board-name"], "model": self._ctrl.data["resource"]["board-name"],
@ -250,22 +251,22 @@ class MikrotikControllerBinarySensor(BinarySensorEntity):
return info return info
async def async_update(self):
"""Synchronize state with controller."""
async def async_added_to_hass(self):
"""Port entity created."""
_LOGGER.debug("New sensor %s (%s)", self._inst, self._sensor)
@property @property
def is_on(self): def is_on(self) -> bool:
"""Return true if sensor is on.""" """Return true if device is on."""
val = False val = False
if self._attr in self._data: if self._attr in self._data:
val = self._data[self._attr] val = self._data[self._attr]
return val return val
async def async_update(self):
"""Synchronize state with controller."""
async def async_added_to_hass(self):
"""Run when entity about to be added to hass."""
_LOGGER.debug("New sensor %s (%s)", self._inst, self._sensor)
# --------------------------- # ---------------------------
# MikrotikControllerPPPSecretBinarySensor # MikrotikControllerPPPSecretBinarySensor
@ -274,32 +275,32 @@ class MikrotikControllerPPPSecretBinarySensor(MikrotikControllerBinarySensor):
"""Representation of a network device.""" """Representation of a network device."""
def __init__(self, inst, uid, mikrotik_controller, config_entry, sid_data): def __init__(self, inst, uid, mikrotik_controller, config_entry, sid_data):
"""Set up tracked port.""" """Initialize."""
super().__init__(mikrotik_controller, inst, uid) super().__init__(mikrotik_controller, inst, uid)
self._sid_data = sid_data self._sid_data = sid_data
self._data = mikrotik_controller.data[self._sid_data["sid"]][uid] self._data = mikrotik_controller.data[self._sid_data["sid"]][uid]
self._config_entry = config_entry self._config_entry = config_entry
@property @property
def option_sensor_ppp(self): def option_sensor_ppp(self) -> bool:
"""Config entry option to not track ARP.""" """Config entry option."""
return self._config_entry.options.get(CONF_SENSOR_PPP, DEFAULT_SENSOR_PPP) return self._config_entry.options.get(CONF_SENSOR_PPP, DEFAULT_SENSOR_PPP)
@property @property
def name(self): def name(self) -> str:
"""Return the name of the port.""" """Return the name."""
return f"{self._inst} PPP {self._data['name']}" return f"{self._inst} PPP {self._data['name']}"
@property @property
def is_on(self): def is_on(self) -> bool:
"""Return true if the host is connected to the network.""" """Return true if device is on."""
if not self.option_sensor_ppp: if not self.option_sensor_ppp:
return False return False
return self._data["connected"] return self._data["connected"]
@property @property
def device_class(self) -> str: def device_class(self) -> Optional[str]:
"""Return the device class.""" """Return the device class."""
return DEVICE_CLASS_CONNECTIVITY return DEVICE_CLASS_CONNECTIVITY
@ -312,12 +313,12 @@ class MikrotikControllerPPPSecretBinarySensor(MikrotikControllerBinarySensor):
return self._ctrl.connected() return self._ctrl.connected()
@property @property
def unique_id(self): def unique_id(self) -> str:
"""Return a unique identifier for this port.""" """Return a unique id for this entity."""
return f"{self._inst.lower()}-{self._sid_data['sid']}_tracker-{self._data[self._sid_data['sid_ref']]}" return f"{self._inst.lower()}-{self._sid_data['sid']}_tracker-{self._data[self._sid_data['sid_ref']]}"
@property @property
def icon(self): def icon(self) -> str:
"""Return the icon.""" """Return the icon."""
if self._data["connected"]: if self._data["connected"]:
return "mdi:account-network-outline" return "mdi:account-network-outline"
@ -325,8 +326,8 @@ class MikrotikControllerPPPSecretBinarySensor(MikrotikControllerBinarySensor):
return "mdi:account-off-outline" return "mdi:account-off-outline"
@property @property
def device_state_attributes(self): def device_state_attributes(self) -> Dict[str, Any]:
"""Return the port state attributes.""" """Return the state attributes."""
attributes = self._attrs attributes = self._attrs
for variable in DEVICE_ATTRIBUTES_PPP_SECRET: for variable in DEVICE_ATTRIBUTES_PPP_SECRET:
if variable in self._data: if variable in self._data:
@ -335,8 +336,8 @@ class MikrotikControllerPPPSecretBinarySensor(MikrotikControllerBinarySensor):
return attributes return attributes
@property @property
def device_info(self): def device_info(self) -> Dict[str, Any]:
"""Return a PPP Secret switch description for device registry.""" """Return a description for device registry."""
info = { info = {
"identifiers": { "identifiers": {
( (
@ -361,36 +362,36 @@ class MikrotikControllerPortBinarySensor(MikrotikControllerBinarySensor):
"""Representation of a network port.""" """Representation of a network port."""
def __init__(self, inst, uid, mikrotik_controller, config_entry, sid_data): def __init__(self, inst, uid, mikrotik_controller, config_entry, sid_data):
"""Set up tracked port.""" """Initialize."""
super().__init__(mikrotik_controller, inst, uid) super().__init__(mikrotik_controller, inst, uid)
self._sid_data = sid_data self._sid_data = sid_data
self._data = mikrotik_controller.data[self._sid_data["sid"]][uid] self._data = mikrotik_controller.data[self._sid_data["sid"]][uid]
self._config_entry = config_entry self._config_entry = config_entry
@property @property
def option_sensor_port_tracker(self): def option_sensor_port_tracker(self) -> bool:
"""Config entry option to not track ARP.""" """Config entry option to not track ARP."""
return self._config_entry.options.get( return self._config_entry.options.get(
CONF_SENSOR_PORT_TRACKER, DEFAULT_SENSOR_PORT_TRACKER CONF_SENSOR_PORT_TRACKER, DEFAULT_SENSOR_PORT_TRACKER
) )
@property @property
def name(self): def name(self) -> str:
"""Return the name of the port.""" """Return the name."""
return f"{self._inst} {self._data[self._sid_data['sid_name']]}" return f"{self._inst} {self._data[self._sid_data['sid_name']]}"
@property @property
def unique_id(self): def unique_id(self) -> str:
"""Return a unique identifier for this port.""" """Return a unique id for this entity."""
return f"{self._inst.lower()}-{self._sid_data['sid']}-{self._data['port-mac-address']}_{self._data['default-name']}" return f"{self._inst.lower()}-{self._sid_data['sid']}-{self._data['port-mac-address']}_{self._data['default-name']}"
@property @property
def is_on(self): def is_on(self) -> bool:
"""Return true if the port is connected to the network.""" """Return true if device is on."""
return self._data["running"] return self._data["running"]
@property @property
def device_class(self) -> str: def device_class(self) -> Optional[str]:
"""Return the device class.""" """Return the device class."""
return DEVICE_CLASS_CONNECTIVITY return DEVICE_CLASS_CONNECTIVITY
@ -403,7 +404,7 @@ class MikrotikControllerPortBinarySensor(MikrotikControllerBinarySensor):
return self._ctrl.connected() return self._ctrl.connected()
@property @property
def icon(self): def icon(self) -> str:
"""Return the icon.""" """Return the icon."""
if self._data["running"]: if self._data["running"]:
icon = "mdi:lan-connect" icon = "mdi:lan-connect"
@ -416,8 +417,8 @@ class MikrotikControllerPortBinarySensor(MikrotikControllerBinarySensor):
return icon return icon
@property @property
def device_state_attributes(self): def device_state_attributes(self) -> Dict[str, Any]:
"""Return the port state attributes.""" """Return the state attributes."""
attributes = self._attrs attributes = self._attrs
for variable in DEVICE_ATTRIBUTES_IFACE: for variable in DEVICE_ATTRIBUTES_IFACE:
if variable in self._data: if variable in self._data:
@ -426,7 +427,7 @@ class MikrotikControllerPortBinarySensor(MikrotikControllerBinarySensor):
return attributes return attributes
@property @property
def device_info(self): def device_info(self) -> Dict[str, Any]:
"""Return a description for device registry.""" """Return a description for device registry."""
info = { info = {
"connections": { "connections": {

View file

@ -1,6 +1,7 @@
"""Support for the Mikrotik Router device tracker.""" """Support for the Mikrotik Router device tracker."""
import logging import logging
from typing import Any, Dict
from datetime import timedelta from datetime import timedelta
from homeassistant.components.device_tracker.config_entry import ScannerEntity from homeassistant.components.device_tracker.config_entry import ScannerEntity
@ -165,7 +166,7 @@ class MikrotikControllerDeviceTracker(ScannerEntity):
return True return True
async def async_added_to_hass(self): async def async_added_to_hass(self):
"""Device tracker entity created.""" """Run when entity about to be added to hass."""
_LOGGER.debug( _LOGGER.debug(
"New device tracker %s (%s %s)", "New device tracker %s (%s %s)",
self._inst, self._inst,
@ -177,21 +178,21 @@ class MikrotikControllerDeviceTracker(ScannerEntity):
"""Synchronize state with controller.""" """Synchronize state with controller."""
@property @property
def source_type(self): def source_type(self) -> str:
"""Return the source type of the port.""" """Return the source type of the port."""
return SOURCE_TYPE_ROUTER return SOURCE_TYPE_ROUTER
@property @property
def name(self): def name(self) -> str:
"""Return the name of the port.""" """Return the name."""
if self._sid_data["sid"] == "interface": if self._sid_data["sid"] == "interface":
return f"{self._inst} {self._data[self._sid_data['sid_name']]}" return f"{self._inst} {self._data[self._sid_data['sid_name']]}"
return f"{self._data[self._sid_data['sid_name']]}" return f"{self._data[self._sid_data['sid_name']]}"
@property @property
def unique_id(self): def unique_id(self) -> str:
"""Return a unique identifier for this port.""" """Return a unique id for this entity."""
return f"{self._inst.lower()}-{self._sid_data['sid']}-{self._data[self._sid_data['sid_ref']]}" return f"{self._inst.lower()}-{self._sid_data['sid']}-{self._data[self._sid_data['sid_ref']]}"
@property @property
@ -200,7 +201,7 @@ class MikrotikControllerDeviceTracker(ScannerEntity):
return self._ctrl.connected() return self._ctrl.connected()
@property @property
def device_info(self): def device_info(self) -> Dict[str, Any]:
"""Return a description for device registry.""" """Return a description for device registry."""
info = { info = {
"connections": { "connections": {
@ -215,8 +216,8 @@ class MikrotikControllerDeviceTracker(ScannerEntity):
return info return info
@property @property
def device_state_attributes(self): def device_state_attributes(self) -> Dict[str, Any]:
"""Return the port state attributes.""" """Return the state attributes."""
attributes = self._attrs attributes = self._attrs
return attributes return attributes
@ -245,7 +246,7 @@ class MikrotikControllerHostDeviceTracker(MikrotikControllerDeviceTracker):
return timedelta(seconds=track_network_hosts_timeout) return timedelta(seconds=track_network_hosts_timeout)
@property @property
def is_connected(self): def is_connected(self) -> bool:
"""Return true if the host is connected to the network.""" """Return true if the host is connected to the network."""
if not self.option_track_network_hosts: if not self.option_track_network_hosts:
return False return False
@ -270,7 +271,7 @@ class MikrotikControllerHostDeviceTracker(MikrotikControllerDeviceTracker):
return self._ctrl.connected() return self._ctrl.connected()
@property @property
def icon(self): def icon(self) -> str:
"""Return the icon.""" """Return the icon."""
if self._data["source"] in ["capsman", "wireless"]: if self._data["source"] in ["capsman", "wireless"]:
if self._data["available"]: if self._data["available"]:
@ -287,8 +288,8 @@ class MikrotikControllerHostDeviceTracker(MikrotikControllerDeviceTracker):
return "mdi:lan-disconnect" return "mdi:lan-disconnect"
@property @property
def device_state_attributes(self): def device_state_attributes(self) -> Dict[str, Any]:
"""Return the host state attributes.""" """Return the state attributes."""
attributes = self._attrs attributes = self._attrs
for variable in DEVICE_ATTRIBUTES_HOST: for variable in DEVICE_ATTRIBUTES_HOST:
if variable not in self._data: if variable not in self._data:
@ -318,7 +319,7 @@ class MikrotikControllerHostDeviceTracker(MikrotikControllerDeviceTracker):
return attributes return attributes
@property @property
def device_info(self): def device_info(self) -> Dict[str, Any]:
"""Return a description for device registry.""" """Return a description for device registry."""
info = { info = {
"connections": { "connections": {

View file

@ -1,6 +1,7 @@
"""Support for the Mikrotik Router sensor service.""" """Support for the Mikrotik Router sensor service."""
import logging import logging
from typing import Any, Dict, Optional
from homeassistant.const import ( from homeassistant.const import (
CONF_NAME, CONF_NAME,
@ -345,12 +346,12 @@ class MikrotikControllerSensor(Entity):
self._attrs = {ATTR_ATTRIBUTION: ATTRIBUTION} self._attrs = {ATTR_ATTRIBUTION: ATTRIBUTION}
@property @property
def name(self): def name(self) -> str:
"""Return the name.""" """Return the name."""
return f"{self._inst} {self._type[ATTR_LABEL]}" return f"{self._inst} {self._type[ATTR_LABEL]}"
@property @property
def state(self): def state(self) -> Optional[str]:
"""Return the state.""" """Return the state."""
val = "unknown" val = "unknown"
if self._attr in self._data: if self._attr in self._data:
@ -359,24 +360,24 @@ class MikrotikControllerSensor(Entity):
return val return val
@property @property
def device_state_attributes(self): def device_state_attributes(self) -> Dict[str, Any]:
"""Return the state attributes.""" """Return the state attributes."""
return self._attrs return self._attrs
@property @property
def icon(self): def icon(self) -> str:
"""Return the icon.""" """Return the icon."""
self._icon = self._type[ATTR_ICON] self._icon = self._type[ATTR_ICON]
return self._icon return self._icon
@property @property
def device_class(self): def device_class(self) -> Optional[str]:
"""Return the device_class.""" """Return the device class."""
return self._type[ATTR_DEVICE_CLASS] return self._type[ATTR_DEVICE_CLASS]
@property @property
def unique_id(self): def unique_id(self) -> str:
"""Return a unique_id for this entity.""" """Return a unique id for this entity."""
return f"{self._inst.lower()}-{self._sensor.lower()}" return f"{self._inst.lower()}-{self._sensor.lower()}"
@property @property
@ -394,8 +395,8 @@ class MikrotikControllerSensor(Entity):
return self._ctrl.connected() return self._ctrl.connected()
@property @property
def device_info(self): def device_info(self) -> Dict[str, Any]:
"""Return a port description for device registry.""" """Return a description for device registry."""
info = { info = {
"manufacturer": self._ctrl.data["resource"]["platform"], "manufacturer": self._ctrl.data["resource"]["platform"],
"model": self._ctrl.data["resource"]["board-name"], "model": self._ctrl.data["resource"]["board-name"],
@ -418,7 +419,7 @@ class MikrotikControllerSensor(Entity):
"""Synchronize state with controller.""" """Synchronize state with controller."""
async def async_added_to_hass(self): async def async_added_to_hass(self):
"""Port entity created.""" """Run when entity about to be added to hass."""
_LOGGER.debug("New sensor %s (%s)", self._inst, self._sensor) _LOGGER.debug("New sensor %s (%s)", self._inst, self._sensor)
@ -426,7 +427,7 @@ class MikrotikControllerSensor(Entity):
# MikrotikControllerTrafficSensor # MikrotikControllerTrafficSensor
# --------------------------- # ---------------------------
class MikrotikControllerTrafficSensor(MikrotikControllerSensor): class MikrotikControllerTrafficSensor(MikrotikControllerSensor):
"""Define an Mikrotik Controller sensor.""" """Define a traffic sensor."""
def __init__(self, mikrotik_controller, inst, sensor, uid): def __init__(self, mikrotik_controller, inst, sensor, uid):
"""Initialize.""" """Initialize."""
@ -435,18 +436,18 @@ class MikrotikControllerTrafficSensor(MikrotikControllerSensor):
self._data = mikrotik_controller.data[SENSOR_TYPES[sensor][ATTR_PATH]][uid] self._data = mikrotik_controller.data[SENSOR_TYPES[sensor][ATTR_PATH]][uid]
@property @property
def name(self): def name(self) -> str:
"""Return the name.""" """Return the name."""
return f"{self._inst} {self._data['name']} {self._type[ATTR_LABEL]}" return f"{self._inst} {self._data['name']} {self._type[ATTR_LABEL]}"
@property @property
def unique_id(self): def unique_id(self) -> str:
"""Return a unique_id for this entity.""" """Return a unique id for this entity."""
return f"{self._inst.lower()}-{self._sensor.lower()}-{self._data['default-name'].lower()}" return f"{self._inst.lower()}-{self._sensor.lower()}-{self._data['default-name'].lower()}"
@property @property
def device_info(self): def device_info(self) -> Dict[str, Any]:
"""Return a port description for device registry.""" """Return a description for device registry."""
info = { info = {
"connections": {(CONNECTION_NETWORK_MAC, self._data["port-mac-address"])}, "connections": {(CONNECTION_NETWORK_MAC, self._data["port-mac-address"])},
"manufacturer": self._ctrl.data["resource"]["platform"], "manufacturer": self._ctrl.data["resource"]["platform"],
@ -456,15 +457,6 @@ class MikrotikControllerTrafficSensor(MikrotikControllerSensor):
return info return info
async def async_added_to_hass(self):
"""Port entity created."""
_LOGGER.debug(
"New sensor %s (%s %s)",
self._inst,
self._data["default-name"],
self._sensor,
)
# --------------------------- # ---------------------------
# MikrotikAccountingSensor # MikrotikAccountingSensor
@ -479,13 +471,13 @@ class MikrotikAccountingSensor(MikrotikControllerSensor):
self._data = mikrotik_controller.data[SENSOR_TYPES[sensor][ATTR_PATH]][uid] self._data = mikrotik_controller.data[SENSOR_TYPES[sensor][ATTR_PATH]][uid]
@property @property
def name(self): def name(self) -> str:
"""Return the name.""" """Return the name."""
return f"{self._data['host-name']} {self._type[ATTR_LABEL]}" return f"{self._data['host-name']} {self._type[ATTR_LABEL]}"
@property @property
def unique_id(self): def unique_id(self) -> str:
"""Return a unique_id for this entity.""" """Return a unique id for this entity."""
return f"{self._inst.lower()}-{self._sensor.lower()}-{self._data['mac-address'].lower()}" return f"{self._inst.lower()}-{self._sensor.lower()}-{self._data['mac-address'].lower()}"
@property @property
@ -503,8 +495,8 @@ class MikrotikAccountingSensor(MikrotikControllerSensor):
return self._ctrl.connected() and self._data["available"] return self._ctrl.connected() and self._data["available"]
@property @property
def device_info(self): def device_info(self) -> Dict[str, Any]:
"""Return a accounting description for device registry.""" """Return a description for device registry."""
info = { info = {
"connections": {(CONNECTION_NETWORK_MAC, self._data["mac-address"])}, "connections": {(CONNECTION_NETWORK_MAC, self._data["mac-address"])},
"default_name": self._data["host-name"], "default_name": self._data["host-name"],
@ -515,7 +507,7 @@ class MikrotikAccountingSensor(MikrotikControllerSensor):
return info return info
@property @property
def device_state_attributes(self): def device_state_attributes(self) -> Dict[str, Any]:
"""Return the state attributes.""" """Return the state attributes."""
attributes = self._attrs attributes = self._attrs
for variable in DEVICE_ATTRIBUTES_ACCOUNTING: for variable in DEVICE_ATTRIBUTES_ACCOUNTING:
@ -524,22 +516,12 @@ class MikrotikAccountingSensor(MikrotikControllerSensor):
return attributes return attributes
async def async_added_to_hass(self):
"""Port entity created."""
_LOGGER.debug(
"New sensor %s (%s [%s] %s)",
self._inst,
self._data["host-name"],
self._data["mac-address"],
self._sensor,
)
# --------------------------- # ---------------------------
# MikrotikControllerEnvironmentSensor # MikrotikControllerEnvironmentSensor
# --------------------------- # ---------------------------
class MikrotikControllerEnvironmentSensor(MikrotikControllerSensor): class MikrotikControllerEnvironmentSensor(MikrotikControllerSensor):
"""Define an Mikrotik Controller sensor.""" """Define an Enviroment variable sensor."""
def __init__(self, mikrotik_controller, inst, sensor, uid): def __init__(self, mikrotik_controller, inst, sensor, uid):
"""Initialize.""" """Initialize."""
@ -548,29 +530,11 @@ class MikrotikControllerEnvironmentSensor(MikrotikControllerSensor):
self._data = mikrotik_controller.data["environment"][uid] self._data = mikrotik_controller.data["environment"][uid]
@property @property
def unique_id(self): def unique_id(self) -> str:
"""Return a unique_id for this entity.""" """Return a unique id for this entity."""
return f"{self._inst.lower()}-environment-{self._uid}" return f"{self._inst.lower()}-environment-{self._uid}"
@property @property
def name(self): def name(self) -> str:
"""Return the name.""" """Return the name."""
return f"{self._inst} {self._data['name']}" return f"{self._inst} {self._data['name']}"
@property
def state(self):
"""Return the state."""
val = "unknown"
if self._attr in self._data:
val = self._data[self._attr]
return val
async def async_added_to_hass(self):
"""Port entity created."""
_LOGGER.debug(
"New sensor %s (%s %s)",
self._inst,
self._data["name"],
self._sensor,
)

View file

@ -1,5 +1,7 @@
"""Support for the Mikrotik Router switches.""" """Support for the Mikrotik Router switches."""
import logging import logging
from typing import Any, Dict
from homeassistant.components.switch import SwitchEntity from homeassistant.components.switch import SwitchEntity
from homeassistant.const import CONF_NAME, ATTR_ATTRIBUTION from homeassistant.const import CONF_NAME, ATTR_ATTRIBUTION
@ -199,7 +201,7 @@ class MikrotikControllerSwitch(SwitchEntity, RestoreEntity):
"""Representation of a switch.""" """Representation of a switch."""
def __init__(self, inst, uid, mikrotik_controller, sid_data): def __init__(self, inst, uid, mikrotik_controller, sid_data):
"""Set up switch.""" """Initialize."""
self._sid_data = sid_data self._sid_data = sid_data
self._inst = inst self._inst = inst
self._ctrl = mikrotik_controller self._ctrl = mikrotik_controller
@ -210,7 +212,7 @@ class MikrotikControllerSwitch(SwitchEntity, RestoreEntity):
} }
async def async_added_to_hass(self): async def async_added_to_hass(self):
"""Device tracker entity created.""" """Run when entity about to be added to hass."""
_LOGGER.debug( _LOGGER.debug(
"New switch %s (%s %s)", "New switch %s (%s %s)",
self._inst, self._inst,
@ -228,22 +230,22 @@ class MikrotikControllerSwitch(SwitchEntity, RestoreEntity):
@property @property
def name(self) -> str: def name(self) -> str:
"""Return the name of the port.""" """Return the name."""
return f"{self._inst} {self._sid_data['sid']} {self._data[self._sid_data['sid_name']]}" return f"{self._inst} {self._sid_data['sid']} {self._data[self._sid_data['sid_name']]}"
@property @property
def unique_id(self) -> str: def unique_id(self) -> str:
"""Return a unique identifier for this port.""" """Return a unique id for this entity."""
return f"{self._inst.lower()}-{self._sid_data['sid']}_switch-{self._data[self._sid_data['sid_ref']]}" return f"{self._inst.lower()}-{self._sid_data['sid']}_switch-{self._data[self._sid_data['sid_ref']]}"
@property @property
def is_on(self): def is_on(self) -> bool:
"""Return true if the queue is on.""" """Return true if device is on."""
return self._data["enabled"] return self._data["enabled"]
@property @property
def device_state_attributes(self): def device_state_attributes(self) -> Dict[str, Any]:
"""Return the port state attributes.""" """Return the state attributes."""
attributes = self._attrs attributes = self._attrs
for variable in self._sid_data["sid_attr"]: for variable in self._sid_data["sid_attr"]:
@ -260,21 +262,21 @@ class MikrotikControllerPortSwitch(MikrotikControllerSwitch):
"""Representation of a network port switch.""" """Representation of a network port switch."""
def __init__(self, inst, uid, mikrotik_controller, sid_data): def __init__(self, inst, uid, mikrotik_controller, sid_data):
"""Set up tracked port.""" """Initialize."""
super().__init__(inst, uid, mikrotik_controller, sid_data) super().__init__(inst, uid, mikrotik_controller, sid_data)
@property @property
def name(self) -> str: def name(self) -> str:
"""Return the name of the port.""" """Return the name."""
return f"{self._inst} port {self._data[self._sid_data['sid_name']]}" return f"{self._inst} port {self._data[self._sid_data['sid_name']]}"
@property @property
def unique_id(self) -> str: def unique_id(self) -> str:
"""Return a unique identifier for this port.""" """Return a unique id for this entity."""
return f"{self._inst.lower()}-enable_switch-{self._data['port-mac-address']}_{self._data['default-name']}" return f"{self._inst.lower()}-enable_switch-{self._data['port-mac-address']}_{self._data['default-name']}"
@property @property
def icon(self): def icon(self) -> str:
"""Return the icon.""" """Return the icon."""
if self._data["running"]: if self._data["running"]:
icon = "mdi:lan-connect" icon = "mdi:lan-connect"
@ -287,8 +289,8 @@ class MikrotikControllerPortSwitch(MikrotikControllerSwitch):
return icon return icon
@property @property
def device_info(self): def device_info(self) -> Dict[str, Any]:
"""Return a port description for device registry.""" """Return a description for device registry."""
info = { info = {
"connections": {(CONNECTION_NETWORK_MAC, self._data["port-mac-address"])}, "connections": {(CONNECTION_NETWORK_MAC, self._data["port-mac-address"])},
"manufacturer": self._ctrl.data["resource"]["platform"], "manufacturer": self._ctrl.data["resource"]["platform"],
@ -297,7 +299,7 @@ class MikrotikControllerPortSwitch(MikrotikControllerSwitch):
} }
return info return info
async def async_turn_on(self): async def async_turn_on(self) -> None:
"""Turn on the switch.""" """Turn on the switch."""
path = "/interface" path = "/interface"
param = "default-name" param = "default-name"
@ -317,8 +319,8 @@ class MikrotikControllerPortSwitch(MikrotikControllerSwitch):
await self._ctrl.force_update() await self._ctrl.force_update()
async def async_turn_off(self): async def async_turn_off(self) -> None:
"""Turn on the switch.""" """Turn off the switch."""
path = "/interface" path = "/interface"
param = "default-name" param = "default-name"
if self._data["about"] == "managed by CAPsMAN": if self._data["about"] == "managed by CAPsMAN":
@ -345,12 +347,12 @@ class MikrotikControllerNATSwitch(MikrotikControllerSwitch):
"""Representation of a NAT switch.""" """Representation of a NAT switch."""
def __init__(self, inst, uid, mikrotik_controller, sid_data): def __init__(self, inst, uid, mikrotik_controller, sid_data):
"""Set up NAT switch.""" """Initialize."""
super().__init__(inst, uid, mikrotik_controller, sid_data) super().__init__(inst, uid, mikrotik_controller, sid_data)
@property @property
def name(self) -> str: def name(self) -> str:
"""Return the name of the NAT switch.""" """Return the name."""
if self._data["comment"]: if self._data["comment"]:
return f"{self._inst} NAT {self._data['comment']}" return f"{self._inst} NAT {self._data['comment']}"
@ -358,11 +360,11 @@ class MikrotikControllerNATSwitch(MikrotikControllerSwitch):
@property @property
def unique_id(self) -> str: def unique_id(self) -> str:
"""Return a unique identifier for this mangle switch.""" """Return a unique id for this entity."""
return f"{self._inst.lower()}-enable_nat-{self._data['uniq-id']}" return f"{self._inst.lower()}-enable_nat-{self._data['uniq-id']}"
@property @property
def icon(self): def icon(self) -> str:
"""Return the icon.""" """Return the icon."""
if not self._data["enabled"]: if not self._data["enabled"]:
icon = "mdi:network-off-outline" icon = "mdi:network-off-outline"
@ -372,8 +374,8 @@ class MikrotikControllerNATSwitch(MikrotikControllerSwitch):
return icon return icon
@property @property
def device_info(self): def device_info(self) -> Dict[str, Any]:
"""Return a NAT switch description for device registry.""" """Return a description for device registry."""
info = { info = {
"identifiers": { "identifiers": {
( (
@ -390,7 +392,7 @@ class MikrotikControllerNATSwitch(MikrotikControllerSwitch):
} }
return info return info
async def async_turn_on(self): async def async_turn_on(self) -> None:
"""Turn on the switch.""" """Turn on the switch."""
path = "/ip/firewall/nat" path = "/ip/firewall/nat"
param = ".id" param = ".id"
@ -407,8 +409,8 @@ class MikrotikControllerNATSwitch(MikrotikControllerSwitch):
self._ctrl.set_value(path, param, value, mod_param, mod_value) self._ctrl.set_value(path, param, value, mod_param, mod_value)
await self._ctrl.force_update() await self._ctrl.force_update()
async def async_turn_off(self): async def async_turn_off(self) -> None:
"""Turn on the switch.""" """Turn off the switch."""
path = "/ip/firewall/nat" path = "/ip/firewall/nat"
param = ".id" param = ".id"
value = None value = None
@ -432,12 +434,12 @@ class MikrotikControllerMangleSwitch(MikrotikControllerSwitch):
"""Representation of a Mangle switch.""" """Representation of a Mangle switch."""
def __init__(self, inst, uid, mikrotik_controller, sid_data): def __init__(self, inst, uid, mikrotik_controller, sid_data):
"""Set up Mangle switch.""" """Initialize."""
super().__init__(inst, uid, mikrotik_controller, sid_data) super().__init__(inst, uid, mikrotik_controller, sid_data)
@property @property
def name(self) -> str: def name(self) -> str:
"""Return the name of the Mangle switch.""" """Return the name."""
if self._data["comment"]: if self._data["comment"]:
return f"{self._inst} Mangle {self._data['comment']}" return f"{self._inst} Mangle {self._data['comment']}"
@ -445,11 +447,11 @@ class MikrotikControllerMangleSwitch(MikrotikControllerSwitch):
@property @property
def unique_id(self) -> str: def unique_id(self) -> str:
"""Return a unique identifier for this mangle switch.""" """Return a unique id for this entity."""
return f"{self._inst.lower()}-enable_mangle-{self._data['name']}" return f"{self._inst.lower()}-enable_mangle-{self._data['name']}"
@property @property
def icon(self): def icon(self) -> str:
"""Return the icon.""" """Return the icon."""
if not self._data["enabled"]: if not self._data["enabled"]:
icon = "mdi:bookmark-off-outline" icon = "mdi:bookmark-off-outline"
@ -459,8 +461,8 @@ class MikrotikControllerMangleSwitch(MikrotikControllerSwitch):
return icon return icon
@property @property
def device_info(self): def device_info(self) -> Dict[str, Any]:
"""Return a Mangle switch description for device registry.""" """Return a description for device registry."""
info = { info = {
"identifiers": { "identifiers": {
( (
@ -477,7 +479,7 @@ class MikrotikControllerMangleSwitch(MikrotikControllerSwitch):
} }
return info return info
async def async_turn_on(self): async def async_turn_on(self) -> None:
"""Turn on the switch.""" """Turn on the switch."""
path = "/ip/firewall/mangle" path = "/ip/firewall/mangle"
param = ".id" param = ".id"
@ -494,8 +496,8 @@ class MikrotikControllerMangleSwitch(MikrotikControllerSwitch):
self._ctrl.set_value(path, param, value, mod_param, mod_value) self._ctrl.set_value(path, param, value, mod_param, mod_value)
await self._ctrl.force_update() await self._ctrl.force_update()
async def async_turn_off(self): async def async_turn_off(self) -> None:
"""Turn on the switch.""" """Turn off the switch."""
path = "/ip/firewall/mangle" path = "/ip/firewall/mangle"
param = ".id" param = ".id"
value = None value = None
@ -519,21 +521,21 @@ class MikrotikControllerPPPSecretSwitch(MikrotikControllerSwitch):
"""Representation of a PPP Secret switch.""" """Representation of a PPP Secret switch."""
def __init__(self, inst, uid, mikrotik_controller, sid_data): def __init__(self, inst, uid, mikrotik_controller, sid_data):
"""Set up PPP Secret switch.""" """Initialize."""
super().__init__(inst, uid, mikrotik_controller, sid_data) super().__init__(inst, uid, mikrotik_controller, sid_data)
@property @property
def name(self) -> str: def name(self) -> str:
"""Return the name of the PPP Secret switch.""" """Return the name."""
return f"{self._inst} PPP Secret {self._data['name']}" return f"{self._inst} PPP Secret {self._data['name']}"
@property @property
def unique_id(self) -> str: def unique_id(self) -> str:
"""Return a unique identifier for this ppp_secret switch.""" """Return a unique id for this entity."""
return f"{self._inst.lower()}-enable_ppp_secret-{self._data['name']}" return f"{self._inst.lower()}-enable_ppp_secret-{self._data['name']}"
@property @property
def icon(self): def icon(self) -> str:
"""Return the icon.""" """Return the icon."""
if not self._data["enabled"]: if not self._data["enabled"]:
icon = "mdi:account-off-outline" icon = "mdi:account-off-outline"
@ -543,8 +545,8 @@ class MikrotikControllerPPPSecretSwitch(MikrotikControllerSwitch):
return icon return icon
@property @property
def device_info(self): def device_info(self) -> Dict[str, Any]:
"""Return a PPP Secret switch description for device registry.""" """Return a description for device registry."""
info = { info = {
"identifiers": { "identifiers": {
( (
@ -561,7 +563,7 @@ class MikrotikControllerPPPSecretSwitch(MikrotikControllerSwitch):
} }
return info return info
async def async_turn_on(self): async def async_turn_on(self) -> None:
"""Turn on the switch.""" """Turn on the switch."""
path = "/ppp/secret" path = "/ppp/secret"
param = "name" param = "name"
@ -571,8 +573,8 @@ class MikrotikControllerPPPSecretSwitch(MikrotikControllerSwitch):
self._ctrl.set_value(path, param, value, mod_param, mod_value) self._ctrl.set_value(path, param, value, mod_param, mod_value)
await self._ctrl.force_update() await self._ctrl.force_update()
async def async_turn_off(self): async def async_turn_off(self) -> None:
"""Turn on the switch.""" """Turn off the switch."""
path = "/ppp/secret" path = "/ppp/secret"
param = "name" param = "name"
value = self._data["name"] value = self._data["name"]
@ -589,17 +591,17 @@ class MikrotikControllerScriptSwitch(MikrotikControllerSwitch):
"""Representation of a script switch.""" """Representation of a script switch."""
def __init__(self, inst, uid, mikrotik_controller, sid_data): def __init__(self, inst, uid, mikrotik_controller, sid_data):
"""Set up script switch.""" """Initialize."""
super().__init__(inst, uid, mikrotik_controller, sid_data) super().__init__(inst, uid, mikrotik_controller, sid_data)
@property @property
def icon(self): def icon(self) -> str:
"""Return the icon.""" """Return the icon."""
return "mdi:script-text-outline" return "mdi:script-text-outline"
@property @property
def device_info(self): def device_info(self) -> Dict[str, Any]:
"""Return a script switch description for device registry.""" """Return a description for device registry."""
info = { info = {
"identifiers": { "identifiers": {
( (
@ -616,16 +618,16 @@ class MikrotikControllerScriptSwitch(MikrotikControllerSwitch):
} }
return info return info
async def async_turn_on(self): async def async_turn_on(self) -> None:
"""Turn on the switch.""" """Turn on the switch."""
self._ctrl.run_script(self._data["name"]) self._ctrl.run_script(self._data["name"])
await self._ctrl.force_update() await self._ctrl.force_update()
async def async_turn_off(self): async def async_turn_off(self) -> None:
"""Turn off the switch.""" """Turn off the switch."""
@property @property
def is_on(self): def is_on(self) -> bool:
"""Return true if device is on.""" """Return true if device is on."""
return False return False
@ -637,11 +639,11 @@ class MikrotikControllerQueueSwitch(MikrotikControllerSwitch):
"""Representation of a queue switch.""" """Representation of a queue switch."""
def __init__(self, inst, uid, mikrotik_controller, sid_data): def __init__(self, inst, uid, mikrotik_controller, sid_data):
"""Set up queue switch.""" """Initialize."""
super().__init__(inst, uid, mikrotik_controller, sid_data) super().__init__(inst, uid, mikrotik_controller, sid_data)
@property @property
def icon(self): def icon(self) -> str:
"""Return the icon.""" """Return the icon."""
if not self._data["enabled"]: if not self._data["enabled"]:
icon = "mdi:leaf-off" icon = "mdi:leaf-off"
@ -651,8 +653,8 @@ class MikrotikControllerQueueSwitch(MikrotikControllerSwitch):
return icon return icon
@property @property
def device_info(self): def device_info(self) -> Dict[str, Any]:
"""Return a queue switch description for device registry.""" """Return a description for device registry."""
info = { info = {
"identifiers": { "identifiers": {
( (
@ -669,8 +671,8 @@ class MikrotikControllerQueueSwitch(MikrotikControllerSwitch):
} }
return info return info
async def async_turn_on(self): async def async_turn_on(self) -> None:
"""Turn on the queue switch.""" """Turn on the switch."""
path = "/queue/simple" path = "/queue/simple"
param = ".id" param = ".id"
value = None value = None
@ -683,8 +685,8 @@ class MikrotikControllerQueueSwitch(MikrotikControllerSwitch):
self._ctrl.set_value(path, param, value, mod_param, mod_value) self._ctrl.set_value(path, param, value, mod_param, mod_value)
await self._ctrl.force_update() await self._ctrl.force_update()
async def async_turn_off(self): async def async_turn_off(self) -> None:
"""Turn on the queue switch.""" """Turn off the switch."""
path = "/queue/simple" path = "/queue/simple"
param = ".id" param = ".id"
value = None value = None
@ -705,11 +707,11 @@ class MikrotikControllerKidcontrolSwitch(MikrotikControllerSwitch):
"""Representation of a queue switch.""" """Representation of a queue switch."""
def __init__(self, inst, uid, mikrotik_controller, sid_data): def __init__(self, inst, uid, mikrotik_controller, sid_data):
"""Set up queue switch.""" """Initialize."""
super().__init__(inst, uid, mikrotik_controller, sid_data) super().__init__(inst, uid, mikrotik_controller, sid_data)
@property @property
def icon(self): def icon(self) -> str:
"""Return the icon.""" """Return the icon."""
if not self._data["enabled"]: if not self._data["enabled"]:
icon = "mdi:account-off-outline" icon = "mdi:account-off-outline"
@ -719,8 +721,8 @@ class MikrotikControllerKidcontrolSwitch(MikrotikControllerSwitch):
return icon return icon
@property @property
def device_info(self): def device_info(self) -> Dict[str, Any]:
"""Return a queue switch description for device registry.""" """Return a description for device registry."""
info = { info = {
"identifiers": { "identifiers": {
( (
@ -737,8 +739,8 @@ class MikrotikControllerKidcontrolSwitch(MikrotikControllerSwitch):
} }
return info return info
async def async_turn_on(self): async def async_turn_on(self) -> None:
"""Turn on the queue switch.""" """Turn on the switch."""
path = "/ip/kid-control" path = "/ip/kid-control"
param = "name" param = "name"
value = self._data["name"] value = self._data["name"]
@ -747,8 +749,8 @@ class MikrotikControllerKidcontrolSwitch(MikrotikControllerSwitch):
self._ctrl.set_value(path, param, value, mod_param, mod_value) self._ctrl.set_value(path, param, value, mod_param, mod_value)
await self._ctrl.force_update() await self._ctrl.force_update()
async def async_turn_off(self): async def async_turn_off(self) -> None:
"""Turn on the queue switch.""" """Turn off the switch."""
path = "/ip/kid-control" path = "/ip/kid-control"
param = "name" param = "name"
value = self._data["name"] value = self._data["name"]