1
0
ZiB 5 mesiacov pred
rodič
commit
59ae453a84

+ 36 - 20
README.md

@@ -2,30 +2,46 @@
 
 ## Guest reservation integration for Home Assistant
 
-##### This integration uses the modern configuration UI and provides any number of devices with entities for:
+##### This integration provides any number of devices with entities for:
 
 - Guest name
 - Door code
-- Arrival date
-- Departure date
-- WiFi name
+- Arrival
+	- datetime `%Y-%m-%d %H-%M-%S`
+	- datetime_abbr `%Y-%m-%d @ %-I %p`
+	- date `%Y-%m-%d`
+	- date_weekday `%a, %b %-d`
+	- datetime_weekday `%a, %b %-d @ %-I %p`
+	- time `%H:%M:%S`
+	- time_abbr `%H:%M`
+	- hour `%-I %p`
+	- weekday `%A`
+	- weekday_abbr `%a`
+	- month `%B`
+	- month_abbr `%b`
+- Departure
+	- [Same attributes as Arrival]
+- Check in time
+	- [Used in Arrival time attributes]
+- Check out time
+	- [Used in Departure time attributes]
+- WiFi SSID
 - WiFi key
-- WiFi QR code
+	- qr `'WIFI:S:' + <wifi_ssid> + ';T:WPA;P:' + <wifi_key> + ';;'`
 
-All entites are settable with service calls (or derived automatically from settable fields) for easy use from other parts of HA, or from the 
-WebSocket/REST API
+I use this data to feed both guest-facing displays, where guests can see WiFi and other information about their own
+reservation, and for backend systems that tell me about upcoming reservations or control automations in relation to
+the reservation state
 
-I use the data to feed both guest-facing displays, like a ePaper display for the WiFi information and for labeling the guest's door. I also feed my own 
-displays so I know when the next guest is arriving and how long they will be staying
+All entites are settable via a service call. I use an external program connected via the WS API to update these sensors
+based on my rental calendar and other external data. There are many ways this data could come into HA, but I wanted to
+use the WS API specifically for a number of reasons: it has an active connection so I'll know right away when HA
+disconnects, it uses simple tokens for auth, clients for several programming environments already exist, I can publish
+from anywhere that can reach the frontend HTTP instance
 
