@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.
Files changed (51) hide show
  1. package/README.md +141 -78
  2. package/client.js +1149 -19
  3. package/cordis.patch.yml +2 -2
  4. package/docs/REPAIR-VALIDATION.md +62 -0
  5. package/lib/bridge.js +126 -44
  6. package/lib/connections.js +46 -0
  7. package/lib/format.js +148 -0
  8. package/lib/index.js +274 -31
  9. package/lib/panel.js +138 -7
  10. package/locale/en.json +3 -3
  11. package/locale/zh.json +2 -2
  12. package/package.json +13 -4
  13. package/python/app/core/service.py +62 -31
  14. package/python/mihome_bridge.py +211 -9
  15. package/python/smart_home/__init__.py +24 -0
  16. package/python/smart_home/adapters/__init__.py +50 -0
  17. package/python/smart_home/adapters/base.py +143 -0
  18. package/python/smart_home/adapters/ble.py +100 -0
  19. package/python/smart_home/adapters/dlna.py +227 -0
  20. package/python/smart_home/adapters/home_assistant.py +454 -0
  21. package/python/smart_home/adapters/hue.py +225 -0
  22. package/python/smart_home/adapters/kasa.py +239 -0
  23. package/python/smart_home/adapters/mihome.py +342 -0
  24. package/python/smart_home/adapters/network.py +250 -0
  25. package/python/smart_home/adapters/shelly.py +289 -0
  26. package/python/smart_home/adapters/tuya.py +95 -0
  27. package/python/smart_home/adapters/tv.py +26 -0
  28. package/python/smart_home/catalog.py +336 -0
  29. package/python/smart_home/cloud.py +85 -0
  30. package/python/smart_home/discovery.py +934 -0
  31. package/python/smart_home/localize.py +787 -0
  32. package/python/smart_home/manager.py +672 -0
  33. package/python/smart_home/oui_table.py +40550 -0
  34. package/python/smart_home/scan.py +73 -0
  35. package/python/smart_home/test_discovery_repairs.py +186 -0
  36. package/python/smart_home/test_localization_repairs.py +229 -0
  37. package/python/smart_home/test_offline.py +195 -0
  38. package/python/smart_home/test_repairs.py +107 -0
  39. package/python/smart_home/util.py +320 -0
  40. package/python/tests/test_bridge_integration.py +108 -0
  41. package/python/tests/test_ha_discovery.py +260 -0
  42. package/python/tests/test_home_assistant.py +365 -0
  43. package/python/tests/test_manager_integration.py +150 -0
  44. package/python/tests/test_mihome_repairs.py +117 -0
  45. package/python/tests/test_network_read_contract.py +50 -0
  46. package/python/tests/test_power_confirmation.py +95 -0
  47. package/python/tests/test_protocol_repairs.py +369 -0
  48. package/python/tests/test_yeelight_repairs.py +70 -0
  49. package/requirements-optional.txt +4 -0
  50. package/requirements.txt +5 -0
  51. package/scripts/update-oui.py +108 -0
