mirror of
https://github.com/tomaae/homeassistant-mikrotik_router.git
synced 2025-08-19 08:48:50 +02:00
Merge pull request #15 from Limych/master
Fix some minor errors and add russian translation.
This commit is contained in:
commit
0107c6f961
10 changed files with 613 additions and 542 deletions
41
custom_components/mikrotik_router/.translations/ru.json
Normal file
41
custom_components/mikrotik_router/.translations/ru.json
Normal file
|
@ -0,0 +1,41 @@
|
||||||
|
{
|
||||||
|
"config": {
|
||||||
|
"title": "Роутер Mikrotik",
|
||||||
|
"step": {
|
||||||
|
"user": {
|
||||||
|
"title": "Роутер Mikrotik",
|
||||||
|
"description": "Настройка интеграции роутера Mikrotik.",
|
||||||
|
"data": {
|
||||||
|
"name": "Название интеграции",
|
||||||
|
"host": "Хост",
|
||||||
|
"port": "Порт",
|
||||||
|
"username": "Имя пользователя",
|
||||||
|
"password": "Пароль",
|
||||||
|
"ssl": "Использовать SSL",
|
||||||
|
"unit_of_measurement": "Единицы измерения"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"error": {
|
||||||
|
"name_exists": "Имя уже используется.",
|
||||||
|
"cannot_connect": "Нет связи с Mikrotik.",
|
||||||
|
"ssl_handshake_failure": "Ошибка SSL-соединения",
|
||||||
|
"connection_timeout": "Таймаут подключения к Mikrotik.",
|
||||||
|
"wrong_login": "Неверные имя пользователя или пароль."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"step": {
|
||||||
|
"init": {
|
||||||
|
"data": {}
|
||||||
|
},
|
||||||
|
"device_tracker": {
|
||||||
|
"data": {
|
||||||
|
"scan_interval": "Период сканирования (требуется перезагрузка HA)",
|
||||||
|
"track_arp": "Показывать в интерфейсе MAC и IP клиентов",
|
||||||
|
"unit_of_measurement": "Единицы измерения"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,7 +1,7 @@
|
||||||
"""Mikrotik Router integration."""
|
"""Mikrotik Router integration."""
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
from homeassistant.exceptions import ConfigEntryNotReady
|
|
||||||
from homeassistant.const import (
|
from homeassistant.const import (
|
||||||
CONF_NAME,
|
CONF_NAME,
|
||||||
CONF_HOST,
|
CONF_HOST,
|
||||||
|
@ -11,14 +11,14 @@ from homeassistant.const import (
|
||||||
CONF_PASSWORD,
|
CONF_PASSWORD,
|
||||||
CONF_SSL,
|
CONF_SSL,
|
||||||
)
|
)
|
||||||
|
from homeassistant.exceptions import ConfigEntryNotReady
|
||||||
from .mikrotik_controller import MikrotikControllerData
|
|
||||||
|
|
||||||
from .const import (
|
from .const import (
|
||||||
DOMAIN,
|
DOMAIN,
|
||||||
DATA_CLIENT,
|
DATA_CLIENT,
|
||||||
DEFAULT_TRAFFIC_TYPE,
|
DEFAULT_TRAFFIC_TYPE,
|
||||||
)
|
)
|
||||||
|
from .mikrotik_controller import MikrotikControllerData
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
@ -50,7 +50,8 @@ async def async_setup_entry(hass, config_entry):
|
||||||
traffic_type = DEFAULT_TRAFFIC_TYPE
|
traffic_type = DEFAULT_TRAFFIC_TYPE
|
||||||
|
|
||||||
mikrotik_controller = MikrotikControllerData(
|
mikrotik_controller = MikrotikControllerData(
|
||||||
hass, config_entry, name, host, port, username, password, use_ssl, traffic_type
|
hass, config_entry, name, host, port, username, password, use_ssl,
|
||||||
|
traffic_type
|
||||||
)
|
)
|
||||||
await mikrotik_controller.hwinfo_update()
|
await mikrotik_controller.hwinfo_update()
|
||||||
await mikrotik_controller.async_update()
|
await mikrotik_controller.async_update()
|
||||||
|
@ -65,11 +66,13 @@ async def async_setup_entry(hass, config_entry):
|
||||||
)
|
)
|
||||||
|
|
||||||
hass.async_create_task(
|
hass.async_create_task(
|
||||||
hass.config_entries.async_forward_entry_setup(config_entry, "binary_sensor")
|
hass.config_entries.async_forward_entry_setup(config_entry,
|
||||||
|
"binary_sensor")
|
||||||
)
|
)
|
||||||
|
|
||||||
hass.async_create_task(
|
hass.async_create_task(
|
||||||
hass.config_entries.async_forward_entry_setup(config_entry, "device_tracker")
|
hass.config_entries.async_forward_entry_setup(config_entry,
|
||||||
|
"device_tracker")
|
||||||
)
|
)
|
||||||
|
|
||||||
hass.async_create_task(
|
hass.async_create_task(
|
||||||
|
@ -95,8 +98,10 @@ async def async_unload_entry(hass, config_entry):
|
||||||
"""Unload a config entry."""
|
"""Unload a config entry."""
|
||||||
mikrotik_controller = hass.data[DOMAIN][DATA_CLIENT][config_entry.entry_id]
|
mikrotik_controller = hass.data[DOMAIN][DATA_CLIENT][config_entry.entry_id]
|
||||||
await hass.config_entries.async_forward_entry_unload(config_entry, "sensor")
|
await hass.config_entries.async_forward_entry_unload(config_entry, "sensor")
|
||||||
await hass.config_entries.async_forward_entry_unload(config_entry, "binary_sensor")
|
await hass.config_entries.async_forward_entry_unload(config_entry,
|
||||||
await hass.config_entries.async_forward_entry_unload(config_entry, "device_tracker")
|
"binary_sensor")
|
||||||
|
await hass.config_entries.async_forward_entry_unload(config_entry,
|
||||||
|
"device_tracker")
|
||||||
await hass.config_entries.async_forward_entry_unload(config_entry, "switch")
|
await hass.config_entries.async_forward_entry_unload(config_entry, "switch")
|
||||||
await mikrotik_controller.async_reset()
|
await mikrotik_controller.async_reset()
|
||||||
hass.data[DOMAIN][DATA_CLIENT].pop(config_entry.entry_id)
|
hass.data[DOMAIN][DATA_CLIENT].pop(config_entry.entry_id)
|
||||||
|
|
|
@ -1,13 +1,14 @@
|
||||||
"""Support for the Mikrotik Router binary sensor service."""
|
"""Support for the Mikrotik Router binary sensor service."""
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
from homeassistant.core import callback
|
|
||||||
from homeassistant.components.binary_sensor import BinarySensorDevice
|
from homeassistant.components.binary_sensor import BinarySensorDevice
|
||||||
from homeassistant.helpers.dispatcher import async_dispatcher_connect
|
|
||||||
from homeassistant.const import (
|
from homeassistant.const import (
|
||||||
CONF_NAME,
|
CONF_NAME,
|
||||||
ATTR_ATTRIBUTION,
|
ATTR_ATTRIBUTION,
|
||||||
)
|
)
|
||||||
|
from homeassistant.core import callback
|
||||||
|
from homeassistant.helpers.dispatcher import async_dispatcher_connect
|
||||||
|
|
||||||
from .const import (
|
from .const import (
|
||||||
DOMAIN,
|
DOMAIN,
|
||||||
|
|
|
@ -1,8 +1,8 @@
|
||||||
"""Config flow to configure Mikrotik Router."""
|
"""Config flow to configure Mikrotik Router."""
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
import voluptuous as vol
|
import voluptuous as vol
|
||||||
from homeassistant.core import callback
|
|
||||||
from homeassistant.config_entries import (
|
from homeassistant.config_entries import (
|
||||||
CONN_CLASS_LOCAL_POLL,
|
CONN_CLASS_LOCAL_POLL,
|
||||||
ConfigFlow,
|
ConfigFlow,
|
||||||
|
@ -17,6 +17,7 @@ from homeassistant.const import (
|
||||||
CONF_PASSWORD,
|
CONF_PASSWORD,
|
||||||
CONF_SSL,
|
CONF_SSL,
|
||||||
)
|
)
|
||||||
|
from homeassistant.core import callback
|
||||||
|
|
||||||
from .const import (
|
from .const import (
|
||||||
DOMAIN,
|
DOMAIN,
|
||||||
|
@ -27,11 +28,11 @@ from .const import (
|
||||||
DEFAULT_TRAFFIC_TYPE,
|
DEFAULT_TRAFFIC_TYPE,
|
||||||
TRAFFIC_TYPES,
|
TRAFFIC_TYPES,
|
||||||
)
|
)
|
||||||
|
|
||||||
from .mikrotikapi import MikrotikAPI
|
from .mikrotikapi import MikrotikAPI
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------
|
# ---------------------------
|
||||||
# configured_instances
|
# configured_instances
|
||||||
# ---------------------------
|
# ---------------------------
|
||||||
|
@ -39,7 +40,8 @@ _LOGGER = logging.getLogger(__name__)
|
||||||
def configured_instances(hass):
|
def configured_instances(hass):
|
||||||
"""Return a set of configured instances."""
|
"""Return a set of configured instances."""
|
||||||
return set(
|
return set(
|
||||||
entry.data[CONF_NAME] for entry in hass.config_entries.async_entries(DOMAIN)
|
entry.data[CONF_NAME] for entry in
|
||||||
|
hass.config_entries.async_entries(DOMAIN)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -1,15 +1,17 @@
|
||||||
"""Support for the Mikrotik Router device tracker."""
|
"""Support for the Mikrotik Router device tracker."""
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
from homeassistant.core import callback
|
|
||||||
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC
|
|
||||||
from homeassistant.helpers.dispatcher import async_dispatcher_connect
|
|
||||||
from homeassistant.components.device_tracker.config_entry import ScannerEntity
|
from homeassistant.components.device_tracker.config_entry import ScannerEntity
|
||||||
from homeassistant.components.device_tracker.const import SOURCE_TYPE_ROUTER
|
from homeassistant.components.device_tracker.const import SOURCE_TYPE_ROUTER
|
||||||
from homeassistant.const import (
|
from homeassistant.const import (
|
||||||
CONF_NAME,
|
CONF_NAME,
|
||||||
ATTR_ATTRIBUTION,
|
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 .const import (
|
from .const import (
|
||||||
DOMAIN,
|
DOMAIN,
|
||||||
DATA_CLIENT,
|
DATA_CLIENT,
|
||||||
|
@ -172,7 +174,8 @@ class MikrotikControllerPortDeviceTracker(ScannerEntity):
|
||||||
def device_info(self):
|
def device_info(self):
|
||||||
"""Return a port description for device registry."""
|
"""Return a port 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"],
|
||||||
"model": self._ctrl.data["resource"]["board-name"],
|
"model": self._ctrl.data["resource"]["board-name"],
|
||||||
"name": self._data["default-name"],
|
"name": self._data["default-name"],
|
||||||
|
|
|
@ -2,13 +2,15 @@
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
|
from voluptuous import Optional
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------
|
# ---------------------------
|
||||||
# from_entry
|
# from_entry
|
||||||
# ---------------------------
|
# ---------------------------
|
||||||
def from_entry(entry, param, default="") -> dict:
|
def from_entry(entry, param, default="") -> str:
|
||||||
"""Validate and return str value from Mikrotik API dict"""
|
"""Validate and return str value from Mikrotik API dict"""
|
||||||
if param not in entry:
|
if param not in entry:
|
||||||
return default
|
return default
|
||||||
|
@ -88,7 +90,7 @@ def parse_api(
|
||||||
# ---------------------------
|
# ---------------------------
|
||||||
# get_uid
|
# get_uid
|
||||||
# ---------------------------
|
# ---------------------------
|
||||||
def get_uid(entry, key, key_search, keymap) -> str:
|
def get_uid(entry, key, key_search, keymap) -> Optional(str):
|
||||||
"""Get UID for data list"""
|
"""Get UID for data list"""
|
||||||
uid = None
|
uid = None
|
||||||
if not key_search:
|
if not key_search:
|
||||||
|
@ -111,7 +113,7 @@ def get_uid(entry, key, key_search, keymap) -> str:
|
||||||
# ---------------------------
|
# ---------------------------
|
||||||
# generate_keymap
|
# generate_keymap
|
||||||
# ---------------------------
|
# ---------------------------
|
||||||
def generate_keymap(data, key_search) -> dict:
|
def generate_keymap(data, key_search) -> Optional(dict):
|
||||||
"""Generate keymap"""
|
"""Generate keymap"""
|
||||||
if not key_search:
|
if not key_search:
|
||||||
return None
|
return None
|
||||||
|
@ -263,7 +265,8 @@ def fill_vals_proc(data, uid, vals_proc) -> dict:
|
||||||
|
|
||||||
if _action == "combine":
|
if _action == "combine":
|
||||||
if "key" in val:
|
if "key" in val:
|
||||||
tmp = _data[val["key"]] if val["key"] in _data else "unknown"
|
tmp = _data[val["key"]]\
|
||||||
|
if val["key"] in _data else "unknown"
|
||||||
if not _value:
|
if not _value:
|
||||||
_value = tmp
|
_value = tmp
|
||||||
else:
|
else:
|
||||||
|
|
|
@ -1,8 +1,10 @@
|
||||||
"""Mikrotik Controller for Mikrotik Router."""
|
"""Mikrotik Controller for Mikrotik Router."""
|
||||||
|
|
||||||
from datetime import timedelta
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import logging
|
import logging
|
||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
|
from homeassistant.core import callback
|
||||||
from homeassistant.helpers.dispatcher import async_dispatcher_send
|
from homeassistant.helpers.dispatcher import async_dispatcher_send
|
||||||
from homeassistant.helpers.event import async_track_time_interval
|
from homeassistant.helpers.event import async_track_time_interval
|
||||||
|
|
||||||
|
@ -15,10 +17,9 @@ from .const import (
|
||||||
DEFAULT_SCAN_INTERVAL,
|
DEFAULT_SCAN_INTERVAL,
|
||||||
DEFAULT_TRAFFIC_TYPE,
|
DEFAULT_TRAFFIC_TYPE,
|
||||||
)
|
)
|
||||||
|
|
||||||
from .mikrotikapi import MikrotikAPI
|
|
||||||
from .helper import from_entry, parse_api
|
|
||||||
from .exceptions import ApiEntryNotFound
|
from .exceptions import ApiEntryNotFound
|
||||||
|
from .helper import from_entry, parse_api
|
||||||
|
from .mikrotikapi import MikrotikAPI
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
@ -72,6 +73,7 @@ class MikrotikControllerData:
|
||||||
# ---------------------------
|
# ---------------------------
|
||||||
# force_update
|
# force_update
|
||||||
# ---------------------------
|
# ---------------------------
|
||||||
|
@callback
|
||||||
async def force_update(self, _now=None):
|
async def force_update(self, _now=None):
|
||||||
"""Trigger update by timer"""
|
"""Trigger update by timer"""
|
||||||
await self.async_update()
|
await self.async_update()
|
||||||
|
@ -79,6 +81,7 @@ class MikrotikControllerData:
|
||||||
# ---------------------------
|
# ---------------------------
|
||||||
# force_fwupdate_check
|
# force_fwupdate_check
|
||||||
# ---------------------------
|
# ---------------------------
|
||||||
|
@callback
|
||||||
async def force_fwupdate_check(self, _now=None):
|
async def force_fwupdate_check(self, _now=None):
|
||||||
"""Trigger hourly update by timer"""
|
"""Trigger hourly update by timer"""
|
||||||
await self.async_fwupdate_check()
|
await self.async_fwupdate_check()
|
||||||
|
@ -273,8 +276,10 @@ class MikrotikControllerData:
|
||||||
traffic_div = 1
|
traffic_div = 1
|
||||||
|
|
||||||
for uid in self.data["interface"]:
|
for uid in self.data["interface"]:
|
||||||
self.data["interface"][uid]["rx-bits-per-second-attr"] = traffic_type
|
self.data["interface"][uid][
|
||||||
self.data["interface"][uid]["tx-bits-per-second-attr"] = traffic_type
|
"rx-bits-per-second-attr"] = traffic_type
|
||||||
|
self.data["interface"][uid][
|
||||||
|
"tx-bits-per-second-attr"] = traffic_type
|
||||||
self.data["interface"][uid]["rx-bits-per-second"] = round(
|
self.data["interface"][uid]["rx-bits-per-second"] = round(
|
||||||
self.data["interface"][uid]["rx-bits-per-second"] * traffic_div
|
self.data["interface"][uid]["rx-bits-per-second"] * traffic_div
|
||||||
)
|
)
|
||||||
|
@ -398,7 +403,8 @@ class MikrotikControllerData:
|
||||||
self.data["arp"][uid]["mac-address"] = "multiple"
|
self.data["arp"][uid]["mac-address"] = "multiple"
|
||||||
self.data["arp"][uid]["address"] = "multiple"
|
self.data["arp"][uid]["address"] = "multiple"
|
||||||
else:
|
else:
|
||||||
self.data["arp"][uid]["mac-address"] = from_entry(entry, "mac-address")
|
self.data["arp"][uid]["mac-address"] = from_entry(entry,
|
||||||
|
"mac-address")
|
||||||
self.data["arp"][uid]["address"] = (
|
self.data["arp"][uid]["address"] = (
|
||||||
mac2ip[self.data["arp"][uid]["mac-address"]]
|
mac2ip[self.data["arp"][uid]["mac-address"]]
|
||||||
if self.data["arp"][uid]["mac-address"] in mac2ip
|
if self.data["arp"][uid]["mac-address"] in mac2ip
|
||||||
|
@ -537,8 +543,8 @@ class MikrotikControllerData:
|
||||||
|
|
||||||
if "status" in self.data["fw-update"]:
|
if "status" in self.data["fw-update"]:
|
||||||
self.data["fw-update"]["available"] = (
|
self.data["fw-update"]["available"] = (
|
||||||
True
|
True if self.data["fw-update"][
|
||||||
if self.data["fw-update"]["status"] == "New version is available"
|
"status"] == "New version is available"
|
||||||
else False
|
else False
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
|
|
|
@ -1,19 +1,23 @@
|
||||||
"""Mikrotik API for Mikrotik Router."""
|
"""Mikrotik API for Mikrotik Router."""
|
||||||
|
|
||||||
import ssl
|
import importlib
|
||||||
import logging
|
import logging
|
||||||
|
import os
|
||||||
|
import ssl
|
||||||
|
import sys
|
||||||
import time
|
import time
|
||||||
from threading import Lock
|
from threading import Lock
|
||||||
from .exceptions import ApiEntryNotFound
|
|
||||||
|
from voluptuous import Optional
|
||||||
|
|
||||||
from .const import (
|
from .const import (
|
||||||
DEFAULT_LOGIN_METHOD,
|
DEFAULT_LOGIN_METHOD,
|
||||||
DEFAULT_ENCODING,
|
DEFAULT_ENCODING,
|
||||||
)
|
)
|
||||||
|
from .exceptions import ApiEntryNotFound
|
||||||
|
|
||||||
import os
|
MODULE_PATH = os.path.join(os.path.dirname(__file__), "librouteros_custom",
|
||||||
import sys
|
"__init__.py")
|
||||||
import importlib
|
|
||||||
MODULE_PATH = os.path.join(os.path.dirname(__file__), "librouteros_custom", "__init__.py")
|
|
||||||
MODULE_NAME = "librouteros_custom"
|
MODULE_NAME = "librouteros_custom"
|
||||||
spec = importlib.util.spec_from_file_location(MODULE_NAME, MODULE_PATH)
|
spec = importlib.util.spec_from_file_location(MODULE_NAME, MODULE_PATH)
|
||||||
librouteros_custom = importlib.util.module_from_spec(spec)
|
librouteros_custom = importlib.util.module_from_spec(spec)
|
||||||
|
@ -64,7 +68,7 @@ class MikrotikAPI:
|
||||||
# ---------------------------
|
# ---------------------------
|
||||||
# disconnect
|
# disconnect
|
||||||
# ---------------------------
|
# ---------------------------
|
||||||
def disconnect(self) -> bool:
|
def disconnect(self):
|
||||||
"""Disconnect from Mikrotik device."""
|
"""Disconnect from Mikrotik device."""
|
||||||
self._connected = False
|
self._connected = False
|
||||||
self._connection = None
|
self._connection = None
|
||||||
|
@ -109,7 +113,8 @@ class MikrotikAPI:
|
||||||
) as api_error:
|
) as api_error:
|
||||||
if not self.connection_error_reported:
|
if not self.connection_error_reported:
|
||||||
_LOGGER.error(
|
_LOGGER.error(
|
||||||
"Mikrotik %s error while connecting: %s", self._host, api_error
|
"Mikrotik %s error while connecting: %s", self._host,
|
||||||
|
api_error
|
||||||
)
|
)
|
||||||
self.connection_error_reported = True
|
self.connection_error_reported = True
|
||||||
|
|
||||||
|
@ -120,7 +125,8 @@ class MikrotikAPI:
|
||||||
except:
|
except:
|
||||||
if not self.connection_error_reported:
|
if not self.connection_error_reported:
|
||||||
_LOGGER.error(
|
_LOGGER.error(
|
||||||
"Mikrotik %s error while connecting: %s", self._host, "Unknown"
|
"Mikrotik %s error while connecting: %s", self._host,
|
||||||
|
"Unknown"
|
||||||
)
|
)
|
||||||
self.connection_error_reported = True
|
self.connection_error_reported = True
|
||||||
|
|
||||||
|
@ -161,7 +167,7 @@ class MikrotikAPI:
|
||||||
# ---------------------------
|
# ---------------------------
|
||||||
# path
|
# path
|
||||||
# ---------------------------
|
# ---------------------------
|
||||||
def path(self, path) -> list:
|
def path(self, path) -> Optional(list):
|
||||||
"""Retrieve data from Mikrotik API."""
|
"""Retrieve data from Mikrotik API."""
|
||||||
if not self._connected or not self._connection:
|
if not self._connected or not self._connection:
|
||||||
if self._connection_epoch > time.time() - self._connection_retry_sec:
|
if self._connection_epoch > time.time() - self._connection_retry_sec:
|
||||||
|
@ -193,7 +199,8 @@ class MikrotikAPI:
|
||||||
ValueError,
|
ValueError,
|
||||||
) as api_error:
|
) as api_error:
|
||||||
if not self.connection_error_reported:
|
if not self.connection_error_reported:
|
||||||
_LOGGER.error("Mikrotik %s error while path %s", self._host, api_error)
|
_LOGGER.error("Mikrotik %s error while path %s", self._host,
|
||||||
|
api_error)
|
||||||
self.connection_error_reported = True
|
self.connection_error_reported = True
|
||||||
|
|
||||||
self.disconnect()
|
self.disconnect()
|
||||||
|
@ -201,7 +208,8 @@ class MikrotikAPI:
|
||||||
return None
|
return None
|
||||||
except:
|
except:
|
||||||
if not self.connection_error_reported:
|
if not self.connection_error_reported:
|
||||||
_LOGGER.error("Mikrotik %s error while path %s", self._host, "unknown")
|
_LOGGER.error("Mikrotik %s error while path %s", self._host,
|
||||||
|
"unknown")
|
||||||
self.connection_error_reported = True
|
self.connection_error_reported = True
|
||||||
|
|
||||||
self.disconnect()
|
self.disconnect()
|
||||||
|
@ -212,7 +220,8 @@ class MikrotikAPI:
|
||||||
tuple(response)
|
tuple(response)
|
||||||
except librouteros_custom.exceptions.ConnectionClosed as api_error:
|
except librouteros_custom.exceptions.ConnectionClosed as api_error:
|
||||||
if not self.connection_error_reported:
|
if not self.connection_error_reported:
|
||||||
_LOGGER.error("Mikrotik %s error while path %s", self._host, api_error)
|
_LOGGER.error("Mikrotik %s error while path %s", self._host,
|
||||||
|
api_error)
|
||||||
self.connection_error_reported = True
|
self.connection_error_reported = True
|
||||||
|
|
||||||
self.disconnect()
|
self.disconnect()
|
||||||
|
@ -220,7 +229,8 @@ class MikrotikAPI:
|
||||||
return None
|
return None
|
||||||
except:
|
except:
|
||||||
if not self.connection_error_reported:
|
if not self.connection_error_reported:
|
||||||
_LOGGER.error("Mikrotik %s error while path %s", self._host, "unknown")
|
_LOGGER.error("Mikrotik %s error while path %s", self._host,
|
||||||
|
"unknown")
|
||||||
self.connection_error_reported = True
|
self.connection_error_reported = True
|
||||||
|
|
||||||
self.disconnect()
|
self.disconnect()
|
||||||
|
@ -238,7 +248,7 @@ class MikrotikAPI:
|
||||||
entry_found = False
|
entry_found = False
|
||||||
if not self._connected or not self._connection:
|
if not self._connected or not self._connection:
|
||||||
if self._connection_epoch > time.time() - self._connection_retry_sec:
|
if self._connection_epoch > time.time() - self._connection_retry_sec:
|
||||||
return None
|
return False
|
||||||
|
|
||||||
if not self.connect():
|
if not self.connect():
|
||||||
return False
|
return False
|
||||||
|
@ -280,7 +290,8 @@ class MikrotikAPI:
|
||||||
) as api_error:
|
) as api_error:
|
||||||
if not self.connection_error_reported:
|
if not self.connection_error_reported:
|
||||||
_LOGGER.error(
|
_LOGGER.error(
|
||||||
"Mikrotik %s error while update %s", self._host, api_error
|
"Mikrotik %s error while update %s", self._host,
|
||||||
|
api_error
|
||||||
)
|
)
|
||||||
self.connection_error_reported = True
|
self.connection_error_reported = True
|
||||||
|
|
||||||
|
@ -290,7 +301,8 @@ class MikrotikAPI:
|
||||||
except:
|
except:
|
||||||
if not self.connection_error_reported:
|
if not self.connection_error_reported:
|
||||||
_LOGGER.error(
|
_LOGGER.error(
|
||||||
"Mikrotik %s error while update %s", self._host, "unknown"
|
"Mikrotik %s error while update %s", self._host,
|
||||||
|
"unknown"
|
||||||
)
|
)
|
||||||
self.connection_error_reported = True
|
self.connection_error_reported = True
|
||||||
|
|
||||||
|
@ -313,7 +325,7 @@ class MikrotikAPI:
|
||||||
entry_found = False
|
entry_found = False
|
||||||
if not self._connected or not self._connection:
|
if not self._connected or not self._connection:
|
||||||
if self._connection_epoch > time.time() - self._connection_retry_sec:
|
if self._connection_epoch > time.time() - self._connection_retry_sec:
|
||||||
return None
|
return False
|
||||||
|
|
||||||
if not self.connect():
|
if not self.connect():
|
||||||
return False
|
return False
|
||||||
|
@ -354,7 +366,8 @@ class MikrotikAPI:
|
||||||
) as api_error:
|
) as api_error:
|
||||||
if not self.connection_error_reported:
|
if not self.connection_error_reported:
|
||||||
_LOGGER.error(
|
_LOGGER.error(
|
||||||
"Mikrotik %s error while run_script %s", self._host, api_error
|
"Mikrotik %s error while run_script %s", self._host,
|
||||||
|
api_error
|
||||||
)
|
)
|
||||||
self.connection_error_reported = True
|
self.connection_error_reported = True
|
||||||
|
|
||||||
|
@ -364,7 +377,8 @@ class MikrotikAPI:
|
||||||
except:
|
except:
|
||||||
if not self.connection_error_reported:
|
if not self.connection_error_reported:
|
||||||
_LOGGER.error(
|
_LOGGER.error(
|
||||||
"Mikrotik %s error while run_script %s", self._host, "unknown"
|
"Mikrotik %s error while run_script %s", self._host,
|
||||||
|
"unknown"
|
||||||
)
|
)
|
||||||
self.connection_error_reported = True
|
self.connection_error_reported = True
|
||||||
|
|
||||||
|
@ -382,7 +396,7 @@ class MikrotikAPI:
|
||||||
# ---------------------------
|
# ---------------------------
|
||||||
# get_traffic
|
# get_traffic
|
||||||
# ---------------------------
|
# ---------------------------
|
||||||
def get_traffic(self, interfaces) -> list:
|
def get_traffic(self, interfaces) -> Optional(list):
|
||||||
"""Get traffic stats"""
|
"""Get traffic stats"""
|
||||||
traffic = None
|
traffic = None
|
||||||
if not self._connected or not self._connection:
|
if not self._connected or not self._connection:
|
||||||
|
@ -423,7 +437,8 @@ class MikrotikAPI:
|
||||||
) as api_error:
|
) as api_error:
|
||||||
if not self.connection_error_reported:
|
if not self.connection_error_reported:
|
||||||
_LOGGER.error(
|
_LOGGER.error(
|
||||||
"Mikrotik %s error while get_traffic %s", self._host, api_error
|
"Mikrotik %s error while get_traffic %s", self._host,
|
||||||
|
api_error
|
||||||
)
|
)
|
||||||
self.connection_error_reported = True
|
self.connection_error_reported = True
|
||||||
|
|
||||||
|
@ -433,7 +448,8 @@ class MikrotikAPI:
|
||||||
except:
|
except:
|
||||||
if not self.connection_error_reported:
|
if not self.connection_error_reported:
|
||||||
_LOGGER.error(
|
_LOGGER.error(
|
||||||
"Mikrotik %s error while get_traffic %s", self._host, "unknown"
|
"Mikrotik %s error while get_traffic %s", self._host,
|
||||||
|
"unknown"
|
||||||
)
|
)
|
||||||
self.connection_error_reported = True
|
self.connection_error_reported = True
|
||||||
|
|
||||||
|
@ -446,7 +462,8 @@ class MikrotikAPI:
|
||||||
except librouteros_custom.exceptions.ConnectionClosed as api_error:
|
except librouteros_custom.exceptions.ConnectionClosed as api_error:
|
||||||
if not self.connection_error_reported:
|
if not self.connection_error_reported:
|
||||||
_LOGGER.error(
|
_LOGGER.error(
|
||||||
"Mikrotik %s error while get_traffic %s", self._host, api_error
|
"Mikrotik %s error while get_traffic %s", self._host,
|
||||||
|
api_error
|
||||||
)
|
)
|
||||||
self.connection_error_reported = True
|
self.connection_error_reported = True
|
||||||
|
|
||||||
|
@ -456,7 +473,8 @@ class MikrotikAPI:
|
||||||
except:
|
except:
|
||||||
if not self.connection_error_reported:
|
if not self.connection_error_reported:
|
||||||
_LOGGER.error(
|
_LOGGER.error(
|
||||||
"Mikrotik %s error while get_traffic %s", self._host, "unknown"
|
"Mikrotik %s error while get_traffic %s", self._host,
|
||||||
|
"unknown"
|
||||||
)
|
)
|
||||||
self.connection_error_reported = True
|
self.connection_error_reported = True
|
||||||
|
|
||||||
|
|
|
@ -1,21 +1,14 @@
|
||||||
"""Support for the Mikrotik Router sensor service."""
|
"""Support for the Mikrotik Router sensor service."""
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
|
from homeassistant.const import (CONF_NAME, ATTR_ATTRIBUTION, ATTR_DEVICE_CLASS)
|
||||||
from homeassistant.core import callback
|
from homeassistant.core import callback
|
||||||
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 homeassistant.helpers.entity import Entity
|
from homeassistant.helpers.entity import Entity
|
||||||
from homeassistant.const import (
|
|
||||||
CONF_NAME,
|
|
||||||
ATTR_ATTRIBUTION,
|
|
||||||
ATTR_DEVICE_CLASS,
|
|
||||||
)
|
|
||||||
|
|
||||||
from .const import (
|
from .const import (DOMAIN, DATA_CLIENT, ATTRIBUTION)
|
||||||
DOMAIN,
|
|
||||||
DATA_CLIENT,
|
|
||||||
ATTRIBUTION,
|
|
||||||
)
|
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
@ -116,13 +109,15 @@ def update_items(inst, mikrotik_controller, async_add_entities, sensors):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
sensors[item_id] = MikrotikControllerSensor(
|
sensors[item_id] = MikrotikControllerSensor(
|
||||||
mikrotik_controller=mikrotik_controller, inst=inst, sensor=sensor
|
mikrotik_controller=mikrotik_controller, inst=inst,
|
||||||
|
sensor=sensor
|
||||||
)
|
)
|
||||||
new_sensors.append(sensors[item_id])
|
new_sensors.append(sensors[item_id])
|
||||||
|
|
||||||
if "traffic_" in sensor:
|
if "traffic_" in sensor:
|
||||||
for uid in mikrotik_controller.data["interface"]:
|
for uid in mikrotik_controller.data["interface"]:
|
||||||
if mikrotik_controller.data["interface"][uid]["type"] == "ether":
|
if mikrotik_controller.data["interface"][uid][
|
||||||
|
"type"] == "ether":
|
||||||
item_id = f"{inst}-{sensor}-{mikrotik_controller.data['interface'][uid]['default-name']}"
|
item_id = f"{inst}-{sensor}-{mikrotik_controller.data['interface'][uid]['default-name']}"
|
||||||
if item_id in sensors:
|
if item_id in sensors:
|
||||||
if sensors[item_id].enabled:
|
if sensors[item_id].enabled:
|
||||||
|
@ -248,7 +243,8 @@ class MikrotikControllerTrafficSensor(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_TYPES[sensor][ATTR_PATH]][
|
||||||
|
uid]
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def name(self):
|
def name(self):
|
||||||
|
@ -264,7 +260,8 @@ class MikrotikControllerTrafficSensor(MikrotikControllerSensor):
|
||||||
def device_info(self):
|
def device_info(self):
|
||||||
"""Return a port description for device registry."""
|
"""Return a port 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"],
|
||||||
"model": self._ctrl.data["resource"]["board-name"],
|
"model": self._ctrl.data["resource"]["board-name"],
|
||||||
"name": self._data["default-name"],
|
"name": self._data["default-name"],
|
||||||
|
|
|
@ -2,20 +2,13 @@
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
from homeassistant.components.switch import SwitchDevice
|
from homeassistant.components.switch import SwitchDevice
|
||||||
|
from homeassistant.const import (CONF_NAME, ATTR_ATTRIBUTION)
|
||||||
from homeassistant.core import callback
|
from homeassistant.core import callback
|
||||||
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 homeassistant.helpers.restore_state import RestoreEntity
|
from homeassistant.helpers.restore_state import RestoreEntity
|
||||||
|
|
||||||
from homeassistant.const import (
|
from .const import (DOMAIN, DATA_CLIENT, ATTRIBUTION)
|
||||||
CONF_NAME,
|
|
||||||
ATTR_ATTRIBUTION,
|
|
||||||
)
|
|
||||||
from .const import (
|
|
||||||
DOMAIN,
|
|
||||||
DATA_CLIENT,
|
|
||||||
ATTRIBUTION,
|
|
||||||
)
|
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
@ -192,7 +185,8 @@ class MikrotikControllerPortSwitch(MikrotikControllerSwitch):
|
||||||
def device_info(self):
|
def device_info(self):
|
||||||
"""Return a port description for device registry."""
|
"""Return a port 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"],
|
||||||
"model": self._ctrl.data["resource"]["board-name"],
|
"model": self._ctrl.data["resource"]["board-name"],
|
||||||
"name": self._data["default-name"],
|
"name": self._data["default-name"],
|
||||||
|
@ -362,7 +356,8 @@ class MikrotikControllerScriptSwitch(MikrotikControllerSwitch):
|
||||||
|
|
||||||
async def async_added_to_hass(self):
|
async def async_added_to_hass(self):
|
||||||
"""Script switch entity created."""
|
"""Script switch entity created."""
|
||||||
_LOGGER.debug("New script switch %s (%s)", self._inst, self._data["name"])
|
_LOGGER.debug("New script switch %s (%s)", self._inst,
|
||||||
|
self._data["name"])
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def name(self) -> str:
|
def name(self) -> str:
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue