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

477 lines
14 KiB
Python
Raw Normal View History

"""Support for the Mikrotik Router switches."""
import logging
from homeassistant.components.switch import SwitchDevice
2020-04-11 05:45:36 +02:00
from homeassistant.const import CONF_NAME, ATTR_ATTRIBUTION
from homeassistant.core import callback
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.restore_state import RestoreEntity
2020-04-11 05:45:36 +02:00
from .const import DOMAIN, DATA_CLIENT, ATTRIBUTION
_LOGGER = logging.getLogger(__name__)
2019-12-03 18:30:45 +01:00
DEVICE_ATTRIBUTES_IFACE = [
"running",
"enabled",
"comment",
"client-ip-address",
"client-mac-address",
"port-mac-address",
"last-link-down-time",
"last-link-up-time",
"link-downs",
"actual-mtu",
"type",
"name",
"default-name",
]
2019-12-03 18:30:45 +01:00
DEVICE_ATTRIBUTES_NAT = [
"protocol",
"dst-port",
"in-interface",
"to-addresses",
"to-ports",
"comment",
]
2019-12-04 20:13:11 +01:00
DEVICE_ATTRIBUTES_SCRIPT = [
"last-started",
"run-count",
]
DEVICE_ATTRIBUTES_QUEUE = [
"target",
"download-max-limit",
"upload-max-limit",
"upload-limit-at",
"download-limit-at",
"upload-burst-limit",
"download-burst-limit",
"upload-burst-threshold",
"download-burst-threshold",
"upload-burst-time",
"download-burst-time",
"packet-marks",
"parent",
"comment",
]
# ---------------------------
# format_attribute
# ---------------------------
2019-12-07 20:50:00 +01:00
def format_attribute(attr):
res = attr.replace("-", " ")
res = res.capitalize()
res = res.replace(" ip ", " IP ")
res = res.replace(" mac ", " MAC ")
res = res.replace(" mtu", " MTU")
return res
# ---------------------------
# 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
2020-04-20 08:39:02 +02:00
for sid, sid_uid, sid_name, sid_ref, sid_attr, sid_func in zip(
# Data point name
["interface", "nat", "script", "queue"],
2020-04-20 08:39:02 +02:00
# Data point unique id
["name", "name", "name", "name"],
# Entry Name
["name", "name", "name", "name"],
# Entry Unique id
["port-mac-address", "name", "name", "name"],
# Attr
[
DEVICE_ATTRIBUTES_IFACE,
DEVICE_ATTRIBUTES_NAT,
DEVICE_ATTRIBUTES_SCRIPT,
DEVICE_ATTRIBUTES_QUEUE,
],
# Switch function
2020-03-16 04:51:41 +01:00
[
MikrotikControllerPortSwitch,
MikrotikControllerNATSwitch,
MikrotikControllerScriptSwitch,
MikrotikControllerQueueSwitch,
2020-03-16 04:51:41 +01:00
],
2019-12-09 09:52:45 +01:00
):
2019-12-05 22:10:42 +01:00
for uid in mikrotik_controller.data[sid]:
2020-04-20 08:39:02 +02:00
item_id = f"{inst}-{sid}-{mikrotik_controller.data[sid][uid][sid_uid]}"
2020-04-04 19:46:40 +02:00
_LOGGER.debug("Updating switch %s", item_id)
if item_id in switches:
if switches[item_id].enabled:
switches[item_id].async_schedule_update_ha_state()
continue
2020-04-20 08:39:02 +02:00
# Create new entity
sid_data = {
"sid": sid,
"sid_uid": sid_uid,
"sid_name": sid_name,
"sid_ref": sid_ref,
"sid_attr": sid_attr,
}
switches[item_id] = sid_func(inst, uid, mikrotik_controller, sid_data)
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
# ---------------------------
2019-12-03 18:30:45 +01:00
class MikrotikControllerSwitch(SwitchDevice, RestoreEntity):
2019-12-06 01:22:34 +01:00
"""Representation of a switch."""
2020-04-20 08:39:02 +02:00
def __init__(self, inst, uid, mikrotik_controller, sid_data):
2019-12-03 18:30:45 +01:00
"""Set up switch."""
2020-04-20 08:39:02 +02:00
self._sid_data = sid_data
2019-12-06 01:22:34 +01:00
self._inst = inst
self._ctrl = mikrotik_controller
2020-04-20 08:39:02 +02:00
self._data = mikrotik_controller.data[self._sid_data["sid"]][uid]
self._attrs = {
ATTR_ATTRIBUTION: ATTRIBUTION,
}
2019-12-03 18:30:45 +01:00
async def async_added_to_hass(self):
2020-04-20 08:39:02 +02:00
"""Device tracker entity created."""
_LOGGER.debug(
"New switch %s (%s %s)",
self._inst,
self._sid_data["sid"],
self._data[self._sid_data["sid_uid"]],
)
2019-12-03 18:30:45 +01:00
async def async_update(self):
"""Synchronize state with controller."""
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:
"""Return the name of the port."""
return f"{self._inst} {self._sid_data['sid']} {self._data[self._sid_data['sid_name']]}"
@property
def unique_id(self) -> str:
"""Return a unique identifier for this port."""
return f"{self._inst.lower()}-{self._sid_data['sid']}_switch-{self._data[self._sid_data['sid_ref']]}"
@property
def is_on(self):
"""Return true if the queue is on."""
return self._data["enabled"]
@property
def device_state_attributes(self):
"""Return the port state attributes."""
attributes = self._attrs
for variable in self._sid_data["sid_attr"]:
if variable in self._data:
attributes[format_attribute(variable)] = self._data[variable]
return attributes
2019-12-03 18:30:45 +01:00
# ---------------------------
# MikrotikControllerPortSwitch
# ---------------------------
class MikrotikControllerPortSwitch(MikrotikControllerSwitch):
"""Representation of a network port switch."""
2020-04-20 08:39:02 +02:00
def __init__(self, inst, uid, mikrotik_controller, sid_data):
2019-12-03 18:30:45 +01:00
"""Set up tracked port."""
2020-04-20 08:39:02 +02:00
super().__init__(inst, uid, mikrotik_controller, sid_data)
@property
def name(self) -> str:
"""Return the name of the port."""
2020-04-20 08:39:02 +02:00
return f"{self._inst} port {self._data[self._sid_data['sid_name']]}"
@property
def unique_id(self) -> str:
"""Return a unique identifier for this port."""
return f"{self._inst.lower()}-enable_switch-{self._data['port-mac-address']}"
@property
def icon(self):
"""Return the icon."""
2020-03-16 04:51:41 +01:00
if self._data["running"]:
icon = "mdi:lan-connect"
else:
2020-03-16 04:51:41 +01:00
icon = "mdi:lan-pending"
2020-03-16 04:51:41 +01:00
if not self._data["enabled"]:
icon = "mdi:lan-disconnect"
return icon
@property
def device_info(self):
"""Return a port description for device registry."""
info = {
2020-04-11 05:45:36 +02:00
"connections": {(CONNECTION_NETWORK_MAC, self._data["port-mac-address"])},
2020-03-16 04:51:41 +01:00
"manufacturer": self._ctrl.data["resource"]["platform"],
"model": self._ctrl.data["resource"]["board-name"],
"name": f"{self._inst} {self._data['default-name']}",
}
return info
async def async_turn_on(self):
"""Turn on the switch."""
2020-03-16 04:51:41 +01:00
path = "/interface"
param = "default-name"
if "-" in self._data["port-mac-address"]:
param = "name"
2019-12-06 01:22:34 +01:00
value = self._data[param]
2020-03-16 04:51:41 +01:00
mod_param = "disabled"
mod_value = False
2019-12-06 01:22:34 +01:00
self._ctrl.set_value(path, param, value, mod_param, mod_value)
await self._ctrl.force_update()
async def async_turn_off(self):
"""Turn on the switch."""
2020-03-16 04:51:41 +01:00
path = "/interface"
param = "default-name"
if "-" in self._data["port-mac-address"]:
param = "name"
2019-12-06 01:22:34 +01:00
value = self._data[param]
2020-03-16 04:51:41 +01:00
mod_param = "disabled"
mod_value = True
2019-12-06 01:22:34 +01:00
self._ctrl.set_value(path, param, value, mod_param, mod_value)
await self._ctrl.async_update()
2019-12-03 18:30:45 +01:00
# ---------------------------
# MikrotikControllerNATSwitch
# ---------------------------
class MikrotikControllerNATSwitch(MikrotikControllerSwitch):
"""Representation of a NAT switch."""
2020-04-20 08:39:02 +02:00
def __init__(self, inst, uid, mikrotik_controller, sid_data):
2019-12-03 18:30:45 +01:00
"""Set up NAT switch."""
2020-04-20 08:39:02 +02:00
super().__init__(inst, uid, mikrotik_controller, sid_data)
2019-12-03 18:30:45 +01:00
@property
def name(self) -> str:
"""Return the name of the NAT switch."""
return f"{self._inst} NAT {self._data['name']}"
2019-12-03 18:30:45 +01:00
@property
def icon(self):
"""Return the icon."""
2020-03-16 04:51:41 +01:00
if not self._data["enabled"]:
icon = "mdi:network-off-outline"
2019-12-03 18:30:45 +01:00
else:
2020-03-16 04:51:41 +01:00
icon = "mdi:network-outline"
2019-12-03 18:30:45 +01:00
return icon
2019-12-03 18:30:45 +01:00
@property
def device_info(self):
"""Return a NAT switch description for device registry."""
info = {
2020-03-16 04:51:41 +01:00
"identifiers": {
(
DOMAIN,
"serial-number",
self._ctrl.data["routerboard"]["serial-number"],
"switch",
"NAT",
)
},
"manufacturer": self._ctrl.data["resource"]["platform"],
"model": self._ctrl.data["resource"]["board-name"],
"name": f"{self._inst} NAT",
2019-12-03 18:30:45 +01:00
}
return info
2019-12-03 18:30:45 +01:00
async def async_turn_on(self):
"""Turn on the switch."""
2020-03-16 04:51:41 +01:00
path = "/ip/firewall/nat"
param = ".id"
value = None
2020-03-16 04:51:41 +01:00
for uid in self._ctrl.data["nat"]:
if (
self._ctrl.data["nat"][uid]["name"]
== f"{self._data['protocol']}:{self._data['dst-port']}"
2020-03-16 04:51:41 +01:00
):
value = self._ctrl.data["nat"][uid][".id"]
2020-03-16 04:51:41 +01:00
mod_param = "disabled"
2019-12-03 18:30:45 +01:00
mod_value = False
2019-12-06 01:22:34 +01:00
self._ctrl.set_value(path, param, value, mod_param, mod_value)
await self._ctrl.force_update()
2019-12-03 18:30:45 +01:00
async def async_turn_off(self):
"""Turn on the switch."""
2020-03-16 04:51:41 +01:00
path = "/ip/firewall/nat"
param = ".id"
value = None
2020-03-16 04:51:41 +01:00
for uid in self._ctrl.data["nat"]:
if (
self._ctrl.data["nat"][uid]["name"]
== f"{self._data['protocol']}:{self._data['dst-port']}"
2020-03-16 04:51:41 +01:00
):
value = self._ctrl.data["nat"][uid][".id"]
2020-03-16 04:51:41 +01:00
mod_param = "disabled"
2019-12-03 18:30:45 +01:00
mod_value = True
2019-12-06 01:22:34 +01:00
self._ctrl.set_value(path, param, value, mod_param, mod_value)
await self._ctrl.async_update()
2019-12-03 18:30:45 +01:00
2019-12-04 20:13:11 +01:00
# ---------------------------
# MikrotikControllerScriptSwitch
# ---------------------------
class MikrotikControllerScriptSwitch(MikrotikControllerSwitch):
"""Representation of a script switch."""
2020-04-20 08:39:02 +02:00
def __init__(self, inst, uid, mikrotik_controller, sid_data):
2019-12-04 20:13:11 +01:00
"""Set up script switch."""
2020-04-20 08:39:02 +02:00
super().__init__(inst, uid, mikrotik_controller, sid_data)
2019-12-04 20:13:11 +01:00
@property
def icon(self):
"""Return the icon."""
2020-03-16 04:51:41 +01:00
return "mdi:script-text-outline"
2019-12-04 20:13:11 +01:00
@property
def device_info(self):
"""Return a script switch description for device registry."""
info = {
2020-03-16 04:51:41 +01:00
"identifiers": {
(
DOMAIN,
"serial-number",
self._ctrl.data["routerboard"]["serial-number"],
"switch",
"Scripts",
)
},
"manufacturer": self._ctrl.data["resource"]["platform"],
"model": self._ctrl.data["resource"]["board-name"],
"name": f"{self._inst} Scripts",
2019-12-04 20:13:11 +01:00
}
return info
2019-12-04 20:13:11 +01:00
async def async_turn_on(self):
"""Turn on the switch."""
2020-03-16 04:51:41 +01:00
self._ctrl.run_script(self._data["name"])
2019-12-06 01:22:34 +01:00
await self._ctrl.force_update()
2019-12-04 20:13:11 +01:00
async def async_turn_off(self):
"""Turn off the switch."""
@property
def is_on(self):
"""Return true if device is on."""
return False
# ---------------------------
# MikrotikControllerQueueSwitch
# ---------------------------
class MikrotikControllerQueueSwitch(MikrotikControllerSwitch):
"""Representation of a queue switch."""
2020-04-20 08:39:02 +02:00
def __init__(self, inst, uid, mikrotik_controller, sid_data):
"""Set up queue switch."""
2020-04-20 08:39:02 +02:00
super().__init__(inst, uid, mikrotik_controller, sid_data)
@property
def icon(self):
"""Return the icon."""
if not self._data["enabled"]:
icon = "mdi:leaf-off"
else:
icon = "mdi:leaf"
return icon
@property
def device_info(self):
"""Return a queue switch description for device registry."""
info = {
"identifiers": {
(
DOMAIN,
"serial-number",
self._ctrl.data["routerboard"]["serial-number"],
"switch",
"Queue",
)
},
"manufacturer": self._ctrl.data["resource"]["platform"],
"model": self._ctrl.data["resource"]["board-name"],
"name": f"{self._inst} Queue",
}
return info
async def async_turn_on(self):
"""Turn on the queue switch."""
path = "/queue/simple"
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"]
mod_param = "disabled"
mod_value = False
self._ctrl.set_value(path, param, value, mod_param, mod_value)
await self._ctrl.force_update()
async def async_turn_off(self):
"""Turn on the queue switch."""
path = "/queue/simple"
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"]
mod_param = "disabled"
mod_value = True
self._ctrl.set_value(path, param, value, mod_param, mod_value)
await self._ctrl.async_update()