Home Assistant Unofficial Reference 2024.12.1
support.py
Go to the documentation of this file.
1 """Support for config validation using voluptuous and Translate Trigger."""
2 
3 from __future__ import annotations
4 
5 import calendar
6 import locale
7 import re
8 from typing import Any
9 
10 import voluptuous as vol
11 
12 
13 def wilight_trigger(value: Any) -> str | None:
14  """Check rules for WiLight Trigger."""
15  step = 1
16  err_desc = "Value is None"
17  result_128 = False
18  result_24 = False
19  result_60 = False
20  result_2 = False
21 
22  if value is not None:
23  step = 2
24  err_desc = "Expected a string"
25 
26  if (step == 2) & isinstance(value, str):
27  step = 3
28  err_desc = "String should only contain 8 decimals character"
29  if re.search(r"^([0-9]{8})$", value) is not None:
30  step = 4
31  err_desc = "First 3 character should be less than 128"
32  result_128 = int(value[0:3]) < 128
33  result_24 = int(value[3:5]) < 24
34  result_60 = int(value[5:7]) < 60
35  result_2 = int(value[7:8]) < 2
36 
37  if (step == 4) & result_128:
38  step = 5
39  err_desc = "Hour part should be less than 24"
40 
41  if (step == 5) & result_24:
42  step = 6
43  err_desc = "Minute part should be less than 60"
44 
45  if (step == 6) & result_60:
46  step = 7
47  err_desc = "Active part should be less than 2"
48 
49  if (step == 7) & result_2:
50  return value
51 
52  raise vol.Invalid(err_desc)
53 
54 
55 def wilight_to_hass_trigger(value: str | None) -> str | None:
56  """Convert wilight trigger to hass description.
57 
58  Ex: "12719001" -> "sun mon tue wed thu fri sat 19:00 On"
59  "00000000" -> "00:00 Off"
60  """
61  if value is None:
62  return value
63 
64  locale.setlocale(locale.LC_ALL, "")
65  week_days = list(calendar.day_abbr)
66  days = bin(int(value[0:3]))[2:].zfill(8)
67  desc = ""
68  if int(days[7:8]) == 1:
69  desc += f"{week_days[6]} "
70  if int(days[6:7]) == 1:
71  desc += f"{week_days[0]} "
72  if int(days[5:6]) == 1:
73  desc += f"{week_days[1]} "
74  if int(days[4:5]) == 1:
75  desc += f"{week_days[2]} "
76  if int(days[3:4]) == 1:
77  desc += f"{week_days[3]} "
78  if int(days[2:3]) == 1:
79  desc += f"{week_days[4]} "
80  if int(days[1:2]) == 1:
81  desc += f"{week_days[5]} "
82  desc += f"{value[3:5]}:{value[5:7]} "
83  if int(value[7:8]) == 1:
84  desc += "On"
85  else:
86  desc += "Off"
87 
88  return desc
str|None wilight_to_hass_trigger(str|None value)
Definition: support.py:55
str|None wilight_trigger(Any value)
Definition: support.py:13