@jessicaisleep/dsh-mihome 1.0.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +141 -78
- package/client.js +1149 -19
- package/cordis.patch.yml +2 -2
- package/docs/REPAIR-VALIDATION.md +62 -0
- package/lib/bridge.js +126 -44
- package/lib/connections.js +46 -0
- package/lib/format.js +148 -0
- package/lib/index.js +274 -31
- package/lib/panel.js +138 -7
- package/locale/en.json +3 -3
- package/locale/zh.json +2 -2
- package/package.json +13 -4
- package/python/app/core/service.py +62 -31
- package/python/mihome_bridge.py +211 -9
- package/python/smart_home/__init__.py +24 -0
- package/python/smart_home/adapters/__init__.py +50 -0
- package/python/smart_home/adapters/base.py +143 -0
- package/python/smart_home/adapters/ble.py +100 -0
- package/python/smart_home/adapters/dlna.py +227 -0
- package/python/smart_home/adapters/home_assistant.py +454 -0
- package/python/smart_home/adapters/hue.py +225 -0
- package/python/smart_home/adapters/kasa.py +239 -0
- package/python/smart_home/adapters/mihome.py +342 -0
- package/python/smart_home/adapters/network.py +250 -0
- package/python/smart_home/adapters/shelly.py +289 -0
- package/python/smart_home/adapters/tuya.py +95 -0
- package/python/smart_home/adapters/tv.py +26 -0
- package/python/smart_home/catalog.py +336 -0
- package/python/smart_home/cloud.py +85 -0
- package/python/smart_home/discovery.py +934 -0
- package/python/smart_home/localize.py +787 -0
- package/python/smart_home/manager.py +672 -0
- package/python/smart_home/oui_table.py +40550 -0
- package/python/smart_home/scan.py +73 -0
- package/python/smart_home/test_discovery_repairs.py +186 -0
- package/python/smart_home/test_localization_repairs.py +229 -0
- package/python/smart_home/test_offline.py +195 -0
- package/python/smart_home/test_repairs.py +107 -0
- package/python/smart_home/util.py +320 -0
- package/python/tests/test_bridge_integration.py +108 -0
- package/python/tests/test_ha_discovery.py +260 -0
- package/python/tests/test_home_assistant.py +365 -0
- package/python/tests/test_manager_integration.py +150 -0
- package/python/tests/test_mihome_repairs.py +117 -0
- package/python/tests/test_network_read_contract.py +50 -0
- package/python/tests/test_power_confirmation.py +95 -0
- package/python/tests/test_protocol_repairs.py +369 -0
- package/python/tests/test_yeelight_repairs.py +70 -0
- package/requirements-optional.txt +4 -0
- package/requirements.txt +5 -0
- package/scripts/update-oui.py +108 -0
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
2
|
+
"""Home Assistant REST bridge, with entity and service verified capabilities.
|
|
3
|
+
|
|
4
|
+
Connection: flat config ``base_url`` / optional ``entity_id`` / ``timeout``;
|
|
5
|
+
private ``device.credentials`` supplies ``token`` (and may supply base_url).
|
|
6
|
+
A hub has no entity_id. ``discover_entities`` returns public records suitable for
|
|
7
|
+
manager expansion; manager must inherit the connection and credential reference.
|
|
8
|
+
|
|
9
|
+
References: https://developers.home-assistant.io/docs/api/rest/
|
|
10
|
+
Feature flags: home-assistant/core homeassistant/components/*/const.py.
|
|
11
|
+
No POST /api/states: that endpoint cannot control a physical device.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import asyncio
|
|
16
|
+
from copy import deepcopy
|
|
17
|
+
import math
|
|
18
|
+
import re
|
|
19
|
+
from urllib.parse import urlsplit, urlunsplit
|
|
20
|
+
|
|
21
|
+
from .. import catalog
|
|
22
|
+
from .base import BaseAdapter, register
|
|
23
|
+
|
|
24
|
+
_ENTITY = re.compile(r"^[a-z0-9_]+\.[a-z0-9_]+$")
|
|
25
|
+
_CATEGORIES = {
|
|
26
|
+
'light': 'light', 'switch': 'switch', 'input_boolean': 'switch', 'fan': 'fan',
|
|
27
|
+
'climate': 'air_conditioner', 'cover': 'curtain', 'media_player': 'tv',
|
|
28
|
+
'vacuum': 'vacuum', 'lock': 'lock', 'humidifier': 'humidifier',
|
|
29
|
+
'sensor': 'sensor', 'binary_sensor': 'sensor',
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _number(value):
|
|
34
|
+
if isinstance(value, bool):
|
|
35
|
+
raise ValueError('Home Assistant value must be a finite number')
|
|
36
|
+
try:
|
|
37
|
+
result = float(value)
|
|
38
|
+
except (TypeError, ValueError):
|
|
39
|
+
raise ValueError('Home Assistant value must be a finite number') from None
|
|
40
|
+
if not math.isfinite(result):
|
|
41
|
+
raise ValueError('Home Assistant value must be a finite number')
|
|
42
|
+
return int(result) if result.is_integer() else result
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _numeric_read(value):
|
|
46
|
+
if value is None:
|
|
47
|
+
return None
|
|
48
|
+
try:
|
|
49
|
+
return _number(value)
|
|
50
|
+
except ValueError:
|
|
51
|
+
return None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@register
|
|
55
|
+
class HomeAssistantAdapter(BaseAdapter):
|
|
56
|
+
protocol = 'home_assistant'
|
|
57
|
+
platform = 'home_assistant'
|
|
58
|
+
|
|
59
|
+
def _entity_id(self) -> str:
|
|
60
|
+
fields = getattr(self.device, 'fields', {}) or {}
|
|
61
|
+
entity = fields.get('entity_id') or getattr(self.device, 'entity_id', '')
|
|
62
|
+
if not entity:
|
|
63
|
+
explicit = getattr(self.device, 'id', '') or getattr(self.device, 'did', '')
|
|
64
|
+
suffix = str(explicit).removeprefix('home_assistant:')
|
|
65
|
+
entity = suffix if _ENTITY.fullmatch(suffix) else ''
|
|
66
|
+
# A child's identity is authoritative over inherited hub configuration.
|
|
67
|
+
entity = entity or self.config.get('entity_id') or ''
|
|
68
|
+
if entity and not _ENTITY.fullmatch(str(entity)):
|
|
69
|
+
raise ValueError('Invalid Home Assistant entity_id')
|
|
70
|
+
return str(entity or '')
|
|
71
|
+
|
|
72
|
+
def _connection(self) -> tuple[str, str, float]:
|
|
73
|
+
credentials = getattr(self.device, 'credentials', {}) or {}
|
|
74
|
+
base = self.config.get('base_url') or credentials.get('base_url') or ''
|
|
75
|
+
token = credentials.get('token') or self.config.get('token') or ''
|
|
76
|
+
try:
|
|
77
|
+
parts = urlsplit(str(base))
|
|
78
|
+
valid = parts.scheme in ('http', 'https') and parts.hostname and not (parts.username or parts.password or parts.query or parts.fragment)
|
|
79
|
+
_ = parts.port
|
|
80
|
+
except ValueError:
|
|
81
|
+
valid = False
|
|
82
|
+
if not valid:
|
|
83
|
+
raise ValueError('Home Assistant requires an http(s) base_url without credentials or query')
|
|
84
|
+
if not isinstance(token, str) or not token.strip() or '\n' in token or '\r' in token:
|
|
85
|
+
raise ValueError('Home Assistant requires a token in private credentials')
|
|
86
|
+
timeout = _number(self.config.get('timeout', 10))
|
|
87
|
+
if not 0 < timeout <= 120:
|
|
88
|
+
raise ValueError('Home Assistant timeout must be between 0 and 120 seconds')
|
|
89
|
+
path = parts.path.rstrip('/')
|
|
90
|
+
# Accept either the frontend base or a copied /api/ base.
|
|
91
|
+
if path.endswith('/api'):
|
|
92
|
+
path = path[:-4]
|
|
93
|
+
return urlunsplit((parts.scheme, parts.netloc, path, '', '')), token, float(timeout)
|
|
94
|
+
|
|
95
|
+
async def _request(self, method: str, path: str, payload: dict | None = None):
|
|
96
|
+
"""Run blocking requests off-loop; never include URL/body/headers in errors."""
|
|
97
|
+
import requests
|
|
98
|
+
base, token, timeout = self._connection()
|
|
99
|
+
if method not in ('GET', 'POST') or not path.startswith('/api/') or '?' in path or '#' in path:
|
|
100
|
+
raise ValueError('Invalid Home Assistant REST request')
|
|
101
|
+
headers = {'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json'}
|
|
102
|
+
def call():
|
|
103
|
+
try:
|
|
104
|
+
response = requests.request(method, base + path, headers=headers,
|
|
105
|
+
json=payload, timeout=timeout, allow_redirects=False)
|
|
106
|
+
except Exception:
|
|
107
|
+
raise RuntimeError('Home Assistant REST transport failed') from None
|
|
108
|
+
if response.status_code not in (200, 201):
|
|
109
|
+
raise RuntimeError(f'Home Assistant REST HTTP {response.status_code}')
|
|
110
|
+
try:
|
|
111
|
+
data = response.json()
|
|
112
|
+
except Exception:
|
|
113
|
+
raise RuntimeError('Home Assistant REST returned invalid JSON') from None
|
|
114
|
+
if not isinstance(data, (dict, list)):
|
|
115
|
+
raise RuntimeError('Home Assistant REST returned an invalid JSON structure')
|
|
116
|
+
if isinstance(data, dict) and ('error' in data or data.get('success') is False):
|
|
117
|
+
raise RuntimeError('Home Assistant REST reported an error')
|
|
118
|
+
return data
|
|
119
|
+
return await asyncio.to_thread(call)
|
|
120
|
+
|
|
121
|
+
async def _services(self) -> dict[str, dict]:
|
|
122
|
+
data = await self._request('GET', '/api/services')
|
|
123
|
+
if not isinstance(data, list):
|
|
124
|
+
raise RuntimeError('Home Assistant returned an invalid service directory')
|
|
125
|
+
result = {}
|
|
126
|
+
for entry in data:
|
|
127
|
+
if not isinstance(entry, dict) or not isinstance(entry.get('domain'), str):
|
|
128
|
+
raise RuntimeError('Home Assistant returned an invalid service directory')
|
|
129
|
+
names = entry.get('services', {})
|
|
130
|
+
if isinstance(names, list) and all(isinstance(name, str) for name in names):
|
|
131
|
+
names = {name: {} for name in names}
|
|
132
|
+
if not isinstance(names, dict):
|
|
133
|
+
raise RuntimeError('Home Assistant returned an invalid service directory')
|
|
134
|
+
result[entry['domain']] = names
|
|
135
|
+
return result
|
|
136
|
+
|
|
137
|
+
async def _state(self) -> dict:
|
|
138
|
+
entity = self._entity_id()
|
|
139
|
+
if not entity:
|
|
140
|
+
raise ValueError('Select a Home Assistant entity before reading or controlling')
|
|
141
|
+
item = await self._request('GET', '/api/states/' + entity)
|
|
142
|
+
if not isinstance(item, dict) or item.get('entity_id') != entity or not isinstance(item.get('attributes'), dict) or 'state' not in item:
|
|
143
|
+
raise RuntimeError('Home Assistant returned an invalid entity state')
|
|
144
|
+
return item
|
|
145
|
+
|
|
146
|
+
async def probe(self) -> dict:
|
|
147
|
+
if self._entity_id():
|
|
148
|
+
item = await self._state()
|
|
149
|
+
return {'entity_id': item['entity_id'], 'domain': item['entity_id'].split('.')[0],
|
|
150
|
+
'online': item['state'] != 'unavailable'}
|
|
151
|
+
rows = await self.discover_entities()
|
|
152
|
+
return {'platform': 'home_assistant', 'entity_count': len(rows)}
|
|
153
|
+
|
|
154
|
+
async def discover_entities(self) -> list[dict]:
|
|
155
|
+
"""GET-only hub expansion; no credentials, URL or arbitrary attrs escape."""
|
|
156
|
+
data = await self._request('GET', '/api/states')
|
|
157
|
+
if not isinstance(data, list):
|
|
158
|
+
raise RuntimeError('Home Assistant returned an invalid state list')
|
|
159
|
+
rows = []
|
|
160
|
+
for item in data:
|
|
161
|
+
if not isinstance(item, dict) or not _ENTITY.fullmatch(str(item.get('entity_id', ''))):
|
|
162
|
+
continue
|
|
163
|
+
entity = item['entity_id']
|
|
164
|
+
domain = entity.split('.')[0]
|
|
165
|
+
attrs = item.get('attributes') or {}
|
|
166
|
+
if not isinstance(attrs, dict):
|
|
167
|
+
continue
|
|
168
|
+
rows.append({'entity_id': entity, 'id': 'home_assistant:' + entity,
|
|
169
|
+
'protocol': self.protocol, 'platform': self.platform,
|
|
170
|
+
'name': attrs.get('friendly_name') or entity,
|
|
171
|
+
'model': 'Home Assistant ' + domain,
|
|
172
|
+
'category': (attrs.get('device_class') if domain == 'media_player' and attrs.get('device_class') in ('tv', 'speaker', 'projector') else _CATEGORIES.get(domain, 'other')),
|
|
173
|
+
'online': item.get('state') != 'unavailable',
|
|
174
|
+
'fields': {'entity_id': entity, 'domain': domain}})
|
|
175
|
+
return rows
|
|
176
|
+
|
|
177
|
+
@staticmethod
|
|
178
|
+
def _action_schema(description: dict) -> dict:
|
|
179
|
+
properties, required = {}, []
|
|
180
|
+
fields = description.get('fields', {}) if isinstance(description, dict) else {}
|
|
181
|
+
for name, field in fields.items():
|
|
182
|
+
if name in ('entity_id', 'device_id', 'area_id', 'floor_id', 'label_id') or not isinstance(field, dict):
|
|
183
|
+
continue
|
|
184
|
+
selector = field.get('selector') or {}
|
|
185
|
+
spec = {'type': 'string'}
|
|
186
|
+
if 'number' in selector:
|
|
187
|
+
spec = {'type': 'number'}
|
|
188
|
+
for source, target in (('min', 'minimum'), ('max', 'maximum'), ('step', 'multipleOf')):
|
|
189
|
+
if source in (selector['number'] or {}):
|
|
190
|
+
spec[target] = selector['number'][source]
|
|
191
|
+
elif 'boolean' in selector:
|
|
192
|
+
spec = {'type': 'boolean'}
|
|
193
|
+
elif 'object' in selector:
|
|
194
|
+
spec = {'type': 'object'}
|
|
195
|
+
elif 'select' in selector:
|
|
196
|
+
options = (selector['select'] or {}).get('options') or []
|
|
197
|
+
if options:
|
|
198
|
+
spec['enum'] = [option.get('value') if isinstance(option, dict) else option for option in options]
|
|
199
|
+
if field.get('description'):
|
|
200
|
+
spec['description'] = str(field['description'])
|
|
201
|
+
properties[name] = spec
|
|
202
|
+
if field.get('required'):
|
|
203
|
+
required.append(name)
|
|
204
|
+
return {'type': 'object', 'properties': properties, 'required': required, 'additionalProperties': False}
|
|
205
|
+
|
|
206
|
+
def _plans(self, item: dict, directory: dict) -> tuple[list[dict], dict, dict]:
|
|
207
|
+
"""Build public capabilities plus private read/service bindings."""
|
|
208
|
+
entity = item['entity_id']
|
|
209
|
+
domain = entity.split('.')[0]
|
|
210
|
+
attrs = item['attributes']
|
|
211
|
+
state = item['state']
|
|
212
|
+
services = directory.get(domain, {})
|
|
213
|
+
try:
|
|
214
|
+
features = int(attrs.get('supported_features', 0) or 0)
|
|
215
|
+
except (TypeError, ValueError):
|
|
216
|
+
features = 0
|
|
217
|
+
available = state != 'unavailable' and (state != 'unknown' or domain in ('button', 'scene', 'script', 'input_button'))
|
|
218
|
+
caps, values, writes = [], {}, {}
|
|
219
|
+
|
|
220
|
+
def has(service, feature=None):
|
|
221
|
+
return available and service in services and (feature is None or bool(features & feature))
|
|
222
|
+
|
|
223
|
+
def add(key, value, kind='text', service='', param='', supported=True, range_=None, unit='', options=None, readable=True, transform=''):
|
|
224
|
+
writable = bool(supported and service and has(service))
|
|
225
|
+
cap = {'key': key, 'name': key, 'zh': catalog.capability_zh(key),
|
|
226
|
+
'en': catalog.capability_en(key), 'kind': kind,
|
|
227
|
+
'readable': readable, 'writable': writable}
|
|
228
|
+
if range_ is not None:
|
|
229
|
+
cap['range'] = list(range_)
|
|
230
|
+
cap.update(zip(('min', 'max', 'step'), range_))
|
|
231
|
+
if unit:
|
|
232
|
+
cap['unit'] = unit
|
|
233
|
+
if options is not None:
|
|
234
|
+
cap['value_list'] = [{'value': option, 'description': str(option)} for option in options]
|
|
235
|
+
caps.append(cap)
|
|
236
|
+
if readable:
|
|
237
|
+
values[key] = value
|
|
238
|
+
if writable:
|
|
239
|
+
writes[key] = {'service': service, 'param': param, 'transform': transform, 'cap': cap}
|
|
240
|
+
|
|
241
|
+
def attr(key, name, kind='text', **kwargs):
|
|
242
|
+
if name in attrs or kwargs.get('supported') and kwargs.get('service'):
|
|
243
|
+
add(key, attrs.get(name), kind, **kwargs)
|
|
244
|
+
|
|
245
|
+
def numeric(key, name, low=None, high=None, step=1, unit='', service='', param='', supported=True, transform=''):
|
|
246
|
+
if name not in attrs and not (service and supported):
|
|
247
|
+
return
|
|
248
|
+
bounds = [low, high, step] if low is not None and high is not None else None
|
|
249
|
+
add(key, _numeric_read(attrs.get(name)), 'range', service, param, supported, bounds, unit, transform=transform)
|
|
250
|
+
|
|
251
|
+
def enum(key, name, options, service, param='', feature=None):
|
|
252
|
+
choices = attrs.get(options) or []
|
|
253
|
+
if not isinstance(choices, list):
|
|
254
|
+
choices = []
|
|
255
|
+
if name in attrs or choices:
|
|
256
|
+
add(key, state if name == '$state' else attrs.get(name), 'enum', service,
|
|
257
|
+
param or name, bool(choices) and (feature is None or bool(features & feature)), options=choices)
|
|
258
|
+
|
|
259
|
+
def action(key, service, feature=None):
|
|
260
|
+
if has(service, feature):
|
|
261
|
+
add(key, None, 'action', service, readable=False)
|
|
262
|
+
caps[-1]['params_schema'] = self._action_schema(services[service])
|
|
263
|
+
writes[key]['schema'] = caps[-1]['params_schema']
|
|
264
|
+
|
|
265
|
+
def power(on_feature=None, off_feature=None):
|
|
266
|
+
readable = None if state in ('unknown', 'unavailable') else state != 'off'
|
|
267
|
+
supported = has('turn_on', on_feature) and has('turn_off', off_feature)
|
|
268
|
+
add('power', readable, 'bool', 'turn_on', supported=supported, transform='power')
|
|
269
|
+
|
|
270
|
+
add('status', state)
|
|
271
|
+
if domain in ('light', 'switch', 'input_boolean', 'humidifier', 'fan', 'media_player', 'climate'):
|
|
272
|
+
if domain == 'fan':
|
|
273
|
+
power(32, 16)
|
|
274
|
+
elif domain == 'media_player':
|
|
275
|
+
power(128, 256)
|
|
276
|
+
elif domain == 'climate':
|
|
277
|
+
power(256, 128)
|
|
278
|
+
else:
|
|
279
|
+
power()
|
|
280
|
+
|
|
281
|
+
if domain == 'light':
|
|
282
|
+
modes = attrs.get('supported_color_modes') or []
|
|
283
|
+
brightness = any(mode not in ('onoff', 'unknown') for mode in modes)
|
|
284
|
+
numeric('brightness', 'brightness', 0, 100, unit='%', service='turn_on', param='brightness', supported=brightness, transform='brightness')
|
|
285
|
+
if 'brightness' in values and values['brightness'] is not None:
|
|
286
|
+
values['brightness'] = round(values['brightness'] * 100 / 255, 4)
|
|
287
|
+
numeric('color_temp', 'color_temp_kelvin', attrs.get('min_color_temp_kelvin'), attrs.get('max_color_temp_kelvin'), unit='K', service='turn_on', param='color_temp_kelvin', supported='color_temp' in modes and attrs.get('min_color_temp_kelvin') is not None and attrs.get('max_color_temp_kelvin') is not None)
|
|
288
|
+
attr('color', 'rgb_color', service='turn_on', param='rgb_color', supported=bool(set(modes) & {'rgb', 'rgbw', 'rgbww', 'hs', 'xy'}), transform='rgb')
|
|
289
|
+
enum('effect', 'effect', 'effect_list', 'turn_on')
|
|
290
|
+
elif domain == 'fan':
|
|
291
|
+
numeric('fan_speed', 'percentage', 0, 100, attrs.get('percentage_step', 1), '%', 'set_percentage', 'percentage', bool(features & 1))
|
|
292
|
+
attr('swing', 'oscillating', 'bool', service='oscillate', param='oscillating', supported=bool(features & 2))
|
|
293
|
+
if 'direction' in attrs or features & 4:
|
|
294
|
+
add('direction', attrs.get('direction'), 'enum', 'set_direction', 'direction', bool(features & 4), options=['forward', 'reverse'])
|
|
295
|
+
enum('mode', 'preset_mode', 'preset_modes', 'set_preset_mode', feature=8)
|
|
296
|
+
elif domain == 'climate':
|
|
297
|
+
unit = attrs.get('temperature_unit') or attrs.get('unit_of_measurement') or self.config.get('temperature_unit') or ''
|
|
298
|
+
numeric('temperature', 'current_temperature', unit=unit, supported=False)
|
|
299
|
+
numeric('humidity', 'current_humidity', unit='%', supported=False)
|
|
300
|
+
for key, name, bit in [('target_temp', 'temperature', 1), ('target_temp_low', 'target_temp_low', 2), ('target_temp_high', 'target_temp_high', 2)]:
|
|
301
|
+
numeric(key, name, attrs.get('min_temp'), attrs.get('max_temp'), attrs.get('target_temp_step', 1), unit, 'set_temperature', name, bool(features & bit), transform='temperature_pair' if bit == 2 else '')
|
|
302
|
+
enum('mode', '$state', 'hvac_modes', 'set_hvac_mode', 'hvac_mode')
|
|
303
|
+
enum('fan_speed', 'fan_mode', 'fan_modes', 'set_fan_mode', feature=8)
|
|
304
|
+
enum('preset', 'preset_mode', 'preset_modes', 'set_preset_mode', feature=16)
|
|
305
|
+
enum('swing', 'swing_mode', 'swing_modes', 'set_swing_mode', feature=32)
|
|
306
|
+
enum('swing_horizontal', 'swing_horizontal_mode', 'swing_horizontal_modes', 'set_swing_horizontal_mode', feature=512)
|
|
307
|
+
numeric('target_humidity', 'humidity', attrs.get('min_humidity', 0), attrs.get('max_humidity', 100), attrs.get('target_humidity_step', 1), '%', 'set_humidity', 'humidity', bool(features & 4))
|
|
308
|
+
elif domain == 'cover':
|
|
309
|
+
numeric('position', 'current_position', 0, 100, unit='%', service='set_cover_position', param='position', supported=bool(features & 4))
|
|
310
|
+
numeric('tilt_position', 'current_tilt_position', 0, 100, unit='%', service='set_cover_tilt_position', param='tilt_position', supported=bool(features & 128))
|
|
311
|
+
for key, service, bit in [('open', 'open_cover', 1), ('close', 'close_cover', 2), ('stop', 'stop_cover', 8), ('open_tilt', 'open_cover_tilt', 16), ('close_tilt', 'close_cover_tilt', 32), ('stop_tilt', 'stop_cover_tilt', 64)]:
|
|
312
|
+
action(key, service, bit)
|
|
313
|
+
elif domain == 'media_player':
|
|
314
|
+
numeric('volume', 'volume_level', 0, 100, unit='%', service='volume_set', param='volume_level', supported=bool(features & 4), transform='volume')
|
|
315
|
+
if 'volume' in values and values['volume'] is not None:
|
|
316
|
+
values['volume'] = round(values['volume'] * 100, 4)
|
|
317
|
+
attr('mute', 'is_volume_muted', 'bool', service='volume_mute', param='is_volume_muted', supported=bool(features & 8))
|
|
318
|
+
enum('input_source', 'source', 'source_list', 'select_source', feature=2048)
|
|
319
|
+
for key, service, bit in [('play', 'media_play', 16384), ('pause', 'media_pause', 1), ('stop', 'media_stop', 4096), ('next', 'media_next_track', 32), ('previous', 'media_previous_track', 16), ('play_media', 'play_media', 512)]:
|
|
320
|
+
action(key, service, bit)
|
|
321
|
+
elif domain == 'vacuum':
|
|
322
|
+
enum('fan_speed', 'fan_speed', 'fan_speed_list', 'set_fan_speed', feature=32)
|
|
323
|
+
for key, service, bit in [('clean', 'start', 8192), ('pause', 'pause', 4), ('stop', 'stop', 8), ('charge', 'return_to_base', 16), ('locate', 'locate', 512), ('clean_spot', 'clean_spot', 1024)]:
|
|
324
|
+
action(key, service, bit)
|
|
325
|
+
numeric('battery', 'battery_level', 0, 100, unit='%', supported=False)
|
|
326
|
+
elif domain == 'lock':
|
|
327
|
+
action('lock', 'lock')
|
|
328
|
+
action('unlock', 'unlock')
|
|
329
|
+
action('open', 'open', 1)
|
|
330
|
+
elif domain == 'humidifier':
|
|
331
|
+
numeric('humidity', 'current_humidity', unit='%', supported=False)
|
|
332
|
+
numeric('target_humidity', 'humidity', attrs.get('min_humidity', 0), attrs.get('max_humidity', 100), attrs.get('target_humidity_step', 1), '%', 'set_humidity', 'humidity')
|
|
333
|
+
enum('mode', 'mode', 'available_modes', 'set_mode', feature=1)
|
|
334
|
+
elif domain in ('select', 'input_select'):
|
|
335
|
+
enum('mode', '$state', 'options', 'select_option', 'option')
|
|
336
|
+
elif domain in ('number', 'input_number'):
|
|
337
|
+
bounds = [attrs['min'], attrs['max'], attrs.get('step', 1)] if 'min' in attrs and 'max' in attrs else None
|
|
338
|
+
add('value', _numeric_read(state), 'range', 'set_value', 'value', bounds is not None, bounds, attrs.get('unit_of_measurement', ''))
|
|
339
|
+
elif domain in ('button', 'input_button', 'scene', 'script'):
|
|
340
|
+
action({'button': 'press', 'input_button': 'press', 'scene': 'activate', 'script': 'run'}[domain], 'press' if domain in ('button', 'input_button') else 'turn_on')
|
|
341
|
+
if domain == 'script':
|
|
342
|
+
action('stop', 'turn_off')
|
|
343
|
+
elif domain == 'sensor':
|
|
344
|
+
key = {'temperature': 'temperature', 'humidity': 'humidity', 'battery': 'battery', 'power': 'power', 'energy': 'energy'}.get(attrs.get('device_class'), 'value')
|
|
345
|
+
numeric_value = _numeric_read(state)
|
|
346
|
+
add(key, numeric_value if numeric_value is not None else state, 'range' if numeric_value is not None else 'text', unit=attrs.get('unit_of_measurement', ''))
|
|
347
|
+
elif domain == 'binary_sensor':
|
|
348
|
+
add('value', {'on': True, 'off': False}.get(state), 'bool')
|
|
349
|
+
return caps, values, writes
|
|
350
|
+
|
|
351
|
+
async def _snapshot(self) -> tuple[dict, list[dict], dict, dict]:
|
|
352
|
+
item = await self._state()
|
|
353
|
+
if item['entity_id'].startswith('climate.') and not (item['attributes'].get('temperature_unit') or item['attributes'].get('unit_of_measurement') or self.config.get('temperature_unit')):
|
|
354
|
+
config = await self._request('GET', '/api/config')
|
|
355
|
+
if not isinstance(config, dict):
|
|
356
|
+
raise RuntimeError('Home Assistant returned invalid configuration')
|
|
357
|
+
item = deepcopy(item)
|
|
358
|
+
item['attributes']['temperature_unit'] = (config.get('unit_system') or {}).get('temperature', '')
|
|
359
|
+
caps, values, writes = self._plans(item, await self._services())
|
|
360
|
+
return item, caps, values, writes
|
|
361
|
+
|
|
362
|
+
async def list_capabilities(self) -> list[dict]:
|
|
363
|
+
if not self._entity_id():
|
|
364
|
+
return []
|
|
365
|
+
return (await self._snapshot())[1]
|
|
366
|
+
|
|
367
|
+
async def read_all(self) -> dict:
|
|
368
|
+
if not self._entity_id():
|
|
369
|
+
return {}
|
|
370
|
+
return (await self._snapshot())[2]
|
|
371
|
+
|
|
372
|
+
async def read_capability(self, capability: str):
|
|
373
|
+
values = await self.read_all()
|
|
374
|
+
if capability not in values:
|
|
375
|
+
raise ValueError('Unknown or unreadable Home Assistant capability')
|
|
376
|
+
return values[capability]
|
|
377
|
+
|
|
378
|
+
async def _call_service(self, entity: str, service: str, payload: dict) -> dict:
|
|
379
|
+
domain = entity.split('.')[0]
|
|
380
|
+
data = await self._request('POST', f'/api/services/{domain}/{service}', {'entity_id': entity, **payload})
|
|
381
|
+
if not isinstance(data, list) or any(not isinstance(row, dict) or 'entity_id' not in row or 'state' not in row or 'error' in row for row in data):
|
|
382
|
+
raise RuntimeError('Home Assistant service returned an invalid response')
|
|
383
|
+
return {'ok': True, 'entity_id': entity, 'service': domain + '.' + service}
|
|
384
|
+
|
|
385
|
+
async def write_capability(self, capability: str, value) -> dict:
|
|
386
|
+
item, _, _, bindings = await self._snapshot()
|
|
387
|
+
binding = bindings.get(capability)
|
|
388
|
+
if not binding or binding['cap']['kind'] == 'action':
|
|
389
|
+
raise ValueError('Home Assistant capability is not writable')
|
|
390
|
+
cap, service = binding['cap'], binding['service']
|
|
391
|
+
if cap['kind'] == 'bool':
|
|
392
|
+
value = self._value_for_capability('power', value)
|
|
393
|
+
elif cap['kind'] == 'range':
|
|
394
|
+
value = _number(value)
|
|
395
|
+
if cap.get('range'):
|
|
396
|
+
low, high, step = cap['range']
|
|
397
|
+
if not low <= value <= high:
|
|
398
|
+
raise ValueError('Home Assistant value is outside the entity range')
|
|
399
|
+
if step and not math.isclose((value - low) / step, round((value - low) / step), abs_tol=1e-7):
|
|
400
|
+
raise ValueError('Home Assistant value does not match the entity step')
|
|
401
|
+
elif cap['kind'] == 'enum':
|
|
402
|
+
if value not in [entry['value'] for entry in cap.get('value_list', [])]:
|
|
403
|
+
raise ValueError('Home Assistant value is not an entity option')
|
|
404
|
+
transform = binding['transform']
|
|
405
|
+
if transform == 'power':
|
|
406
|
+
service = 'turn_on' if value else 'turn_off'
|
|
407
|
+
payload = {}
|
|
408
|
+
elif transform == 'rgb':
|
|
409
|
+
try:
|
|
410
|
+
rgb = [_number(part) for part in (value.split(',') if isinstance(value, str) else value)]
|
|
411
|
+
except (ValueError, TypeError):
|
|
412
|
+
raise ValueError('Home Assistant color requires an RGB triple') from None
|
|
413
|
+
if len(rgb) != 3 or any(not isinstance(part, int) or not 0 <= part <= 255 for part in rgb):
|
|
414
|
+
raise ValueError('Home Assistant RGB values must be integers from 0 to 255')
|
|
415
|
+
payload = {binding['param']: rgb}
|
|
416
|
+
else:
|
|
417
|
+
if transform == 'brightness':
|
|
418
|
+
value = int(value * 255 / 100 + 0.5)
|
|
419
|
+
elif transform == 'volume':
|
|
420
|
+
value /= 100
|
|
421
|
+
payload = {binding['param']: value}
|
|
422
|
+
if transform == 'temperature_pair':
|
|
423
|
+
other = 'target_temp_high' if binding['param'] == 'target_temp_low' else 'target_temp_low'
|
|
424
|
+
paired = _numeric_read(item['attributes'].get(other))
|
|
425
|
+
if paired is None:
|
|
426
|
+
raise ValueError('Home Assistant paired target temperature is unavailable')
|
|
427
|
+
payload[other] = paired
|
|
428
|
+
if payload['target_temp_low'] > payload['target_temp_high']:
|
|
429
|
+
raise ValueError('Home Assistant target temperature low exceeds high')
|
|
430
|
+
return await self._call_service(item['entity_id'], service, payload)
|
|
431
|
+
|
|
432
|
+
async def run_action(self, name: str, params: dict | None = None) -> dict:
|
|
433
|
+
item, _, _, bindings = await self._snapshot()
|
|
434
|
+
binding = bindings.get(name)
|
|
435
|
+
if not binding or binding['cap']['kind'] != 'action':
|
|
436
|
+
raise ValueError('Home Assistant action is not supported by the entity')
|
|
437
|
+
params = {} if params is None else params
|
|
438
|
+
if not isinstance(params, dict):
|
|
439
|
+
raise ValueError('Home Assistant action parameters must be an object')
|
|
440
|
+
schema = binding['schema']
|
|
441
|
+
if set(params) - set(schema['properties']) or set(schema['required']) - set(params):
|
|
442
|
+
raise ValueError('Home Assistant action parameters do not match the declared service')
|
|
443
|
+
for key, value in params.items():
|
|
444
|
+
spec = schema['properties'][key]
|
|
445
|
+
kind = spec['type']
|
|
446
|
+
valid = {'string': isinstance(value, str), 'boolean': isinstance(value, bool),
|
|
447
|
+
'object': isinstance(value, dict), 'number': isinstance(value, (int, float)) and not isinstance(value, bool)}[kind]
|
|
448
|
+
if not valid or ('enum' in spec and value not in spec['enum']):
|
|
449
|
+
raise ValueError('Invalid Home Assistant action parameter')
|
|
450
|
+
if kind == 'number':
|
|
451
|
+
number = _number(value)
|
|
452
|
+
if ('minimum' in spec and number < spec['minimum']) or ('maximum' in spec and number > spec['maximum']):
|
|
453
|
+
raise ValueError('Home Assistant action parameter is outside the declared range')
|
|
454
|
+
return await self._call_service(item['entity_id'], binding['service'], deepcopy(params))
|