@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,934 @@
1
+ # SPDX-License-Identifier: GPL-3.0-or-later
2
+ """局域网发现:扫描网段、识别设备、给出协议与类别。
3
+
4
+ 扫描分三步,每步都设计成「失败不致命」:
5
+
6
+ 1. **候选主机**:先读 ARP 表拿到已缓存的主机,再按需要做 ping 扫描补齐。
7
+ ARP 表是最快的一条路径,绝大多数常在线设备都会在表里。
8
+ 2. **端口探测**:对候选主机并发探测一组常见端口。
9
+ 3. **指纹识别**:对开放端口做协议级探测(HTTP 页面、SSDP、mDNS、miIO
10
+ hello、涂鸦 UDP 等),输出 ``protocol`` / ``category`` / ``name`` /
11
+ ``model``,交给 ``manager`` 建适配器。
12
+
13
+ 识别不到的设备仍然会被保留(协议为 ``unknown``),只是不能控制——
14
+ 宁可把设备列出来让用户看到,也不要悄悄漏掉。
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import asyncio
20
+ import ipaddress
21
+ import json
22
+ import re
23
+ import time
24
+ from dataclasses import dataclass, field
25
+
26
+ from . import catalog, util
27
+
28
+ # ------------------------------------------------------------------ 数据结构
29
+
30
+
31
+ @dataclass
32
+ class ProbeResult:
33
+ """一次指纹识别的结论。"""
34
+
35
+ protocol: str
36
+ category: str
37
+ name: str = ""
38
+ model: str = ""
39
+ confidence: float = 0.5
40
+ fields: dict = field(default_factory=dict)
41
+
42
+
43
+ _SENSITIVE_FIELD_RE = re.compile(
44
+ r"(?:^|[_-])(local[_-]?key|password|passwd|token|secret|credential|api[_-]?key|private[_-]?key|auth)(?:$|[_-])",
45
+ re.I,
46
+ )
47
+
48
+
49
+ def _public_value(value):
50
+ if isinstance(value, dict):
51
+ return {
52
+ str(key): _public_value(item)
53
+ for key, item in value.items()
54
+ if not _SENSITIVE_FIELD_RE.search(str(key))
55
+ }
56
+ if isinstance(value, (list, tuple)):
57
+ return [_public_value(item) for item in value]
58
+ return value
59
+
60
+
61
+ @dataclass
62
+ class ScannedDevice:
63
+ """扫描得到的一台设备(尚未建适配器)。"""
64
+
65
+ ip: str
66
+ address: str = ""
67
+ mac: str = ""
68
+ vendor: str = ""
69
+ ports: list[int] = field(default_factory=list)
70
+ protocol: str = "unknown"
71
+ category: str = "other"
72
+ name: str = ""
73
+ model: str = ""
74
+ confidence: float = 0.0
75
+ source: str = ""
76
+ http_title: str = ""
77
+ http_server: str = ""
78
+ requires_credentials: bool = False
79
+ fields: dict = field(default_factory=dict)
80
+ credentials: dict = field(default_factory=dict, repr=False)
81
+
82
+ def to_dict(self) -> dict:
83
+ """序列化可公开设备信息;credential 永不进入扫描结果。"""
84
+ return {
85
+ "ip": self.ip,
86
+ "address": self.address,
87
+ "mac": self.mac,
88
+ "vendor": self.vendor,
89
+ "ports": list(self.ports),
90
+ "protocol": self.protocol,
91
+ "category": self.category,
92
+ "name": self.name,
93
+ "model": self.model,
94
+ "confidence": round(self.confidence, 3),
95
+ "source": self.source,
96
+ "http_title": self.http_title,
97
+ "http_server": self.http_server,
98
+ "requires_credentials": bool(self.requires_credentials),
99
+ "fields": _public_value(self.fields),
100
+ }
101
+
102
+
103
+ # ------------------------------------------------------------------ 基础探测
104
+
105
+
106
+ async def fetch_http(ip: str, port: int, use_tls: bool = False, path: str = "/", timeout: float = 2.5):
107
+ """抓一次 HTTP 响应,返回 ``(title, server, text, final_url)``;失败返回 None。"""
108
+ scheme = "https" if use_tls else "http"
109
+ resp = await util.http_get_async(f"{scheme}://{ip}:{port}{path}", timeout=timeout)
110
+ if resp is None:
111
+ return None
112
+ try:
113
+ text = resp.text or ""
114
+ except Exception: # noqa: BLE001
115
+ text = resp.content.decode("utf-8", errors="replace")
116
+ title = ""
117
+ match = re.search(r"(?is)<title[^>]*>(.*?)</title>", text)
118
+ if match:
119
+ title = util.strip_html(match.group(1))[:120]
120
+ server = resp.headers.get("Server", "") if resp.headers is not None else ""
121
+ return title, server, text[:8000], f"{scheme}://{ip}:{port}{path}"
122
+
123
+
124
+ def fingerprint_http(
125
+ title: str,
126
+ server: str,
127
+ text: str,
128
+ ip: str,
129
+ port: int,
130
+ ) -> ProbeResult | None:
131
+ """从 HTTP 首页文本识别设备。
132
+
133
+ 注意:识别顺序很重要。像「Tasmota」「WLED」「Shelly」这类固件会在页面
134
+ 里写明自己,先看它们,再退回通用的「管理页面」判断,避免把
135
+ Tasmota 设备误判成普通路由器。
136
+ """
137
+ haystack = f"{title} {server} {text}".lower()
138
+
139
+ # ---- 智能家居固件(优先,特征最明确)------------------------
140
+ if "tasmota" in haystack or "tasmota" in title.lower():
141
+ model = _first(text, r"Tasmota\s+([0-9][0-9.]*)", r"Device:\s*([^\n<]+)")
142
+ return ProbeResult("tasmota", catalog.guess_category(title, text), name=title,
143
+ model=model, confidence=0.95, fields={"http_title": title, "http_server": server})
144
+ if "wled" in haystack:
145
+ model = _first(text, r'"ver"\s*:\s*"([^"]+)"')
146
+ return ProbeResult("wled", catalog.guess_category(title, text), name=title,
147
+ model=model, confidence=0.95, fields={"http_title": title})
148
+ if "shelly" in haystack or "shelly" in title.lower():
149
+ model = _first(text, r'"model"\s*:\s*"([^"]+)"', r'"device"\s*:\s*"([^"]+)"')
150
+ return ProbeResult("shelly", catalog.guess_category(title, text), name=title,
151
+ model=model, confidence=0.95, fields={"http_title": title})
152
+ if "esphome" in haystack:
153
+ model = _first(text, r'"model"\s*:\s*"([^"]+)"', r'"name"\s*:\s*"([^"]+)"')
154
+ return ProbeResult("esphome", catalog.guess_category(title, text), name=title,
155
+ model=model, confidence=0.9, fields={"http_title": title})
156
+ if "yeelight" in haystack or "yeelink" in haystack:
157
+ model = _first(text, r'"model"\s*:\s*"([^"]+)"', r'"id"\s*:\s*"([^"]+)"')
158
+ return ProbeResult("yeelight", catalog.guess_category(title, text), name=title,
159
+ model=model, confidence=0.95, fields={"http_title": title})
160
+ if "home assistant" in haystack:
161
+ return ProbeResult("home_assistant", "gateway", name=title,
162
+ model="home-assistant", confidence=0.95, fields={"http_title": title})
163
+ if "hue bridge" in haystack or "philips hue" in haystack:
164
+ return ProbeResult("hue", "gateway", name=title, model="hue-bridge",
165
+ confidence=0.95, fields={"http_title": title})
166
+ if "onvif" in haystack or "/onvif/" in text.lower():
167
+ return ProbeResult("onvif", catalog.guess_category(title, text), name=title,
168
+ model="onvif", confidence=0.85, fields={"http_title": title})
169
+
170
+ # ---- 电视 / 投影 ----------------------------------------------
171
+ if "samsung" in haystack or "tizen" in haystack or "samsung" in server.lower():
172
+ return ProbeResult("samsung_tv", "tv", name=title, model="samsung-tv",
173
+ confidence=0.9, fields={"http_title": title, "http_server": server})
174
+ if "lg webos" in haystack or "webos" in haystack:
175
+ return ProbeResult("lg_tv", "tv", name=title, model="lg-tv",
176
+ confidence=0.9, fields={"http_title": title})
177
+ if "vizio" in haystack:
178
+ return ProbeResult("vizio_tv", "tv", name=title, model="vizio-tv",
179
+ confidence=0.9, fields={"http_title": title})
180
+ if "tcl" in haystack and "tv" in haystack:
181
+ return ProbeResult("tcl_tv", "tv", name=title, model="tcl-tv",
182
+ confidence=0.75, fields={"http_title": title})
183
+ if "hisense" in haystack or "海信" in title:
184
+ return ProbeResult("hisense_tv", "tv", name=title, model="hisense-tv",
185
+ confidence=0.75, fields={"http_title": title})
186
+
187
+ # ---- 网络设备 -------------------------------------------------
188
+ # 顺序很重要:先认「厂商 + 品类都很明确」的条目(NAS / OpenWrt / H3C /
189
+ # TP-Link / 小米路由),再退到「可能的光猫」这种弱判断。光猫只按
190
+ # GPON/EPON 这类协议词或页面明确自称 ONT 来认,不能因为标题里有个
191
+ # 「光纤」就把路由器当成光猫。
192
+ if "synology" in haystack or "dsm" in haystack:
193
+ return ProbeResult("synology", "nas", name=title, model="synology",
194
+ confidence=0.9, fields={"http_title": title})
195
+ if "qnap" in haystack:
196
+ return ProbeResult("qnap", "nas", name=title, model="qnap",
197
+ confidence=0.9, fields={"http_title": title})
198
+ if "truenas" in haystack:
199
+ return ProbeResult("truenas", "nas", name=title, model="truenas",
200
+ confidence=0.9, fields={"http_title": title})
201
+ if "openwrt" in haystack or "luci" in haystack:
202
+ return ProbeResult("openwrt", "router", name=title, model="openwrt",
203
+ confidence=0.85, fields={"http_title": title})
204
+ if "h3c" in haystack or "comware" in haystack:
205
+ return ProbeResult("h3c", "net_switch", name=title, model="h3c",
206
+ confidence=0.8, fields={"http_title": title})
207
+ if _looks_like_tplink(title, haystack):
208
+ return ProbeResult("tplink", _router_or_light(haystack), name=title, model="tp-link",
209
+ confidence=0.85, fields={"http_title": title})
210
+ if "miwifi" in haystack or "小米路由器" in title or "xiaomi router" in haystack:
211
+ return ProbeResult("mirouter", "router", name=title, model="mi-router",
212
+ confidence=0.85, fields={"http_title": title})
213
+ if "huawei" in haystack or "华为" in title or "epon" in haystack or "gpon" in haystack:
214
+ # 华为 + GPON/EPON 才像光猫;单说华为更可能是路由器/交换机
215
+ category = "onu" if ("epon" in haystack or "gpon" in haystack or "光猫" in title) else _router_or_light(haystack)
216
+ return ProbeResult("onu", category, name=title, model="huawei",
217
+ confidence=0.75, fields={"http_title": title})
218
+ if "zte" in haystack or "中兴" in title:
219
+ category = "onu" if ("epon" in haystack or "gpon" in haystack or "光猫" in title) else _router_or_light(haystack)
220
+ return ProbeResult("onu", category, name=title, model="zte",
221
+ confidence=0.7, fields={"http_title": title})
222
+
223
+ # ---- 兜底:能开 HTTP 管理页 ---------------------------------
224
+ if title or server:
225
+ category = catalog.guess_category(title, text, server)
226
+ # 标题里没认出品类的管理页,按页面里的路由/光猫/交换机词做一次
227
+ # 弱判断:家庭网段里能开 HTTP 管理页、又不是已知固件的,绝大多数
228
+ # 是网络设备。判不出来才退回 other。
229
+ if category == "other":
230
+ guessed = _router_or_light(haystack)
231
+ if guessed != "router" or _has_network_words(haystack):
232
+ category = guessed
233
+ return ProbeResult("http", category, name=title or f"{ip}:{port}",
234
+ model=server or "", confidence=0.4,
235
+ fields={"http_title": title, "http_server": server})
236
+ return None
237
+
238
+
239
+ def _has_network_words(haystack: str) -> bool:
240
+ """页面里有没有管理界面的网络词(用来确认「这是个网络设备管理页」)。"""
241
+ return any(_word_hit(haystack, w) for w in _ROUTER_WORDS + _ONU_WORDS + _SWITCH_WORDS)
242
+
243
+
244
+ def _first(text: str, *patterns: str) -> str:
245
+ for pattern in patterns:
246
+ match = re.search(pattern, text, re.I)
247
+ if match:
248
+ return match.group(1).strip()[:120]
249
+ return ""
250
+
251
+
252
+ # 路由器管理页里常见的词。厂商前缀能认出牌子,但「路由器 / 光猫 / 交换机」
253
+ # 还得看页面是不是这套 Web 管理界面;TP-Link / 华为 / 中兴都同时做路由器和
254
+ # 光猫,不能只凭厂商名定品类。
255
+ _ROUTER_WORDS = (
256
+ "archer", "易展", "router", "wireless", "wifi", "wlan", "lan", "wan",
257
+ "dhcp", "ssid", "无线", "路由", "上网", "宽带",
258
+ )
259
+ _ONU_WORDS = ("gpon", "epon", "ont", "光猫", "光调制", "光纤入户", "宽带接入")
260
+ _SWITCH_WORDS = ("switch", "vlan", "trunk", "交换机", "端口镜像", "生成树")
261
+
262
+
263
+ def _looks_like_tplink(title: str, haystack: str) -> bool:
264
+ """认得 TP-Link 的三种写法:品牌名、``TL-`` 型号前缀、``tplink``。
265
+
266
+ TP-Link 的 Web 登录页标题往往只有型号(``TL-WDA6332RE``、
267
+ ``TL-7DR7230易展版``),页面里反而不出现品牌名——只看 "tp-link"
268
+ 会把它们漏成未知设备。
269
+ """
270
+ lowered = (title or "").lower()
271
+ return (
272
+ "tp-link" in haystack
273
+ or "tplink" in haystack
274
+ or "tp-link" in lowered
275
+ or re.match(r"^\s*tl-[a-z0-9]", lowered) is not None
276
+ )
277
+
278
+
279
+ def _word_hit(haystack: str, word: str) -> bool:
280
+ """关键词命中:ASCII 词按词边界,中文词按包含。
281
+
282
+ 与 ``catalog.guess_category`` 同一规则。这里必须一致——``ont``(光猫
283
+ 缩写)若用裸包含判断,会命中 HTML 里的 ``content=``,把路由器判成光猫。
284
+ """
285
+ token = (word or "").lower()
286
+ if not token:
287
+ return False
288
+ if token.isascii():
289
+ return re.search(rf"(?<![a-z0-9]){re.escape(token)}(?![a-z0-9])", haystack) is not None
290
+ return token in haystack
291
+
292
+
293
+ def _router_or_light(haystack: str) -> str:
294
+ """在「路由器 / 光猫 / 交换机」之间做一次弱判断。
295
+
296
+ 只在厂商已经确定、但品类还不清楚时调用。命中数打平或一个都没命中
297
+ 时按「路由器」处理——家庭网段里 HTTP 管理页设备最常见的确实是路由器,
298
+ 但这只是**默认值**,不是断言:UI 上仍会显示协议与页面标题,用户能自己
299
+ 判断。
300
+ """
301
+ def score(words) -> int:
302
+ return sum(1 for w in words if _word_hit(haystack, w))
303
+
304
+ onu = score(_ONU_WORDS)
305
+ switch = score(_SWITCH_WORDS)
306
+ router = score(_ROUTER_WORDS)
307
+ if onu > max(router, switch):
308
+ return "onu"
309
+ if switch > max(router, onu):
310
+ return "net_switch"
311
+ return "router"
312
+
313
+
314
+ # ------------------------------------------------------------------ SSDP / mDNS
315
+
316
+ SSDP_ADDR = "239.255.255.250"
317
+ SSDP_PORT = 1900
318
+
319
+
320
+ async def ssdp_discover(timeout: float = 2.0) -> list[dict]:
321
+ """用 UDP 组播做一次通用 SSDP 发现(DLNA / AirPlay / Chromecast / UPnP)。"""
322
+ import socket
323
+
324
+ targets = [
325
+ "ssdp:all",
326
+ "urn:dial-multiscreen-org:service:dial:1",
327
+ "urn:schemas-upnp-org:device:MediaServer:1",
328
+ "urn:schemas-upnp-org:device:MediaRenderer:1",
329
+ ]
330
+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
331
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
332
+ try:
333
+ sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
334
+ except OSError:
335
+ pass
336
+ out: list[dict] = []
337
+ try:
338
+ sock.bind(("", 0))
339
+ for st in targets:
340
+ query = (
341
+ "M-SEARCH * HTTP/1.1\r\n"
342
+ f"HOST: {SSDP_ADDR}:{SSDP_PORT}\r\n"
343
+ "MAN: \"ssdp:discover\"\r\n"
344
+ "MX: 1\r\n"
345
+ f"ST: {st}\r\n\r\n"
346
+ )
347
+ sock.sendto(query.encode(), (SSDP_ADDR, SSDP_PORT))
348
+ deadline = time.time() + timeout
349
+ sock.settimeout(max(0.1, deadline - time.time()))
350
+ while time.time() < deadline:
351
+ try:
352
+ data, addr = sock.recvfrom(4096)
353
+ except (socket.timeout, OSError):
354
+ break
355
+ text = data.decode("utf-8", errors="replace")
356
+ location = ""
357
+ match = re.search(r"LOCATION:\s*(\S+)", text, re.I)
358
+ if match:
359
+ location = match.group(1)
360
+ server = ""
361
+ match = re.search(r"SERVER:\s*([^\r\n]+)", text, re.I)
362
+ if match:
363
+ server = match.group(1)
364
+ out.append({
365
+ "ip": addr[0],
366
+ "location": location,
367
+ "server": server,
368
+ "raw": text[:500],
369
+ })
370
+ except OSError:
371
+ pass
372
+ finally:
373
+ try:
374
+ sock.close()
375
+ except OSError:
376
+ pass
377
+ return out
378
+
379
+
380
+ async def mdns_discover(timeout: float = 2.5) -> list[dict]:
381
+ """用 zeroconf 的异步浏览器发现并解析 mDNS 服务。
382
+
383
+ zeroconf 的 ``async_get_service_info`` 只能解析一个完整的服务名,不能
384
+ 把服务类型本身当成可迭代结果。先用 ``AsyncServiceBrowser`` 收集服务名,
385
+ 再逐个解析地址和 TXT 属性;解析失败只跳过该条服务。
386
+ """
387
+ try:
388
+ from zeroconf import IPVersion # type: ignore
389
+ from zeroconf.asyncio import AsyncServiceBrowser, AsyncZeroconf # type: ignore
390
+ except Exception: # noqa: BLE001
391
+ return []
392
+
393
+ wanted = (
394
+ "_googlecast._tcp.local.",
395
+ "_airplay._tcp.local.",
396
+ "_matter._tcp.local.",
397
+ "_hap._tcp.local.",
398
+ "_sop._tcp.local.",
399
+ "_home-assistant._tcp.local.",
400
+ )
401
+
402
+ class Listener:
403
+ def __init__(self, service_type: str):
404
+ self.service_type = service_type
405
+ self.names: set[str] = set()
406
+
407
+ def add_service(self, _zeroconf, _type, name):
408
+ self.names.add(str(name))
409
+
410
+ def update_service(self, _zeroconf, _type, name):
411
+ self.names.add(str(name))
412
+
413
+ def remove_service(self, _zeroconf, _type, name):
414
+ self.names.discard(str(name))
415
+
416
+ try:
417
+ azc = AsyncZeroconf(ip_version=IPVersion.V4Only)
418
+ except Exception: # noqa: BLE001
419
+ return []
420
+
421
+ browsers = []
422
+ listeners: list[Listener] = []
423
+ loop = asyncio.get_running_loop()
424
+ budget = max(0.0, float(timeout))
425
+ deadline = loop.time() + budget
426
+ try:
427
+ for service in wanted:
428
+ listener = Listener(service)
429
+ listeners.append(listener)
430
+ browsers.append(AsyncServiceBrowser(azc.zeroconf, service, listener=listener))
431
+ await asyncio.sleep(budget * 0.5)
432
+
433
+ found: list[dict] = []
434
+ for listener in listeners:
435
+ for name in sorted(listener.names):
436
+ remaining_ms = int((deadline - loop.time()) * 1000)
437
+ if remaining_ms <= 0:
438
+ break
439
+ try:
440
+ info = await azc.async_get_service_info(
441
+ listener.service_type, name, timeout=remaining_ms
442
+ )
443
+ except Exception: # noqa: BLE001
444
+ continue
445
+ if info is None:
446
+ continue
447
+ try:
448
+ addresses = list(info.parsed_addresses())
449
+ except Exception: # noqa: BLE001
450
+ addresses = []
451
+ props = getattr(info, "decoded_properties", None)
452
+ if not isinstance(props, dict):
453
+ props = getattr(info, "properties", {}) or {}
454
+ normalized_props = {}
455
+ if isinstance(props, dict):
456
+ for key, value in props.items():
457
+ key = key.decode("utf-8", errors="replace") if isinstance(key, bytes) else str(key)
458
+ value = value.decode("utf-8", errors="replace") if isinstance(value, bytes) else value
459
+ normalized_props[key] = value
460
+ model = normalized_props.get("model", normalized_props.get("md", ""))
461
+ for ip in addresses:
462
+ item = {
463
+ "ip": str(ip).strip("[]"),
464
+ "service": listener.service_type.rstrip("."),
465
+ "name": str(getattr(info, "name", "") or name),
466
+ "model": str(model or ""),
467
+ }
468
+ try:
469
+ port = int(getattr(info, "port", 0))
470
+ except (TypeError, ValueError):
471
+ port = 0
472
+ if 1 <= port <= 65535:
473
+ item["port"] = port
474
+ if listener.service_type == "_home-assistant._tcp.local.":
475
+ # Only public identity metadata is needed. TXT URLs may
476
+ # contain userinfo or point outside the resolved LAN host.
477
+ for key in ("uuid", "version", "location_name"):
478
+ value = normalized_props.get(key)
479
+ if isinstance(value, str) and value:
480
+ item[key] = value
481
+ found.append(item)
482
+ return found
483
+ except Exception: # noqa: BLE001
484
+ return []
485
+ finally:
486
+ for browser in browsers:
487
+ try:
488
+ await browser.async_cancel()
489
+ except Exception: # noqa: BLE001
490
+ pass
491
+ try:
492
+ await azc.async_close()
493
+ except Exception: # noqa: BLE001
494
+ pass
495
+
496
+
497
+ # ------------------------------------------------------------------ miIO hello
498
+
499
+ MIIO_HELLO = bytes.fromhex("21310020ffffffffffffffffffffffffffffffffffffffffffffffffffffffff")
500
+
501
+
502
+ async def miio_hello(ip: str, timeout: float = 1.5) -> dict:
503
+ """发送 UDP/54321 hello,只返回公开的设备 ID 与时间戳。
504
+
505
+ python-miio 的握手响应是 32 字节大端二进制头,不包含型号或固件 JSON。
506
+ 后 16 字节可能包含未初始化设备的 token,不能进入公开发现结果。
507
+ https://python-miio.readthedocs.io/en/stable/_modules/miio/miioprotocol.html
508
+ """
509
+ import math
510
+ import socket
511
+ import struct
512
+
513
+ try:
514
+ address = ipaddress.ip_address(ip)
515
+ budget = float(timeout)
516
+ except (TypeError, ValueError):
517
+ return {}
518
+ if address.version != 4 or not math.isfinite(budget) or budget <= 0:
519
+ return {}
520
+
521
+ def exchange() -> dict:
522
+ sock = None
523
+ try:
524
+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
525
+ sock.settimeout(budget)
526
+ # Connected UDP accepts responses only from this host and port.
527
+ sock.connect((str(address), 54321))
528
+ sock.send(MIIO_HELLO)
529
+ data = sock.recv(512)
530
+ if len(data) != 32:
531
+ return {}
532
+ magic, length, _, device_id, timestamp = struct.unpack(">HHIII", data[:16])
533
+ if (magic != 0x2131 or length != 32
534
+ or device_id == 0xffffffff or timestamp == 0xffffffff):
535
+ return {}
536
+ return {"device_id": str(device_id), "timestamp": timestamp}
537
+ except OSError:
538
+ return {}
539
+ finally:
540
+ if sock is not None:
541
+ sock.close()
542
+
543
+ return await asyncio.to_thread(exchange)
544
+
545
+
546
+ # ------------------------------------------------------------------ 涂鸦发现
547
+
548
+ async def tuya_discover(timeout: float = 3.0) -> list[dict]:
549
+ """涂鸦设备局域网发现。
550
+
551
+ 优先用 ``tinytuya``(可选依赖,支持 3.1/3.3/3.4/3.5 与本地密钥);
552
+ 没装就退化为 UDP 广播探测端口,把设备列出来但标为「需要本地密钥」。
553
+ """
554
+ try:
555
+ import tinytuya # type: ignore
556
+ except Exception: # noqa: BLE001
557
+ return []
558
+ results: list[dict] = []
559
+ try:
560
+ # tinytuya 1.21+ 用 deviceScan()(同步、阻塞 UDP 等待),没有旧版
561
+ # Scanner 类。放线程里跑,避免卡住事件循环。
562
+ scanner = await asyncio.to_thread(
563
+ tinytuya.deviceScan, False, None, False, True, False
564
+ )
565
+ except Exception as exc: # noqa: BLE001
566
+ print(f"[smart-home] 涂鸦扫描失败:{exc}")
567
+ return []
568
+ for dev in (scanner or {}).values():
569
+ if not isinstance(dev, dict):
570
+ continue
571
+ try:
572
+ results.append({
573
+ "ip": dev.get("ip", ""),
574
+ "mac": dev.get("mac", ""),
575
+ "gw_id": dev.get("gwId", ""),
576
+ "product_key": dev.get("productKey", ""),
577
+ "version": dev.get("version", ""),
578
+ "local_key": dev.get("localKey", ""),
579
+ "dps": dev.get("dps", {}),
580
+ "protocol": "tuya",
581
+ "category": catalog.guess_category(
582
+ dev.get("productKey", ""), json.dumps(dev.get("dps", {}), ensure_ascii=False)
583
+ ),
584
+ "name": dev.get("name", ""),
585
+ "confidence": 0.9,
586
+ "source": "tuya-udp",
587
+ })
588
+ except Exception: # noqa: BLE001
589
+ continue
590
+ return results
591
+
592
+
593
+ # ------------------------------------------------------------------ 主扫描
594
+
595
+
596
+ def _device_identity(device: ScannedDevice) -> str:
597
+ return device.ip or f"{device.protocol}:{device.address or device.mac}"
598
+
599
+
600
+ def _device_sort_key(device: ScannedDevice) -> tuple:
601
+ return (0, util._ip_key(device.ip)) if device.ip else (1, device.address or device.mac)
602
+
603
+
604
+ def _merge_item(target: ScannedDevice, item: dict, credentials: dict | None = None) -> None:
605
+ """提升弱指纹并显式保存扩展字段,密钥只进入私有凭据。"""
606
+ incoming_confidence = float(item.get("confidence") or 0)
607
+ promote = target.protocol in ("unknown", "http", "mdns") or incoming_confidence > target.confidence
608
+ known = set(ScannedDevice.__dataclass_fields__)
609
+ for key, value in item.items():
610
+ if key == "credentials":
611
+ target.credentials.update(value or {})
612
+ elif _SENSITIVE_FIELD_RE.search(str(key)):
613
+ target.credentials[key] = value
614
+ elif key == "fields":
615
+ for name, content in (value or {}).items():
616
+ if _SENSITIVE_FIELD_RE.search(str(name)):
617
+ target.credentials[name] = content
618
+ else:
619
+ # mDNS supplies an HTTP fallback, while an HTTP probe may
620
+ # already have confirmed this endpoint requires TLS.
621
+ if (name == "base_url" and item.get("source") == "mdns"
622
+ and target.fields.get(name)):
623
+ continue
624
+ target.fields[name] = _public_value(content)
625
+ elif key == "ports":
626
+ target.ports = sorted(set(target.ports) | set(value or []))
627
+ elif key == "requires_credentials":
628
+ target.requires_credentials = target.requires_credentials or bool(value)
629
+ elif key in ("protocol", "category"):
630
+ if value not in (None, "", "unknown", "other") and (promote or getattr(target, key) in ("unknown", "other")):
631
+ setattr(target, key, value)
632
+ elif key == "confidence":
633
+ target.confidence = max(target.confidence, incoming_confidence)
634
+ elif key in known:
635
+ if value and (not getattr(target, key) or (promote and key in ("name", "model", "source"))):
636
+ setattr(target, key, value)
637
+ elif value is not None:
638
+ target.fields[key] = _public_value(value)
639
+ target.credentials.update(credentials or {})
640
+ if target.address:
641
+ target.fields["address"] = target.address
642
+ if target.mac and not target.vendor:
643
+ target.vendor = util.mac_vendor(target.mac)
644
+
645
+
646
+ async def scan_subnet(
647
+ subnet: str,
648
+ ports: list[int] | None = None,
649
+ port_timeout: float = 0.5,
650
+ scan_ping: bool = True,
651
+ concurrency: int = 24,
652
+ ) -> list[ScannedDevice]:
653
+ """扫描一个子网。
654
+
655
+ 返回按 IP 排序的设备列表。任何一步失败都只影响该步,不会让扫描中断。
656
+ """
657
+ subnets, _, _, ports, scan_ping = normalize_scan_options([subnet], 24, None, ports, scan_ping)
658
+ network = ipaddress.ip_network(subnets[0])
659
+
660
+ # 1. 候选主机:ARP 表优先,再 ping 扫描兜底
661
+ arp = util.arp_table()
662
+ candidates: set[str] = set()
663
+ for ip, mac in arp.items():
664
+ try:
665
+ if ipaddress.ip_address(ip) in network:
666
+ candidates.add(ip)
667
+ except ValueError:
668
+ continue
669
+
670
+ if scan_ping and len(candidates) < max(8, network.num_addresses // 8) and network.num_addresses <= 258:
671
+ addresses = [str(addr) for addr in network.hosts()]
672
+ alive = util.ping_sweep(addresses, timeout=port_timeout + 0.1, concurrency=64)
673
+ candidates.update(alive)
674
+
675
+ # 广播发现(SSDP/mDNS/Tuya/BLE)独立于ARP与ping候选,不能因空候选而跳过。
676
+
677
+ # 2. 端口探测(并发受限)
678
+ sem = asyncio.Semaphore(max(1, concurrency))
679
+
680
+ async def probe_host(ip: str) -> tuple[str, list[int]]:
681
+ async with sem:
682
+ # miIO uses UDP; a failed TCP probe on 54321 says nothing about it.
683
+ tcp_ports = [port for port in ports if port != 54321]
684
+ open_ports = await util.scan_ports(ip, tcp_ports, port_timeout)
685
+ return ip, open_ports
686
+
687
+ hosts = await asyncio.gather(*(probe_host(ip) for ip in candidates))
688
+
689
+ # 3. 指纹识别
690
+ async def identify_host(ip: str, open_ports: list[int]) -> ScannedDevice:
691
+ mac = arp.get(ip, "")
692
+ device = ScannedDevice(ip=ip, mac=mac, vendor=util.mac_vendor(mac), ports=open_ports)
693
+ async with sem:
694
+ await _fingerprint(device, probe_miio=54321 in ports)
695
+ return device
696
+
697
+ # A UDP timeout is normal on non-miIO hosts. Bound concurrency rather than
698
+ # adding one full timeout serially for every ARP/ping candidate.
699
+ devices = list(await asyncio.gather(*(identify_host(ip, found) for ip, found in hosts)))
700
+
701
+ # 4. 跨协议发现补充(SSDP / mDNS / 涂鸦 / miIO)
702
+ try:
703
+ extra = await _extra_discovery(subnet)
704
+ except Exception as exc: # 单个广播发现失败不能抹掉已经探测到的主机
705
+ print(f"[smart-home] 跨协议发现失败:{exc}")
706
+ extra = []
707
+ by_identity = {_device_identity(d): d for d in devices}
708
+ for item in extra:
709
+ ip = str(item.get("ip") or "")
710
+ address = str(item.get("address") or "")
711
+ if ip:
712
+ try:
713
+ if ipaddress.ip_address(ip) not in network:
714
+ continue
715
+ except ValueError:
716
+ continue
717
+ elif not address:
718
+ continue
719
+ incoming = ScannedDevice(ip=ip, address=address)
720
+ _merge_item(incoming, item)
721
+ identity = _device_identity(incoming)
722
+ if identity in by_identity:
723
+ _merge_item(by_identity[identity], incoming.to_dict(), incoming.credentials)
724
+ else:
725
+ devices.append(incoming)
726
+ by_identity[identity] = incoming
727
+ return sorted(devices, key=_device_sort_key)
728
+
729
+
730
+ async def _fingerprint(device: ScannedDevice, probe_miio: bool = False) -> None:
731
+ """对一台设备的开放 TCP 端口及可选 UDP miIO 服务做指纹识别。"""
732
+ if probe_miio or 54321 in device.ports:
733
+ info = await miio_hello(device.ip, timeout=1.2)
734
+ if info:
735
+ device.protocol = "miio"
736
+ device.category = catalog.guess_category(info.get("model", ""), info.get("description", ""))
737
+ device.model = str(info.get("model", ""))
738
+ device.name = str(info.get("description", "")) or device.name
739
+ device.confidence = 0.9
740
+ device.fields["miio"] = info
741
+ return
742
+
743
+ # HTTP 指纹
744
+ http_ports = [p for p in device.ports if p in (80, 443, 8080, 8081, 8000, 5000, 5001, 8123)]
745
+ for port in http_ports:
746
+ for tls in (False, True):
747
+ result = await fetch_http(device.ip, port, use_tls=tls)
748
+ if result is None:
749
+ continue
750
+ title, server, text, _url = result
751
+ probe = fingerprint_http(title, server, text, device.ip, port)
752
+ if probe and probe.confidence >= 0.4:
753
+ device.protocol = probe.protocol
754
+ device.category = probe.category
755
+ device.name = probe.name or device.name
756
+ device.model = probe.model or device.model
757
+ device.confidence = probe.confidence
758
+ device.http_title = title
759
+ device.http_server = server
760
+ device.fields["http"] = {"title": title, "server": server, "path": "/"}
761
+ if probe.protocol == "home_assistant":
762
+ scheme = "https" if tls else "http"
763
+ device.fields.update({"port": port, "base_url": f"{scheme}://{device.ip}:{port}"})
764
+ device.requires_credentials = True
765
+ return
766
+ if not device.http_title and title:
767
+ device.http_title = title
768
+ device.http_server = server
769
+
770
+ # 非 HTTP 端口但已知协议
771
+ for port, protocol in ((6666, "tuya"), (6667, "tuya"), (7000, "airplay"), (1883, "mqtt")):
772
+ if port in device.ports and device.protocol == "unknown":
773
+ device.protocol = protocol
774
+ device.category = catalog.guess_category(device.http_title)
775
+ device.confidence = 0.5
776
+ return
777
+
778
+ if device.http_title or device.http_server:
779
+ device.protocol = "http"
780
+ device.category = catalog.guess_category(device.http_title, device.http_server)
781
+ device.confidence = 0.35
782
+
783
+
784
+ async def _extra_discovery(subnet: str) -> list[dict]:
785
+ """跨协议发现:SSDP、mDNS、涂鸦、以及已知端口的 miIO。"""
786
+ out: list[dict] = []
787
+ ssdp = await ssdp_discover(timeout=1.5)
788
+ for item in ssdp:
789
+ ip = item.get("ip", "")
790
+ if not ip or not util.ip_in_subnets(ip, [subnet]):
791
+ continue
792
+ server = item.get("server", "")
793
+ protocol = "dlna"
794
+ category = "other"
795
+ if "dial" in (server + item.get("raw", "")).lower():
796
+ protocol = "cast"
797
+ category = "tv"
798
+ elif "mediaserver" in server.lower() or "mediarenderer" in server.lower():
799
+ protocol = "dlna"
800
+ category = catalog.guess_category(server)
801
+ elif "airplay" in server.lower() or "airplay" in item.get("raw", "").lower():
802
+ protocol = "airplay"
803
+ category = "tv"
804
+ out.append({
805
+ "ip": ip,
806
+ "protocol": protocol,
807
+ "category": category,
808
+ "name": item.get("server", ""),
809
+ "model": server,
810
+ "confidence": 0.7,
811
+ "source": "ssdp",
812
+ "location": item.get("location", ""),
813
+ })
814
+
815
+ for item in await mdns_discover(timeout=1.5):
816
+ ip = item.get("ip", "")
817
+ if not ip or not util.ip_in_subnets(ip, [subnet]):
818
+ continue
819
+ service = item.get("service", "")
820
+ protocol = "mdns"
821
+ category = "other"
822
+ if service.rstrip(".") == "_home-assistant._tcp.local":
823
+ try:
824
+ port = int(item.get("port", 0))
825
+ except (TypeError, ValueError):
826
+ port = 0
827
+ # The SRV record, rather than a default or TXT URL, owns the port.
828
+ if not 1 <= port <= 65535:
829
+ continue
830
+ out.append({
831
+ "ip": ip, "ports": [port], "protocol": "home_assistant", "category": "gateway",
832
+ "name": item.get("location_name") or item.get("name", ""),
833
+ "model": "home-assistant", "confidence": 0.95, "source": "mdns",
834
+ "requires_credentials": True,
835
+ "fields": {"port": port, "base_url": f"http://{ip}:{port}",
836
+ **{key: item[key] for key in ("uuid", "version", "location_name") if item.get(key)}},
837
+ })
838
+ continue
839
+ if "googlecast" in service:
840
+ protocol, category = "cast", "tv"
841
+ elif "airplay" in service:
842
+ protocol, category = "airplay", "tv"
843
+ elif "matter" in service:
844
+ protocol, category = "matter", "other"
845
+ elif "hap" in service:
846
+ protocol, category = "homekit", "other"
847
+ out.append({
848
+ "ip": ip,
849
+ "protocol": protocol,
850
+ "category": category,
851
+ "name": item.get("name", ""),
852
+ "model": item.get("model", ""),
853
+ "confidence": 0.65,
854
+ "source": "mdns",
855
+ })
856
+
857
+ for item in await tuya_discover(timeout=2.0):
858
+ out.append(item)
859
+
860
+ # 蓝牙设备没有 IP,用地址作为键;不参与子网过滤
861
+ from .adapters.ble import ble_scan
862
+
863
+ for item in await ble_scan(timeout=2.0):
864
+ out.append(item)
865
+ return out
866
+
867
+
868
+ def normalize_scan_options(subnets=None, prefix=24, extra_subnets=None, ports=None, scan_ping=True):
869
+ """兼容工具/UI字符串输入,在开始任何网络操作前严格验证。"""
870
+ def items(value):
871
+ if value is None or value == "":
872
+ return []
873
+ if isinstance(value, str):
874
+ return [part for part in re.split(r"[,;\s]+", value.strip()) if part]
875
+ if not isinstance(value, (list, tuple)):
876
+ raise ValueError("子网/端口必须为列表或逗号分隔字符串")
877
+ return list(value)
878
+
879
+ def networks(value):
880
+ result = []
881
+ for part in items(value):
882
+ network = ipaddress.ip_network(str(part), strict=False)
883
+ if network.version != 4:
884
+ raise ValueError("当前子网扫描仅支持 IPv4")
885
+ result.append(str(network))
886
+ return list(dict.fromkeys(result))
887
+
888
+ if isinstance(prefix, bool) or not str(prefix).isdigit() or not 0 <= int(prefix) <= 32:
889
+ raise ValueError("prefix 必须为 0–32 的单个整数")
890
+ parsed_ports = items(ports) if ports is not None else list(util.DEFAULT_PORTS)
891
+ for port in parsed_ports:
892
+ if isinstance(port, bool) or not str(port).isdigit() or not 1 <= int(port) <= 65535:
893
+ raise ValueError("端口必须为 1–65535 的整数")
894
+ if isinstance(scan_ping, str):
895
+ if scan_ping.lower() not in ("true", "false", "1", "0"):
896
+ raise ValueError("scan_ping 必须为布尔值")
897
+ scan_ping = scan_ping.lower() in ("true", "1")
898
+ if not isinstance(scan_ping, bool):
899
+ raise ValueError("scan_ping 必须为布尔值")
900
+ return networks(subnets), int(prefix), networks(extra_subnets), list(dict.fromkeys(map(int, parsed_ports))), scan_ping
901
+
902
+
903
+ async def discover_all(
904
+ subnets: list[str] | None = None,
905
+ prefix: int = 24,
906
+ extra_subnets: list[str] | None = None,
907
+ ports: list[int] | None = None,
908
+ scan_ping: bool = True,
909
+ ) -> list[ScannedDevice]:
910
+ """扫描所有配置子网,汇总去重。
911
+
912
+ 子网为空时自动取本机网卡所在子网,用户不用先查 IP。
913
+ """
914
+ subnets, prefix, extra_subnets, ports, scan_ping = normalize_scan_options(
915
+ subnets, prefix, extra_subnets, ports, scan_ping
916
+ )
917
+ if not subnets:
918
+ subnets = util.local_subnets(prefix, extra_subnets)
919
+ devices: list[ScannedDevice] = []
920
+ for subnet in subnets:
921
+ try:
922
+ found = await scan_subnet(subnet, ports=ports, scan_ping=scan_ping)
923
+ except Exception as exc: # noqa: BLE001 - 单个子网失败不影响其余
924
+ print(f"[smart-home] 扫描子网 {subnet} 失败:{exc}")
925
+ found = []
926
+ devices.extend(found)
927
+ by_identity: dict[str, ScannedDevice] = {}
928
+ for device in devices:
929
+ identity = _device_identity(device)
930
+ if identity in by_identity:
931
+ _merge_item(by_identity[identity], device.to_dict(), device.credentials)
932
+ else:
933
+ by_identity[identity] = device
934
+ return sorted(by_identity.values(), key=_device_sort_key)