1
0
mirror of https://github.com/home-assistant/core.git synced 2025-08-13 23:40:06 +00:00
Files
.github
docs
homeassistant
auth
components
abode
ads
air_quality
alarm_control_panel
alarmdecoder
alert
alexa
ambient_station
amcrest
android_ip_webcam
apcupsd
api
apple_tv
aqualogic
arduino
arlo
asterisk_mbox
asuswrt
august
auth
automation
axis
bbb_gpio
binary_sensor
__init__.py
arest.py
aurora.py
bayesian.py
command_line.py
concord232.py
demo.py
ffmpeg_motion.py
ffmpeg_noise.py
flic.py
hikvision.py
iss.py
mystrom.py
ness_alarm.py
nx584.py
ping.py
random.py
rest.py
rflink.py
ring.py
sleepiq.py
spc.py
tapsaff.py
tcp.py
template.py
threshold.py
trend.py
uptimerobot.py
vultr.py
workday.py
blink
bloomsky
bmw_connected_drive
browser
calendar
camera
canary
cast
climate
cloud
cloudflare
coinbase
comfoconnect
config
configurator
conversation
counter
cover
daikin
danfoss_air
datadog
deconz
default_config
demo
device_sun_light_trigger
device_tracker
dialogflow
digital_ocean
discovery
dominos
doorbird
dovado
downloader
duckdns
dweet
dyson
ebusd
ecoal_boiler
ecobee
ecovacs
edp_redy
egardia
eight_sleep
elkm1
emoncms_history
emulated_hue
emulated_roku
enocean
envisalink
esphome
eufy
evohome
fan
fastdotcom
feedreader
ffmpeg
fibaro
folder_watcher
foursquare
freebox
freedns
fritzbox
frontend
gc100
geo_location
geofency
goalfeed
google
google_assistant
google_domains
google_pubsub
googlehome
gpslogger
graphite
greeneye_monitor
group
habitica
hangouts
harmony
hassio
hdmi_cec
history
history_graph
hive
hlk_sw16
homekit
homekit_controller
homematic
homematicip_cloud
homeworks
http
huawei_lte
hue
hydrawise
idteck_prox
ifttt
ihc
image_processing
influxdb
input_boolean
input_datetime
input_number
input_select
input_text
insteon
insteon_local
insteon_plm
intent_script
introduction
ios
iota
ipma
isy994
itach
joaoapps_join
juicenet
keyboard
keyboard_remote
kira
knx
konnected
lametric
lcn
lifx
light
lightwave
linode
lirc
litejet
locative
lock
logbook
logentries
logger
logi_circle
lovelace
luftdaten
lupusec
lutron
lutron_caseta
mailbox
mailgun
map
matrix
maxcube
media_extractor
media_player
melissa
microsoft_face
mochad
modbus
mqtt
mqtt_eventstream
mqtt_statestream
mychevy
mycroft
mysensors
mythicbeastsdns
namecheapdns
neato
ness_alarm
nest
netatmo
netgear_lte
no_ip
notify
nuheat
nuimo_controller
octoprint
onboarding
opentherm_gw
openuv
owntracks
panel_custom
panel_iframe
persistent_notification
person
pilight
plant
plum_lightpad
point
prometheus
proximity
python_script
qwikswitch
rachio
rainbird
raincloud
rainmachine
raspihats
recorder
remember_the_milk
remote
rest_command
rflink
rfxtrx
ring
roku
route53
rpi_gpio
rpi_pfio
rss_feed_template
sabnzbd
satel_integra
scene
script
scsgate
sense
sensor
shell_command
shiftr
shopping_list
simplisafe
sisyphus
skybell
sleepiq
smappee
smartthings
smhi
snips
sonos
spaceapi
spc
speedtestdotnet
spider
splunk
statsd
sun
switch
system_health
system_log
tado
tahoma
telegram_bot
tellduslive
tellstick
tesla
thethingsnetwork
thingspeak
thinkingcleaner
tibber
timer
toon
tplink_lte
tradfri
transmission
tts
tuya
twilio
unifi
upcloud
updater
upnp
usps
utility_meter
vacuum
velbus
velux
vera
verisure
volvooncall
vultr
w800rf32
wake_on_lan
water_heater
waterfurnace
watson_iot
weather
webhook
weblink
webostv
websocket_api
wemo
wink
wirelesstag
wunderlist
xiaomi_aqara
xiaomi_miio
xs1
zabbix
zeroconf
zha
zigbee
zone
zoneminder
zwave
__init__.py
meteo_france.py
services.yaml
helpers
scripts
util
__init__.py
__main__.py
bootstrap.py
config.py
config_entries.py
const.py
core.py
data_entry_flow.py
exceptions.py
loader.py
monkey_patch.py
package_constraints.txt
requirements.py
setup.py
script
tests
virtualization
.coveragerc
.dockerignore
.gitattributes
.gitignore
.hound.yml
.ignore
.readthedocs.yml
.travis.yml
CLA.md
CODEOWNERS
CODE_OF_CONDUCT.md
CONTRIBUTING.md
Dockerfile
LICENSE.md
MANIFEST.in
README.rst
mypy.ini
pylintrc
requirements_all.txt
requirements_docs.txt
requirements_test.txt
requirements_test_all.txt
setup.cfg
setup.py
tox.ini
core/homeassistant/components/binary_sensor/arest.py
Paulus Schoutsen 994b829cb4 add_devices -> add_entities ()
* add_devices -> add_entities

