core/homeassistant/components/arest/switch.py

211 lines
6.4 KiB
Python
Raw Normal View History

"""Support for an exposed aREST RESTful API of a device."""
2015-09-09 12:22:08 +00:00
import logging
2016-02-19 05:27:50 +00:00
2015-10-15 16:20:46 +00:00
import requests
import voluptuous as vol
2015-09-09 12:22:08 +00:00
2019-07-31 19:25:30 +00:00
from homeassistant.components.switch import SwitchDevice, PLATFORM_SCHEMA
from homeassistant.const import CONF_NAME, CONF_RESOURCE
import homeassistant.helpers.config_validation as cv
2015-09-09 12:22:08 +00:00
_LOGGER = logging.getLogger(__name__)
2019-07-31 19:25:30 +00:00
CONF_FUNCTIONS = "functions"
CONF_PINS = "pins"
CONF_INVERT = "invert"
DEFAULT_NAME = "aREST switch"
PIN_FUNCTION_SCHEMA = vol.Schema(
{
vol.Optional(CONF_NAME): cv.string,
vol.Optional(CONF_INVERT, default=False): cv.boolean,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_RESOURCE): cv.url,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_PINS, default={}): vol.Schema(
{cv.string: PIN_FUNCTION_SCHEMA}
),
vol.Optional(CONF_FUNCTIONS, default={}): vol.Schema(
{cv.string: PIN_FUNCTION_SCHEMA}
),
}
)
2015-09-09 12:22:08 +00:00
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the aREST switches."""
resource = config.get(CONF_RESOURCE)
2015-09-09 12:22:08 +00:00
try:
2015-10-15 16:20:46 +00:00
response = requests.get(resource, timeout=10)
except requests.exceptions.MissingSchema:
2019-07-31 19:25:30 +00:00
_LOGGER.error(
"Missing resource or schema in configuration. " "Add http:// to your URL"
)
2015-09-09 12:22:08 +00:00
return False
2015-10-15 16:20:46 +00:00
except requests.exceptions.ConnectionError:
_LOGGER.error("No route to device at %s", resource)
2015-09-09 12:22:08 +00:00
return False
dev = []
pins = config.get(CONF_PINS)
2015-09-09 12:22:08 +00:00
for pinnum, pin in pins.items():
2019-07-31 19:25:30 +00:00
dev.append(
ArestSwitchPin(
resource,
config.get(CONF_NAME, response.json()[CONF_NAME]),
pin.get(CONF_NAME),
pinnum,
pin.get(CONF_INVERT),
)
)
functions = config.get(CONF_FUNCTIONS)
for funcname, func in functions.items():
2019-07-31 19:25:30 +00:00
dev.append(
ArestSwitchFunction(
resource,
config.get(CONF_NAME, response.json()[CONF_NAME]),
func.get(CONF_NAME),
funcname,
)
)
add_entities(dev)
2015-09-09 12:22:08 +00:00
class ArestSwitchBase(SwitchDevice):
"""Representation of an aREST switch."""
2015-09-09 12:22:08 +00:00
def __init__(self, resource, location, name):
2016-03-08 12:35:39 +00:00
"""Initialize the switch."""
2015-09-09 12:22:08 +00:00
self._resource = resource
2019-07-31 19:25:30 +00:00
self._name = "{} {}".format(location.title(), name.title())
2015-09-09 12:22:08 +00:00
self._state = None
2016-10-04 07:51:45 +00:00
self._available = True
2015-09-09 12:22:08 +00:00
@property
def name(self):
2016-03-08 12:35:39 +00:00
"""Return the name of the switch."""
2015-09-09 12:22:08 +00:00
return self._name
@property
def is_on(self):
2016-03-08 12:35:39 +00:00
"""Return true if device is on."""
2015-09-09 12:22:08 +00:00
return self._state
2016-10-04 07:51:45 +00:00
@property
def available(self):
"""Could the device be accessed during the last update call."""
return self._available
class ArestSwitchFunction(ArestSwitchBase):
2016-03-08 12:35:39 +00:00
"""Representation of an aREST switch."""
def __init__(self, resource, location, name, func):
2016-03-08 12:35:39 +00:00
"""Initialize the switch."""
super().__init__(resource, location, name)
self._func = func
request = requests.get(f"{self._resource}/{self._func}", timeout=10)
if request.status_code != 200:
_LOGGER.error("Can't find function")
return
try:
2019-07-31 19:25:30 +00:00
request.json()["return_value"]
except KeyError:
_LOGGER.error("No return_value received")
except ValueError:
_LOGGER.error("Response invalid")
def turn_on(self, **kwargs):
2016-03-08 12:35:39 +00:00
"""Turn the device on."""
request = requests.get(
f"{self._resource}/{self._func}", timeout=10, params={"params": "1"}
2019-07-31 19:25:30 +00:00
)
if request.status_code == 200:
self._state = True
else:
2019-07-31 19:25:30 +00:00
_LOGGER.error("Can't turn on function %s at %s", self._func, self._resource)
def turn_off(self, **kwargs):
2016-03-08 12:35:39 +00:00
"""Turn the device off."""
request = requests.get(
f"{self._resource}/{self._func}", timeout=10, params={"params": "0"}
2019-07-31 19:25:30 +00:00
)
if request.status_code == 200:
self._state = False
else:
_LOGGER.error(
2019-07-31 19:25:30 +00:00
"Can't turn off function %s at %s", self._func, self._resource
)
def update(self):
2016-03-08 12:35:39 +00:00
"""Get the latest data from aREST API and update the state."""
2016-10-04 07:51:45 +00:00
try:
request = requests.get(f"{self._resource}/{self._func}", timeout=10)
2019-07-31 19:25:30 +00:00
self._state = request.json()["return_value"] != 0
2016-10-04 07:51:45 +00:00
self._available = True
except requests.exceptions.ConnectionError:
_LOGGER.warning("No route to device %s", self._resource)
2016-10-04 07:51:45 +00:00
self._available = False
class ArestSwitchPin(ArestSwitchBase):
2016-03-08 12:35:39 +00:00
"""Representation of an aREST switch. Based on digital I/O."""
def __init__(self, resource, location, name, pin, invert):
2016-03-08 12:35:39 +00:00
"""Initialize the switch."""
super().__init__(resource, location, name)
self._pin = pin
self.invert = invert
request = requests.get(f"{self._resource}/mode/{self._pin}/o", timeout=10)
if request.status_code != 200:
_LOGGER.error("Can't set mode")
2016-10-04 07:51:45 +00:00
self._available = False
2015-09-09 12:22:08 +00:00
def turn_on(self, **kwargs):
2016-03-08 12:35:39 +00:00
"""Turn the device on."""
turn_on_payload = int(not self.invert)
request = requests.get(
f"{self._resource}/digital/{self._pin}/{turn_on_payload}", timeout=10
2019-07-31 19:25:30 +00:00
)
2015-09-10 19:07:06 +00:00
if request.status_code == 200:
self._state = True
else:
2019-07-31 19:25:30 +00:00
_LOGGER.error("Can't turn on pin %s at %s", self._pin, self._resource)
2015-09-09 12:22:08 +00:00
def turn_off(self, **kwargs):
2016-03-08 12:35:39 +00:00
"""Turn the device off."""
turn_off_payload = int(self.invert)
request = requests.get(
f"{self._resource}/digital/{self._pin}/{turn_off_payload}", timeout=10
2019-07-31 19:25:30 +00:00
)
2015-09-10 19:07:06 +00:00
if request.status_code == 200:
self._state = False
else:
2019-07-31 19:25:30 +00:00
_LOGGER.error("Can't turn off pin %s at %s", self._pin, self._resource)
2015-09-10 17:11:20 +00:00
def update(self):
2016-03-08 12:35:39 +00:00
"""Get the latest data from aREST API and update the state."""
2016-10-04 07:51:45 +00:00
try:
request = requests.get(f"{self._resource}/digital/{self._pin}", timeout=10)
status_value = int(self.invert)
2019-07-31 19:25:30 +00:00
self._state = request.json()["return_value"] != status_value
2016-10-04 07:51:45 +00:00
self._available = True
except requests.exceptions.ConnectionError:
_LOGGER.warning("No route to device %s", self._resource)
2016-10-04 07:51:45 +00:00
self._available = False