@@ -0,0 +1,289 @@
1
+ # SPDX-License-Identifier: GPL-3.0-or-later
2
+ """Adapters for selected Shelly, Tasmota and WLED local endpoints.
3
+
4
+ Capabilities are limited to fields confirmed by the device response. ESPHome's
5
+ unverified REST write path is disabled; firmware generations may expose
6
+ additional controls not represented here.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import json
13
+ import urllib.parse
14
+
15
+ from .base import BaseAdapter, register
16
+
17
+
18
+ def _post_json(url: str, payload: dict, timeout: float = 4.0):
19
+ import requests
20
+
21
+ return requests.post(url, json=payload, timeout=timeout,
22
+ headers={"User-Agent": "dsh-mihome/2.0"})
23
+
24
+
25
+ def _post_form(url: str, payload: dict, timeout: float = 4.0):
26
+ import requests
27
+
28
+ return requests.post(url, data=payload, timeout=timeout,
29
+ headers={"User-Agent": "dsh-mihome/2.0"})
30
+
31
+
32
+ def _get(url: str, timeout: float = 3.0):
33
+ import requests
34
+
35
+ return requests.get(url, timeout=timeout, headers={"User-Agent": "dsh-mihome/2.0"})
36
+
37
+
38
+ def _bool(value) -> bool:
39
+ if isinstance(value, bool):
40
+ return value
41
+ if isinstance(value, (int, float)):
42
+ return value != 0
43
+ if isinstance(value, str):
44
+ return value.lower() in ("1", "true", "on", "yes", "开")
45
+ return bool(value)
46
+
47
+
48
+ # ------------------------------------------------------------------ Shelly
49
+
50
+
51
+ @register
52
+ class ShellyAdapter(BaseAdapter):
53
+ """Shelly(Gen1 用 /status,Gen2 用 /rpc JSON-RPC)。"""
54
+
55
+ protocol = "shelly"
56
+ platform = ""
57
+
58
+ def _base(self) -> str:
59
+ return f"http://{self.ip}"
60
+
61
+ async def _rpc(self, method: str, params: dict | None = None) -> dict:
62
+ payload = {"id": 1, "method": method, "params": params or {}}
63
+ resp = await asyncio.to_thread(_post_json, f"{self._base()}/rpc", payload)
64
+ if resp is None or resp.status_code != 200:
65
+ raise RuntimeError(f"Shelly RPC 失败:{resp.status_code if resp else '无响应'}")
66
+ data = resp.json()
67
+ if data.get("error"):
68
+ raise RuntimeError(f"Shelly RPC 错误:{data['error']}")
69
+ return data.get("result") or {}
70
+
71
+ async def _status(self):
72
+ if self.config.get('shelly_gen') == 1:
73
+ resp = await asyncio.to_thread(_get, f"{self._base()}/status")
74
+ if resp is None or resp.status_code != 200:
75
+ raise RuntimeError('Shelly status unavailable')
76
+ return resp.json()
77
+ return await self._rpc('Shelly.GetStatus')
78
+
79
+ async def read_all(self):
80
+ status = await self._status()
81
+ out = {}
82
+ if isinstance(status.get('switch:0'), dict) and 'output' in status['switch:0']:
83
+ out['power'] = status['switch:0']['output']
84
+ elif status.get('relays') and 'ison' in status['relays'][0]:
85
+ out['power'] = status['relays'][0]['ison']
86
+ if isinstance(status.get('cover:0'), dict) and 'current_pos' in status['cover:0']:
87
+ out['position'] = status['cover:0']['current_pos']
88
+ elif status.get('rollers') and 'current_pos' in status['rollers'][0]:
89
+ out['position'] = status['rollers'][0]['current_pos']
90
+ return out
91
+
92
+ async def list_capabilities(self):
93
+ state = await self.read_all()
94
+ controls = []
95
+ if 'power' in state:
96
+ controls.append({'key':'power','name':'power','kind':'bool','readable':True,'writable':True})
97
+ if 'position' in state:
98
+ controls.append({'key':'position','name':'position','kind':'range','range':[0,100,1],'unit':'%','readable':True,'writable':self.config.get('shelly_gen') != 1})
99
+ return controls
100
+
101
+ async def read_capability(self, capability):
102
+ return (await self.read_all()).get(capability)
103
+ async def write_capability(self, capability: str, value) -> dict:
104
+ value = self._value_for_capability(capability, value)
105
+ if capability == "power":
106
+ if self.config.get('shelly_gen') == 1:
107
+ resp = await asyncio.to_thread(_get, f"{self._base()}/relay/0?turn={'on' if value else 'off'}")
108
+ if resp is None or resp.status_code != 200 or resp.json().get('ison') is not value:
109
+ raise RuntimeError('Shelly Gen1 relay write failed')
110
+ else:
111
+ await self._rpc("Switch.Set", {"id": 0, "on": value})
112
+ elif capability == "position":
113
+ if self.config.get('shelly_gen') == 1:
114
+ raise ValueError('Shelly Gen1 position writes are not implemented')
115
+ if not 0 <= value <= 100:
116
+ raise ValueError("Position must be between 0 and 100")
117
+ await self._rpc("Cover.GoToPosition", {"id": 0, "pos": int(value)})
118
+ else:
119
+ raise ValueError(f"Shelly 不支持写入 {capability}")
120
+ return {"ok": True, "capability": capability, "value": value}
121
+
122
+ async def run_action(self, name: str, params: dict | None = None) -> dict:
123
+ await self._rpc(name, params or {})
124
+ return {"ok": True, "action": name}
125
+
126
+ # ------------------------------------------------------------------ Tasmota
127
+
128
+
129
+ @register
130
+ class TasmotaAdapter(BaseAdapter):
131
+ """Tasmota(/cm?cmnd=...)。"""
132
+
133
+ protocol = "tasmota"
134
+ platform = ""
135
+
136
+ def _base(self) -> str:
137
+ return f"http://{self.ip}"
138
+
139
+ async def _cmd(self, command: str) -> dict:
140
+ url = f"{self._base()}/cm?cmnd={urllib.parse.quote(command)}"
141
+ resp = await asyncio.to_thread(_get, url)
142
+ if resp is None or resp.status_code != 200:
143
+ raise RuntimeError(f"Tasmota 命令失败:{command}")
144
+ text = resp.text or ""
145
+ if not text.startswith("{"):
146
+ return {}
147
+ try:
148
+ return json.loads(text)
149
+ except ValueError:
150
+ return {}
151
+
152
+ async def list_capabilities(self):
153
+ state = await self.read_all()
154
+ controls = []
155
+ for key, kind, limits, unit in [('power','bool',None,''), ('brightness','range',[0,100,1],'%'), ('color_temp','range',None,'mired'), ('color','text',None,'')]:
156
+ if key in state:
157
+ item = {'key':key,'name':key,'kind':kind,'readable':True,'writable':key in ('power','brightness')}
158
+ if limits is not None: item['range'] = limits
159
+ if unit: item['unit'] = unit
160
+ controls.append(item)
161
+ return controls
162
+ async def read_capability(self, capability: str):
163
+ return (await self.read_all()).get(capability)
164
+
165
+ async def write_capability(self, capability: str, value) -> dict:
166
+ if capability == "power":
167
+ wanted = self._value_for_capability(capability, value)
168
+ response = await self._cmd("Power " + ("On" if wanted else "Off"))
169
+ if response.get('POWER') not in ('ON', 'OFF') or _bool(response['POWER']) != wanted:
170
+ raise RuntimeError('Tasmota power command was not confirmed')
171
+ elif capability == "brightness":
172
+ brightness = self._value_for_capability(capability, value)
173
+ if not 0 <= brightness <= 100:
174
+ raise ValueError('Tasmota brightness must be 0..100')
175
+ response = await self._cmd(f"Dimmer {int(brightness)}")
176
+ if response.get('Dimmer') != int(brightness):
177
+ raise RuntimeError('Tasmota dimmer command was not confirmed')
178
+ else:
179
+ raise ValueError(f"Tasmota 不支持写入 {capability}")
180
+ return {"ok": True, "capability": capability, "value": value}
181
+
182
+ async def read_all(self) -> dict:
183
+ status = (await self._cmd("Status 11")).get("StatusSTS", {})
184
+ out = {}
185
+ if "POWER" in status:
186
+ out["power"] = _bool(status["POWER"])
187
+ if "Dimmer" in status:
188
+ out["brightness"] = status["Dimmer"]
189
+ if "CT" in status:
190
+ out["color_temp"] = status["CT"]
191
+ if "Color" in status:
192
+ out["color"] = status["Color"]
193
+ return out
194
+
195
+
196
+ # ------------------------------------------------------------------ WLED
197
+
198
+
199
+ @register
200
+ class WledAdapter(BaseAdapter):
201
+ """WLED(/json/state)。"""
202
+
203
+ protocol = "wled"
204
+ platform = ""
205
+
206
+ def _base(self) -> str:
207
+ return f"http://{self.ip}"
208
+
209
+ async def list_capabilities(self) -> list[dict]:
210
+ return [
211
+ {'key': 'power', 'name': 'on', 'kind': 'bool', 'writable': True},
212
+ {'key': 'brightness', 'name': 'bri', 'kind': 'range', 'range': [0, 100, 1], 'unit': '%', 'writable': True},
213
+ {'key': 'color', 'name': 'col', 'kind': 'text', 'writable': True},
214
+ ]
215
+
216
+ async def read_capability(self, capability: str):
217
+ resp = await asyncio.to_thread(_get, f"{self._base()}/json/state")
218
+ if resp is None or resp.status_code != 200:
219
+ return None
220
+ data = resp.json()
221
+ if capability == "power":
222
+ return _bool(data.get("on"))
223
+ if capability == "brightness":
224
+ return round(data['bri'] * 100 / 255) if 'bri' in data else None
225
+ if capability == "color":
226
+ seg = data.get("seg") or [{}]
227
+ col = seg[0].get("col") or []
228
+ if col and len(col[0]) >= 3:
229
+ return "#%02x%02x%02x" % tuple(col[0][:3])
230
+ return None
231
+
232
+ async def write_capability(self, capability: str, value) -> dict:
233
+ if capability == "power":
234
+ payload = {"on": bool(self._value_for_capability(capability, value))}
235
+ elif capability == "brightness":
236
+ brightness = self._value_for_capability(capability, value)
237
+ if not 0 <= brightness <= 100:
238
+ raise ValueError("Brightness must be between 0 and 100")
239
+ payload = {"bri": round(brightness * 255 / 100)}
240
+ elif capability == "color":
241
+ import re
242
+ if not isinstance(value, str) or not re.fullmatch(r'#[0-9a-fA-F]{6}', value):
243
+ raise ValueError('Color must be #RRGGBB')
244
+ payload = {"seg": [{"col": [[_hex_to_int(value[1:3]), _hex_to_int(value[3:5]), _hex_to_int(value[5:7])]]}]}
245
+ else:
246
+ raise ValueError(f"WLED 不支持写入 {capability}")
247
+ resp = await asyncio.to_thread(_post_json, f"{self._base()}/json/state", payload)
248
+ if resp is None or resp.status_code != 200:
249
+ raise RuntimeError("WLED 写入失败")
250
+ return {"ok": True, "capability": capability, "value": value}
251
+
252
+ async def read_all(self) -> dict:
253
+ resp = await asyncio.to_thread(_get, f"{self._base()}/json/state")
254
+ if resp is None or resp.status_code != 200:
255
+ return {}
256
+ data = resp.json()
257
+ out = {}
258
+ if 'on' in data:
259
+ out['power'] = bool(data['on'])
260
+ if 'bri' in data:
261
+ out['brightness'] = round(data['bri'] * 100 / 255)
262
+ segments = data.get('seg') or []
263
+ colors = segments[0].get('col') or [] if segments else []
264
+ if colors and len(colors[0]) >= 3:
265
+ out['color'] = '#%02x%02x%02x' % tuple(colors[0][:3])
266
+ return out
267
+
268
+
269
+ def _hex_to_int(text: str) -> int:
270
+ return int(text, 16) if text else 0
271
+
272
+
273
+ # ------------------------------------------------------------------ ESPHome
274
+
275
+
276
+ @register
277
+ class EspHomeAdapter(BaseAdapter):
278
+ """ESPHome entity discovery and its native API are not implemented."""
279
+ protocol = 'esphome'
280
+ platform = ''
281
+
282
+ async def list_capabilities(self):
283
+ return []
284
+
285
+ async def write_capability(self, capability, value):
286
+ raise NotImplementedError('ESPHome entity API is not implemented')
287
+
288
+ async def read_all(self):
289
+ return {}
@@ -0,0 +1,95 @@
1
+ # SPDX-License-Identifier: GPL-3.0-or-later
2
+ """Tuya LAN adapter using explicitly configured data-point schemas."""
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from .. import catalog
7
+ from .base import BaseAdapter, register
8
+
9
+
10
+ def _make_device(ip: str, key: str, version: str, device_id: str, timeout: float = 5.0):
11
+ import tinytuya
12
+ return tinytuya.Device(device_id, address=ip, local_key=key,
13
+ version=version, connection_timeout=timeout)
14
+
15
+
16
+ def _checked(result):
17
+ if not isinstance(result, dict):
18
+ raise RuntimeError("Tuya returned an invalid response")
19
+ if result.get('Error') or result.get('Err'):
20
+ raise RuntimeError(f"Tuya request failed (code {result.get('Err', 'unknown')})")
21
+ return result
22
+
23
+
24
+ @register
25
+ class TuyaAdapter(BaseAdapter):
26
+ protocol = 'tuya'
27
+ platform = 'aligenie'
28
+
29
+ def __init__(self, device, config=None):
30
+ super().__init__(device, config)
31
+ credentials = getattr(device, 'credentials', {}) or {}
32
+ self.key = self.config.get('local_key') or credentials.get('local_key') or getattr(device, 'local_key', '')
33
+ self.gw_id = self.config.get('device_id') or credentials.get('device_id') or credentials.get('gw_id') or getattr(device, 'gw_id', '')
34
+ self.version = self.config.get('version') or credentials.get('version') or getattr(device, 'version', '') or '3.3'
35
+ self.dps = self.config.get('dps') or getattr(device, 'dps', {}) or {}
36
+ self._dev = None
37
+
38
+ async def _device(self):
39
+ if self._dev is None:
40
+ if not self.key or not self.gw_id:
41
+ raise RuntimeError('Tuya requires device_id and local_key')
42
+ self._dev = await asyncio.to_thread(_make_device, self.ip, self.key, self.version, self.gw_id)
43
+ return self._dev
44
+
45
+ def _schema(self):
46
+ for dp, spec in self.dps.items():
47
+ if isinstance(spec, dict) and spec.get('key') and spec.get('kind') in ('bool', 'range', 'enum', 'text'):
48
+ yield str(dp), spec
49
+
50
+ async def list_capabilities(self):
51
+ result = []
52
+ for dp, spec in self._schema():
53
+ cap = {'key': spec['key'], 'name': spec.get('name', f'dp{dp}'),
54
+ 'kind': spec['kind'], 'writable': spec.get('writable') is True,
55
+ 'zh': catalog.capability_zh(spec['key']), 'en': catalog.capability_en(spec['key'])}
56
+ for field in ('range', 'unit', 'value_list'):
57
+ if field in spec:
58
+ cap[field] = spec[field]
59
+ result.append(cap)
60
+ return result
61
+
62
+ def _dp_for(self, capability, writable=False):
63
+ matches = [(dp, spec) for dp, spec in self._schema() if spec['key'] == capability]
64
+ if len(matches) != 1 or (writable and matches[0][1].get('writable') is not True):
65
+ raise ValueError(f'Tuya capability not explicitly mapped: {capability}')
66
+ return matches[0]
67
+
68
+ async def read_capability(self, capability):
69
+ dp, _ = self._dp_for(capability)
70
+ dev = await self._device()
71
+ result = _checked(await asyncio.to_thread(dev.status))
72
+ if not isinstance(result.get('dps'), dict):
73
+ raise RuntimeError('Tuya status has no DPS')
74
+ return result['dps'].get(dp)
75
+
76
+ async def write_capability(self, capability, value):
77
+ dp, spec = self._dp_for(capability, writable=True)
78
+ if spec['kind'] == 'bool':
79
+ value = self._value_for_capability(capability, value)
80
+ dev = await self._device()
81
+ _checked(await asyncio.to_thread(dev.set_value, dp, value))
82
+ return {'ok': True, 'capability': capability, 'value': value, 'dp': dp}
83
+
84
+ async def read_all(self):
85
+ dev = await self._device()
86
+ result = _checked(await asyncio.to_thread(dev.status))
87
+ dps = result.get('dps')
88
+ if not isinstance(dps, dict):
89
+ raise RuntimeError('Tuya status has no DPS')
90
+ return {spec['key']: dps[dp] for dp, spec in self._schema() if dp in dps}
91
+
92
+ async def close(self):
93
+ dev, self._dev = self._dev, None
94
+ if dev is not None and callable(getattr(dev, 'close', None)):
95
+ await asyncio.to_thread(dev.close)
@@ -0,0 +1,26 @@
1
+ # SPDX-License-Identifier: GPL-3.0-or-later
2
+ """Television adapters. Authenticated device protocols are not implemented yet."""
3
+ from .base import BaseAdapter, register
4
+
5
+
6
+ class _UnsupportedTelevision(BaseAdapter):
7
+ async def list_capabilities(self):
8
+ return []
9
+
10
+ async def write_capability(self, capability, value):
11
+ raise NotImplementedError(f'{self.protocol} control requires a supported paired client')
12
+
13
+
14
+ @register
15
+ class SamsungTvAdapter(_UnsupportedTelevision):
16
+ protocol = 'samsung_tv'
17
+
18
+
19
+ @register
20
+ class LgTvAdapter(_UnsupportedTelevision):
21
+ protocol = 'lg_tv'
22
+
23
+
24
+ @register
25
+ class VizioTvAdapter(_UnsupportedTelevision):
26
+ protocol = 'vizio_tv'