Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Support for the worldtides.info API."""
2 
3 from __future__ import annotations
4 
5 from datetime import timedelta
6 import logging
7 import time
8 
9 import requests
10 import voluptuous as vol
11 
13  PLATFORM_SCHEMA as SENSOR_PLATFORM_SCHEMA,
14  SensorEntity,
15 )
16 from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME
17 from homeassistant.core import HomeAssistant
19 from homeassistant.helpers.entity_platform import AddEntitiesCallback
20 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
21 
22 _LOGGER = logging.getLogger(__name__)
23 
24 ATTRIBUTION = "Data provided by WorldTides"
25 
26 DEFAULT_NAME = "WorldTidesInfo"
27 
28 SCAN_INTERVAL = timedelta(seconds=3600)
29 
30 PLATFORM_SCHEMA = SENSOR_PLATFORM_SCHEMA.extend(
31  {
32  vol.Required(CONF_API_KEY): cv.string,
33  vol.Optional(CONF_LATITUDE): cv.latitude,
34  vol.Optional(CONF_LONGITUDE): cv.longitude,
35  vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
36  }
37 )
38 
39 
41  hass: HomeAssistant,
42  config: ConfigType,
43  add_entities: AddEntitiesCallback,
44  discovery_info: DiscoveryInfoType | None = None,
45 ) -> None:
46  """Set up the WorldTidesInfo sensor."""
47  name = config.get(CONF_NAME)
48 
49  lat = config.get(CONF_LATITUDE, hass.config.latitude)
50  lon = config.get(CONF_LONGITUDE, hass.config.longitude)
51  key = config.get(CONF_API_KEY)
52 
53  if None in (lat, lon):
54  _LOGGER.error("Latitude or longitude not set in Home Assistant config")
55 
56  tides = WorldTidesInfoSensor(name, lat, lon, key)
57  tides.update()
58  if tides.data.get("error") == "No location found":
59  _LOGGER.error("Location not available")
60  return
61 
62  add_entities([tides])
63 
64 
66  """Representation of a WorldTidesInfo sensor."""
67 
68  _attr_attribution = ATTRIBUTION
69 
70  def __init__(self, name, lat, lon, key):
71  """Initialize the sensor."""
72  self._name_name = name
73  self._lat_lat = lat
74  self._lon_lon = lon
75  self._key_key = key
76  self.datadata = None
77 
78  @property
79  def name(self):
80  """Return the name of the sensor."""
81  return self._name_name
82 
83  @property
85  """Return the state attributes of this device."""
86  attr = {}
87 
88  if "High" in str(self.datadata["extremes"][0]["type"]):
89  attr["high_tide_time_utc"] = self.datadata["extremes"][0]["date"]
90  attr["high_tide_height"] = self.datadata["extremes"][0]["height"]
91  attr["low_tide_time_utc"] = self.datadata["extremes"][1]["date"]
92  attr["low_tide_height"] = self.datadata["extremes"][1]["height"]
93  elif "Low" in str(self.datadata["extremes"][0]["type"]):
94  attr["high_tide_time_utc"] = self.datadata["extremes"][1]["date"]
95  attr["high_tide_height"] = self.datadata["extremes"][1]["height"]
96  attr["low_tide_time_utc"] = self.datadata["extremes"][0]["date"]
97  attr["low_tide_height"] = self.datadata["extremes"][0]["height"]
98  return attr
99 
100  @property
101  def native_value(self):
102  """Return the state of the device."""
103  if self.datadata:
104  if "High" in str(self.datadata["extremes"][0]["type"]):
105  tidetime = time.strftime(
106  "%I:%M %p", time.localtime(self.datadata["extremes"][0]["dt"])
107  )
108  return f"High tide at {tidetime}"
109  if "Low" in str(self.datadata["extremes"][0]["type"]):
110  tidetime = time.strftime(
111  "%I:%M %p", time.localtime(self.datadata["extremes"][0]["dt"])
112  )
113  return f"Low tide at {tidetime}"
114  return None
115  return None
116 
117  def update(self) -> None:
118  """Get the latest data from WorldTidesInfo API."""
119  start = int(time.time())
120  resource = (
121  "https://www.worldtides.info/api?extremes&length=86400"
122  f"&key={self._key}&lat={self._lat}&lon={self._lon}&start={start}"
123  )
124 
125  try:
126  self.datadata = requests.get(resource, timeout=10).json()
127  _LOGGER.debug("Data: %s", self.datadata)
128  _LOGGER.debug("Tide data queried with start time set to: %s", start)
129  except ValueError as err:
130  _LOGGER.error("Error retrieving data from WorldTidesInfo: %s", err.args)
131  self.datadata = None
def add_entities(account, async_add_entities, tracked)
Definition: sensor.py:40
None setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback add_entities, DiscoveryInfoType|None discovery_info=None)
Definition: sensor.py:45