redo system sensors

This commit is contained in:
Tomaae 2022-02-01 10:12:38 +01:00
parent 123044fceb
commit 74b46ed562
2 changed files with 450 additions and 409 deletions

View file

@ -1,19 +1,17 @@
"""Support for the Mikrotik Router sensor service.""" """Implementation of Mikrotik Router sensor entities."""
import logging import logging
from typing import Any, Dict, Optional from typing import Any, Dict, Optional
from homeassistant.const import ( from homeassistant.const import (
CONF_NAME, CONF_NAME,
CONF_HOST, CONF_HOST,
ATTR_ATTRIBUTION, ATTR_ATTRIBUTION,
ATTR_DEVICE_CLASS,
TEMP_CELSIUS,
ELECTRIC_POTENTIAL_VOLT,
) )
from homeassistant.helpers.entity import EntityCategory from homeassistant.helpers.entity import DeviceInfo
from homeassistant.components.sensor import SensorDeviceClass from homeassistant.components.sensor import SensorEntity
from .const import ( from .const import (
CONF_SENSOR_PORT_TRAFFIC, CONF_SENSOR_PORT_TRAFFIC,
@ -21,11 +19,15 @@ from .const import (
) )
from homeassistant.core import callback from homeassistant.core import callback
from homeassistant.components.sensor import SensorEntity
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC
from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.dispatcher import async_dispatcher_connect
from .const import DOMAIN, DATA_CLIENT, ATTRIBUTION from .const import DOMAIN, DATA_CLIENT, ATTRIBUTION
from .sensor_types import (
MikrotikSensorEntityDescription,
SENSOR_TYPES,
DEVICE_ATTRIBUTES_CLIENT_TRAFFIC,
)
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -46,191 +48,6 @@ def format_attribute(attr):
return res return res
ATTR_ICON = "icon"
ATTR_LABEL = "label"
ATTR_UNIT = "unit"
ATTR_UNIT_ATTR = "unit_attr"
ATTR_GROUP = "group"
ATTR_PATH = "data_path"
ATTR_ATTR = "data_attr"
ATTR_CTGR = "entity_category"
SENSOR_TYPES = {
"system_temperature": {
ATTR_DEVICE_CLASS: SensorDeviceClass.TEMPERATURE,
ATTR_ICON: "mdi:thermometer",
ATTR_LABEL: "Temperature",
ATTR_UNIT: TEMP_CELSIUS,
ATTR_GROUP: "System",
ATTR_PATH: "health",
ATTR_ATTR: "temperature",
ATTR_CTGR: None,
},
"system_voltage": {
ATTR_DEVICE_CLASS: SensorDeviceClass.VOLTAGE,
ATTR_ICON: "mdi:lightning-bolt",
ATTR_LABEL: "Voltage",
ATTR_UNIT: ELECTRIC_POTENTIAL_VOLT,
ATTR_GROUP: "System",
ATTR_PATH: "health",
ATTR_ATTR: "voltage",
ATTR_CTGR: EntityCategory.DIAGNOSTIC,
},
"system_cpu-temperature": {
ATTR_DEVICE_CLASS: SensorDeviceClass.TEMPERATURE,
ATTR_ICON: "mdi:thermometer",
ATTR_LABEL: "CPU temperature",
ATTR_UNIT: TEMP_CELSIUS,
ATTR_GROUP: "System",
ATTR_PATH: "health",
ATTR_ATTR: "cpu-temperature",
ATTR_CTGR: None,
},
"system_board-temperature1": {
ATTR_DEVICE_CLASS: SensorDeviceClass.TEMPERATURE,
ATTR_ICON: "mdi:thermometer",
ATTR_LABEL: "Board temperature",
ATTR_UNIT: TEMP_CELSIUS,
ATTR_GROUP: "System",
ATTR_PATH: "health",
ATTR_ATTR: "board-temperature1",
ATTR_CTGR: None,
},
"system_power-consumption": {
ATTR_DEVICE_CLASS: SensorDeviceClass.POWER,
ATTR_ICON: "mdi:transmission-tower",
ATTR_LABEL: "Power consumption",
ATTR_UNIT: "W",
ATTR_GROUP: "System",
ATTR_PATH: "health",
ATTR_ATTR: "power-consumption",
ATTR_CTGR: None,
},
"system_fan1-speed": {
ATTR_DEVICE_CLASS: None,
ATTR_ICON: "mdi:fan",
ATTR_LABEL: "Fan1 speed",
ATTR_UNIT: "RPM",
ATTR_GROUP: "System",
ATTR_PATH: "health",
ATTR_ATTR: "fan1-speed",
ATTR_CTGR: None,
},
"system_fan2-speed": {
ATTR_DEVICE_CLASS: None,
ATTR_ICON: "mdi:fan",
ATTR_LABEL: "Fan2 speed",
ATTR_UNIT: "RPM",
ATTR_GROUP: "System",
ATTR_PATH: "health",
ATTR_ATTR: "fan2-speed",
ATTR_CTGR: None,
},
"system_uptime": {
ATTR_DEVICE_CLASS: SensorDeviceClass.TIMESTAMP,
ATTR_ICON: None,
ATTR_LABEL: "Uptime",
ATTR_UNIT: None,
ATTR_GROUP: "System",
ATTR_PATH: "resource",
ATTR_ATTR: "uptime",
ATTR_CTGR: EntityCategory.DIAGNOSTIC,
},
"system_cpu-load": {
ATTR_DEVICE_CLASS: None,
ATTR_ICON: "mdi:speedometer",
ATTR_LABEL: "CPU load",
ATTR_UNIT: "%",
ATTR_GROUP: "System",
ATTR_PATH: "resource",
ATTR_ATTR: "cpu-load",
ATTR_CTGR: None,
},
"system_memory-usage": {
ATTR_DEVICE_CLASS: None,
ATTR_ICON: "mdi:memory",
ATTR_LABEL: "Memory usage",
ATTR_UNIT: "%",
ATTR_GROUP: "System",
ATTR_PATH: "resource",
ATTR_ATTR: "memory-usage",
ATTR_CTGR: None,
},
"system_hdd-usage": {
ATTR_DEVICE_CLASS: None,
ATTR_ICON: "mdi:harddisk",
ATTR_LABEL: "HDD usage",
ATTR_UNIT: "%",
ATTR_GROUP: "System",
ATTR_PATH: "resource",
ATTR_ATTR: "hdd-usage",
ATTR_CTGR: None,
},
"traffic_tx": {
ATTR_DEVICE_CLASS: None,
ATTR_ICON: "mdi:upload-network-outline",
ATTR_LABEL: "TX",
ATTR_UNIT: "ps",
ATTR_UNIT_ATTR: "tx-bits-per-second-attr",
ATTR_PATH: "interface",
ATTR_ATTR: "tx-bits-per-second",
ATTR_CTGR: None,
},
"traffic_rx": {
ATTR_DEVICE_CLASS: None,
ATTR_ICON: "mdi:download-network-outline",
ATTR_LABEL: "RX",
ATTR_UNIT: "ps",
ATTR_UNIT_ATTR: "rx-bits-per-second-attr",
ATTR_PATH: "interface",
ATTR_ATTR: "rx-bits-per-second",
ATTR_CTGR: None,
},
"client_traffic_lan_tx": {
ATTR_DEVICE_CLASS: None,
ATTR_ICON: "mdi:upload-network",
ATTR_LABEL: "LAN TX",
ATTR_UNIT: "ps",
ATTR_UNIT_ATTR: "tx-rx-attr",
ATTR_PATH: "client_traffic",
ATTR_ATTR: "lan-tx",
ATTR_CTGR: None,
},
"client_traffic_lan_rx": {
ATTR_DEVICE_CLASS: None,
ATTR_ICON: "mdi:download-network",
ATTR_LABEL: "LAN RX",
ATTR_UNIT: "ps",
ATTR_UNIT_ATTR: "tx-rx-attr",
ATTR_PATH: "client_traffic",
ATTR_ATTR: "lan-rx",
ATTR_CTGR: None,
},
"client_traffic_wan_tx": {
ATTR_DEVICE_CLASS: None,
ATTR_ICON: "mdi:upload-network",
ATTR_LABEL: "WAN TX",
ATTR_UNIT: "ps",
ATTR_UNIT_ATTR: "tx-rx-attr",
ATTR_PATH: "client_traffic",
ATTR_ATTR: "wan-tx",
ATTR_CTGR: None,
},
"client_traffic_wan_rx": {
ATTR_DEVICE_CLASS: None,
ATTR_ICON: "mdi:download-network",
ATTR_LABEL: "WAN RX",
ATTR_UNIT: "ps",
ATTR_UNIT_ATTR: "tx-rx-attr",
ATTR_PATH: "client_traffic",
ATTR_ATTR: "wan-rx",
ATTR_CTGR: None,
},
}
DEVICE_ATTRIBUTES_CLIENT_TRAFFIC = ["address", "mac-address", "host-name"]
# --------------------------- # ---------------------------
# async_setup_entry # async_setup_entry
# --------------------------- # ---------------------------
@ -264,53 +81,37 @@ def update_items(inst, config_entry, mikrotik_controller, async_add_entities, se
"""Update sensor state from the controller.""" """Update sensor state from the controller."""
new_sensors = [] new_sensors = []
for sid, sid_uid, sid_name, sid_val, sid_ref, sid_attr, sid_func in zip( for sensor, sid_func in zip(
# Data point name # Data point name
["environment"], ["environment"],
# Data point unique id
["name"],
# Entry Name
["name"],
# Entry Value
["value"],
# Entry Unique id
["name"],
# Attr
[
None,
],
# Switch function # Switch function
[ [
MikrotikControllerEnvironmentSensor, MikrotikControllerSensor,
], ],
): ):
for uid in mikrotik_controller.data[sid]: for uid in mikrotik_controller.data[sensor]:
item_id = f"{inst}-{sid}-{mikrotik_controller.data[sid][uid][sid_uid]}" item_id = f"{inst}-{sensor}-{mikrotik_controller.data[sensor][uid][SENSOR_TYPES[sensor].data_uid]}"
_LOGGER.debug("Updating sensor %s", item_id) _LOGGER.debug("Updating sensor %s", item_id)
if item_id in sensors: if item_id in sensors:
if sensors[item_id].enabled: if sensors[item_id].enabled:
sensors[item_id].async_schedule_update_ha_state() sensors[item_id].async_schedule_update_ha_state()
continue continue
# Create new entity sensors[item_id] = sid_func(
sid_data = { inst=inst,
"sid": sid, uid=uid,
"sid_uid": sid_uid, mikrotik_controller=mikrotik_controller,
"sid_name": sid_name, entity_description=SENSOR_TYPES[sensor],
"sid_ref": sid_ref, )
"sid_attr": sid_attr,
"sid_val": sid_val,
}
sensors[item_id] = sid_func(inst, uid, mikrotik_controller, sid_data)
new_sensors.append(sensors[item_id]) new_sensors.append(sensors[item_id])
for sensor in SENSOR_TYPES: for sensor in SENSOR_TYPES:
if sensor.startswith("system_"): if sensor.startswith("system_"):
if ( if (
SENSOR_TYPES[sensor][ATTR_ATTR] SENSOR_TYPES[sensor].data_attribute
not in mikrotik_controller.data[SENSOR_TYPES[sensor][ATTR_PATH]] not in mikrotik_controller.data[SENSOR_TYPES[sensor].data_path]
or mikrotik_controller.data[SENSOR_TYPES[sensor][ATTR_PATH]][ or mikrotik_controller.data[SENSOR_TYPES[sensor].data_path][
SENSOR_TYPES[sensor][ATTR_ATTR] SENSOR_TYPES[sensor].data_attribute
] ]
== "unknown" == "unknown"
): ):
@ -323,52 +124,55 @@ def update_items(inst, config_entry, mikrotik_controller, async_add_entities, se
continue continue
sensors[item_id] = MikrotikControllerSensor( sensors[item_id] = MikrotikControllerSensor(
mikrotik_controller=mikrotik_controller, inst=inst, sid_data=sensor inst=inst,
uid="",
mikrotik_controller=mikrotik_controller,
entity_description=SENSOR_TYPES[sensor],
) )
new_sensors.append(sensors[item_id]) new_sensors.append(sensors[item_id])
if sensor.startswith("traffic_"): # if sensor.startswith("traffic_"):
if not config_entry.options.get( # if not config_entry.options.get(
CONF_SENSOR_PORT_TRAFFIC, DEFAULT_SENSOR_PORT_TRAFFIC # CONF_SENSOR_PORT_TRAFFIC, DEFAULT_SENSOR_PORT_TRAFFIC
): # ):
continue # continue
#
for uid in mikrotik_controller.data["interface"]: # for uid in mikrotik_controller.data["interface"]:
if mikrotik_controller.data["interface"][uid]["type"] != "bridge": # if mikrotik_controller.data["interface"][uid]["type"] != "bridge":
item_id = f"{inst}-{sensor}-{mikrotik_controller.data['interface'][uid]['default-name']}" # item_id = f"{inst}-{sensor}-{mikrotik_controller.data['interface'][uid]['default-name']}"
_LOGGER.debug("Updating sensor %s", item_id) # _LOGGER.debug("Updating sensor %s", item_id)
if item_id in sensors: # if item_id in sensors:
if sensors[item_id].enabled: # if sensors[item_id].enabled:
sensors[item_id].async_schedule_update_ha_state() # sensors[item_id].async_schedule_update_ha_state()
continue # continue
#
sensors[item_id] = MikrotikControllerTrafficSensor( # sensors[item_id] = MikrotikControllerTrafficSensor(
mikrotik_controller=mikrotik_controller, # mikrotik_controller=mikrotik_controller,
inst=inst, # inst=inst,
sensor=sensor, # sensor=SENSOR_TYPES[sensor],
uid=uid, # uid=uid,
) # )
new_sensors.append(sensors[item_id]) # new_sensors.append(sensors[item_id])
#
if sensor.startswith("client_traffic_"): # if sensor.startswith("client_traffic_"):
for uid in mikrotik_controller.data["client_traffic"]: # for uid in mikrotik_controller.data["client_traffic"]:
item_id = f"{inst}-{sensor}-{mikrotik_controller.data['client_traffic'][uid]['mac-address']}" # item_id = f"{inst}-{sensor}-{mikrotik_controller.data['client_traffic'][uid]['mac-address']}"
if item_id in sensors: # if item_id in sensors:
if sensors[item_id].enabled: # if sensors[item_id].enabled:
sensors[item_id].async_schedule_update_ha_state() # sensors[item_id].async_schedule_update_ha_state()
continue # continue
#
if ( # if (
SENSOR_TYPES[sensor][ATTR_ATTR] # SENSOR_TYPES[sensor].data_attribute
in mikrotik_controller.data["client_traffic"][uid].keys() # in mikrotik_controller.data["client_traffic"][uid].keys()
): # ):
sensors[item_id] = MikrotikClientTrafficSensor( # sensors[item_id] = MikrotikClientTrafficSensor(
mikrotik_controller=mikrotik_controller, # mikrotik_controller=mikrotik_controller,
inst=inst, # inst=inst,
sensor=sensor, # sensor=SENSOR_TYPES[sensor],
uid=uid, # uid=uid,
) # )
new_sensors.append(sensors[item_id]) # new_sensors.append(sensors[item_id])
if new_sensors: if new_sensors:
async_add_entities(new_sensors, True) async_add_entities(new_sensors, True)
@ -380,76 +184,49 @@ def update_items(inst, config_entry, mikrotik_controller, async_add_entities, se
class MikrotikControllerSensor(SensorEntity): class MikrotikControllerSensor(SensorEntity):
"""Define an Mikrotik Controller sensor.""" """Define an Mikrotik Controller sensor."""
def __init__(self, mikrotik_controller, inst, sid_data): def __init__(
self,
mikrotik_controller,
inst,
uid: "",
entity_description: MikrotikSensorEntityDescription,
):
"""Initialize.""" """Initialize."""
self._inst = inst self._inst = inst
self._sensor = sid_data self.entity_description = entity_description
self._ctrl = mikrotik_controller self._ctrl = mikrotik_controller
self._attr_extra_state_attributes = {ATTR_ATTRIBUTION: ATTRIBUTION}
if sid_data in SENSOR_TYPES: self._uid = uid
self._data = mikrotik_controller.data[SENSOR_TYPES[sid_data][ATTR_PATH]] if self._uid:
self._type = SENSOR_TYPES[sid_data] self._data = mikrotik_controller.data[self.entity_description.data_path][
self._icon = self._type[ATTR_ICON] self._uid
self._attr = self._type[ATTR_ATTR] ]
self._dcls = self._type[ATTR_DEVICE_CLASS]
self._ctgr = self._type[ATTR_CTGR]
else: else:
self._type = {} self._data = mikrotik_controller.data[self.entity_description.data_path]
self._icon = None
self._attr = None
self._dcls = None
self._ctgr = None
self._state = None
self._attrs = {ATTR_ATTRIBUTION: ATTRIBUTION}
@property @property
def name(self) -> str: def name(self) -> str:
"""Return the name.""" """Return the name."""
return f"{self._inst} {self._type[ATTR_LABEL]}" if self._uid:
return f"{self._inst} {self._data[self.entity_description.data_reference]}"
@property else:
def state(self) -> Optional[str]: return f"{self._inst} {self.entity_description.name}"
"""Return the state."""
val = "unknown"
if self._attr in self._data:
val = self._data[self._attr]
return val
@property
def extra_state_attributes(self) -> Dict[str, Any]:
"""Return the state attributes."""
return self._attrs
@property
def icon(self) -> str:
"""Return the icon."""
return self._icon
@property
def entity_category(self) -> str:
"""Return entity category"""
return self._ctgr
@property
def device_class(self) -> Optional[str]:
"""Return the device class."""
return self._dcls
@property @property
def unique_id(self) -> str: 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()}" if self._uid:
return f"{self._inst.lower()}-{self.entity_description.key}-{self._data[self.entity_description.data_reference].lower()}"
else:
return f"{self._inst.lower()}-{self.entity_description.key}"
@property @property
def unit_of_measurement(self): def state(self) -> Optional[str]:
"""Return the unit the value is expressed in.""" """Return the state."""
if ATTR_UNIT_ATTR in self._type: if self.entity_description.data_attribute:
return self._data[SENSOR_TYPES[self._sensor][ATTR_UNIT_ATTR]] return self._data[self.entity_description.data_attribute]
else:
if ATTR_UNIT in self._type: return "unknown"
return self._type[ATTR_UNIT]
@property @property
def available(self) -> bool: def available(self) -> bool:
@ -457,40 +234,28 @@ class MikrotikControllerSensor(SensorEntity):
return self._ctrl.connected() return self._ctrl.connected()
@property @property
def device_info(self) -> Dict[str, Any]: def device_info(self) -> DeviceInfo:
"""Return a description for device registry.""" """Return a description for device registry."""
if self._type[ATTR_GROUP] == "System": di_domain = self.entity_description.data_reference
self._type[ATTR_GROUP] = self._ctrl.data["resource"]["board-name"] if self.entity_description.ha_group == "System":
self.entity_description.ha_group = self._ctrl.data["resource"]["board-name"]
di_domain = self._ctrl.data["routerboard"]["serial-number"]
info = { info = DeviceInfo(
"connections": { connections={(DOMAIN, f"{di_domain}")},
(DOMAIN, f"{self._ctrl.data['routerboard']['serial-number']}") name=f"{self._inst} {self.entity_description.ha_group}",
}, model=f"{self._ctrl.data['resource']['board-name']}",
"manufacturer": self._ctrl.data["resource"]["platform"], manufacturer=f"{self._ctrl.data['resource']['platform']}",
"model": self._ctrl.data["resource"]["board-name"], sw_version=f"{self._ctrl.data['resource']['version']}",
"name": f"{self._inst} {self._type[ATTR_GROUP]}", configuration_url=f"http://{self._ctrl.config_entry.data[CONF_HOST]}",
"sw_version": self._ctrl.data["resource"]["version"], via_device=(DOMAIN, f"{self._ctrl.data['routerboard']['serial-number']}"),
"configuration_url": f"http://{self._ctrl.config_entry.data[CONF_HOST]}", )
}
if ATTR_GROUP in self._type:
info["identifiers"] = {
(
DOMAIN,
"serial-number",
f"{self._ctrl.data['routerboard']['serial-number']}",
"sensor",
f"{self._inst} {self._type[ATTR_GROUP]}",
)
}
return info return info
async def async_update(self):
"""Synchronize state with controller."""
async def async_added_to_hass(self): async def async_added_to_hass(self):
"""Run when entity about to be added to hass.""" """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.entity_description.name)
# --------------------------- # ---------------------------
@ -502,18 +267,19 @@ class MikrotikControllerTrafficSensor(MikrotikControllerSensor):
def __init__(self, mikrotik_controller, inst, sensor, uid): def __init__(self, mikrotik_controller, inst, sensor, uid):
"""Initialize.""" """Initialize."""
super().__init__(mikrotik_controller, inst, sensor) super().__init__(mikrotik_controller, inst, sensor)
self._uid = uid if uid:
self._data = mikrotik_controller.data[SENSOR_TYPES[sensor][ATTR_PATH]][uid] self._uid = uid
self._data = mikrotik_controller.data[sensor.data_path][uid]
@property @property
def name(self) -> str: 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.entity_description.name}"
@property @property
def unique_id(self) -> str: 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.entity_description.lower()}-{self._data['default-name'].lower()}"
@property @property
def state_class(self) -> str: def state_class(self) -> str:
@ -543,17 +309,17 @@ class MikrotikClientTrafficSensor(MikrotikControllerSensor):
"""Initialize.""" """Initialize."""
super().__init__(mikrotik_controller, inst, sensor) super().__init__(mikrotik_controller, inst, sensor)
self._uid = uid self._uid = uid
self._data = mikrotik_controller.data[SENSOR_TYPES[sensor][ATTR_PATH]][uid] self._data = mikrotik_controller.data[sensor.data_path][uid]
@property @property
def name(self) -> str: 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.entity_description.name}"
@property @property
def unique_id(self) -> str: 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.entity_description.lower()}-{self._data['mac-address'].lower()}"
@property @property
def available(self) -> bool: def available(self) -> bool:
@ -590,57 +356,3 @@ class MikrotikClientTrafficSensor(MikrotikControllerSensor):
attributes[format_attribute(variable)] = self._data[variable] attributes[format_attribute(variable)] = self._data[variable]
return attributes return attributes
# ---------------------------
# MikrotikControllerEnvironmentSensor
# ---------------------------
class MikrotikControllerEnvironmentSensor(MikrotikControllerSensor):
"""Define an Enviroment variable sensor."""
def __init__(self, inst, uid, mikrotik_controller, sid_data):
"""Initialize."""
super().__init__(mikrotik_controller, inst, "")
self._uid = uid
self._sid_data = sid_data
self._data = mikrotik_controller.data[self._sid_data["sid"]][uid]
@property
def name(self) -> str:
"""Return the name."""
return f"{self._inst} {self._data[self._sid_data['sid_ref']]}"
@property
def unique_id(self) -> str:
"""Return a unique id for this entity."""
return f"{self._inst.lower()}-{self._sid_data['sid']}-{self._data[self._sid_data['sid_ref']]}"
@property
def state(self) -> Optional[str]:
"""Return the state."""
return self._data[self._sid_data["sid_val"]]
@property
def icon(self) -> str:
"""Return the icon."""
return "mdi:clipboard-list"
@property
def device_info(self) -> Dict[str, Any]:
"""Return a description for device registry."""
info = {
"identifiers": {
(
DOMAIN,
"serial-number",
f"{self._ctrl.data['routerboard']['serial-number']}",
"sensor",
"Environment",
)
},
"manufacturer": self._ctrl.data["resource"]["platform"],
"model": self._ctrl.data["resource"]["board-name"],
"name": f"{self._inst} Environment",
}
return info

View file

@ -0,0 +1,329 @@
"""Definitions for Mikrotik Router sensor entities."""
from dataclasses import dataclass
from homeassistant.helpers.entity import EntityCategory, DeviceInfo
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorStateClass,
SensorEntityDescription,
)
from homeassistant.const import (
TEMP_CELSIUS,
ELECTRIC_POTENTIAL_VOLT,
POWER_WATT,
PERCENTAGE,
)
@dataclass
class MikrotikSensorEntityDescriptionAdd:
"""Required values when describing secondary sensor attributes."""
ha_group: str
data_path: str
data_attribute: str
data_name: str
data_uid: str
data_reference: str
data_attributes_list: []
@dataclass
class MikrotikSensorEntityDescription(
SensorEntityDescription,
MikrotikSensorEntityDescriptionAdd,
):
"""Class describing mikrotik entities."""
SENSOR_TYPES = {
"system_temperature": MikrotikSensorEntityDescription(
key="system_temperature",
name="Temperature",
icon="mdi:thermometer",
native_unit_of_measurement=TEMP_CELSIUS,
device_class=SensorDeviceClass.TEMPERATURE,
state_class=SensorStateClass.MEASUREMENT,
entity_category=None,
ha_group="System",
data_path="health",
data_attribute="temperature",
data_name="",
data_uid="",
data_reference="",
data_attributes_list=None,
),
"system_voltage": MikrotikSensorEntityDescription(
key="system_voltage",
name="Voltage",
icon="mdi:lightning-bolt",
native_unit_of_measurement=ELECTRIC_POTENTIAL_VOLT,
device_class=SensorDeviceClass.VOLTAGE,
state_class=SensorStateClass.MEASUREMENT,
entity_category=EntityCategory.DIAGNOSTIC,
ha_group="System",
data_path="health",
data_attribute="voltage",
data_name="",
data_uid="",
data_reference="",
data_attributes_list=None,
),
"system_cpu-temperature": MikrotikSensorEntityDescription(
key="system_cpu-temperature",
name="CPU temperature",
icon="mdi:thermometer",
native_unit_of_measurement=TEMP_CELSIUS,
device_class=SensorDeviceClass.TEMPERATURE,
state_class=SensorStateClass.MEASUREMENT,
entity_category=None,
ha_group="System",
data_path="health",
data_attribute="cpu-temperature",
data_name="",
data_uid="",
data_reference="",
data_attributes_list=None,
),
"system_board-temperature1": MikrotikSensorEntityDescription(
key="system_board-temperature1",
name="Board temperature",
icon="mdi:thermometer",
native_unit_of_measurement=TEMP_CELSIUS,
device_class=SensorDeviceClass.TEMPERATURE,
state_class=SensorStateClass.MEASUREMENT,
entity_category=None,
ha_group="System",
data_path="health",
data_attribute="board-temperature1",
data_name="",
data_uid="",
data_reference="",
data_attributes_list=None,
),
"system_power-consumption": MikrotikSensorEntityDescription(
key="system_power-consumption",
name="Power consumption",
icon="mdi:transmission-tower",
native_unit_of_measurement=POWER_WATT,
device_class=SensorDeviceClass.POWER,
state_class=SensorStateClass.MEASUREMENT,
entity_category=None,
ha_group="System",
data_path="health",
data_attribute="power-consumption",
data_name="",
data_uid="",
data_reference="",
data_attributes_list=None,
),
"system_fan1-speed": MikrotikSensorEntityDescription(
key="system_fan1-speed",
name="Fan1 speed",
icon="mdi:fan",
native_unit_of_measurement="RPM",
device_class=None,
state_class=None,
entity_category=None,
ha_group="System",
data_path="health",
data_attribute="fan1-speed",
data_name="",
data_uid="",
data_reference="",
data_attributes_list=None,
),
"system_fan2-speed": MikrotikSensorEntityDescription(
key="system_fan2-speed",
name="Fan2 speed",
icon="mdi:fan",
native_unit_of_measurement="RPM",
device_class=None,
state_class=None,
entity_category=None,
ha_group="System",
data_path="health",
data_attribute="fan2-speed",
data_name="",
data_uid="",
data_reference="",
data_attributes_list=None,
),
"system_uptime": MikrotikSensorEntityDescription(
key="system_uptime",
name="Uptime",
icon=None,
native_unit_of_measurement=None,
device_class=SensorDeviceClass.TIMESTAMP,
state_class=None,
entity_category=EntityCategory.DIAGNOSTIC,
ha_group="System",
data_path="resource",
data_attribute="uptime",
data_name="",
data_uid="",
data_reference="",
data_attributes_list=None,
),
"system_cpu-load": MikrotikSensorEntityDescription(
key="system_cpu-load",
name="CPU load",
icon="mdi:speedometer",
native_unit_of_measurement=PERCENTAGE,
device_class=None,
state_class=None,
entity_category=None,
ha_group="System",
data_path="resource",
data_attribute="cpu-load",
data_name="",
data_uid="",
data_reference="",
data_attributes_list=None,
),
"system_memory-usage": MikrotikSensorEntityDescription(
key="system_memory-usage",
name="Memory usage",
icon="mdi:memory",
native_unit_of_measurement=PERCENTAGE,
device_class=None,
state_class=None,
entity_category=None,
ha_group="System",
data_path="resource",
data_attribute="memory-usage",
data_name="",
data_uid="",
data_reference="",
data_attributes_list=None,
),
"system_hdd-usage": MikrotikSensorEntityDescription(
key="system_hdd-usage",
name="HDD usage",
icon="mdi:harddisk",
native_unit_of_measurement=PERCENTAGE,
device_class=None,
state_class=None,
entity_category=None,
ha_group="System",
data_path="resource",
data_attribute="hdd-usage",
data_name="",
data_uid="",
data_reference="",
data_attributes_list=None,
),
"traffic_tx": MikrotikSensorEntityDescription(
key="traffic_tx",
name="TX",
icon="mdi:upload-network-outline",
native_unit_of_measurement="ps",
device_class=None,
state_class=None,
entity_category=None,
ha_group="",
data_path="interface",
data_attribute="tx-bits-per-second",
data_name="",
data_uid="",
data_reference="",
data_attributes_list=None,
),
"traffic_rx": MikrotikSensorEntityDescription(
key="traffic_rx",
name="RX",
icon="mdi:download-network-outline",
native_unit_of_measurement="ps",
device_class=None,
state_class=None,
entity_category=None,
ha_group="",
data_path="interface",
data_attribute="rx-bits-per-second",
data_name="",
data_uid="",
data_reference="",
data_attributes_list=None,
),
"client_traffic_lan_tx": MikrotikSensorEntityDescription(
key="client_traffic_lan_tx",
name="LAN TX",
icon="mdi:upload-network",
native_unit_of_measurement="tx-rx-attr",
device_class=None,
state_class=None,
entity_category=None,
ha_group="",
data_path="client_traffic",
data_attribute="lan-tx",
data_name="",
data_uid="",
data_reference="",
data_attributes_list=None,
),
"client_traffic_lan_rx": MikrotikSensorEntityDescription(
key="client_traffic_lan_rx",
name="LAN RX",
icon="mdi:download-network",
native_unit_of_measurement="tx-rx-attr",
device_class=None,
state_class=None,
entity_category=None,
ha_group="",
data_path="client_traffic",
data_attribute="lan-rx",
data_name="",
data_uid="",
data_reference="",
data_attributes_list=None,
),
"client_traffic_wan_tx": MikrotikSensorEntityDescription(
key="client_traffic_wan_tx",
name="WAN TX",
icon="mdi:upload-network",
native_unit_of_measurement="tx-rx-attr",
device_class=None,
state_class=None,
entity_category=None,
ha_group="",
data_path="client_traffic",
data_attribute="wan-tx",
data_name="",
data_uid="",
data_reference="",
data_attributes_list=None,
),
"client_traffic_wan_rx": MikrotikSensorEntityDescription(
key="client_traffic_wan_rx",
name="WAN RX",
icon="mdi:download-network",
native_unit_of_measurement="tx-rx-attr",
device_class=None,
state_class=None,
entity_category=None,
ha_group="",
data_path="client_traffic",
data_attribute="wan-rx",
data_name="",
data_uid="",
data_reference="",
data_attributes_list=None,
),
"environment": MikrotikSensorEntityDescription(
key="environment",
name="",
icon="mdi:clipboard-list",
native_unit_of_measurement="",
device_class=None,
state_class=None,
entity_category=None,
ha_group="Environment",
data_path="environment",
data_attribute="value",
data_name="name",
data_uid="name",
data_reference="name",
data_attributes_list=None,
),
}
DEVICE_ATTRIBUTES_CLIENT_TRAFFIC = ["address", "mac-address", "host-name"]