1
0
mirror of https://github.com/home-assistant/core.git synced 2025-08-10 22:10:02 +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
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
firetv
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
iperf3
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
meteo_france
microsoft_face
mobile_app
mochad
modbus
mqtt
mqtt_eventstream
mqtt_statestream
mychevy
mycroft
mysensors
mythicbeastsdns
namecheapdns
neato
ness_alarm
nest
netatmo
netgear_lte
nissan_leaf
no_ip
notify
nuheat
nuimo_controller
octoprint
onboarding
opentherm_gw
openuv
owlet
owntracks
panel_custom
panel_iframe
persistent_notification
person
pilight
plant
plum_lightpad
point
prometheus
proximity
ps4
python_script
qwikswitch
rachio
rainbird
raincloud
rainmachine
raspihats
recorder
reddit
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
.translations
__init__.py
aftership.py
airvisual.py
alpha_vantage.py
api_streams.py
arest.py
arwn.py
asuswrt.py
awair.py
bbox.py
bh1750.py
bitcoin.py
blockchain.py
bme280.py
bme680.py
bom.py
broadlink.py
brottsplatskartan.py
buienradar.py
canary.py
cert_expiry.py
citybikes.py
co2signal.py
coinbase.py
coinmarketcap.py
comed_hourly_pricing.py
command_line.py
cpuspeed.py
crimereports.py
cups.py
currencylayer.py
darksky.py
deluge.py
demo.py
deutsche_bahn.py
dht.py
discogs.py
dnsip.py
dsmr.py
dte_energy_bridge.py
dublin_bus_transport.py
duke_energy.py
dwd_weather_warnings.py
dyson.py
ebox.py
eddystone_temperature.py
efergy.py
eliqonline.py
emoncms.py
enphase_envoy.py
entur_public_transport.py
envirophat.py
etherscan.py
fail2ban.py
fedex.py
fido.py
file.py
filesize.py
filter.py
fints.py
fitbit.py
fixer.py
flunearyou.py
folder.py
foobot.py
fritzbox_callmonitor.py
fritzbox_netmonitor.py
gearbest.py
geizhals.py
geo_rss_events.py
github.py
gitlab_ci.py
gitter.py
glances.py
google_travel_time.py
google_wifi.py
gpsd.py
greeneye_monitor.py
gtfs.py
gtt.py
haveibeenpwned.py
hddtemp.py
history_stats.py
hp_ilo.py
htu21d.py
hydroquebec.py
iliad_italy.py
imap.py
imap_email_content.py
influxdb.py
integration.py
irish_rail_transport.py
islamic_prayer_times.py
jewish_calendar.py
kwb.py
lacrosse.py
lastfm.py
launch_library.py
linky.py
linux_battery.py
london_air.py
london_underground.py
loopenergy.py
lyft.py
magicseaweed.py
metoffice.py
mfi.py
mhz19.py
miflora.py
min_max.py
mitemp_bt.py
modem_callerid.py
mold_indicator.py
moon.py
mopar.py
mqtt_room.py
mvglive.py
nederlandse_spoorwegen.py
netatmo_public.py
netdata.py
neurio_energy.py
nmbs.py
noaa_tides.py
nsw_fuel_station.py
nut.py
nzbget.py
ohmconnect.py
onewire.py
openevse.py
openexchangerates.py
openhardwaremonitor.py
opensky.py
openweathermap.py
otp.py
pi_hole.py
plex.py
pocketcasts.py
pollen.py
postnl.py
prezzibenzina.py
pushbullet.py
pvoutput.py
pyload.py
qbittorrent.py
qnap.py
radarr.py
rainbird.py
random.py
recollect_waste.py
rejseplanen.py
rest.py
rflink.py
ring.py
ripple.py
rmvtransport.py
rova.py
rtorrent.py
ruter.py
scrape.py
season.py
sensehat.py
serial.py
serial_pm.py
seventeentrack.py
shodan.py
sht31.py
sigfox.py
simulated.py
skybeacon.py
sleepiq.py
sma.py
snmp.py
sochain.py
socialblade.py
solaredge.py
sonarr.py
spotcrime.py
sql.py
srp_energy.py
starlingbank.py
startca.py
statistics.py
steam_online.py
strings.moon.json
strings.season.json
supervisord.py
swiss_hydrological_data.py
swiss_public_transport.py
syncthru.py
synologydsm.py
systemmonitor.py
sytadin.py
tank_utility.py
tautulli.py
tcp.py
ted5000.py
teksavvy.py
temper.py
template.py
thermoworks_smoke.py
time_date.py
torque.py
trafikverket_weatherstation.py
transport_nsw.py
travisci.py
twitch.py
uber.py
uk_transport.py
ups.py
uptime.py
uscis.py
vasttrafik.py
version.py
viaggiatreno.py
volkszaehler.py
vultr.py
waqi.py
waze_travel_time.py
whois.py
worldclock.py
worldtidesinfo.py
worxlandroid.py
wsdot.py
wunderground.py
xbox_live.py
yr.py
yweather.py
zamg.py
zestimate.py
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
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
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/sensor/rest.py
2019-02-26 10:23:46 -08:00

204 lines
7.0 KiB
Python

