2019-04-03 15:40:03 +00:00
|
|
|
"""Tracks the latency of a host by sending ICMP echo requests (ping)."""
|
2020-08-18 22:25:50 +00:00
|
|
|
import asyncio
|
2019-12-09 13:29:39 +00:00
|
|
|
from datetime import timedelta
|
2017-04-20 06:15:26 +00:00
|
|
|
import logging
|
2018-10-19 07:29:48 +00:00
|
|
|
import re
|
2017-04-20 06:15:26 +00:00
|
|
|
import sys
|
2020-08-18 22:25:50 +00:00
|
|
|
from typing import Any, Dict
|
2017-04-20 06:15:26 +00:00
|
|
|
|
|
|
|
import voluptuous as vol
|
|
|
|
|
2020-04-23 19:57:07 +00:00
|
|
|
from homeassistant.components.binary_sensor import PLATFORM_SCHEMA, BinarySensorEntity
|
2019-12-09 13:29:39 +00:00
|
|
|
from homeassistant.const import CONF_HOST, CONF_NAME
|
2018-10-02 09:43:34 +00:00
|
|
|
import homeassistant.helpers.config_validation as cv
|
2020-08-05 10:43:35 +00:00
|
|
|
|
|
|
|
from .const import PING_TIMEOUT
|
2017-04-20 06:15:26 +00:00
|
|
|
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
2020-08-05 10:43:35 +00:00
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
ATTR_ROUND_TRIP_TIME_AVG = "round_trip_time_avg"
|
|
|
|
ATTR_ROUND_TRIP_TIME_MAX = "round_trip_time_max"
|
|
|
|
ATTR_ROUND_TRIP_TIME_MDEV = "round_trip_time_mdev"
|
|
|
|
ATTR_ROUND_TRIP_TIME_MIN = "round_trip_time_min"
|
2017-04-20 06:15:26 +00:00
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
CONF_PING_COUNT = "count"
|
2017-04-20 06:15:26 +00:00
|
|
|
|
2020-08-05 10:43:35 +00:00
|
|
|
DEFAULT_NAME = "Ping"
|
2017-04-20 06:15:26 +00:00
|
|
|
DEFAULT_PING_COUNT = 5
|
2019-07-31 19:25:30 +00:00
|
|
|
DEFAULT_DEVICE_CLASS = "connectivity"
|
2017-04-20 06:15:26 +00:00
|
|
|
|
|
|
|
SCAN_INTERVAL = timedelta(minutes=5)
|
|
|
|
|
2020-08-05 10:43:35 +00:00
|
|
|
PARALLEL_UPDATES = 0
|
|
|
|
|
2017-04-20 06:15:26 +00:00
|
|
|
PING_MATCHER = re.compile(
|
2019-07-31 19:25:30 +00:00
|
|
|
r"(?P<min>\d+.\d+)\/(?P<avg>\d+.\d+)\/(?P<max>\d+.\d+)\/(?P<mdev>\d+.\d+)"
|
|
|
|
)
|
2017-04-20 06:15:26 +00:00
|
|
|
|
2017-07-22 17:50:31 +00:00
|
|
|
PING_MATCHER_BUSYBOX = re.compile(
|
2019-07-31 19:25:30 +00:00
|
|
|
r"(?P<min>\d+.\d+)\/(?P<avg>\d+.\d+)\/(?P<max>\d+.\d+)"
|
|
|
|
)
|
2017-07-22 17:50:31 +00:00
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
WIN32_PING_MATCHER = re.compile(r"(?P<min>\d+)ms.+(?P<max>\d+)ms.+(?P<avg>\d+)ms")
|
2017-04-24 21:32:12 +00:00
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
|
|
|
|
{
|
|
|
|
vol.Required(CONF_HOST): cv.string,
|
2020-08-05 10:43:35 +00:00
|
|
|
vol.Optional(CONF_NAME): cv.string,
|
|
|
|
vol.Optional(CONF_PING_COUNT, default=DEFAULT_PING_COUNT): vol.Range(
|
|
|
|
min=1, max=100
|
|
|
|
),
|
2019-07-31 19:25:30 +00:00
|
|
|
}
|
|
|
|
)
|
2017-04-20 06:15:26 +00:00
|
|
|
|
|
|
|
|
2020-08-18 22:25:50 +00:00
|
|
|
def setup_platform(hass, config, add_entities, discovery_info=None) -> None:
|
2017-04-20 06:15:26 +00:00
|
|
|
"""Set up the Ping Binary sensor."""
|
2020-08-05 10:43:35 +00:00
|
|
|
host = config[CONF_HOST]
|
|
|
|
count = config[CONF_PING_COUNT]
|
|
|
|
name = config.get(CONF_NAME, f"{DEFAULT_NAME} {host}")
|
2017-04-20 06:15:26 +00:00
|
|
|
|
2018-10-19 07:29:48 +00:00
|
|
|
add_entities([PingBinarySensor(name, PingData(host, count))], True)
|
2017-04-20 06:15:26 +00:00
|
|
|
|
|
|
|
|
2020-04-23 19:57:07 +00:00
|
|
|
class PingBinarySensor(BinarySensorEntity):
|
2017-04-20 06:15:26 +00:00
|
|
|
"""Representation of a Ping Binary sensor."""
|
|
|
|
|
2020-08-18 22:25:50 +00:00
|
|
|
def __init__(self, name: str, ping) -> None:
|
2017-04-20 06:15:26 +00:00
|
|
|
"""Initialize the Ping Binary sensor."""
|
|
|
|
self._name = name
|
2020-08-18 22:25:50 +00:00
|
|
|
self._ping = ping
|
2017-04-20 06:15:26 +00:00
|
|
|
|
|
|
|
@property
|
2020-08-18 22:25:50 +00:00
|
|
|
def name(self) -> str:
|
2017-04-20 06:15:26 +00:00
|
|
|
"""Return the name of the device."""
|
|
|
|
return self._name
|
|
|
|
|
|
|
|
@property
|
2020-08-18 22:25:50 +00:00
|
|
|
def device_class(self) -> str:
|
2017-04-20 06:15:26 +00:00
|
|
|
"""Return the class of this sensor."""
|
2017-07-29 23:46:27 +00:00
|
|
|
return DEFAULT_DEVICE_CLASS
|
2017-04-20 06:15:26 +00:00
|
|
|
|
|
|
|
@property
|
2020-08-18 22:25:50 +00:00
|
|
|
def is_on(self) -> bool:
|
2017-04-20 06:15:26 +00:00
|
|
|
"""Return true if the binary sensor is on."""
|
2020-08-18 22:25:50 +00:00
|
|
|
return self._ping.available
|
2017-04-20 06:15:26 +00:00
|
|
|
|
|
|
|
@property
|
2020-08-18 22:25:50 +00:00
|
|
|
def device_state_attributes(self) -> Dict[str, Any]:
|
2017-04-20 06:15:26 +00:00
|
|
|
"""Return the state attributes of the ICMP checo request."""
|
2020-08-18 22:25:50 +00:00
|
|
|
if self._ping.data is not False:
|
2017-04-20 06:15:26 +00:00
|
|
|
return {
|
2020-08-18 22:25:50 +00:00
|
|
|
ATTR_ROUND_TRIP_TIME_AVG: self._ping.data["avg"],
|
|
|
|
ATTR_ROUND_TRIP_TIME_MAX: self._ping.data["max"],
|
|
|
|
ATTR_ROUND_TRIP_TIME_MDEV: self._ping.data["mdev"],
|
|
|
|
ATTR_ROUND_TRIP_TIME_MIN: self._ping.data["min"],
|
2017-04-20 06:15:26 +00:00
|
|
|
}
|
|
|
|
|
2020-08-18 22:25:50 +00:00
|
|
|
async def async_update(self) -> None:
|
2017-04-20 06:15:26 +00:00
|
|
|
"""Get the latest data."""
|
2020-08-18 22:25:50 +00:00
|
|
|
await self._ping.async_update()
|
2017-04-20 06:15:26 +00:00
|
|
|
|
|
|
|
|
2018-07-20 08:45:20 +00:00
|
|
|
class PingData:
|
2017-04-20 06:15:26 +00:00
|
|
|
"""The Class for handling the data retrieval."""
|
|
|
|
|
2020-08-18 22:25:50 +00:00
|
|
|
def __init__(self, host, count) -> None:
|
2017-04-20 06:15:26 +00:00
|
|
|
"""Initialize the data object."""
|
|
|
|
self._ip_address = host
|
|
|
|
self._count = count
|
|
|
|
self.data = {}
|
|
|
|
self.available = False
|
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
if sys.platform == "win32":
|
2017-04-20 06:15:26 +00:00
|
|
|
self._ping_cmd = [
|
2019-07-31 19:25:30 +00:00
|
|
|
"ping",
|
|
|
|
"-n",
|
|
|
|
str(self._count),
|
|
|
|
"-w",
|
|
|
|
"1000",
|
|
|
|
self._ip_address,
|
|
|
|
]
|
2017-04-20 06:15:26 +00:00
|
|
|
else:
|
|
|
|
self._ping_cmd = [
|
2019-07-31 19:25:30 +00:00
|
|
|
"ping",
|
|
|
|
"-n",
|
|
|
|
"-q",
|
|
|
|
"-c",
|
|
|
|
str(self._count),
|
|
|
|
"-W1",
|
|
|
|
self._ip_address,
|
|
|
|
]
|
2017-04-20 06:15:26 +00:00
|
|
|
|
2020-08-18 22:25:50 +00:00
|
|
|
async def async_ping(self):
|
2017-04-20 06:15:26 +00:00
|
|
|
"""Send ICMP echo request and return details if success."""
|
2020-08-18 22:25:50 +00:00
|
|
|
pinger = await asyncio.create_subprocess_exec(
|
|
|
|
*self._ping_cmd,
|
|
|
|
stdin=None,
|
|
|
|
stdout=asyncio.subprocess.PIPE,
|
|
|
|
stderr=asyncio.subprocess.PIPE,
|
2019-07-31 19:25:30 +00:00
|
|
|
)
|
2017-04-20 06:15:26 +00:00
|
|
|
try:
|
2020-08-18 22:25:50 +00:00
|
|
|
out_data, out_error = await asyncio.wait_for(
|
|
|
|
pinger.communicate(), self._count + PING_TIMEOUT
|
|
|
|
)
|
|
|
|
|
|
|
|
if out_data:
|
|
|
|
_LOGGER.debug(
|
|
|
|
"Output of command: `%s`, return code: %s:\n%s",
|
|
|
|
" ".join(self._ping_cmd),
|
|
|
|
pinger.returncode,
|
|
|
|
out_data,
|
|
|
|
)
|
|
|
|
if out_error:
|
|
|
|
_LOGGER.debug(
|
|
|
|
"Error of command: `%s`, return code: %s:\n%s",
|
|
|
|
" ".join(self._ping_cmd),
|
|
|
|
pinger.returncode,
|
|
|
|
out_error,
|
|
|
|
)
|
|
|
|
|
|
|
|
if pinger.returncode != 0:
|
|
|
|
_LOGGER.exception(
|
|
|
|
"Error running command: `%s`, return code: %s",
|
|
|
|
" ".join(self._ping_cmd),
|
|
|
|
pinger.returncode,
|
|
|
|
)
|
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
if sys.platform == "win32":
|
2020-08-18 22:25:50 +00:00
|
|
|
match = WIN32_PING_MATCHER.search(str(out_data).split("\n")[-1])
|
2017-04-24 21:32:12 +00:00
|
|
|
rtt_min, rtt_avg, rtt_max = match.groups()
|
2019-07-31 19:25:30 +00:00
|
|
|
return {"min": rtt_min, "avg": rtt_avg, "max": rtt_max, "mdev": ""}
|
2020-08-18 22:25:50 +00:00
|
|
|
if "max/" not in str(out_data):
|
|
|
|
match = PING_MATCHER_BUSYBOX.search(str(out_data).split("\n")[-1])
|
2017-07-22 17:50:31 +00:00
|
|
|
rtt_min, rtt_avg, rtt_max = match.groups()
|
2019-07-31 19:25:30 +00:00
|
|
|
return {"min": rtt_min, "avg": rtt_avg, "max": rtt_max, "mdev": ""}
|
2020-08-18 22:25:50 +00:00
|
|
|
match = PING_MATCHER.search(str(out_data).split("\n")[-1])
|
2017-07-06 06:30:01 +00:00
|
|
|
rtt_min, rtt_avg, rtt_max, rtt_mdev = match.groups()
|
2019-07-31 19:25:30 +00:00
|
|
|
return {"min": rtt_min, "avg": rtt_avg, "max": rtt_max, "mdev": rtt_mdev}
|
2020-08-18 22:25:50 +00:00
|
|
|
except asyncio.TimeoutError:
|
|
|
|
_LOGGER.exception(
|
|
|
|
"Timed out running command: `%s`, after: %ss",
|
|
|
|
self._ping_cmd,
|
|
|
|
self._count + PING_TIMEOUT,
|
|
|
|
)
|
|
|
|
if pinger:
|
|
|
|
try:
|
|
|
|
await pinger.kill()
|
|
|
|
except TypeError:
|
|
|
|
pass
|
|
|
|
del pinger
|
|
|
|
|
2020-08-05 10:43:35 +00:00
|
|
|
return False
|
2020-08-18 22:25:50 +00:00
|
|
|
except AttributeError:
|
2017-04-20 06:15:26 +00:00
|
|
|
return False
|
|
|
|
|
2020-08-18 22:25:50 +00:00
|
|
|
async def async_update(self) -> None:
|
2017-04-20 06:15:26 +00:00
|
|
|
"""Retrieve the latest details from the host."""
|
2020-08-18 22:25:50 +00:00
|
|
|
self.data = await self.async_ping()
|
2017-04-20 06:15:26 +00:00
|
|
|
self.available = bool(self.data)
|