core/homeassistant/components/uptimerobot/binary_sensor.py

86 lines
2.6 KiB
Python
Raw Normal View History

"""A platform that to monitor Uptime Robot monitors."""
import logging
from pyuptimerobot import UptimeRobot
import voluptuous as vol
from homeassistant.components.binary_sensor import PLATFORM_SCHEMA, BinarySensorEntity
2018-06-10 08:58:45 +00:00
from homeassistant.const import ATTR_ATTRIBUTION, CONF_API_KEY
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
2019-07-31 19:25:30 +00:00
ATTR_TARGET = "target"
ATTRIBUTION = "Data provided by Uptime Robot"
2018-06-10 08:58:45 +00:00
2019-07-31 19:25:30 +00:00
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({vol.Required(CONF_API_KEY): cv.string})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Uptime Robot binary_sensors."""
up_robot = UptimeRobot()
2018-06-10 08:58:45 +00:00
api_key = config.get(CONF_API_KEY)
monitors = up_robot.getMonitors(api_key)
devices = []
2019-07-31 19:25:30 +00:00
if not monitors or monitors.get("stat") != "ok":
2018-06-10 08:58:45 +00:00
_LOGGER.error("Error connecting to Uptime Robot")
return
2019-07-31 19:25:30 +00:00
for monitor in monitors["monitors"]:
devices.append(
UptimeRobotBinarySensor(
api_key,
up_robot,
monitor["id"],
monitor["friendly_name"],
monitor["url"],
)
)
add_entities(devices, True)
class UptimeRobotBinarySensor(BinarySensorEntity):
2018-06-10 08:58:45 +00:00
"""Representation of a Uptime Robot binary sensor."""
2018-06-10 08:58:45 +00:00
def __init__(self, api_key, up_robot, monitor_id, name, target):
"""Initialize Uptime Robot the binary sensor."""
self._api_key = api_key
self._monitor_id = str(monitor_id)
self._name = name
self._target = target
self._up_robot = up_robot
self._state = None
@property
def name(self):
2018-06-10 08:58:45 +00:00
"""Return the name of the binary sensor."""
return self._name
@property
def is_on(self):
"""Return the state of the binary sensor."""
return self._state
@property
def device_class(self):
"""Return the class of this device, from component DEVICE_CLASSES."""
2019-07-31 19:25:30 +00:00
return "connectivity"
@property
def device_state_attributes(self):
2018-06-10 08:58:45 +00:00
"""Return the state attributes of the binary sensor."""
2019-07-31 19:25:30 +00:00
return {ATTR_ATTRIBUTION: ATTRIBUTION, ATTR_TARGET: self._target}
def update(self):
2018-06-10 08:58:45 +00:00
"""Get the latest state of the binary sensor."""
monitor = self._up_robot.getMonitors(self._api_key, self._monitor_id)
2019-07-31 19:25:30 +00:00
if not monitor or monitor.get("stat") != "ok":
2018-06-10 08:58:45 +00:00
_LOGGER.warning("Failed to get new state")
return
2019-07-31 19:25:30 +00:00
status = monitor["monitors"][0]["status"]
self._state = 1 if status == 2 else 0