Home Assistant Unofficial Reference 2024.12.1
helper.py
Go to the documentation of this file.
1 """Helper functions for swiss_public_transport."""
2 
3 from datetime import timedelta
4 from types import MappingProxyType
5 from typing import Any
6 
7 from opendata_transport import OpendataTransport
8 
9 import homeassistant.util.dt as dt_util
10 
11 from .const import (
12  CONF_DESTINATION,
13  CONF_START,
14  CONF_TIME_FIXED,
15  CONF_TIME_OFFSET,
16  CONF_TIME_STATION,
17  CONF_VIA,
18  DEFAULT_TIME_STATION,
19 )
20 
21 
22 def offset_opendata(opendata: OpendataTransport, offset: dict[str, int]) -> None:
23  """In place offset the opendata connector."""
24 
25  duration = timedelta(**offset)
26  if duration:
27  now_offset = dt_util.as_local(dt_util.now() + duration)
28  opendata.date = now_offset.date()
29  opendata.time = now_offset.time()
30 
31 
33  d: dict[str, int],
34 ) -> str:
35  """Build a string from a dict duration."""
36  return f"{d['hours']:02d}:{d['minutes']:02d}:{d['seconds']:02d}"
37 
38 
39 def unique_id_from_config(config: MappingProxyType[str, Any] | dict[str, Any]) -> str:
40  """Build a unique id from a config entry."""
41  return (
42  f"{config[CONF_START]} {config[CONF_DESTINATION]}"
43  + (
44  " via " + ", ".join(config[CONF_VIA])
45  if CONF_VIA in config and len(config[CONF_VIA]) > 0
46  else ""
47  )
48  + (
49  " arrival"
50  if config.get(CONF_TIME_STATION, DEFAULT_TIME_STATION) == "arrival"
51  else ""
52  )
53  + (" at " + config[CONF_TIME_FIXED] if CONF_TIME_FIXED in config else "")
54  + (
55  " in " + dict_duration_to_str_duration(config[CONF_TIME_OFFSET])
56  if CONF_TIME_OFFSET in config
57  else ""
58  )
59  )
None offset_opendata(OpendataTransport opendata, dict[str, int] offset)
Definition: helper.py:22
str unique_id_from_config(MappingProxyType[str, Any]|dict[str, Any] config)
Definition: helper.py:39