@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,342 @@
1
+ # SPDX-License-Identifier: GPL-3.0-or-later
2
+ """Mi Home cloud and explicitly mapped local miIO adapters.
3
+
4
+ Cloud capabilities come from the available MIoT specification and service
5
+ metadata. Local miIO controls require a token and explicit method mappings;
6
+ there is no automatic fallback between transports and no claim of parity with
7
+ the Mi Home app.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import json
14
+ import struct
15
+ import socket
16
+
17
+ from .. import localize
18
+ from .base import BaseAdapter, register
19
+
20
+
21
+ def _capability_from_spec(spec_type: str, prop_name: str) -> str | None:
22
+ """把米家规格属性名映射到统一能力项。
23
+
24
+ 映射不了的返回 None(这些属性仍会作为「其他属性」展示,只是不进
25
+ 统一控制面)。
26
+ """
27
+ name = (prop_name or "").lower()
28
+ if name in ("power", "on", "switch", "power_state"):
29
+ return "power"
30
+ if "brightness" in name or name in ("bri", "bright"):
31
+ return "brightness"
32
+ if "color_temp" in name or "ct" in name.split("_"):
33
+ return "color_temp"
34
+ if name in ("color", "color_value", "rgb", "hue", "saturation"):
35
+ return "color"
36
+ if name in ("mode", "mode_enum", "work_mode"):
37
+ return "mode"
38
+ if "fan_speed" in name or "speed" in name.split("_"):
39
+ return "fan_speed"
40
+ if "target_temp" in name or "target_temperature" in name:
41
+ return "target_temp"
42
+ if "target_humidity" in name or "target_humidity" in name:
43
+ return "target_humidity"
44
+ if "swing" in name or "swing_vertical" in name or "swing_horizontal" in name:
45
+ return "swing"
46
+ if name in ("position", "curtain_position", "percent"):
47
+ return "position"
48
+ if name in ("volume", "volume_level"):
49
+ return "volume"
50
+ if name in ("mute", "muted"):
51
+ return "mute"
52
+ if "input_source" in name or "input" in name.split("_"):
53
+ return "input_source"
54
+ if name in ("channel", "tv_channel"):
55
+ return "channel"
56
+ if name in ("clean", "start_clean", "clean_mode"):
57
+ return "clean"
58
+ if name in ("charge", "start_charge", "go_charge"):
59
+ return "charge"
60
+ if name in ("locate", "find", "find_device"):
61
+ return "locate"
62
+ if name in ("reboot", "restart"):
63
+ return "reboot"
64
+ if name in ("filter_life", "filter_life_remaining", "filter_life_time"):
65
+ return "filter_life"
66
+ if name in ("battery", "battery_level", "battery_percentage"):
67
+ return "battery"
68
+ return None
69
+
70
+
71
+ def _map_spec_props(props: list[dict]) -> tuple[list[dict], list[dict]]:
72
+ """Keep property names as stable, service-qualified control identifiers."""
73
+ controls = []
74
+ for prop in props or []:
75
+ name = str(prop.get('name') or '')
76
+ if not name:
77
+ continue
78
+ values = prop.get('value_list') or []
79
+ value_range = prop.get('range')
80
+ typ = str(prop.get('type') or '').lower()
81
+ kind = 'enum' if values else ('bool' if typ in ('bool', 'boolean') else ('range' if value_range else 'text'))
82
+ controls.append({'key': name, 'name': name, 'zh': prop.get('zh') or prop.get('desc') or name,
83
+ 'kind': kind, 'type': prop.get('type'), 'readable': bool(prop.get('readable')),
84
+ 'writable': bool(prop.get('writable')), 'range': value_range,
85
+ 'value_list': values, 'unit': prop.get('unit') or ''})
86
+ return controls, []
87
+
88
+
89
+ @register
90
+ class MiHomeCloudAdapter(BaseAdapter):
91
+ protocol = 'mihome'
92
+ platform = 'mihome'
93
+
94
+ def __init__(self, device, config=None):
95
+ super().__init__(device, config)
96
+ self.cloud = (config or {}).get('cloud')
97
+ self._detail = None
98
+
99
+ def _svc(self):
100
+ if self.cloud is None:
101
+ raise RuntimeError('米家云端未注入')
102
+ return self.cloud
103
+
104
+ async def _ensure_detail(self):
105
+ if self._detail is None:
106
+ detail = self._svc().device_detail(self.device.did)
107
+ self._detail = localize.localize_device(_plain_detail(detail), self.protocol, self.platform)
108
+ return self._detail
109
+
110
+ async def list_capabilities(self):
111
+ if self.cloud is None:
112
+ return []
113
+ try:
114
+ detail = await self._ensure_detail()
115
+ except Exception as exc:
116
+ self.log(f'[smart-home] 米家规格读取失败:{exc}')
117
+ return []
118
+ controls, _ = _map_spec_props(detail.get('props', []))
119
+ for action in detail.get('actions', []):
120
+ name = str(action.get('name') or '')
121
+ if name:
122
+ controls.append({'key': name, 'name': name, 'zh': action.get('zh') or action.get('desc') or name,
123
+ 'kind': 'action', 'readable': False, 'writable': True,
124
+ 'range': None, 'value_list': [], 'unit': ''})
125
+ return controls
126
+
127
+ async def power_state(self):
128
+ """Use Mi Home's confirmed power-state mapping, not a guessed spec key."""
129
+ return self._svc().power_state(self.device.did)
130
+
131
+ async def power(self, state):
132
+ if not isinstance(state, bool):
133
+ raise ValueError('state 必须为布尔值')
134
+ self._svc().set_power_state(self.device.did, state)
135
+ return {'ok': True, 'on': state}
136
+
137
+ async def read_capability(self, capability):
138
+ controls = await self.list_capabilities()
139
+ control = next((c for c in controls if c['key'] == capability and c['kind'] != 'action'), None)
140
+ if not control or not control['readable']:
141
+ return None
142
+ values = self._svc().read_props(self.device.did, [control['name']])
143
+ if isinstance(values, dict):
144
+ return values.get(control['name'])
145
+ return values[0] if isinstance(values, list) and values else None
146
+
147
+ async def write_capability(self, capability, value):
148
+ controls = await self.list_capabilities()
149
+ control = next((c for c in controls if c['key'] == capability and c['kind'] != 'action'), None)
150
+ if not control or not control['writable']:
151
+ raise ValueError(f'属性 {capability} 不可写')
152
+ self._svc().write_prop(self.device.did, control['name'], value)
153
+ return {'ok': True, 'capability': capability, 'value': value}
154
+
155
+ async def run_action(self, name, params=None):
156
+ if not any(c['key'] == name and c['kind'] == 'action' for c in await self.list_capabilities()):
157
+ raise ValueError(f'未知动作 {name}')
158
+ self._svc().run_action(self.device.did, name, params)
159
+ return {'ok': True, 'action': name}
160
+
161
+ async def read_all(self):
162
+ controls = [c for c in await self.list_capabilities() if c['readable'] and c['kind'] != 'action']
163
+ if not controls:
164
+ return {}
165
+ values = self._svc().read_props(self.device.did, [c['name'] for c in controls])
166
+ if isinstance(values, dict):
167
+ return {c['key']: values[c['name']] for c in controls if c['name'] in values}
168
+ if isinstance(values, list):
169
+ return {c['key']: value for c, value in zip(controls, values)}
170
+ return {}
171
+
172
+ async def close(self):
173
+ self._detail = None
174
+
175
+
176
+ def _plain_detail(detail):
177
+ from dataclasses import asdict, is_dataclass
178
+ if is_dataclass(detail):
179
+ return asdict(detail)
180
+ return detail if isinstance(detail, dict) else {}
181
+
182
+
183
+ _MIIO_NOOP = bytes.fromhex('21310020ffffffffffffffffffffffffffffffffffffffffffffffffffffffff')
184
+
185
+
186
+ def _miio_unpack(packet, token, expected_id=None):
187
+ import hashlib
188
+ import hmac
189
+ from Crypto.Cipher import AES
190
+ from Crypto.Util.Padding import unpad
191
+ if len(packet) < 32:
192
+ raise ValueError('Truncated miIO packet')
193
+ magic, length, _, did, stamp = struct.unpack('>HHIII', packet[:16])
194
+ if magic != 0x2131 or length != len(packet):
195
+ raise ValueError('Invalid miIO packet header')
196
+ if expected_id is not None and did != expected_id:
197
+ raise ValueError('Unexpected miIO device id')
198
+ body = packet[32:]
199
+ checksum = hashlib.md5(packet[:16] + token + body).digest()
200
+ if not hmac.compare_digest(packet[16:32], checksum):
201
+ raise ValueError('Invalid miIO checksum')
202
+ if not body or len(body) % 16:
203
+ raise ValueError('Invalid miIO ciphertext length')
204
+ key = hashlib.md5(token).digest()
205
+ iv = hashlib.md5(key + token).digest()
206
+ return json.loads(unpad(AES.new(key, AES.MODE_CBC, iv).decrypt(body), 16).decode('utf-8'))
207
+
208
+
209
+ async def _miio_send(ip, token, payload, timeout=5.0):
210
+ import hashlib
211
+ import time
212
+ from Crypto.Cipher import AES
213
+ from Crypto.Util.Padding import pad
214
+ try:
215
+ token = bytes.fromhex(token)
216
+ except (ValueError, TypeError):
217
+ raise ValueError('miIO token must be 16-byte hex') from None
218
+ if len(token) != 16:
219
+ raise ValueError('miIO token must be 16-byte hex')
220
+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
221
+ sock.setblocking(False)
222
+ sock.connect((ip, 54321))
223
+ loop = asyncio.get_running_loop()
224
+ try:
225
+ await asyncio.wait_for(loop.sock_sendall(sock, _MIIO_NOOP), timeout)
226
+ hello = await asyncio.wait_for(loop.sock_recv(sock, 65535), timeout)
227
+ if len(hello) != 32:
228
+ raise ValueError('Invalid miIO hello length')
229
+ magic, length, _, did, stamp = struct.unpack('>HHIII', hello[:16])
230
+ if magic != 0x2131 or length != 32 or did == 0xffffffff or stamp == 0xffffffff:
231
+ raise ValueError('Invalid miIO hello')
232
+ start = time.monotonic()
233
+ key = hashlib.md5(token).digest()
234
+ iv = hashlib.md5(key + token).digest()
235
+ body = AES.new(key, AES.MODE_CBC, iv).encrypt(pad(json.dumps(payload, separators=(',', ':')).encode('utf-8'), 16))
236
+ header = struct.pack('>HHIII', 0x2131, 32 + len(body), 0, did, (stamp + int(time.monotonic() - start)) & 0xffffffff)
237
+ packet = header + hashlib.md5(header + token + body).digest() + body
238
+ await asyncio.wait_for(loop.sock_sendall(sock, packet), timeout)
239
+ response = await asyncio.wait_for(loop.sock_recv(sock, 65535), timeout)
240
+ result = _miio_unpack(response, token, did)
241
+ if not isinstance(result, dict) or result.get('id') != payload.get('id'):
242
+ raise ValueError('Unexpected miIO response id')
243
+ return result
244
+ finally:
245
+ sock.close()
246
+
247
+
248
+ def _replace_value(obj, value):
249
+ if obj == '$value':
250
+ return value
251
+ if isinstance(obj, list):
252
+ return [_replace_value(x, value) for x in obj]
253
+ if isinstance(obj, dict):
254
+ return {k: _replace_value(v, value) for k, v in obj.items()}
255
+ return obj
256
+
257
+
258
+ @register
259
+ class MiIOAdapter(BaseAdapter):
260
+ """Local miIO controls require an explicit per-device miio_mapping.
261
+
262
+ Each mapping entry declares kind, readable/writable, read_method/read_params,
263
+ write_method/write_params; '$value' is replaced without type conversion.
264
+ """
265
+ protocol = 'miio'
266
+ platform = 'mihome'
267
+
268
+ def __init__(self, device, config=None):
269
+ super().__init__(device, config)
270
+ self.cloud = self.config.get('cloud')
271
+ creds = getattr(device, 'credentials', {}) or {}
272
+ tokens = self.config.get('miio_tokens') or {}
273
+ self.token = tokens.get(self.ip) or tokens.get(self.mac.upper()) or creds.get('token') or self.config.get('miio_token') or ''
274
+ if not self.token and self.cloud is not None and getattr(self.cloud, 'miio_token', None):
275
+ self.token = self.cloud.miio_token(self.ip, self.mac)
276
+
277
+ def is_supported(self):
278
+ return bool(self.token)
279
+
280
+ def _mapping(self):
281
+ mapping = self.config.get('miio_mapping') or self.config.get('miot_mapping') or {}
282
+ return mapping if isinstance(mapping, dict) else {}
283
+
284
+ async def _call(self, method, params=None):
285
+ if not self.token:
286
+ raise RuntimeError('miIO 控制需要设备 token')
287
+ result = await _miio_send(self.ip, self.token, {'id': 1, 'method': method, 'params': [] if params is None else params})
288
+ if result.get('error') or result.get('code', 0) != 0:
289
+ raise RuntimeError(f"miIO 返回错误:{result.get('error', result)}")
290
+ if 'result' not in result:
291
+ raise RuntimeError('miIO response missing result')
292
+ for item in result['result'] if isinstance(result['result'], list) else [result['result']]:
293
+ if isinstance(item, dict) and item.get('code', 0) != 0:
294
+ raise RuntimeError(f'miIO property error: {item}')
295
+ return result
296
+
297
+ async def list_capabilities(self):
298
+ controls = []
299
+ for key, spec in self._mapping().items():
300
+ if not isinstance(spec, dict):
301
+ continue
302
+ item = {k: spec[k] for k in ('kind', 'range', 'value_list', 'unit', 'zh') if k in spec}
303
+ item.update({'key': key, 'name': spec.get('name', key), 'kind': spec.get('kind', 'text'),
304
+ 'readable': bool(spec.get('readable') and spec.get('read_method')),
305
+ 'writable': bool(spec.get('writable') and spec.get('write_method'))})
306
+ controls.append(item)
307
+ return controls
308
+
309
+ def _spec(self, capability, operation):
310
+ spec = self._mapping().get(capability)
311
+ if not isinstance(spec, dict) or not spec.get('readable' if operation == 'read' else 'writable') or not spec.get(operation + '_method'):
312
+ raise ValueError(f'miIO {capability} does not support {operation}')
313
+ return spec
314
+
315
+ async def read_capability(self, capability):
316
+ spec = self._spec(capability, 'read')
317
+ result = (await self._call(spec['read_method'], spec.get('read_params', [])))['result']
318
+ if isinstance(result, list):
319
+ result = result[0] if result else None
320
+ if isinstance(result, dict) and 'value' in result:
321
+ result = result['value']
322
+ return result
323
+
324
+ async def write_capability(self, capability, value):
325
+ spec = self._spec(capability, 'write')
326
+ params = _replace_value(spec.get('write_params', ['$value']), value)
327
+ await self._call(spec['write_method'], params)
328
+ return {'ok': True, 'capability': capability, 'value': value}
329
+
330
+ async def run_action(self, name, params=None):
331
+ spec = self._mapping().get(name)
332
+ if not isinstance(spec, dict) or spec.get('kind') != 'action' or not spec.get('writable') or not spec.get('write_method'):
333
+ raise ValueError(f'未知动作 {name}')
334
+ result = await self._call(spec['write_method'], params if params is not None else spec.get('write_params', []))
335
+ return {'ok': True, 'action': name, 'result': result['result']}
336
+
337
+ async def read_all(self):
338
+ out = {}
339
+ for cap in await self.list_capabilities():
340
+ if cap['readable'] and cap['kind'] != 'action':
341
+ out[cap['key']] = await self.read_capability(cap['key'])
342
+ return out
@@ -0,0 +1,250 @@
1
+ # SPDX-License-Identifier: GPL-3.0-or-later
2
+ """路由器、交换机、光猫、NAS 和通用 HTTP 设备的公开页面读取。
3
+
4
+ 提取公开页面的标题、表单字段名和表格;HTTP 成功仅表示页面读取成功,
5
+ 不表示已经登录或取得管理设置。当前没有厂商认证、提权或设置写入实现。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+
12
+ from .. import catalog, util
13
+ from .base import BaseAdapter, register
14
+
15
+
16
+ def _bool(value) -> bool:
17
+ if isinstance(value, bool):
18
+ return value
19
+ if isinstance(value, (int, float)):
20
+ return value != 0
21
+ if isinstance(value, str):
22
+ return value.lower() in ("1", "true", "on", "yes", "开")
23
+ return bool(value)
24
+
25
+
26
+ def _parse_html(text: str) -> dict:
27
+ """从 HTML 里提取可读的结构化信息。
28
+
29
+ 不引第三方 HTML 解析库(插件依赖已经不少):标签结构用正则即可,
30
+ 目标是「把页面里用户能看到的信息搬出来」,不是渲染页面。
31
+ """
32
+ title = ""
33
+ match = re.search(r"(?is)<title[^>]*>(.*?)</title>", text)
34
+ if match:
35
+ title = util.strip_html(match.group(1))[:200]
36
+
37
+ links: list[str] = []
38
+ for href in re.findall(r'(?is)href=["\']([^"\']+)["\']', text):
39
+ if href and not href.startswith(("javascript:", "#", "data:")):
40
+ links.append(href[:200])
41
+
42
+ forms: list[dict] = []
43
+ for form in re.findall(r"(?is)<form[^>]*>(.*?)</form>", text):
44
+ fields: dict[str, str] = {}
45
+ for m in re.finditer(r'(?is)<input[^>]+>', form):
46
+ tag = m.group(0)
47
+ name = re.search(r'name=["\']([^"\']+)["\']', tag)
48
+ if name:
49
+ # Form values can include credentials, CSRF tokens and session IDs.
50
+ fields[name.group(1)] = ""
51
+ if fields:
52
+ forms.append(fields)
53
+
54
+ # 表格:第一列作键、第二列作值
55
+ table: dict[str, str] = {}
56
+ for row in re.findall(r"(?is)<tr[^>]*>(.*?)</tr>", text):
57
+ cells = [util.strip_html(c) for c in re.findall(r"(?is)<t[dh][^>]*>(.*?)</t[dh]>", row)]
58
+ cells = [c for c in cells if c]
59
+ if len(cells) >= 2:
60
+ table[cells[0][:100]] = cells[1][:200]
61
+
62
+ visible = util.strip_html(text)[:4000]
63
+
64
+ return {
65
+ "title": title,
66
+ "links": links[:50],
67
+ "forms": forms[:20],
68
+ "table": table,
69
+ "visible": visible,
70
+ }
71
+
72
+
73
+ async def _page(ip: str, port: int, path: str = "/", tls: bool = False, timeout: float = 3.0):
74
+ from .. import util
75
+
76
+ resp = await util.http_get_async(f"{'https' if tls else 'http'}://{ip}:{port}{path}", timeout=timeout)
77
+ if resp is None:
78
+ return None
79
+ try:
80
+ text = resp.text or ""
81
+ except Exception: # noqa: BLE001
82
+ text = resp.content.decode("utf-8", errors="replace")
83
+ server = resp.headers.get("Server", "") if resp.headers is not None else ""
84
+ return {
85
+ "url": f"{'https' if tls else 'http'}://{ip}:{port}{path}",
86
+ "status": resp.status_code,
87
+ "server": server,
88
+ "text": text[:20000],
89
+ }
90
+
91
+
92
+ class _PageAdapter(BaseAdapter):
93
+ """按 HTTP 管理页工作的设备适配器基类。"""
94
+
95
+ def _ports(self) -> list[int]:
96
+ return list(getattr(self.device, "ports", []) or [])
97
+
98
+ async def _scrape(self) -> dict:
99
+ ports = self._ports() or [80, 443]
100
+ failure = {"ok": False, "public_only": True, "protocol": self.protocol,
101
+ "error": "管理页不可达或未返回可读取的公开页面"}
102
+ for port in ports:
103
+ if port not in (80, 443, 8080, 8081, 8000, 5000, 5001):
104
+ continue
105
+ for tls in (False, True):
106
+ page = await _page(self.ip, port, "/", tls)
107
+ if page is None:
108
+ continue
109
+ if not 200 <= page["status"] < 300:
110
+ failure.update(http_status=page["status"], url=page["url"],
111
+ error=f"公开页面读取失败(HTTP {page['status']});未执行登录或设置修改")
112
+ continue
113
+ data = _parse_html(page["text"])
114
+ data.update(ok=True, public_only=True)
115
+ data["url"] = page["url"]
116
+ data["server"] = page["server"]
117
+ data["status"] = page["status"]
118
+ data["http_status"] = page["status"]
119
+ data["protocol"] = self.protocol
120
+ return data
121
+ return failure
122
+
123
+ async def read_capability(self, capability: str):
124
+ if capability == "status":
125
+ return await self.scrape()
126
+ if capability == "reboot":
127
+ return False
128
+ return None
129
+
130
+ async def write_capability(self, capability: str, value) -> dict:
131
+ if capability == "reboot":
132
+ return await self.reboot()
133
+ raise ValueError(f"{self.protocol} 不支持写入 {capability}")
134
+
135
+ async def reboot(self) -> dict:
136
+ raise NotImplementedError(f"{self.protocol} 未实现重启接口")
137
+
138
+ async def scrape(self) -> dict:
139
+ return await self._scrape()
140
+
141
+
142
+ @register
143
+ class RouterAdapter(_PageAdapter):
144
+ """路由器:扒管理页设置。"""
145
+
146
+ protocol = "router"
147
+ platform = ""
148
+
149
+ async def list_capabilities(self) -> list[dict]:
150
+ return [
151
+ {"key": "status", "name": "system_info", "zh": catalog.capability_zh("status"),
152
+ "en": catalog.capability_en("status"), "kind": "json", "readable": True, "writable": False},
153
+ ]
154
+
155
+ async def reboot(self) -> dict:
156
+ raise NotImplementedError("Unverified router reboot is unsupported")
157
+
158
+ async def scrape(self) -> dict:
159
+ data = await self._scrape()
160
+ if not data:
161
+ return {"protocol": "router", "note": "管理页不可达(可能需要登录或页面由 JS 动态加载)"}
162
+ data["note"] = "仅读取公开管理页;登录页不等于设备设置,当前未实现登录或设置修改"
163
+ return data
164
+
165
+
166
+ @register
167
+ class SwitchAdapter(_PageAdapter):
168
+ """交换机:仅读取可公开访问的管理页内容。"""
169
+
170
+ protocol = "switch"
171
+ platform = ""
172
+
173
+ async def list_capabilities(self) -> list[dict]:
174
+ return [
175
+ {"key": "status", "name": "system_info", "zh": catalog.capability_zh("status"),
176
+ "en": catalog.capability_en("status"), "kind": "json", "readable": True, "writable": False},
177
+ ]
178
+
179
+ async def scrape(self) -> dict:
180
+ data = await self._scrape()
181
+ if not data:
182
+ return {"protocol": "switch", "note": "交换机管理页不可达(可能需要登录或非网管型交换机)"}
183
+ data["note"] = "交换机设置通过管理页扒取;品牌页面差异大,字段以页面为准"
184
+ return data
185
+
186
+
187
+ @register
188
+ class OnuAdapter(_PageAdapter):
189
+ """光猫 / ONT:需要超级管理员权限。"""
190
+
191
+ protocol = "onu"
192
+ platform = ""
193
+
194
+ async def list_capabilities(self) -> list[dict]:
195
+ return [
196
+ {"key": "status", "name": "system_info", "zh": catalog.capability_zh("status"),
197
+ "en": catalog.capability_en("status"), "kind": "json", "readable": True, "writable": False},
198
+ ]
199
+
200
+ async def scrape(self) -> dict:
201
+ data = await self._scrape()
202
+ if not data:
203
+ return {"protocol": "onu", "note": "光猫管理页不可达(可能被运营商锁定或需要超管账号)"}
204
+ data["note"] = "仅读取公开信息页;当前未实现超管认证、提权或光猫设置修改"
205
+ return data
206
+
207
+
208
+ @register
209
+ class NasAdapter(_PageAdapter):
210
+ """NAS:扒官方 Web 管理页。"""
211
+
212
+ protocol = "nas"
213
+ platform = ""
214
+
215
+ async def list_capabilities(self) -> list[dict]:
216
+ return [
217
+ {"key": "status", "name": "system_info", "zh": catalog.capability_zh("status"),
218
+ "en": catalog.capability_en("status"), "kind": "json", "readable": True, "writable": False},
219
+ ]
220
+
221
+ async def reboot(self) -> dict:
222
+ raise NotImplementedError("Unverified NAS reboot is unsupported")
223
+
224
+ async def scrape(self) -> dict:
225
+ data = await self._scrape()
226
+ if not data:
227
+ return {"protocol": "nas", "note": "NAS 管理页不可达(可能需要登录)"}
228
+ data["note"] = "仅读取公开 Web 页面;当前未实现 NAS 认证会话或设置修改"
229
+ return data
230
+
231
+
232
+ @register
233
+ class HttpGenericAdapter(_PageAdapter):
234
+ """识别不出具体协议、但开了 HTTP 服务的设备:扒页面当状态看。"""
235
+
236
+ protocol = "http"
237
+ platform = ""
238
+
239
+ async def list_capabilities(self) -> list[dict]:
240
+ return [
241
+ {"key": "status", "name": "page", "zh": catalog.capability_zh("status"),
242
+ "en": catalog.capability_en("status"), "kind": "json", "readable": True, "writable": False},
243
+ ]
244
+
245
+ async def scrape(self) -> dict:
246
+ data = await self._scrape()
247
+ if not data:
248
+ return {"protocol": "http", "note": "HTTP 服务不可达或未返回可解析页面"}
249
+ data["note"] = "未识别到具体协议,仅展示 HTTP 页面内容"
250
+ return data