sensor.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. from __future__ import annotations
  2. import re
  3. from datetime import date, datetime, time
  4. from homeassistant.components.sensor import SensorDeviceClass, SensorEntity
  5. from homeassistant.config_entries import ConfigEntry
  6. from homeassistant.const import EntityCategory
  7. from homeassistant.core import HomeAssistant
  8. from homeassistant.helpers.device_registry import DeviceInfo
  9. from homeassistant.helpers.entity_platform import AddEntitiesCallback
  10. from homeassistant.helpers.update_coordinator import CoordinatorEntity
  11. from .const import (
  12. CONF_API_BASE_URL,
  13. CONF_CALDAV_URL,
  14. CONF_ROOM_NAME,
  15. CONF_SYNC_MODE,
  16. DOMAIN,
  17. STORE_CURRENT,
  18. STORE_NEXT,
  19. SYNC_MODE_API,
  20. SYNC_MODE_CALDAV,
  21. SYNC_MODE_MANUAL,
  22. )
  23. from .coordinator import CoordinatorData, RoomCalCoordinator
  24. from .models import ReservationData
  25. async def async_setup_entry(
  26. hass: HomeAssistant,
  27. entry: ConfigEntry,
  28. async_add_entities: AddEntitiesCallback,
  29. ) -> None:
  30. coordinator: RoomCalCoordinator = hass.data[DOMAIN][entry.entry_id]["coordinator"]
  31. room_name = entry.data.get(CONF_ROOM_NAME, entry.title)
  32. room_state_device = DeviceInfo(
  33. identifiers={(DOMAIN, f"{entry.entry_id}_room_state")},
  34. name=f"{room_name} Room State",
  35. )
  36. entities: list[SensorEntity] = [
  37. SyncSourceSensor(entry, room_name, room_state_device),
  38. ActiveLastUpdatedSensor(coordinator, entry, room_state_device),
  39. ]
  40. if entry.options.get(CONF_SYNC_MODE) == SYNC_MODE_API:
  41. entities.append(ApiHealthSensor(coordinator, entry, room_state_device))
  42. for slot, device_name in (
  43. (STORE_CURRENT, f"{room_name} Current"),
  44. (STORE_NEXT, f"{room_name} Next"),
  45. ):
  46. device_id = f"{entry.entry_id}_{slot}"
  47. device_info = DeviceInfo(
  48. identifiers={(DOMAIN, device_id)},
  49. name=device_name,
  50. )
  51. entities += [
  52. GuestNameSensor(coordinator, entry, slot, device_info, "guest_name", "guest_name", "mdi:account-convert"),
  53. ReservationDateTimeSensor(coordinator, entry, slot, device_info, "arrival", "check_in_date", "check_in_time", "mdi:calendar-start"),
  54. ReservationTimeSensor(coordinator, entry, slot, device_info, "check_in", "check_in_time", "mdi:timer-check-outline"),
  55. ReservationDateTimeSensor(coordinator, entry, slot, device_info, "departure", "check_out_date", "check_out_time", "mdi:calendar-end"),
  56. ReservationTimeSensor(coordinator, entry, slot, device_info, "check_out", "check_out_time", "mdi:timer-cancel-outline"),
  57. ReservationStrSensor(coordinator, entry, slot, device_info, "wifi_ssid", "wifi_ssid", "mdi:wifi"),
  58. WiFiKeySensor(coordinator, entry, slot, device_info),
  59. ReservationStrSensor(coordinator, entry, slot, device_info, "door_code", "door_code", "mdi:door-closed-lock"),
  60. LastUpdatedSensor(coordinator, entry, slot, device_info),
  61. ]
  62. async_add_entities(entities)
  63. class SyncSourceSensor(SensorEntity):
  64. _attr_has_entity_name = True
  65. _attr_translation_key = "sync_source"
  66. _attr_icon = "mdi:sync"
  67. _attr_entity_category = EntityCategory.DIAGNOSTIC
  68. def __init__(self, entry: ConfigEntry, room_name: str, device_info: DeviceInfo) -> None:
  69. self._entry = entry
  70. self._attr_unique_id = f"{entry.entry_id}_sync_source"
  71. self._attr_device_info = device_info
  72. @property
  73. def native_value(self) -> str:
  74. return self._entry.options.get(CONF_SYNC_MODE, SYNC_MODE_MANUAL)
  75. @property
  76. def extra_state_attributes(self) -> dict[str, str | None]:
  77. mode = self._entry.options.get(CONF_SYNC_MODE, SYNC_MODE_MANUAL)
  78. if mode == SYNC_MODE_CALDAV:
  79. url = self._entry.options.get(CONF_CALDAV_URL)
  80. elif mode == SYNC_MODE_API:
  81. url = self._entry.options.get(CONF_API_BASE_URL)
  82. else:
  83. url = None
  84. return {"server_url": url}
  85. class _ReservationSensor(CoordinatorEntity[RoomCalCoordinator], SensorEntity):
  86. _attr_has_entity_name = True
  87. def __init__(
  88. self,
  89. coordinator: RoomCalCoordinator,
  90. entry: ConfigEntry,
  91. slot: str,
  92. device_info: DeviceInfo,
  93. translation_key: str,
  94. field: str,
  95. icon: str | None = None,
  96. ) -> None:
  97. super().__init__(coordinator)
  98. self._slot = slot
  99. self._field = field
  100. self._attr_translation_key = translation_key
  101. self._attr_unique_id = f"{entry.entry_id}_{slot}_{field}"
  102. self._attr_device_info = device_info
  103. self._attr_icon = icon
  104. def _reservation(self) -> ReservationData:
  105. data: CoordinatorData = self.coordinator.data
  106. return data.current if self._slot == STORE_CURRENT else data.next
  107. class ReservationStrSensor(_ReservationSensor):
  108. @property
  109. def native_value(self) -> str | None:
  110. return getattr(self._reservation(), self._field)
  111. class GuestNameSensor(ReservationStrSensor):
  112. @property
  113. def extra_state_attributes(self) -> dict[str, str | None] | None:
  114. full: str | None = self._reservation().guest_name
  115. if full is None:
  116. return None
  117. parts = full.split()
  118. first_name = parts[0]
  119. last_name = parts[len(parts) - 1] if len(parts) > 1 else None
  120. first_abbr = first_name[0].upper() if first_name else None
  121. last_abbr = last_name[0].upper() if last_name else None
  122. public = f"{first_name} {last_abbr}." if last_abbr else full
  123. return {
  124. "first_name": first_name,
  125. "first_abbr": first_abbr,
  126. "last_name": last_name,
  127. "last_abbr": last_abbr,
  128. "public": public,
  129. }
  130. _WIFI_QR_ESCAPE_RE = re.compile(r'([\\;,:"])')
  131. def _wifi_qr_escape(value: str) -> str:
  132. """Escape special characters in a WiFi QR field per the de-facto MECARD-style spec."""
  133. return _WIFI_QR_ESCAPE_RE.sub(r"\\\1", value)
  134. class WiFiKeySensor(_ReservationSensor):
  135. def __init__(self, coordinator, entry, slot, device_info) -> None:
  136. super().__init__(coordinator, entry, slot, device_info, "wifi_key", "wifi_key", "mdi:wifi-lock")
  137. @property
  138. def native_value(self) -> str | None:
  139. return self._reservation().wifi_key
  140. @property
  141. def extra_state_attributes(self) -> dict[str, str] | None:
  142. res = self._reservation()
  143. if res.wifi_ssid is None or res.wifi_key is None:
  144. return None
  145. ssid = _wifi_qr_escape(res.wifi_ssid)
  146. if res.wifi_key == "":
  147. return {"qr": f"WIFI:S:{ssid};T:nopass;;"}
  148. key = _wifi_qr_escape(res.wifi_key)
  149. return {"qr": f"WIFI:S:{ssid};T:WPA;P:{key};;"}
  150. class ReservationTimeSensor(_ReservationSensor):
  151. """Time sensor. HA has no TIME device class for sensors; we expose as string ISO."""
  152. @property
  153. def native_value(self) -> str | None:
  154. val: time | None = getattr(self._reservation(), self._field)
  155. return val.isoformat() if val is not None else None
  156. def _dt_attrs(dt: datetime) -> dict[str, str]:
  157. _h12 = dt.hour % 12 or 12
  158. _pad = " " if _h12 < 10 else ""
  159. return {
  160. "datetime": dt.isoformat(),
  161. "datetime_abbr": dt.strftime("%Y-%m-%d @ %-I %p"),
  162. "date": dt.strftime("%Y-%m-%d"),
  163. "date_weekday": dt.strftime("%a, %b %-d"),
  164. "datetime_weekday_pad": f"{dt.strftime('%a, %b %-d @')} {_pad}{_h12} {dt.strftime('%p')}",
  165. "time": dt.strftime("%H:%M:%S"),
  166. "time_abbr": dt.strftime("%H:%M"),
  167. "hour": dt.strftime("%-I %p"),
  168. "weekday": dt.strftime("%A"),
  169. "weekday_abbr": dt.strftime("%a"),
  170. "month": dt.strftime("%B"),
  171. "month_abbr": dt.strftime("%b"),
  172. }
  173. class ReservationDateTimeSensor(_ReservationSensor):
  174. """Date sensor that also exposes combined datetime attributes."""
  175. _attr_device_class = SensorDeviceClass.DATE
  176. def __init__(
  177. self,
  178. coordinator: RoomCalCoordinator,
  179. entry: ConfigEntry,
  180. slot: str,
  181. device_info: DeviceInfo,
  182. name: str,
  183. field: str,
  184. time_field: str,
  185. icon: str | None = None,
  186. ) -> None:
  187. super().__init__(coordinator, entry, slot, device_info, name, field, icon)
  188. self._time_field = time_field
  189. @property
  190. def native_value(self) -> date | None:
  191. return getattr(self._reservation(), self._field)
  192. @property
  193. def extra_state_attributes(self) -> dict[str, str] | None:
  194. res = self._reservation()
  195. d: date | None = getattr(res, self._field)
  196. t: time | None = getattr(res, self._time_field)
  197. if d is None or t is None:
  198. return None
  199. return _dt_attrs(datetime.combine(d, t))
  200. class LastUpdatedSensor(CoordinatorEntity[RoomCalCoordinator], SensorEntity):
  201. _attr_has_entity_name = True
  202. _attr_translation_key = "last_updated"
  203. _attr_device_class = SensorDeviceClass.TIMESTAMP
  204. _attr_icon = "mdi:clock-edit-outline"
  205. _attr_entity_category = EntityCategory.DIAGNOSTIC
  206. def __init__(
  207. self,
  208. coordinator: RoomCalCoordinator,
  209. entry: ConfigEntry,
  210. slot: str,
  211. device_info: DeviceInfo,
  212. ) -> None:
  213. super().__init__(coordinator)
  214. self._slot = slot
  215. self._attr_unique_id = f"{entry.entry_id}_{slot}_last_updated"
  216. self._attr_device_info = device_info
  217. @property
  218. def native_value(self) -> datetime | None:
  219. data: CoordinatorData = self.coordinator.data
  220. return (
  221. data.current_last_updated
  222. if self._slot == STORE_CURRENT
  223. else data.next_last_updated
  224. )
  225. @property
  226. def extra_state_attributes(self) -> dict:
  227. data: CoordinatorData = self.coordinator.data
  228. refresh = (
  229. data.current_last_refresh
  230. if self._slot == STORE_CURRENT
  231. else data.next_last_refresh
  232. )
  233. return {"last_refresh": refresh}
  234. class ActiveLastUpdatedSensor(CoordinatorEntity[RoomCalCoordinator], SensorEntity):
  235. """Last time the live/active record changed — distinct from the Current device's
  236. LastUpdatedSensor, which only tracks the backend-mirror feed and never reflects
  237. override/patch activity."""
  238. _attr_has_entity_name = True
  239. _attr_translation_key = "active_last_updated"
  240. _attr_device_class = SensorDeviceClass.TIMESTAMP
  241. _attr_icon = "mdi:clock-edit-outline"
  242. _attr_entity_category = EntityCategory.DIAGNOSTIC
  243. def __init__(
  244. self,
  245. coordinator: RoomCalCoordinator,
  246. entry: ConfigEntry,
  247. device_info: DeviceInfo,
  248. ) -> None:
  249. super().__init__(coordinator)
  250. self._attr_unique_id = f"{entry.entry_id}_active_last_updated"
  251. self._attr_device_info = device_info
  252. @property
  253. def native_value(self) -> datetime | None:
  254. return self.coordinator.data.active_last_updated
  255. @property
  256. def extra_state_attributes(self) -> dict:
  257. return {"last_refresh": self.coordinator.data.active_last_refresh}
  258. class ApiHealthSensor(CoordinatorEntity[RoomCalCoordinator], SensorEntity):
  259. _attr_has_entity_name = True
  260. _attr_translation_key = "api_health"
  261. _attr_icon = "mdi:api"
  262. _attr_entity_category = EntityCategory.DIAGNOSTIC
  263. def __init__(
  264. self,
  265. coordinator: RoomCalCoordinator,
  266. entry: ConfigEntry,
  267. device_info: DeviceInfo,
  268. ) -> None:
  269. super().__init__(coordinator)
  270. self._attr_unique_id = f"{entry.entry_id}_api_health"
  271. self._attr_device_info = device_info
  272. @property
  273. def native_value(self) -> str | None:
  274. api_status = self.coordinator.data.api_status
  275. if api_status is None:
  276. return None
  277. return "OK" if api_status.status == "ok" else "Degraded"
  278. @property
  279. def extra_state_attributes(self) -> dict | None:
  280. api_status = self.coordinator.data.api_status
  281. if api_status is None:
  282. return None
  283. attrs: dict = {
  284. "stale": api_status.stale,
  285. "checked_at": api_status.checked_at.isoformat() if api_status.checked_at else None,
  286. }
  287. for key, val in api_status.checks.items():
  288. if key == "credentials" and isinstance(val, dict):
  289. for svc_key, svc_val in val.items():
  290. attrs[svc_key] = svc_val.get("ok") if isinstance(svc_val, dict) else svc_val
  291. elif isinstance(val, dict):
  292. attrs[key] = val.get("ok")
  293. else:
  294. attrs[key] = val
  295. return attrs