"""
Support for RESTful API sensors.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.rest/
"""
import logging
import json
import voluptuous as vol
import requests
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
from homeassistant.components.sensor import (
PLATFORM_SCHEMA, DEVICE_CLASSES_SCHEMA)
from homeassistant.const import (
CONF_AUTHENTICATION, CONF_FORCE_UPDATE, CONF_HEADERS, CONF_NAME,
CONF_METHOD, CONF_PASSWORD, CONF_PAYLOAD, CONF_RESOURCE,
CONF_UNIT_OF_MEASUREMENT, CONF_USERNAME, CONF_TIMEOUT,
CONF_VALUE_TEMPLATE, CONF_VERIFY_SSL, CONF_DEVICE_CLASS,
HTTP_BASIC_AUTHENTICATION, HTTP_DIGEST_AUTHENTICATION)
from homeassistant.exceptions import PlatformNotReady
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
DEFAULT_METHOD = 'GET'
DEFAULT_NAME = 'REST Sensor'
DEFAULT_VERIFY_SSL = True
DEFAULT_FORCE_UPDATE = False
DEFAULT_TIMEOUT = 10
CONF_JSON_ATTRS = 'json_attributes'
METHODS = ['POST', 'GET']
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_RESOURCE): cv.url,
vol.Optional(CONF_AUTHENTICATION):
vol.In([HTTP_BASIC_AUTHENTICATION, HTTP_DIGEST_AUTHENTICATION]),
vol.Optional(CONF_HEADERS): vol.Schema({cv.string: cv.string}),
vol.Optional(CONF_JSON_ATTRS, default=[]): cv.ensure_list_csv,
vol.Optional(CONF_METHOD, default=DEFAULT_METHOD): vol.In(METHODS),
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_PASSWORD): cv.string,
vol.Optional(CONF_PAYLOAD): cv.string,
vol.Optional(CONF_UNIT_OF_MEASUREMENT): cv.string,
vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA,
vol.Optional(CONF_USERNAME): cv.string,
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean,
vol.Optional(CONF_FORCE_UPDATE, default=DEFAULT_FORCE_UPDATE): cv.boolean,
vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int,
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the RESTful sensor."""
name = config.get(CONF_NAME)
resource = config.get(CONF_RESOURCE)
method = config.get(CONF_METHOD)
payload = config.get(CONF_PAYLOAD)
verify_ssl = config.get(CONF_VERIFY_SSL)
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
headers = config.get(CONF_HEADERS)
unit = config.get(CONF_UNIT_OF_MEASUREMENT)
device_class = config.get(CONF_DEVICE_CLASS)
value_template = config.get(CONF_VALUE_TEMPLATE)
json_attrs = config.get(CONF_JSON_ATTRS)
force_update = config.get(CONF_FORCE_UPDATE)
timeout = config.get(CONF_TIMEOUT)
if value_template is not None:
value_template.hass = hass
if username and password:
if config.get(CONF_AUTHENTICATION) == HTTP_DIGEST_AUTHENTICATION:
auth = HTTPDigestAuth(username, password)
else:
auth = HTTPBasicAuth(username, password)
else:
auth = None
rest = RestData(method, resource, auth, headers, payload, verify_ssl,
timeout)
rest.update()
if rest.data is None:
raise PlatformNotReady
# Must update the sensor now (including fetching the rest resource) to
# ensure it's updating its state.
add_entities([RestSensor(
hass, rest, name, unit, device_class,
value_template, json_attrs, force_update
)], True)
class RestSensor(Entity):
"""Implementation of a REST sensor."""
def __init__(self, hass, rest, name, unit_of_measurement,
device_class, value_template, json_attrs, force_update):
"""Initialize the REST sensor."""
self._hass = hass
self.rest = rest
self._name = name
self._state = None
self._unit_of_measurement = unit_of_measurement
self._device_class = device_class
self._value_template = value_template
self._json_attrs = json_attrs
self._attributes = None
self._force_update = force_update
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return self._unit_of_measurement
@property
def device_class(self):
"""Return the class of this sensor."""
return self._device_class
@property
def available(self):
"""Return if the sensor data are available."""
return self.rest.data is not None
@property
def state(self):
"""Return the state of the device."""
return self._state
@property
def force_update(self):
"""Force update."""
return self._force_update
def update(self):
"""Get the latest data from REST API and update the state."""
self.rest.update()
value = self.rest.data
if self._json_attrs:
self._attributes = {}
if value:
try:
json_dict = json.loads(value)
if isinstance(json_dict, dict):
attrs = {k: json_dict[k] for k in self._json_attrs
if k in json_dict}
self._attributes = attrs
else:
_LOGGER.warning("JSON result was not a dictionary")
except ValueError:
_LOGGER.warning("REST result could not be parsed as JSON")
_LOGGER.debug("Erroneous JSON: %s", value)
else:
_LOGGER.warning("Empty reply found when expecting JSON data")
if value is not None and self._value_template is not None:
value = self._value_template.render_with_possible_json_value(
value, None)
self._state = value
@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._attributes
class RestData:
"""Class for handling the data retrieval."""
def __init__(self, method, resource, auth, headers, data, verify_ssl,
timeout=DEFAULT_TIMEOUT):
"""Initialize the data object."""
self._request = requests.Request(
method, resource, headers=headers, auth=auth, data=data).prepare()
self._verify_ssl = verify_ssl
self._timeout = timeout
self.data = None
def update(self):
"""Get the latest data from REST service with provided method."""
_LOGGER.debug("Updating from %s", self._request.url)
try:
with requests.Session() as sess:
response = sess.send(
self._request, timeout=self._timeout,
verify=self._verify_ssl)
self.data = response.text
except requests.exceptions.RequestException as ex:
_LOGGER.error("Error fetching data: %s from %s failed with %s",
self._request, self._request.url, ex)
self.data = None