Debian Codegraph @

asusrouter/modules/homeassistant.py

raw
1 """Home Assistant module for AsusRouter.
2
3 This module is used to convert some of the AsusRouter data
4 to a format easy to handle by Home Assistant integration.
5
6 Native AsusRouter integration: https://github.com/vaskivskyi/ha-asusrouter.
7 """
8
9 from __future__ import annotations
10
11 from enum import Enum
12 import logging
13 from typing import Any
14
15 from asusrouter.modules.data import AsusData
16 from asusrouter.modules.state import AsusState
17 from asusrouter.modules.vpnc import AsusVPNC
18 from asusrouter.tools.converters import flatten_dict, list_from_dict
19
20 _LOGGER = logging.getLogger(__name__)
21
22 SENSORS_CPU = ["total", "usage", "used"]
23 SENSORS_NETWORK = ["rx", "rx_speed", "tx", "tx_speed"]
24 SENSORS_VPN = {
25 "client": [
26 "state",
27 "remote",
28 "datetime",
29 "tun_tap_read",
30 "tun_tap_write",
31 "tcp_udp_read",
32 "tcp_udp_write",
33 "auth_read",
34 "pre_compress",
35 "post_compress",
36 "pre_decompress",
37 "post_decompress",
38 ],
39 "server": ["state", "client_list", "routing_table"],
40 }
41
42
43 def convert_to_ha_sensors(
44 data: dict[str, Any], datatype: AsusData
45 ) -> list[str]:
46 """Convert available data.
47
48 The result is a list of sensors compatible with Home Assistant.
49 """
50
51 sensors = []
52
53 match datatype:
54 case AsusData.CPU:
55 sensors = convert_to_ha_sensors_by_map(data, SENSORS_CPU)
56 case AsusData.NETWORK:
57 sensors = convert_to_ha_sensors_by_map(data, SENSORS_NETWORK)
58 case AsusData.OPENVPN:
59 sensors = convert_to_ha_sensors_by_map_2(data, SENSORS_VPN)
60 # case AsusData.PORTS:
61 case _:
62 sensors = convert_to_ha_sensors_list(data)
63
64 return sensors
65
66
67 def convert_to_ha_data(data: dict[str, Any]) -> dict[str, Any]:
68 """Convert available data to the HA-compatible dictionary."""
69
70 def convert_recursive(data: dict[str, Any]) -> dict[str, Any]:
71 """Convert data to the HA-compatible dictionary recursively."""
72 return {
73 key: convert_recursive(value)
74 if isinstance(value, dict)
75 else convert_to_ha_state_bool(value)
76 if key.endswith(("state", "link"))
77 else value
78 for key, value in data.items()
79 }
80
81 # Flatten the dictionary
82 # Skip all the `list`, `clients` etc keys - this data should be preserved
83 output = flatten_dict(data, exclude=["list", "clients", "rules"])
84
85 # Convert values to HA-compatible format
86 if output is not None:
87 return convert_recursive(output)
88
89 return {}
90
91
92 def convert_to_ha_sensors_by_map(
93 data: dict[str, Any], sensor_map: list[str]
94 ) -> list[str]:
95 """Convert available data to the list of sensors using static map."""
96
97 _LOGGER.debug("Converting data to the list of sensors by map: %s", data)
98
99 if not isinstance(data, dict):
100 _LOGGER.warning(
101 "Invalid data format for sensors generation from a map: %s",
102 sensor_map,
103 )
104 return []
105
106 sensors = []
107
108 for sensor in data:
109 sensors.extend(
110 [f"{sensor}_{sensor_type}" for sensor_type in sensor_map]
111 )
112
113 return sensors
114
115
116 def convert_to_ha_sensors_by_map_2(
117 data: dict[str, Any], sensor_map: dict[str, list[str]]
118 ) -> list[str]:
119 """Convert available data to the list of sensors.
120
121 Use first two levels of the data and static map.
122 """
123
124 _LOGGER.debug(
125 "Converting data to the list of sensors by 2 levels: %s", data
126 )
127
128 if not isinstance(data, dict):
129 _LOGGER.warning(
130 "Invalid data format for sensors generation from a map: %s",
131 sensor_map,
132 )
133 return []
134
135 sensors = []
136
137 for sensor, sensor_ids in data.items():
138 sensors.extend(
139 [
140 f"{sensor}_{sensor_id}_{sensor_type}"
141 for sensor_id in sensor_ids
142 for sensor_type in sensor_map.get(sensor, [])
143 ]
144 )
145
146 return sensors
147
148
149 def convert_to_ha_sensors_group(data: dict[str, Any]) -> list[str]:
150 """Convert the top level of data to the list of sensors."""
151
152 return list_from_dict(data)
153
154
155 def convert_to_ha_sensors_list(data: dict[str, Any]) -> list[str]:
156 """Convert all the available data to the list of sensors."""
157
158 return list_from_dict(convert_to_ha_data(data))
159
160
161 def convert_to_ha_state_bool( # noqa: PLR0911
162 data: AsusState | bool | None,
163 ) -> bool | None:
164 """Convers native state to a binary state."""
165
166 # Check whether the state is None
167 if data is None:
168 return None
169
170 # Check whether the state is already a bool
171 if isinstance(data, bool):
172 return data
173
174 # Special cases
175 if isinstance(data, AsusVPNC):
176 match data:
177 case a if a in (
178 AsusVPNC.CONNECTED,
179 AsusVPNC.CONNECTING,
180 AsusVPNC.ON,
181 ):
182 return True
183 case a if a in (
184 AsusVPNC.OFF,
185 AsusVPNC.DISCONNECTED,
186 AsusVPNC.ERROR,
187 ):
188 return False
189 case _:
190 return None
191
192 # Check whether the state is based on (int, Enum)
193 if isinstance(data, int) and isinstance(data, Enum):
194 if data.value == 0:
195 return False
196 if data.value > 0:
197 return True
198 if data.value < 0:
199 return None
200
201 return None
202
203
204 def convert_to_ha_string(data: Any) -> str:
205 """Convert data to a string."""
206
207 # Check if we have None
208 if data is None:
209 return ""
210
211 # If we have an enum
212 # Check whether value is an enum or a string
213 # If string, return it, if enum, go recursive
214 if isinstance(data, Enum):
215 return convert_to_ha_string(data.value)
216
217 # Check if we have string
218 if isinstance(data, str):
219 return data
220
221 # For any other type, return string representation
222 return str(data)