1
0
mirror of https://github.com/home-assistant/core.git synced 2025-08-18 09:50:04 +00:00
Files
.github
docs
homeassistant
auth
components
abode
ads
air_quality
alarm_control_panel
alarmdecoder
alert
alexa
ambient_station
amcrest
android_ip_webcam
androidtv
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
cisco_mobility_express
climate
cloud
cloudflare
coinbase
comfoconnect
config
configurator
conversation
counter
cover
cppm_tracker
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
enigma2
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
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
stream
sun
switch
system_health
system_log
tado
tahoma
telegram_bot
tellduslive
tellstick
tesla
thethingsnetwork
thingspeak
thinkingcleaner
tibber
timer
tof
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/worldtidesinfo.py
Fabian Affolter cdc4dc3f11 Rename CONF_ATTRIBUTION to ATTRIBUTION ()
* Rename CONF_ATTRIBUTION to ATTRIBUTION

* Update homeassistant/components/sensor/irish_rail_transport.py

Co-Authored-By: fabaff <mail@fabian-affolter.ch>
2019-02-14 22:09:22 +01:00

120 lines
4.1 KiB
Python

"""
Support for the worldtides.info API.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.worldtidesinfo/
"""
from datetime import timedelta
import logging
import time
import requests
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
ATTR_ATTRIBUTION, CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
_LOGGER = logging.getLogger(__name__)
ATTRIBUTION = "Data provided by WorldTides"
DEFAULT_NAME = 'WorldTidesInfo'
SCAN_INTERVAL = timedelta(seconds=3600)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_API_KEY): cv.string,
vol.Optional(CONF_LATITUDE): cv.latitude,
vol.Optional(CONF_LONGITUDE): cv.longitude,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the WorldTidesInfo sensor."""
name = config.get(CONF_NAME)
lat = config.get(CONF_LATITUDE, hass.config.latitude)
lon = config.get(CONF_LONGITUDE, hass.config.longitude)
key = config.get(CONF_API_KEY)
if None in (lat, lon):
_LOGGER.error("Latitude or longitude not set in Home Assistant config")
tides = WorldTidesInfoSensor(name, lat, lon, key)
tides.update()
if tides.data.get('error') == 'No location found':
_LOGGER.error("Location not available")
return
add_entities([tides])
class WorldTidesInfoSensor(Entity):
"""Representation of a WorldTidesInfo sensor."""
def __init__(self, name, lat, lon, key):
"""Initialize the sensor."""
self._name = name
self._lat = lat
self._lon = lon
self._key = key
self.data = None
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def device_state_attributes(self):
"""Return the state attributes of this device."""
attr = {ATTR_ATTRIBUTION: ATTRIBUTION}
if 'High' in str(self.data['extremes'][0]['type']):
attr['high_tide_time_utc'] = self.data['extremes'][0]['date']
attr['high_tide_height'] = self.data['extremes'][0]['height']
attr['low_tide_time_utc'] = self.data['extremes'][1]['date']
attr['low_tide_height'] = self.data['extremes'][1]['height']
elif 'Low' in str(self.data['extremes'][0]['type']):
attr['high_tide_time_utc'] = self.data['extremes'][1]['date']
attr['high_tide_height'] = self.data['extremes'][1]['height']
attr['low_tide_time_utc'] = self.data['extremes'][0]['date']
attr['low_tide_height'] = self.data['extremes'][0]['height']
return attr
@property
def state(self):
"""Return the state of the device."""
if self.data:
if 'High' in str(self.data['extremes'][0]['type']):
tidetime = time.strftime('%I:%M %p', time.localtime(
self.data['extremes'][0]['dt']))
return "High tide at {}".format(tidetime)
if 'Low' in str(self.data['extremes'][0]['type']):
tidetime = time.strftime('%I:%M %p', time.localtime(
self.data['extremes'][0]['dt']))
return "Low tide at {}".format(tidetime)
return None
return None
def update(self):
"""Get the latest data from WorldTidesInfo API."""
start = int(time.time())
resource = ('https://www.worldtides.info/api?extremes&length=86400'
'&key={}&lat={}&lon={}&start={}').format(
self._key, self._lat, self._lon, start)
try:
self.data = requests.get(resource, timeout=10).json()
_LOGGER.debug("Data: %s", self.data)
_LOGGER.debug(
"Tide data queried with start time set to: %s", start)
except ValueError as err:
_LOGGER.error(
"Error retrieving data from WorldTidesInfo: %s", err.args)
self.data = None