@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,225 @@
1
+ # SPDX-License-Identifier: GPL-3.0-or-later
2
+ """Philips Hue light adapter.
3
+
4
+ Hue controls are limited to fields exposed by the configured bridge resource.
5
+ LIFX writes are intentionally disabled until its LAN protocol path is verified.
6
+ The Hue bridge username must be supplied in the private connection record.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import struct
13
+
14
+ from .base import BaseAdapter, register
15
+
16
+
17
+ def _bool(value) -> bool:
18
+ if isinstance(value, bool):
19
+ return value
20
+ if isinstance(value, (int, float)):
21
+ return value != 0
22
+ if isinstance(value, str):
23
+ return value.lower() in ("1", "true", "on", "yes", "开")
24
+ return bool(value)
25
+
26
+
27
+ # ------------------------------------------------------------------ Hue
28
+
29
+
30
+ @register
31
+ class HueAdapter(BaseAdapter):
32
+ """Philips Hue 桥接器(端口 80 / 443)。"""
33
+
34
+ protocol = "hue"
35
+ platform = ""
36
+
37
+ def _base(self) -> str:
38
+ return f"http://{self.ip}"
39
+
40
+ def _username(self) -> str:
41
+ return self.config.get("hue_username") or (getattr(self.device, 'credentials', {}) or {}).get('hue_username') or ""
42
+
43
+ def _pair(self) -> str:
44
+ """按物理按钮配对;已配对直接返回用户名。"""
45
+ if self._username():
46
+ return self._username()
47
+ import requests
48
+
49
+ payload = {"devicetype": "dsh-mihome#plugin"}
50
+ resp = requests.post(f"{self._base()}/api", json=payload, timeout=5,
51
+ headers={"User-Agent": "dsh-mihome/2.0"})
52
+ if resp.status_code in (200, 201):
53
+ data = resp.json()
54
+ if isinstance(data, list):
55
+ for entry in data:
56
+ username = entry.get('success', {}).get('username')
57
+ if username:
58
+ self.config['hue_username'] = username
59
+ return username
60
+ raise RuntimeError("Hue 配对失败:请先按住桥接器上的物理配对按钮 5 秒,再重试")
61
+
62
+ async def _api(self, method: str, path: str, payload: dict | None = None) -> dict | str:
63
+ import requests
64
+
65
+ username = self._pair()
66
+ url = f"{self._base()}/api/{username}{path}"
67
+ if method == "GET":
68
+ resp = requests.get(url, timeout=5, headers={"User-Agent": "dsh-mihome/2.0"})
69
+ else:
70
+ resp = requests.put(url, json=payload or {}, timeout=5,
71
+ headers={"User-Agent": "dsh-mihome/2.0"})
72
+ if resp.status_code >= 400:
73
+ raise RuntimeError(f"Hue API {path} 失败:{resp.status_code} {resp.text[:200]}")
74
+ data = resp.json()
75
+ if isinstance(data, list):
76
+ for entry in data:
77
+ if 'error' in entry:
78
+ raise RuntimeError(f"Hue API error: {entry['error']}")
79
+ if method != 'GET' and (not data or not all('success' in entry for entry in data)):
80
+ raise RuntimeError('Invalid Hue write response')
81
+ elif method != 'GET':
82
+ raise RuntimeError('Invalid Hue write response')
83
+ return data
84
+
85
+ async def _lights(self) -> dict:
86
+ data = await self._api("GET", "/lights")
87
+ return data if isinstance(data, dict) else {}
88
+
89
+ async def _selected_light(self):
90
+ lights = await self._lights()
91
+ if not lights:
92
+ raise ValueError('No Hue lights found')
93
+ light_id = str(self.config.get('hue_light_id') or next(iter(lights)))
94
+ if light_id not in lights:
95
+ raise ValueError('Configured Hue light not found')
96
+ return light_id, lights[light_id]
97
+
98
+ async def list_capabilities(self):
99
+ _, light = await self._selected_light()
100
+ state = light.get('state') or {}
101
+ result = []
102
+ if 'on' in state:
103
+ result.append({'key':'power','name':'on','kind':'bool','readable':True,'writable':True})
104
+ if 'bri' in state:
105
+ result.append({'key':'brightness','name':'bri','kind':'range','range':[1,254,1],'readable':True,'writable':True})
106
+ if 'xy' in state:
107
+ result.append({'key':'color','name':'xy','kind':'text','readable':True,'writable':True})
108
+ if 'ct' in state:
109
+ limits = ((light.get('capabilities') or {}).get('control') or {}).get('ct') or {}
110
+ valid = isinstance(limits.get('min'), int) and isinstance(limits.get('max'), int) and limits['min'] < limits['max']
111
+ item = {'key':'color_temp','name':'ct','kind':'range','unit':'mired','readable':True,'writable':bool(valid)}
112
+ if valid: item['range'] = [limits['min'], limits['max'], 1]
113
+ result.append(item)
114
+ return result
115
+ async def read_capability(self, capability: str):
116
+ lights = await self._lights()
117
+ if not lights:
118
+ return None
119
+ # 没有单灯标识时,取第一盏灯
120
+ light_id = str(self.config.get('hue_light_id') or next(iter(lights)))
121
+ if light_id not in lights:
122
+ raise ValueError('Configured Hue light not found')
123
+ light = lights[light_id] or {}
124
+ state = light.get("state") or {}
125
+ if capability == "power":
126
+ return _bool(state.get("on", False))
127
+ if capability == "brightness":
128
+ return state.get("bri")
129
+ if capability == "color":
130
+ xy = state.get("xy") or [0, 0]
131
+ return f"{xy[0]:.4f},{xy[1]:.4f}"
132
+ if capability == "color_temp":
133
+ return state.get("ct")
134
+ return None
135
+
136
+ async def write_capability(self, capability: str, value) -> dict:
137
+ controls = {c['key']: c for c in await self.list_capabilities()}
138
+ if capability not in controls or not controls[capability]['writable']:
139
+ raise ValueError(f'Hue does not support writing {capability}')
140
+ light_id, _ = await self._selected_light()
141
+ if capability == "power":
142
+ payload = {"on": bool(self._value_for_capability(capability, value))}
143
+ elif capability == "brightness":
144
+ value = self._value_for_capability(capability, value)
145
+ if not 1 <= value <= 254: raise ValueError('Hue brightness must be 1..254')
146
+ payload = {"bri": int(value)}
147
+ elif capability == "color":
148
+ try:
149
+ xy = [float(x) for x in (value.split(',') if isinstance(value, str) else value)]
150
+ except (TypeError, ValueError):
151
+ raise ValueError('Hue color must be an x,y pair') from None
152
+ if len(xy) != 2 or not all(0 <= x <= 1 for x in xy):
153
+ raise ValueError('Hue color must be an x,y pair between 0 and 1')
154
+ payload = {"xy": xy}
155
+ elif capability == "color_temp":
156
+ value = self._value_for_capability(capability, value)
157
+ low, high, _ = controls['color_temp']['range']
158
+ if not low <= value <= high: raise ValueError('Hue color temperature outside light range')
159
+ payload = {"ct": int(value)}
160
+ else:
161
+ raise ValueError(f"Hue 不支持写入 {capability}")
162
+ await self._api("PUT", f"/lights/{light_id}/state", payload)
163
+ return {"ok": True, "capability": capability, "value": value}
164
+
165
+ def _first_light_id(self) -> str:
166
+ return (self.config or {}).get("hue_light_id") or "1"
167
+
168
+ async def read_all(self) -> dict:
169
+ try:
170
+ lights = await self._lights()
171
+ out: dict = {}
172
+ for light_id, light in (lights or {}).items():
173
+ out[light_id] = {
174
+ "name": light.get("name", ""),
175
+ "state": light.get("state", {}),
176
+ }
177
+ return out
178
+ except Exception: # noqa: BLE001
179
+ return {}
180
+
181
+
182
+ # ------------------------------------------------------------------ LIFX
183
+
184
+
185
+ def _build_lifx(type_id: int, payload: bytes = b"") -> bytes:
186
+ """构造 LIFX 局域网报文。"""
187
+ seq = 0
188
+ size = 36 + len(payload)
189
+ header = struct.pack(
190
+ "<IBHIQBB",
191
+ size,
192
+ 2, # Origin = Link
193
+ type_id,
194
+ 1, # Version
195
+ seq,
196
+ 0, # Success
197
+ 0, # Reserved
198
+ ) + struct.pack("<I", len(payload))
199
+ return header + payload
200
+
201
+
202
+ async def _lifx_call(ip: str, type_id: int, payload: bytes = b"", timeout: float = 4.0) -> bytes:
203
+ reader, writer = await asyncio.open_connection(ip, 56700)
204
+ try:
205
+ writer.write(_build_lifx(type_id, payload))
206
+ await writer.drain()
207
+ data = await asyncio.wait_for(reader.read(2048), timeout=timeout)
208
+ finally:
209
+ try:
210
+ writer.close()
211
+ except OSError:
212
+ pass
213
+ return data[36:] if len(data) > 36 else b""
214
+
215
+
216
+ @register
217
+ class LifxAdapter(BaseAdapter):
218
+ protocol = 'lifx'
219
+ platform = ''
220
+
221
+ async def list_capabilities(self):
222
+ return []
223
+
224
+ async def write_capability(self, capability, value):
225
+ raise NotImplementedError('LIFX LAN protocol is not implemented')
@@ -0,0 +1,239 @@
1
+ # SPDX-License-Identifier: GPL-3.0-or-later
2
+ """Legacy TP-Link Kasa and Yeelight local protocol adapters.
3
+
4
+ Kasa support is limited to observed legacy relay states. Yeelight controls
5
+ require a reported method in the device's support list. Newer encrypted Kasa
6
+ variants are not implemented here.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import json
13
+ import struct
14
+
15
+ from .base import BaseAdapter, register
16
+
17
+
18
+ def _bool(value) -> bool:
19
+ if isinstance(value, bool):
20
+ return value
21
+ if isinstance(value, (int, float)):
22
+ return value != 0
23
+ if isinstance(value, str):
24
+ return value.lower() in ("1", "true", "on", "yes", "开")
25
+ return bool(value)
26
+
27
+
28
+ # ------------------------------------------------------------------ Kasa
29
+
30
+
31
+ def _kasa_encode(payload: bytes) -> bytes:
32
+ """Legacy Kasa TCP framing and rolling XOR."""
33
+ key = 0xAB
34
+ body = bytearray()
35
+ for byte in payload:
36
+ key ^= byte
37
+ body.append(key)
38
+ return struct.pack(">I", len(body)) + body
39
+
40
+
41
+ def _kasa_decode(data: bytes) -> bytes:
42
+ if len(data) < 4:
43
+ raise ValueError("Truncated Kasa header")
44
+ length = struct.unpack(">I", data[:4])[0]
45
+ if len(data) != length + 4:
46
+ raise ValueError("Invalid Kasa frame length")
47
+ key = 0xAB
48
+ result = bytearray()
49
+ for byte in data[4:]:
50
+ result.append(byte ^ key)
51
+ key = byte
52
+ return bytes(result)
53
+
54
+
55
+ async def _kasa_call(ip: str, payload: dict, timeout: float = 4.0) -> dict:
56
+ body = json.dumps(payload, separators=(",", ":")).encode("utf-8")
57
+ reader, writer = await asyncio.wait_for(asyncio.open_connection(ip, 9999), timeout)
58
+ try:
59
+ writer.write(_kasa_encode(body))
60
+ await writer.drain()
61
+ header = await asyncio.wait_for(reader.readexactly(4), timeout=timeout)
62
+ length = struct.unpack(">I", header)[0]
63
+ if length > 1024 * 1024:
64
+ raise ValueError("Kasa frame too large")
65
+ data = header + await asyncio.wait_for(reader.readexactly(length), timeout=timeout)
66
+ finally:
67
+ writer.close()
68
+ await writer.wait_closed()
69
+ result = json.loads(_kasa_decode(data).decode("utf-8"))
70
+ for module in result.values():
71
+ if isinstance(module, dict):
72
+ for response in module.values():
73
+ if isinstance(response, dict) and response.get("err_code", 0) != 0:
74
+ raise RuntimeError(f"Kasa error: {response}")
75
+ return result
76
+
77
+
78
+ @register
79
+ class KasaAdapter(BaseAdapter):
80
+ """TP-Link Kasa 智能插座 / 开关。"""
81
+
82
+ protocol = "kasa"
83
+ platform = ""
84
+
85
+ async def _sysinfo(self) -> dict:
86
+ result = await _kasa_call(self.ip, {"system": {"get_sysinfo": {}}})
87
+ return (result.get("system") or {}).get("get_sysinfo") or {}
88
+
89
+ async def list_capabilities(self):
90
+ info = await self._sysinfo()
91
+ if 'relay_state' not in info:
92
+ return []
93
+ return [{'key':'power','name':'relay_state','kind':'bool','readable':True,'writable':True}]
94
+
95
+ async def read_capability(self, capability):
96
+ if capability != 'power':
97
+ return None
98
+ info = await self._sysinfo()
99
+ return _bool(info['relay_state']) if 'relay_state' in info else None
100
+
101
+ async def write_capability(self, capability, value):
102
+ if capability != 'power' or 'relay_state' not in await self._sysinfo():
103
+ raise ValueError(f'Kasa unsupported capability {capability}')
104
+ state = 1 if self._value_for_capability(capability, value) else 0
105
+ result = await _kasa_call(self.ip, {'system': {'set_relay_state': {'state': state}}})
106
+ ack = (result.get('system') or {}).get('set_relay_state')
107
+ if not isinstance(ack, dict) or ack.get('err_code') != 0:
108
+ raise RuntimeError('Kasa relay command not acknowledged')
109
+ return {'ok':True,'capability':capability,'value':value}
110
+ async def read_all(self) -> dict:
111
+ info = await self._sysinfo()
112
+ return {'power': _bool(info['relay_state'])} if 'relay_state' in info else {}
113
+
114
+
115
+ # ------------------------------------------------------------------ Yeelight
116
+
117
+
118
+ async def _yeelight_call(ip: str, method: str, params: list, timeout: float = 4.0) -> dict:
119
+ payload = json.dumps({"id": 1, "method": method, "params": params}, separators=(",", ":"))
120
+ reader, writer = await asyncio.wait_for(asyncio.open_connection(ip, 55443), timeout)
121
+ try:
122
+ writer.write((payload + "\r\n").encode("utf-8"))
123
+ await writer.drain()
124
+ async def receive():
125
+ while True:
126
+ line = await reader.readline()
127
+ if not line:
128
+ raise EOFError("Yeelight connection closed before response")
129
+ result = json.loads(line.decode("utf-8"))
130
+ if result.get("id") != 1:
131
+ continue
132
+ if "error" in result:
133
+ raise RuntimeError(f"Yeelight error: {result['error']}")
134
+ if "result" not in result:
135
+ raise ValueError("Invalid Yeelight response")
136
+ return result
137
+ return await asyncio.wait_for(receive(), timeout)
138
+ finally:
139
+ writer.close()
140
+ await writer.wait_closed()
141
+
142
+
143
+ @register
144
+ class YeelightAdapter(BaseAdapter):
145
+ """Yeelight 智能灯(端口 55443)。"""
146
+
147
+ protocol = "yeelight"
148
+ platform = "mihome"
149
+
150
+ _props = {'power':'power', 'brightness':'bright', 'color_temp':'ct', 'color':'rgb'}
151
+ _methods = {'power':'set_power', 'brightness':'set_bright', 'color_temp':'set_ct_abx', 'color':'set_rgb'}
152
+
153
+ def _supported(self):
154
+ fields = getattr(self.device, 'fields', {}) or {}
155
+ support = self.config.get('support', fields.get('support', []))
156
+ if isinstance(support, str):
157
+ return set(support.replace(',', ' ').split())
158
+ return set(support) if isinstance(support, (list, tuple, set)) else set()
159
+
160
+ def _ct_range(self):
161
+ limits = self.config.get('color_temp_range')
162
+ if isinstance(limits, (list,tuple)) and len(limits) == 2 and all(type(x) is int for x in limits) and 0 < limits[0] < limits[1]:
163
+ return list(limits)
164
+ return None
165
+
166
+ async def read_all(self):
167
+ result = await _yeelight_call(self.ip, 'get_prop', list(self._props.values()))
168
+ values = result.get('result')
169
+ if not isinstance(values, list) or len(values) != len(self._props):
170
+ raise RuntimeError('Invalid Yeelight property response')
171
+ out = {}
172
+ for key, value in zip(self._props, values):
173
+ if value is None or value == '':
174
+ continue
175
+ if key == 'power':
176
+ if value not in ('on','off'):
177
+ continue
178
+ out[key] = value == 'on'
179
+ else:
180
+ try:
181
+ val = int(value)
182
+ except (TypeError, ValueError):
183
+ continue
184
+ if key == 'brightness' and not 1 <= val <= 100: continue
185
+ if key == 'color' and not 0 <= val <= 0xffffff: continue
186
+ if key == 'color_temp' and val <= 0: continue
187
+ out[key] = val
188
+ return out
189
+
190
+ async def list_capabilities(self):
191
+ values = await self.read_all()
192
+ supported = self._supported()
193
+ controls = []
194
+ for key in self._props:
195
+ if key not in values: continue
196
+ writable = self._methods[key] in supported
197
+ item = {'key':key,'name':self._props[key],'kind':'bool' if key == 'power' else 'range',
198
+ 'readable':True,'writable':writable}
199
+ if key == 'brightness': item.update({'range':[1,100,1], 'unit':'%'})
200
+ if key == 'color': item['range'] = [0,0xffffff,1]
201
+ if key == 'color_temp':
202
+ limits = self._ct_range()
203
+ item['unit'] = 'K'
204
+ item['writable'] = writable and limits is not None
205
+ if limits: item['range'] = [*limits,1]
206
+ controls.append(item)
207
+ return controls
208
+
209
+ async def read_capability(self, capability):
210
+ return (await self.read_all()).get(capability)
211
+
212
+ async def write_capability(self, capability, value):
213
+ controls = {c['key']:c for c in await self.list_capabilities()}
214
+ if capability not in controls or not controls[capability]['writable']:
215
+ raise ValueError(f'Yeelight does not support writing {capability}')
216
+ if capability == 'power':
217
+ value = self._value_for_capability(capability, value)
218
+ arg = 'on' if value else 'off'
219
+ else:
220
+ if type(value) is not int:
221
+ raise ValueError('Yeelight value must be an integer')
222
+ low, high, _ = controls[capability]['range']
223
+ if not low <= value <= high:
224
+ raise ValueError('Yeelight value outside supported range')
225
+ arg = value
226
+ result = await _yeelight_call(self.ip, self._methods[capability], [arg,'smooth',300])
227
+ if result.get('result') != ['ok']:
228
+ raise RuntimeError('Yeelight command not acknowledged')
229
+ return {'ok':True,'capability':capability,'value':value}
230
+
231
+ async def run_action(self, name, params=None):
232
+ raise NotImplementedError('Yeelight actions are not mapped')
233
+
234
+
235
+ def _rgb_to_int(text: str) -> int:
236
+ import re
237
+ if not isinstance(text, str) or not re.fullmatch(r'#[0-9a-fA-F]{6}', text):
238
+ raise ValueError('RGB must be #RRGGBB')
239
+ return int(text[1:], 16)