tomaae.homeassistant-mikrot.../custom_components/mikrotik_router/switch.py

493 lines
19 KiB
Python
Raw Normal View History

"""Support for the Mikrotik Router switches."""
2020-12-25 20:28:36 +01:00
import logging
2022-02-04 21:26:10 +01:00
from typing import Any, Optional
2022-02-03 10:28:22 +01:00
from collections.abc import Mapping
from homeassistant.components.switch import SwitchEntity
2022-02-03 10:28:22 +01:00
from homeassistant.const import CONF_NAME, CONF_HOST, ATTR_ATTRIBUTION
from homeassistant.core import callback
2022-02-03 10:28:22 +01:00
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.restore_state import RestoreEntity
2022-02-02 22:13:39 +01:00
from .helper import format_attribute
2020-04-11 05:45:36 +02:00
from .const import DOMAIN, DATA_CLIENT, ATTRIBUTION
2022-02-03 10:28:22 +01:00
from .switch_types import (
MikrotikSwitchEntityDescription,
SWITCH_TYPES,
DEVICE_ATTRIBUTES_IFACE_ETHER,
DEVICE_ATTRIBUTES_IFACE_SFP,
)
_LOGGER = logging.getLogger(__name__)
2020-12-25 11:48:24 +01:00
# ---------------------------
# async_setup_entry
# ---------------------------
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up switches for Mikrotik Router component."""
2019-12-06 01:22:34 +01:00
inst = config_entry.data[CONF_NAME]
mikrotik_controller = hass.data[DOMAIN][DATA_CLIENT][config_entry.entry_id]
switches = {}
@callback
def update_controller():
"""Update the values of the controller."""
2019-12-06 01:22:34 +01:00
update_items(inst, mikrotik_controller, async_add_entities, switches)
mikrotik_controller.listeners.append(
2020-03-16 04:51:41 +01:00
async_dispatcher_connect(
hass, mikrotik_controller.signal_update, update_controller
)
)
update_controller()
# ---------------------------
# update_items
# ---------------------------
@callback
2019-12-06 01:22:34 +01:00
def update_items(inst, mikrotik_controller, async_add_entities, switches):
"""Update device switch state from the controller."""
new_switches = []
2019-12-05 22:10:42 +01:00
# Add switches
2022-02-03 10:28:22 +01:00
for switch, sid_func in zip(
# Switch type name
2022-02-04 21:24:24 +01:00
[
"interface",
"nat",
"mangle",
"filter",
"ppp_secret",
"queue",
2022-02-04 21:25:01 +01:00
"kidcontrol_enable",
"kidcontrol_pause",
2022-02-04 21:24:24 +01:00
],
2022-02-04 20:44:59 +01:00
# Entity function
2021-04-12 12:40:45 +02:00
[
2022-02-04 20:44:59 +01:00
MikrotikControllerPortSwitch,
MikrotikControllerNATSwitch,
MikrotikControllerMangleSwitch,
2022-02-04 20:52:22 +01:00
MikrotikControllerFilterSwitch,
2022-02-04 21:01:23 +01:00
MikrotikControllerSwitch,
2022-02-04 21:24:24 +01:00
MikrotikControllerQueueSwitch,
2022-02-04 21:25:01 +01:00
MikrotikControllerSwitch,
MikrotikControllerKidcontrolPauseSwitch,
2020-04-20 08:39:02 +02:00
],
2019-12-09 09:52:45 +01:00
):
2022-02-03 10:28:22 +01:00
uid_switch = SWITCH_TYPES[switch]
for uid in mikrotik_controller.data[SWITCH_TYPES[switch].data_path]:
uid_data = mikrotik_controller.data[SWITCH_TYPES[switch].data_path]
item_id = f"{inst}-{switch}-{uid_data[uid][uid_switch.data_reference]}"
_LOGGER.debug("Updating sensor %s", item_id)
if item_id in switches:
if switches[item_id].enabled:
switches[item_id].async_schedule_update_ha_state()
continue
2022-02-03 10:28:22 +01:00
switches[item_id] = sid_func(
inst=inst,
uid=uid,
mikrotik_controller=mikrotik_controller,
entity_description=uid_switch,
)
2019-12-05 22:10:42 +01:00
new_switches.append(switches[item_id])
if new_switches:
async_add_entities(new_switches)
# ---------------------------
2019-12-03 18:30:45 +01:00
# MikrotikControllerSwitch
# ---------------------------
class MikrotikControllerSwitch(SwitchEntity, RestoreEntity):
2019-12-06 01:22:34 +01:00
"""Representation of a switch."""
2022-02-03 10:28:22 +01:00
def __init__(
self,
inst,
uid,
mikrotik_controller,
entity_description: MikrotikSwitchEntityDescription,
):
self.entity_description = entity_description
2019-12-06 01:22:34 +01:00
self._inst = inst
self._ctrl = mikrotik_controller
2022-02-03 10:28:22 +01:00
self._attr_extra_state_attributes = {ATTR_ATTRIBUTION: ATTRIBUTION}
self._data = mikrotik_controller.data[self.entity_description.data_path][uid]
2019-12-03 18:30:45 +01:00
@property
def available(self) -> bool:
"""Return if controller is available."""
2019-12-06 01:22:34 +01:00
return self._ctrl.connected()
2019-12-03 18:30:45 +01:00
2020-04-20 08:39:02 +02:00
@property
def name(self) -> str:
2020-12-25 20:28:36 +01:00
"""Return the name."""
if self.entity_description.data_name_comment and self._data["comment"]:
return (
f"{self._inst} {self.entity_description.name} {self._data['comment']}"
)
2022-02-03 10:28:22 +01:00
return f"{self._inst} {self.entity_description.name} {self._data[self.entity_description.data_name]}"
2020-04-20 08:39:02 +02:00
@property
def unique_id(self) -> str:
2020-12-25 20:28:36 +01:00
"""Return a unique id for this entity."""
2022-02-03 10:28:22 +01:00
return f"{self._inst.lower()}-{self.entity_description.key}-{self._data[self.entity_description.data_reference].lower()}"
2020-04-20 08:39:02 +02:00
@property
2020-12-25 20:28:36 +01:00
def is_on(self) -> bool:
"""Return true if device is on."""
2022-02-03 10:28:22 +01:00
return self._data[self.entity_description.data_is_on]
2020-04-20 08:39:02 +02:00
@property
2022-02-03 10:28:22 +01:00
def icon(self) -> str:
"""Return the icon."""
if self._data[self.entity_description.data_is_on]:
return self.entity_description.icon_enabled
else:
return self.entity_description.icon_disabled
2020-04-20 08:39:02 +02:00
2022-02-03 10:28:22 +01:00
@property
def extra_state_attributes(self) -> Mapping[str, Any]:
"""Return the state attributes."""
attributes = super().extra_state_attributes
for variable in self.entity_description.data_attributes_list:
2020-04-20 08:39:02 +02:00
if variable in self._data:
attributes[format_attribute(variable)] = self._data[variable]
return attributes
2022-02-03 10:28:22 +01:00
def turn_on(self, **kwargs: Any) -> None:
2020-12-25 23:31:51 +01:00
"""Required abstract method."""
pass
2022-02-03 10:28:22 +01:00
def turn_off(self, **kwargs: Any) -> None:
2020-12-25 23:31:51 +01:00
"""Required abstract method."""
pass
2022-02-03 10:28:22 +01:00
async def async_turn_on(self) -> None:
"""Turn on the switch."""
path = self.entity_description.data_switch_path
param = self.entity_description.data_reference
value = self._data[self.entity_description.data_reference]
mod_param = self.entity_description.data_switch_parameter
self._ctrl.set_value(path, param, value, mod_param, False)
await self._ctrl.force_update()
async def async_turn_off(self) -> None:
"""Turn off the switch."""
path = self.entity_description.data_switch_path
param = self.entity_description.data_reference
value = self._data[self.entity_description.data_reference]
mod_param = self.entity_description.data_switch_parameter
self._ctrl.set_value(path, param, value, mod_param, True)
await self._ctrl.async_update()
@property
def device_info(self) -> DeviceInfo:
"""Return a description for device registry."""
dev_connection = DOMAIN
dev_connection_value = self.entity_description.data_reference
dev_group = self.entity_description.ha_group
if self.entity_description.ha_group.startswith("data__"):
dev_group = self.entity_description.ha_group[6:]
if dev_group in self._data:
dev_group = self._data[dev_group]
dev_connection_value = dev_group
if self.entity_description.ha_connection:
dev_connection = self.entity_description.ha_connection
if self.entity_description.ha_connection_value:
dev_connection_value = self.entity_description.ha_connection_value
if dev_connection_value.startswith("data__"):
dev_connection_value = dev_connection_value[6:]
dev_connection_value = self._data[dev_connection_value]
info = DeviceInfo(
connections={(dev_connection, f"{dev_connection_value}")},
identifiers={(dev_connection, f"{dev_connection_value}")},
default_name=f"{self._inst} {dev_group}",
model=f"{self._ctrl.data['resource']['board-name']}",
manufacturer=f"{self._ctrl.data['resource']['platform']}",
sw_version=f"{self._ctrl.data['resource']['version']}",
configuration_url=f"http://{self._ctrl.config_entry.data[CONF_HOST]}",
via_device=(DOMAIN, f"{self._ctrl.data['routerboard']['serial-number']}"),
)
return info
async def async_added_to_hass(self):
"""Run when entity about to be added to hass."""
_LOGGER.debug("New switch %s (%s)", self._inst, self.unique_id)
2019-12-03 18:30:45 +01:00
# ---------------------------
# MikrotikControllerPortSwitch
# ---------------------------
class MikrotikControllerPortSwitch(MikrotikControllerSwitch):
"""Representation of a network port switch."""
@property
2022-02-03 10:28:22 +01:00
def extra_state_attributes(self) -> Mapping[str, Any]:
2021-04-12 14:28:39 +02:00
"""Return the state attributes."""
2022-02-03 10:28:22 +01:00
attributes = super().extra_state_attributes
2021-04-12 14:28:39 +02:00
if self._data["type"] == "ether":
for variable in DEVICE_ATTRIBUTES_IFACE_ETHER:
if variable in self._data:
attributes[format_attribute(variable)] = self._data[variable]
2021-04-12 14:28:39 +02:00
if "sfp-shutdown-temperature" in self._data:
for variable in DEVICE_ATTRIBUTES_IFACE_SFP:
if variable in self._data:
attributes[format_attribute(variable)] = self._data[variable]
2021-04-12 14:28:39 +02:00
return attributes
@property
2020-12-25 20:28:36 +01:00
def icon(self) -> str:
"""Return the icon."""
2020-03-16 04:51:41 +01:00
if self._data["running"]:
2022-02-03 10:28:22 +01:00
icon = self.entity_description.icon_enabled
else:
2022-02-03 10:28:22 +01:00
icon = self.entity_description.icon_disabled
2020-03-16 04:51:41 +01:00
if not self._data["enabled"]:
icon = "mdi:lan-disconnect"
return icon
2020-12-25 23:31:51 +01:00
async def async_turn_on(self) -> Optional[str]:
"""Turn on the switch."""
2022-02-03 10:28:22 +01:00
path = self.entity_description.data_switch_path
param = self.entity_description.data_reference
if self._data["about"] == "managed by CAPsMAN":
_LOGGER.error("Unable to enable %s, managed by CAPsMAN", self._data[param])
return "managed by CAPsMAN"
if "-" in self._data["port-mac-address"]:
param = "name"
2022-02-03 10:28:22 +01:00
value = self._data[self.entity_description.data_reference]
mod_param = self.entity_description.data_switch_parameter
self._ctrl.set_value(path, param, value, mod_param, False)
if "poe-out" in self._data and self._data["poe-out"] == "off":
path = "/interface/ethernet"
self._ctrl.set_value(path, param, value, "poe-out", "auto-on")
2019-12-06 01:22:34 +01:00
await self._ctrl.force_update()
2020-12-25 23:31:51 +01:00
async def async_turn_off(self) -> Optional[str]:
2020-12-25 20:28:36 +01:00
"""Turn off the switch."""
2022-02-03 10:28:22 +01:00
path = self.entity_description.data_switch_path
param = self.entity_description.data_reference
if self._data["about"] == "managed by CAPsMAN":
_LOGGER.error("Unable to disable %s, managed by CAPsMAN", self._data[param])
return "managed by CAPsMAN"
if "-" in self._data["port-mac-address"]:
param = "name"
2022-02-03 10:28:22 +01:00
value = self._data[self.entity_description.data_reference]
mod_param = self.entity_description.data_switch_parameter
self._ctrl.set_value(path, param, value, mod_param, True)
if "poe-out" in self._data and self._data["poe-out"] == "auto-on":
path = "/interface/ethernet"
self._ctrl.set_value(path, param, value, "poe-out", "off")
2019-12-06 01:22:34 +01:00
await self._ctrl.async_update()
2020-12-02 15:38:17 +01:00
2019-12-03 18:30:45 +01:00
# ---------------------------
# MikrotikControllerNATSwitch
# ---------------------------
class MikrotikControllerNATSwitch(MikrotikControllerSwitch):
"""Representation of a NAT switch."""
2019-12-03 18:30:45 +01:00
@property
def name(self) -> str:
2020-12-25 20:28:36 +01:00
"""Return the name."""
if self._data["comment"]:
return f"{self._inst} NAT {self._data['comment']}"
return f"{self._inst} NAT {self._data['name']}"
2020-12-25 20:28:36 +01:00
async def async_turn_on(self) -> None:
2019-12-03 18:30:45 +01:00
"""Turn on the switch."""
2022-02-04 20:34:51 +01:00
path = self.entity_description.data_switch_path
2020-03-16 04:51:41 +01:00
param = ".id"
value = None
2020-03-16 04:51:41 +01:00
for uid in self._ctrl.data["nat"]:
2020-12-25 23:31:51 +01:00
if self._ctrl.data["nat"][uid]["uniq-id"] == (
f"{self._data['chain']},{self._data['action']},{self._data['protocol']},"
f"{self._data['in-interface']}:{self._data['dst-port']}-"
f"{self._data['out-interface']}:{self._data['to-addresses']}:{self._data['to-ports']}"
2020-03-16 04:51:41 +01:00
):
value = self._ctrl.data["nat"][uid][".id"]
2022-02-04 20:34:51 +01:00
mod_param = self.entity_description.data_switch_parameter
self._ctrl.set_value(path, param, value, mod_param, False)
2019-12-06 01:22:34 +01:00
await self._ctrl.force_update()
2019-12-03 18:30:45 +01:00
2020-12-25 20:28:36 +01:00
async def async_turn_off(self) -> None:
"""Turn off the switch."""
2022-02-04 20:34:51 +01:00
path = self.entity_description.data_switch_path
2020-03-16 04:51:41 +01:00
param = ".id"
value = None
2020-03-16 04:51:41 +01:00
for uid in self._ctrl.data["nat"]:
2020-12-25 23:31:51 +01:00
if self._ctrl.data["nat"][uid]["uniq-id"] == (
f"{self._data['chain']},{self._data['action']},{self._data['protocol']},"
f"{self._data['in-interface']}:{self._data['dst-port']}-"
f"{self._data['out-interface']}:{self._data['to-addresses']}:{self._data['to-ports']}"
2020-03-16 04:51:41 +01:00
):
value = self._ctrl.data["nat"][uid][".id"]
2022-02-04 20:34:51 +01:00
mod_param = self.entity_description.data_switch_parameter
self._ctrl.set_value(path, param, value, mod_param, True)
2019-12-06 01:22:34 +01:00
await self._ctrl.async_update()
2019-12-03 18:30:45 +01:00
2019-12-04 20:13:11 +01:00
2020-12-18 19:58:54 +01:00
# ---------------------------
# MikrotikControllerMangleSwitch
# ---------------------------
class MikrotikControllerMangleSwitch(MikrotikControllerSwitch):
"""Representation of a Mangle switch."""
2020-12-25 20:28:36 +01:00
async def async_turn_on(self) -> None:
2020-12-18 19:58:54 +01:00
"""Turn on the switch."""
2022-02-04 20:44:59 +01:00
path = self.entity_description.data_switch_path
2020-12-18 19:58:54 +01:00
param = ".id"
value = None
for uid in self._ctrl.data["mangle"]:
2020-12-25 23:31:51 +01:00
if self._ctrl.data["mangle"][uid]["uniq-id"] == (
f"{self._data['chain']},{self._data['action']},{self._data['protocol']},"
f"{self._data['src-address']}:{self._data['src-port']}-"
2021-08-24 18:24:41 +07:00
f"{self._data['dst-address']}:{self._data['dst-port']},"
2021-08-24 19:24:50 +07:00
f"{self._data['src-address-list']}-{self._data['dst-address-list']}"
2020-12-18 19:58:54 +01:00
):
value = self._ctrl.data["mangle"][uid][".id"]
2022-02-04 20:44:59 +01:00
mod_param = self.entity_description.data_switch_parameter
self._ctrl.set_value(path, param, value, mod_param, False)
2020-12-18 19:58:54 +01:00
await self._ctrl.force_update()
2020-12-25 20:28:36 +01:00
async def async_turn_off(self) -> None:
"""Turn off the switch."""
2022-02-04 20:44:59 +01:00
path = self.entity_description.data_switch_path
2020-12-18 19:58:54 +01:00
param = ".id"
value = None
for uid in self._ctrl.data["mangle"]:
2020-12-25 23:31:51 +01:00
if self._ctrl.data["mangle"][uid]["uniq-id"] == (
f"{self._data['chain']},{self._data['action']},{self._data['protocol']},"
f"{self._data['src-address']}:{self._data['src-port']}-"
2021-08-24 18:24:41 +07:00
f"{self._data['dst-address']}:{self._data['dst-port']},"
2021-08-24 19:24:50 +07:00
f"{self._data['src-address-list']}-{self._data['dst-address-list']}"
2020-12-18 19:58:54 +01:00
):
value = self._ctrl.data["mangle"][uid][".id"]
2022-02-04 20:44:59 +01:00
mod_param = self.entity_description.data_switch_parameter
self._ctrl.set_value(path, param, value, mod_param, True)
2020-12-18 19:58:54 +01:00
await self._ctrl.async_update()
2021-04-12 12:40:45 +02:00
# ---------------------------
# MikrotikControllerFilterSwitch
# ---------------------------
class MikrotikControllerFilterSwitch(MikrotikControllerSwitch):
"""Representation of a Filter switch."""
async def async_turn_on(self) -> None:
"""Turn on the switch."""
2022-02-04 20:52:22 +01:00
path = self.entity_description.data_switch_path
2021-04-12 12:40:45 +02:00
param = ".id"
value = None
for uid in self._ctrl.data["filter"]:
if self._ctrl.data["filter"][uid]["uniq-id"] == (
f"{self._data['chain']},{self._data['action']},{self._data['protocol']},{self._data['layer7-protocol']},"
f"{self._data['in-interface']}:{self._data['src-address']}:{self._data['src-port']}-"
f"{self._data['out-interface']}:{self._data['dst-address']}:{self._data['dst-port']}"
):
value = self._ctrl.data["filter"][uid][".id"]
2022-02-04 20:52:22 +01:00
mod_param = self.entity_description.data_switch_parameter
self._ctrl.set_value(path, param, value, mod_param, False)
2021-04-12 12:40:45 +02:00
await self._ctrl.force_update()
async def async_turn_off(self) -> None:
"""Turn off the switch."""
2022-02-04 20:52:22 +01:00
path = self.entity_description.data_switch_path
2021-04-12 12:40:45 +02:00
param = ".id"
value = None
for uid in self._ctrl.data["filter"]:
if self._ctrl.data["filter"][uid]["uniq-id"] == (
f"{self._data['chain']},{self._data['action']},{self._data['protocol']},{self._data['layer7-protocol']},"
f"{self._data['in-interface']}:{self._data['src-address']}:{self._data['src-port']}-"
f"{self._data['out-interface']}:{self._data['dst-address']}:{self._data['dst-port']}"
):
value = self._ctrl.data["filter"][uid][".id"]
2022-02-04 20:52:22 +01:00
mod_param = self.entity_description.data_switch_parameter
self._ctrl.set_value(path, param, value, mod_param, True)
2021-04-12 12:40:45 +02:00
await self._ctrl.async_update()
# ---------------------------
# MikrotikControllerQueueSwitch
# ---------------------------
class MikrotikControllerQueueSwitch(MikrotikControllerSwitch):
"""Representation of a queue switch."""
2020-12-25 20:28:36 +01:00
async def async_turn_on(self) -> None:
"""Turn on the switch."""
2022-02-04 21:24:24 +01:00
path = self.entity_description.data_switch_path
param = ".id"
value = None
for uid in self._ctrl.data["queue"]:
2020-04-11 05:45:36 +02:00
if self._ctrl.data["queue"][uid]["name"] == f"{self._data['name']}":
value = self._ctrl.data["queue"][uid][".id"]
2022-02-04 21:24:24 +01:00
mod_param = self.entity_description.data_switch_parameter
self._ctrl.set_value(path, param, value, mod_param, False)
await self._ctrl.force_update()
2020-12-25 20:28:36 +01:00
async def async_turn_off(self) -> None:
"""Turn off the switch."""
2022-02-04 21:24:24 +01:00
path = self.entity_description.data_switch_path
param = ".id"
value = None
for uid in self._ctrl.data["queue"]:
2020-04-11 05:45:36 +02:00
if self._ctrl.data["queue"][uid]["name"] == f"{self._data['name']}":
value = self._ctrl.data["queue"][uid][".id"]
2022-02-04 21:24:24 +01:00
mod_param = self.entity_description.data_switch_parameter
self._ctrl.set_value(path, param, value, mod_param, True)
2020-12-25 18:42:57 +01:00
await self._ctrl.async_update()
2022-02-04 21:25:01 +01:00
# ---------------------------
# MikrotikControllerKidcontrolPauseSwitch
# ---------------------------
class MikrotikControllerKidcontrolPauseSwitch(MikrotikControllerSwitch):
"""Representation of a queue switch."""
async def async_turn_on(self) -> None:
"""Turn on the switch."""
path = self.entity_description.data_switch_path
param = self.entity_description.data_reference
value = self._data[self.entity_description.data_reference]
command = "resume"
self._ctrl.execute(path, command, param, value)
await self._ctrl.force_update()
async def async_turn_off(self) -> None:
"""Turn off the switch."""
path = self.entity_description.data_switch_path
param = self.entity_description.data_reference
value = self._data[self.entity_description.data_reference]
command = "pause"
self._ctrl.execute(path, command, param, value)
await self._ctrl.async_update()