core/homeassistant/components/binary_sensor/rest.py

74 lines
2.2 KiB
Python
Raw Normal View History

2015-12-16 23:47:12 +00:00
"""
homeassistant.components.binary_sensor.rest
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The rest binary sensor will consume responses sent by an exposed REST API.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/binary_sensor.rest/
"""
import logging
from homeassistant.const import CONF_VALUE_TEMPLATE
2016-01-02 21:29:33 +00:00
from homeassistant.util import template
from homeassistant.components.sensor.rest import RestData
2015-12-16 23:47:12 +00:00
from homeassistant.components.binary_sensor import BinarySensorDevice
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = 'REST Binary Sensor'
DEFAULT_METHOD = 'GET'
2015-12-22 21:33:20 +00:00
# pylint: disable=unused-variable
2015-12-16 23:47:12 +00:00
def setup_platform(hass, config, add_devices, discovery_info=None):
2016-02-01 10:31:27 +00:00
""" Setup REST binary sensors. """
2015-12-16 23:47:12 +00:00
resource = config.get('resource', None)
method = config.get('method', DEFAULT_METHOD)
payload = config.get('payload', None)
verify_ssl = config.get('verify_ssl', True)
2016-01-02 21:29:33 +00:00
rest = RestData(method, resource, payload, verify_ssl)
rest.update()
2015-12-16 23:47:12 +00:00
2016-01-02 21:29:33 +00:00
if rest.data is None:
_LOGGER.error('Unable to fetch Rest data')
return False
2015-12-16 23:47:12 +00:00
2016-01-02 21:29:33 +00:00
add_devices([RestBinarySensor(
hass, rest, config.get('name', DEFAULT_NAME),
config.get(CONF_VALUE_TEMPLATE))])
2015-12-16 23:47:12 +00:00
# pylint: disable=too-many-arguments
class RestBinarySensor(BinarySensorDevice):
2016-02-01 10:31:27 +00:00
""" A REST binary sensor. """
2015-12-16 23:47:12 +00:00
def __init__(self, hass, rest, name, value_template):
2016-02-01 10:31:27 +00:00
""" Initialize a REST binary sensor. """
2015-12-16 23:47:12 +00:00
self._hass = hass
self.rest = rest
self._name = name
self._state = False
self._value_template = value_template
self.update()
@property
def name(self):
2016-02-01 10:31:27 +00:00
""" Name of the binary sensor. """
2015-12-16 23:47:12 +00:00
return self._name
@property
def is_on(self):
2016-02-01 10:31:27 +00:00
""" Return if the binary sensor is on. """
2016-01-02 21:29:33 +00:00
if self.rest.data is None:
2015-12-16 23:47:12 +00:00
return False
2016-01-02 21:29:33 +00:00
if self._value_template is not None:
self.rest.data = template.render_with_possible_json_value(
self._hass, self._value_template, self.rest.data, False)
return bool(int(self.rest.data))
2015-12-16 23:47:12 +00:00
def update(self):
2016-02-01 10:31:27 +00:00
""" Get the latest data from REST API and updates the state. """
2016-01-02 21:29:33 +00:00
self.rest.update()