-I use an external program connected via the WS API to update these sensors based on my rental calendar and other external databases. It would be 
-possible to do something similar with existing integrations; for example the mobile_app integration allows publishing sensors. For that matter the REST 
-API (but not the WS API) can construct (ephemeral) states out of thin air. But I wanted something with all the modern UI tooling, that I could feed via 
-the WS API for easy secure access from remote systems, so I wrote this
-
-This project also covers at least the miminal parts required to build async push sensors, config_flow UI, and service calls for any HA integration, if 
-you're looking to build something for yourself. The HA team [publishes examples](https://github.com/home-assistant/example-custom-config/tree/master) of 
-many parts of the integration framework. If you just want a basic integration for a simple sensor it's not a lot of work. If you want to support all the 
-modern features like config_flow and async push updates it's still very usable but not as straightforward. You'll want to start with the 
-[detailed_hello_world_push example](https://github.com/home-assistant/example-custom-config/tree/master/custom_components/detailed_hello_world_push), or 
-with a repo like this one
+This project also covers at least the minimal parts required for any HA integration to publish async push sensors, add
+extra attributes, use the config_flow UI, and receive service calls. Feel free to use it as an example if you are working
+on your own integration. The HA team also [publishes 
+examples](https://github.com/home-assistant/example-custom-config/tree/master) of many parts of the integration framework. 
+If you want all the modern features start with the [detailed_hello_world_push 
+example](https://github.com/home-assistant/example-custom-config/tree/master/custom_components/detailed_hello_world_push)

+ 59 - 0
custom_components/zib_guest/__init__.py

@@ -0,0 +1,59 @@
+from __future__ import annotations
+from homeassistant.core import HomeAssistant, callback
+from homeassistant.const import Platform
+from homeassistant.config_entries import ConfigEntry
+from homeassistant.helpers.device import async_entity_id_to_device
+from homeassistant.helpers.device_registry import DATA_REGISTRY
+from homeassistant.helpers.entity_component import DATA_INSTANCES
+
+from .reservation import Reservation
+from .const import DOMAIN, PLATFORMS, RESERVATION_FIELDS
+type ZiBConfigEntry = ConfigEntry[Reservation]
+
+async def async_setup_entry(hass: HomeAssistant, entry: ZiBConfigEntry) -> bool:
+  entry.runtime_data = Reservation(hass, entry.data["Name"])
+  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
+  return True
+
+async def async_unload_entry(hass: HomeAssistant, entry: ZiBConfigEntry) -> bool:
+  unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
+  return unload_ok
+
+async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
+  @callback
+  async def get_reservations(devices, entities) -> list:
+    reservations = []
+
+    if devices:
+      for device in devices:
+        dev = hass.data[DATA_REGISTRY].async_get(device)
+        if not dev:
+          continue
+        conf = hass.config_entries.async_get_entry(dev.primary_config_entry)
+        if not conf:
+          continue
+        reservations.append(conf.runtime_data)
+
+    if entities:
+      for entity in hass.data[DATA_INSTANCES][Platform.SENSOR].entities:
+        if entity.entity_id in entities:
+          reservations.append(entity.platform.config_entry.runtime_data)
+
+    for res in reservations:
+      if not isinstance(res, Reservation):
+        reservations.remove(res);
+
+    return reservations
+
+  @callback
+  async def set_reservation(call: ServiceCall) -> None:
+    reservations = await get_reservations(call.data.get('device_id'), call.data.get('entity_id'))
+    for res in reservations:
+      for field in RESERVATION_FIELDS:
+        value = call.data.get(field)
+        if value is not None:
+          res.set(field, value)
+      await res.publish_updates()
+  hass.services.async_register(DOMAIN, 'set_reservation', set_reservation)
+
+  return True

BIN
custom_components/zib_guest/brand/icon.png


BIN
custom_components/zib_guest/brand/icon@2x.png


+ 36 - 0
custom_components/zib_guest/config_flow.py

@@ -0,0 +1,36 @@
+from __future__ import annotations
+import voluptuous as vol
+from homeassistant import config_entries, exceptions
+from homeassistant.core import HomeAssistant
+
+from .const import DOMAIN  # pylint:disable=unused-import
+from .reservation import Reservation
+
+DATA_SCHEMA = vol.Schema({("Name"): str})
+
+class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
+  VERSION = 1
+  CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_PUSH
+
+  async def async_step_user(self, user_input=None):
+    errors = {}
+    if user_input is not None:
+      try:
+        reservation = Reservation(self.hass, user_input['Name'])
+        for entry in self._async_current_entries():
+          if entry.title == reservation.name:
+            raise DuplicateConfig
+
+        return self.async_create_entry(title=reservation.name, data=user_input)
+      except DuplicateConfig:
+        errors["base"] = "Duplicate reservation name"
+      except Exception:  # pylint: disable=broad-except
+        errors["base"] = "Unexpected exception"
+
+    # Re-prompt if validation failed
+    return self.async_show_form(
+      step_id="user", data_schema=DATA_SCHEMA, errors=errors
+    )
+
+class DuplicateConfig(exceptions.HomeAssistantError):
+    """Duplicated entity ID"""

+ 11 - 0
custom_components/zib_guest/const.py

@@ -0,0 +1,11 @@
+from homeassistant.const import Platform
+
+DOMAIN = "zib_guest"
+PLATFORMS = [Platform.SENSOR]
+
+RESERVATION_FIELDS = [
+  'guest_name', 'door_code',
+  'arrival', 'departure',
+  'check_in', 'check_out',
+  'wifi_ssid', 'wifi_key',
+]

+ 14 - 0
custom_components/zib_guest/manifest.json

@@ -0,0 +1,14 @@
+{
+  "domain": "zib_guest",
+  "name": "ZiB Guest",
+  "codeowners": [],
+  "config_flow": true,
+  "dependencies": [],
+  "documentation": "",
+  "homekit": {},
+  "iot_class": "local_push",
+  "requirements": [],
+  "ssdp": [],
+  "version": "0.5.0",
+  "zeroconf": []
+}

+ 75 - 0
custom_components/zib_guest/reservation.py

@@ -0,0 +1,75 @@
+from __future__ import annotations
+import asyncio, datetime
+from homeassistant.core import HomeAssistant
+
+from .const import RESERVATION_FIELDS
+
+class Reservation:
+  def __init__(self, hass: HomeAssistant, name: str) -> None:
+    self._hass = hass
+    self._loop = asyncio.get_event_loop()
+    self._callbacks = set()
+
+    self._id = name.lower().replace(' ', '_')
+    self._name = name
+    self._online = True
+
+    self._data = {}
+    for field in RESERVATION_FIELDS:
+      self._data[field] = None
+
+  def register_callback(self, callback: Callable[[], None]) -> None:
+    self._callbacks.add(callback)
+  def remove_callback(self, callback: Callable[[], None]) -> None:
+    self._callbacks.discard(callback)
+  async def publish_updates(self) -> None:
+    for callback in self._callbacks:
+      callback()
+
+  @property
+  def id(self) -> str:
+    return self._id
+  @property
+  def name(self) -> str:
+    return self._name
+  @property
+  def online(self) -> bool:
+    """ TODO: Expire or something """
+    return self._online
+
+  @property
+  def guest_name(self) -> str:
+    return self._data['guest_name']
+  @property
+  def door_code(self) -> str:
+    return self._data['door_code']
+
+  @property
+  def arrival(self) -> str:
+    return self._data['arrival'].isoformat()
+  @property
+  def departure(self) -> str:
+    return self._data['departure'].isoformat()
+
+  @property
+  def check_in(self) -> str:
+    return self._data['check_in'].isoformat()
+  @property
+  def check_out(self) -> str:
+    return self._data['check_out'].isoformat()
+
+  @property
+  def wifi_ssid(self) -> str:
+    return self._data['wifi_ssid']
+  @property
+  def wifi_key(self) -> str:
+    return self._data['wifi_key']
+
+  def set(self, field, value):
+    if field not in RESERVATION_FIELDS:
+      raise KeyError(f'Unknown field: {field}')
+    if field in ['arrival', 'departure']:
+      value = datetime.date.fromisoformat(value)
+    elif field in ['check_in', 'check_out']:
+      value = datetime.time.fromisoformat(value)
+    self._data[field] = value

+ 141 - 0
custom_components/zib_guest/sensor.py

@@ -0,0 +1,141 @@
+from homeassistant.core import HomeAssistant
+from homeassistant.helpers.entity import Entity
+from homeassistant.helpers.entity_platform import AddEntitiesCallback
+from homeassistant.components.sensor import SensorDeviceClass
+import datetime
+
+from . import ZiBConfigEntry
+from .const import DOMAIN
+
+async def async_setup_entry(
+  hass: HomeAssistant,
+  config_entry: ZiBConfigEntry,
+  async_add_entities: AddEntitiesCallback,
+) -> None:
+  reservation = config_entry.runtime_data
+  entities = []
+  entities.append(Guest_Name(reservation))
+  entities.append(Door_Code(reservation))
+  entities.append(Arrival(reservation))
+  entities.append(Departure(reservation))
+  entities.append(Check_In(reservation))
+  entities.append(Check_Out(reservation))
+  entities.append(WiFi_SSID(reservation))
+  entities.append(WiFi_Key(reservation))
+  async_add_entities(entities)
+
+class ZiBBase(Entity):
+  should_poll = False
+  _attr_has_entity_name = True
+
+  def __init__(self, reservation: Reservation, name: str, icon: str = None):
+    self._reservation = reservation
+    self._name = name
+    self._icon = icon
+    self._id = name.lower().replace(' ', '_')
+    self._attr_unique_id = f"{self._reservation.id}_{self._id}"
+    self._attr_name = self._name
+
+    # Fake in some values for testing
+    self._reservation.set('guest_name', 'Veronica')
+    self._reservation.set('door_code',  '0217')
+    self._reservation.set('arrival',    '2026-05-29')
+    self._reservation.set('departure',  '2026-05-30')
+    self._reservation.set('check_in',   '14:00:00')
+    self._reservation.set('check_out',  '12:00:00')
+    self._reservation.set('wifi_ssid',  '4114')
+    self._reservation.set('wifi_key',   'pioneer-plato-carmen')
+
+  async def async_added_to_hass(self):
+    self._reservation.register_callback(self.async_write_ha_state)
+  async def async_will_remove_from_hass(self):
+    self._reservation.remove_callback(self.async_write_ha_state)
+
+  def date_parts(self, dt: datetime) -> dict:
+    return {
+      'datetime': dt.isoformat(),
+      'datetime_abbr': dt.strftime('%Y-%m-%d @ %-I %p'),
+      'date': dt.strftime('%Y-%m-%d'),
+      'date_weekday': dt.strftime('%a, %b %-d'),
+      'datetime_weekday': dt.strftime('%a, %b %-d @ %-I %p'),
+      'time': dt.strftime('%H:%M:%S'),
+      'time_abbr': dt.strftime('%H:%M'),
+      'hour': dt.strftime('%-I %p'),
+      'weekday': dt.strftime('%A'),
+      'weekday_abbr': dt.strftime('%a'),
+      'month': dt.strftime('%B'),
+      'month_abbr': dt.strftime('%b'),
+    }
+
+  @property
+  def device_info(self):
+    return {"identifiers": {(DOMAIN, self._reservation.id)}}
+  @property
+  def available(self) -> bool:
+    return self._reservation.online
+  @property
+  def state(self):
+    return self._reservation._data[self._id]
+  @property
+  def icon(self):
+    return self._icon
+
+class Guest_Name(ZiBBase):
+  def __init__(self, reservation: Reservation):
+    super().__init__(reservation, 'Guest Name', 'mdi:account-convert')
+    self._attr_name = None # Make Guest_Name the eponymous attribute
+  # Add device-level info (i.e. name) to Guest_Name
+  @property
+  def device_info(self) -> DeviceInfo:
+    return super().device_info | {
+      "name": self._reservation.name,
+    }
+
+class Door_Code(ZiBBase):
+  def __init__(self, reservation):
+    super().__init__(reservation, 'Door Code', 'mdi:door-closed-lock')
+
+class Arrival(ZiBBase):
+  def __init__(self, reservation):
+    super().__init__(reservation, 'Arrival', 'mdi:calendar-start')
+    self._attr_device_class = SensorDeviceClass.DATE
+  @property
+  def extra_state_attributes(self):
+    dt = datetime.datetime.fromisoformat(
+        self._reservation.arrival +
+        ' ' + self._reservation.check_in
+      )
+    return self.date_parts(dt)
+
+class Departure(ZiBBase):
+  def __init__(self, reservation):
+    super().__init__(reservation, 'Departure', 'mdi:calendar-end')
+    self._attr_device_class = SensorDeviceClass.DATE
+  @property
+  def extra_state_attributes(self):
+    dt = datetime.datetime.fromisoformat(
+        self._reservation.departure +
+        ' ' + self._reservation.check_out
+      )
+    return self.date_parts(dt)
+
+class Check_In(ZiBBase):
+  def __init__(self, reservation):
+    super().__init__(reservation, 'Check In', 'mdi:timer-check-outline')
+
+class Check_Out(ZiBBase):
+  def __init__(self, reservation):
+    super().__init__(reservation, 'Check Out', 'mdi:timer-cancel-outline')
+
+class WiFi_SSID(ZiBBase):
+  def __init__(self, reservation):
+    super().__init__(reservation, 'WiFi SSID', 'mdi:wifi')
+
+class WiFi_Key(ZiBBase):
+  def __init__(self, reservation):
+    super().__init__(reservation, 'WiFi Key', 'mdi:wifi-lock')
+  @property
+  def extra_state_attributes(self):
+    return {
+      'qr': 'WIFI:S:' + self._reservation.wifi_ssid + ';T:WPA;P:' + self._reservation.wifi_key + ';;'
+    }

+ 33 - 0
custom_components/zib_guest/services.yaml

@@ -0,0 +1,33 @@
+set_reservation:
+  description: Update any set of reservation fields. Fields not specified will not be updated
+  target:
+    device:
+      integration: zib_guest
+    entity:
+      integration: zib_guest
+      domain: sensor
+  fields:
+    guest_name:
+      name: Name
+      selector: { text: }
+    door_code:
+      name: Door Code
+      selector: { text: }
+    arrival:
+      name: Arrival
+      selector: { date: }
+    departure:
+      name: Depature
+      selector: { date: }
+    check_in:
+      name: Check In
+      selector: { time: }
+    check_out:
+      name: Check Out
+      selector: { time: }
+    wifi_ssid:
+      name: WiFi SSID
+      selector: { text: }
+    wifi_key:
+      name: WiFi Key
+      selector: { text: }