* Lint

* PyLint

* Revert external method in scsgate
2018-08-24 16:37:30 +02:00

110 lines
3.4 KiB
Python

"""
Support for an exposed aREST RESTful API of a device.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/binary_sensor.arest/
"""
import logging
from datetime import timedelta
import requests
import voluptuous as vol
from homeassistant.components.binary_sensor import (
BinarySensorDevice, PLATFORM_SCHEMA, DEVICE_CLASSES_SCHEMA)
from homeassistant.const import (
CONF_RESOURCE, CONF_PIN, CONF_NAME, CONF_DEVICE_CLASS)
from homeassistant.util import Throttle
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=30)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_RESOURCE): cv.url,
vol.Optional(CONF_NAME): cv.string,
vol.Required(CONF_PIN): cv.string,
vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA,
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the aREST binary sensor."""
resource = config.get(CONF_RESOURCE)
pin = config.get(CONF_PIN)
device_class = config.get(CONF_DEVICE_CLASS)
try:
response = requests.get(resource, timeout=10).json()
except requests.exceptions.MissingSchema:
_LOGGER.error("Missing resource or schema in configuration. "
"Add http:// to your URL")
return False
except requests.exceptions.ConnectionError:
_LOGGER.error("No route to device at %s", resource)
return False
arest = ArestData(resource, pin)
add_entities([ArestBinarySensor(
arest, resource, config.get(CONF_NAME, response[CONF_NAME]),
device_class, pin)], True)
class ArestBinarySensor(BinarySensorDevice):
"""Implement an aREST binary sensor for a pin."""
def __init__(self, arest, resource, name, device_class, pin):
"""Initialize the aREST device."""
self.arest = arest
self._resource = resource
self._name = name
self._device_class = device_class
self._pin = pin
if self._pin is not None:
request = requests.get(
'{}/mode/{}/i'.format(self._resource, self._pin), timeout=10)
if request.status_code != 200:
_LOGGER.error("Can't set mode of %s", self._resource)
@property
def name(self):
"""Return the name of the binary sensor."""
return self._name
@property
def is_on(self):
"""Return true if the binary sensor is on."""
return bool(self.arest.data.get('state'))
@property
def device_class(self):
"""Return the class of this sensor."""
return self._device_class
def update(self):
"""Get the latest data from aREST API."""
self.arest.update()
class ArestData:
"""Class for handling the data retrieval for pins."""
def __init__(self, resource, pin):
"""Initialize the aREST data object."""
self._resource = resource
self._pin = pin
self.data = {}
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
"""Get the latest data from aREST device."""
try:
response = requests.get('{}/digital/{}'.format(
self._resource, self._pin), timeout=10)
self.data = {'state': response.json()['return_value']}
except requests.exceptions.ConnectionError:
_LOGGER.error("No route to device '%s'", self._resource)