@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,195 @@
1
+ #!/usr/bin/env python
2
+ # SPDX-License-Identifier: GPL-3.0-or-later
3
+ """全屋智能家居离线自检。
4
+
5
+ 不联网、不碰真实设备:用假适配器验证管理器的核心链路(扫描结构 → 设备
6
+ 详情 → 统一控制 → 场景 → 翻译),作为插件改动的回归基线。
7
+
8
+ .venv\\Scripts\\python.exe python\\smart_home\\test_offline.py
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import sys
15
+ import tempfile
16
+ from pathlib import Path
17
+
18
+ _HERE = Path(__file__).resolve().parent
19
+ if str(_HERE.parent) not in sys.path:
20
+ sys.path.insert(0, str(_HERE.parent))
21
+
22
+ from smart_home import catalog, localize # noqa: E402
23
+ from smart_home.adapters import BaseAdapter, register # noqa: E402
24
+ from smart_home.manager import SmartHomeManager # noqa: E402
25
+
26
+
27
+ @register
28
+ class FakeAdapter(BaseAdapter):
29
+ """假适配器:记录写入,模拟可读写能力。"""
30
+
31
+ protocol = "fake"
32
+
33
+ def __init__(self, device, config=None):
34
+ super().__init__(device, config)
35
+ self.written: list[tuple] = []
36
+ self.read = {"power": True, "brightness": 60}
37
+
38
+ async def list_capabilities(self) -> list[dict]:
39
+ return [
40
+ {"key": "power", "name": "power", "zh": catalog.capability_zh("power"),
41
+ "en": catalog.capability_en("power"), "kind": "bool", "writable": True},
42
+ {"key": "brightness", "name": "brightness", "zh": catalog.capability_zh("brightness"),
43
+ "en": catalog.capability_en("brightness"), "kind": "range", "writable": True},
44
+ ]
45
+
46
+ async def read_capability(self, capability: str):
47
+ return self.read.get(capability)
48
+
49
+ async def write_capability(self, capability: str, value) -> dict:
50
+ if capability not in ("power", "brightness"):
51
+ raise ValueError(f"fake 不支持写入 {capability}")
52
+ self.written.append((capability, value))
53
+ self.read[capability] = value
54
+ return {"ok": True, "capability": capability, "value": value}
55
+
56
+ async def run_action(self, name: str, params=None) -> dict:
57
+ self.written.append((f"action:{name}", params))
58
+ return {"ok": True, "action": name}
59
+
60
+ async def read_all(self) -> dict:
61
+ return dict(self.read)
62
+
63
+
64
+ class FakeScanned:
65
+ """模拟 discovery.ScannedDevice 的最小对象。"""
66
+
67
+ def __init__(self, **kwargs):
68
+ self.__dict__.update(kwargs)
69
+
70
+
71
+ def _check(label: str, condition: bool, detail: str = "") -> None:
72
+ if condition:
73
+ print(f" PASS {label}")
74
+ else:
75
+ print(f" FAIL {label} {detail}")
76
+ raise SystemExit(1)
77
+
78
+
79
+ async def main() -> int:
80
+ tmp = tempfile.mkdtemp(prefix="dsh-mihome-smarthome-")
81
+ manager = SmartHomeManager({"data_dir": tmp})
82
+
83
+ print("[1] 目录与翻译")
84
+ _check("能力项有中文名", catalog.capability_zh("brightness") == "亮度")
85
+ _check("类别有中文名", catalog.category_zh("vacuum") == "扫地机器人")
86
+ _check("枚举有中文名", catalog.enum_zh("power", "on") == "开")
87
+ _check("官网规格翻译", localize.protocol_zh("mihome", "brightness") == "亮度")
88
+ _check("通用翻译", localize.translate_name("target_temp") == "目标温度")
89
+ _check("平台字典", localize.platform_zh("aligenie", "color_temp") == "色温")
90
+ _check("类别推断", catalog.guess_category("Roborock S8", "扫地机器人") == "vacuum")
91
+ # 回归:ont 是「光猫」缩写,但会命中 HTML 的 content= / font。
92
+ # 裸 in 判断曾把 TP-Link 路由器判成光猫。
93
+ _check("ont 不误命中 content", catalog.guess_category("x", '<meta content="text/html">') != "onu")
94
+ _check("ont 能认出真光猫", catalog.guess_category("ONT GPON 光猫") == "onu")
95
+
96
+ print("[1b] 指纹识别(不联网,走纯函数)")
97
+ from smart_home import discovery as _disc
98
+ # TP-Link 登录页标题只有型号,页面里不出现品牌名——必须靠 TL- 前缀认出来
99
+ probe = _disc.fingerprint_http("TL-WDA6332RE", "", "<title>TL-WDA6332RE</title>", "192.0.2.9", 80)
100
+ _check("TL- 型号认作 TP-Link", probe is not None and probe.protocol == "tplink", str(probe))
101
+ _check("TP-Link 型号不当光猫", probe is not None and probe.category != "onu", str(probe))
102
+ probe_onu = _disc.fingerprint_http("ONT", "", "<title>GPON ONT</title> gpon epon", "192.0.2.10", 80)
103
+ _check("真光猫仍判为 onu", probe_onu is not None and probe_onu.category == "onu", str(probe_onu))
104
+
105
+ print("[1c] 指纹产出的协议都有适配器 / 别名")
106
+ # 扫描层会给出 tplink / h3c / synology 这类「更细的厂商协议」用于展示,
107
+ # 它们没有独立适配器,必须能经别名落到通用的扒页面适配器上,否则会
108
+ # 出现「扫得到、点开报没有适配器」。
109
+ from smart_home.adapters import get_adapter_class
110
+ from smart_home.manager import _ADAPTER_ALIASES
111
+
112
+ def resolvable(proto: str) -> bool:
113
+ return (
114
+ get_adapter_class(proto) is not None
115
+ or get_adapter_class(_ADAPTER_ALIASES.get(proto, "")) is not None
116
+ )
117
+
118
+ fingerprints = [
119
+ "tplink", "h3c", "openwrt", "mirouter", "synology", "qnap", "truenas",
120
+ "hisense_tv", "tcl_tv", "shelly", "tasmota", "wled", "esphome", "yeelight",
121
+ "hue", "lifx", "kasa", "tuya", "miio", "mihome", "onvif", "dlna", "cast",
122
+ "samsung_tv", "lg_tv", "vizio_tv", "ble", "router", "nas", "onu", "http",
123
+ ]
124
+ unresolved = [p for p in fingerprints if not resolvable(p)]
125
+ _check("全部协议可适配", not unresolved, f"未适配:{unresolved}")
126
+
127
+ print("[2] 扫描结构与设备详情")
128
+ fake = FakeScanned(
129
+ ip="192.168.1.50", mac="A42B58C1D2E3", vendor="TP-Link",
130
+ ports=[80, 55443], protocol="fake", category="light", name="客厅灯",
131
+ model="fake.lamp.v1", confidence=0.9, source="arp",
132
+ http_title="", http_server="", fields={},
133
+ )
134
+ device = manager._build_device(fake)
135
+ manager._scan = {"devices": [device]}
136
+ manager._scan_at = 0
137
+ _check("设备 id", device["id"] == "fake:192.168.1.50", device["id"])
138
+ _check("类别中文", device["category_zh"] == "灯具", device["category_zh"])
139
+
140
+ detail = await manager.device("fake:192.168.1.50")
141
+ _check("详情有控制项", len(detail["controls"]) == 2, str(detail["controls"]))
142
+ _check("详情有当前值", detail["values"].get("power") is True)
143
+
144
+ print("[3] 统一控制")
145
+ out = await manager.control("fake:192.168.1.50", "power", state=False)
146
+ _check("开关关闭", out["on"] is False)
147
+ adapter = manager._adapter_for(device)
148
+ _check("写入被记录", ("power", False) in adapter.written, str(adapter.written))
149
+
150
+ out = await manager.control("fake:192.168.1.50", "write", name="brightness", value=80)
151
+ _check("写属性", out["value"] == 80)
152
+ out = await manager.control("fake:192.168.1.50", "action", name="clean")
153
+ _check("执行动作", out["action"] == "clean")
154
+
155
+ print("[4] 场景")
156
+ scene = manager.scene_save({
157
+ "name": "回家模式",
158
+ "actions": [
159
+ {"device": "fake:192.168.1.50", "mode": "power", "state": True},
160
+ {"device": "fake:192.168.1.50", "mode": "write", "name": "brightness", "value": 70},
161
+ ],
162
+ })
163
+ _check("场景保存", bool(scene.get("id")))
164
+ _check("场景列表", len(manager.scenes_list()) == 1)
165
+ run = await manager.scene_run(scene["id"])
166
+ _check("场景执行成功", run["success"] == 2 and run["total"] == 2, str(run))
167
+ _check("场景动作生效", ("power", True) in adapter.written)
168
+ _check("场景删除", manager.scene_delete(scene["id"]) is True)
169
+ _check("删除后为空", len(manager.scenes_list()) == 0)
170
+
171
+ print("[5] 目录输出")
172
+ cat = manager.catalog()
173
+ _check("目录有类别", len(cat["categories"]) > 30, str(len(cat["categories"])))
174
+ _check("目录有能力项", len(cat["capabilities"]) > 20)
175
+ _check("目录有枚举", "power" in cat["enums"])
176
+
177
+ print("[6] 错误处理")
178
+ try:
179
+ await manager.control("nope", "power")
180
+ _check("未知设备报错", False)
181
+ except ValueError:
182
+ _check("未知设备报错", True)
183
+ try:
184
+ await manager.control("fake:192.168.1.50", "write", name="color")
185
+ _check("不支持的写报错", False)
186
+ except ValueError:
187
+ _check("不支持的写报错", True)
188
+
189
+ await manager.close()
190
+ print("\n全部通过。")
191
+ return 0
192
+
193
+
194
+ if __name__ == "__main__":
195
+ raise SystemExit(asyncio.run(main()))
@@ -0,0 +1,107 @@
1
+ #!/usr/bin/env python
2
+ """回归测试:核心控制错误必须在修复前失败。仅使用假设备,不联网。"""
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import sys
7
+ import tempfile
8
+ from pathlib import Path
9
+
10
+ _HERE = Path(__file__).resolve().parent
11
+ if str(_HERE.parent) not in sys.path:
12
+ sys.path.insert(0, str(_HERE.parent))
13
+
14
+ from smart_home.adapters import BaseAdapter, register
15
+ from smart_home.manager import SmartHomeManager
16
+
17
+
18
+ @register
19
+ class FailingAdapter(BaseAdapter):
20
+ protocol = "repair-failing"
21
+ written = []
22
+
23
+ async def list_capabilities(self):
24
+ return [{"key": "power", "name": "power", "kind": "bool", "writable": True}]
25
+
26
+ async def read_capability(self, capability):
27
+ return False
28
+
29
+ async def write_capability(self, capability, value):
30
+ self.written.append((capability, value))
31
+ return {"ok": False, "error": "device rejected command"}
32
+
33
+ async def run_action(self, name, params=None):
34
+ return {"ok": False, "error": "action rejected"}
35
+
36
+
37
+ class Scanned:
38
+ def __init__(self, **values):
39
+ self.__dict__.update(values)
40
+
41
+
42
+ def make_manager():
43
+ manager = SmartHomeManager({"data_dir": tempfile.mkdtemp(prefix="repair-test-")})
44
+ device = manager._build_device(Scanned(
45
+ ip="192.0.2.10", mac="AA:BB:CC:00:00:10", protocol="repair-failing",
46
+ category="switch", name="失败设备", model="fake", ports=[], fields={},
47
+ ))
48
+ manager._scan = {"devices": [device]}
49
+ return manager, device
50
+
51
+
52
+ async def main():
53
+ manager, device = make_manager()
54
+ device_id = device["id"]
55
+
56
+ power = await manager.control(device_id, "power", state=True)
57
+ assert power["ok"] is False, power
58
+
59
+ assert FailingAdapter(manager._adapter_for(device))._value_for_capability("power", "off") is False
60
+ assert FailingAdapter(manager._adapter_for(device))._value_for_capability("power", "on") is True
61
+ await manager.control(device_id, "power", state="off")
62
+ assert FailingAdapter.written[-1] == ("power", False)
63
+
64
+ action = await manager.control(device_id, "action", name="toggle")
65
+ assert action["ok"] is False, action
66
+
67
+ scene_file = Path(manager.data_dir) / "smart_home" / "scenes.json"
68
+ try:
69
+ manager.scene_save({"name": "坏场景", "actions": [None]})
70
+ except ValueError:
71
+ pass
72
+ else:
73
+ raise AssertionError("scene_save must reject non-object actions")
74
+
75
+ scene = manager.scene_save({
76
+ "name": "失败场景",
77
+ "actions": [{"device": device_id, "mode": "power", "state": True}],
78
+ })
79
+ try:
80
+ manager.scene_save({"id": scene["id"], "name": scene["name"], "actions": [None]})
81
+ except ValueError:
82
+ pass
83
+ else:
84
+ raise AssertionError("scene updates must validate actions too")
85
+ result = await manager.scene_run(scene["id"])
86
+ assert result["ok"] is False, result
87
+ assert result["success"] == 0, result
88
+
89
+ assert manager._find_device("mihome:123") is None
90
+ cloud_device = {"id": "mihome:123", "protocol": "mihome", "ip": "", "category": "other"}
91
+ manager._scan = {"devices": [cloud_device]}
92
+ assert manager._find_device("123") == cloud_device
93
+
94
+ ble_a = manager._build_device(Scanned(
95
+ ip="", mac="AA:BB:CC:00:00:11", protocol="ble", category="sensor", name="手表A", fields={}, ports=[]
96
+ ))
97
+ ble_b = manager._build_device(Scanned(
98
+ ip="", mac="AA:BB:CC:00:00:12", protocol="ble", category="sensor", name="手表B", fields={}, ports=[]
99
+ ))
100
+ assert ble_a["id"] != ble_b["id"], (ble_a, ble_b)
101
+ await manager.close()
102
+ assert scene_file.exists()
103
+
104
+
105
+ if __name__ == "__main__":
106
+ asyncio.run(main())
107
+ print("repair tests passed")
@@ -0,0 +1,320 @@
1
+ # SPDX-License-Identifier: GPL-3.0-or-later
2
+ """网络与 HTTP 工具。
3
+
4
+ 尽量只依赖标准库:扫描和控制是插件的核心路径,不希望再引入一个重量级
5
+ 依赖。``requests`` 是米家桥接本来就有依赖,这里复用它,但所有调用都
6
+ 显式传短超时,避免网络异常把桥接进程拖死。
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import ipaddress
13
+ import os
14
+ import re
15
+ import socket
16
+ import subprocess
17
+ from typing import Iterable
18
+
19
+ # 默认探针端口:覆盖常见智能家居与网络设备。顺序越靠前越常见,扫描时
20
+ # 命中即停,减少对每台设备的尝试次数。
21
+ DEFAULT_PORTS = [
22
+ 55443, # Yeelight / 米家灯
23
+ 54321, # 小米 miIO
24
+ 6666, 6667, 7000, # 涂鸦 / AirPlay
25
+ 9999, # TP-Link Kasa
26
+ 1883, # MQTT
27
+ 6053, # ESPHome
28
+ 8123, # Home Assistant
29
+ 8080, 8081, 8000, 8009, 5000, 5001,
30
+ 80, 443,
31
+ ]
32
+
33
+ DEFAULT_PROBE_TIMEOUT = 0.5
34
+
35
+
36
+ def _run(cmd: list[str], timeout: float = 5.0) -> str:
37
+ """跑外部命令拿文本输出,失败返回空串。
38
+
39
+ 扫描依赖 ``arp`` / ``ping``,它们在 Windows 与 Linux 上参数不同,
40
+ 这里做一次平台判断;命令不存在或超时都不该让整次扫描失败。
41
+ """
42
+ try:
43
+ proc = subprocess.run(
44
+ cmd,
45
+ capture_output=True,
46
+ text=True,
47
+ timeout=timeout,
48
+ errors="replace",
49
+ )
50
+ except (OSError, subprocess.SubprocessError):
51
+ return ""
52
+ return (proc.stdout or "") + (proc.stderr or "")
53
+
54
+
55
+ # ------------------------------------------------------------------ 地址工具
56
+
57
+
58
+ def own_ipv4_addresses() -> list[str]:
59
+ """本机所有 IPv4 地址(去重、跳过回环与链路本地)。
60
+
61
+ 不依赖 psutil:先用 UDP socket 拿主地址,再解析 ``ipconfig`` 补齐多网卡
62
+ (有线 / 无线 / Docker 网桥),这样多网卡机器上的设备不会被漏掉。
63
+ """
64
+ found: set[str] = set()
65
+
66
+ # 主地址:向公网地址「connect」一个 UDP socket 不会真的发包,只是让
67
+ # 内核选出源地址,代价极低。
68
+ try:
69
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
70
+ try:
71
+ s.connect(("8.8.8.8", 80))
72
+ found.add(s.getsockname()[0])
73
+ finally:
74
+ s.close()
75
+ except OSError:
76
+ pass
77
+
78
+ # 多网卡:Windows 用 ipconfig,Linux 用 ip addr。
79
+ text = _run(["ipconfig"]) if os.name == "nt" else _run(["ip", "-4", "addr"])
80
+ # 只解析接口地址字段;整段 IPv4 正则会把 DNS、网关、掩码和广播地址
81
+ # 也当成本机接口,进而把不相关的网段加入扫描范围。IPv4 标签不受
82
+ # Windows 的 Address / 地址本地化影响,inet 则对应 ip -4 addr。
83
+ pattern = r"(?im)^\s*(?:IPv4[^:\r\n]*[::]\s*|inet\s+)(\d{1,3}(?:\.\d{1,3}){3})(?:/\d+)?"
84
+ found.update(match.group(1) for match in re.finditer(pattern, text))
85
+ addresses: set[str] = set()
86
+ for ip in found:
87
+ try:
88
+ addr = ipaddress.IPv4Address(ip)
89
+ except ValueError:
90
+ continue
91
+ if (addr.is_loopback or addr.is_link_local or addr.is_unspecified
92
+ or addr.is_multicast or int(addr) == 0xFFFFFFFF):
93
+ continue
94
+ addresses.add(str(addr))
95
+ return sorted(addresses, key=_ip_key)
96
+
97
+
98
+ def _ip_key(ip: str) -> tuple[int, ...]:
99
+ return tuple(int(x) for x in ip.split("."))
100
+
101
+
102
+ def subnet_for(ip: str, prefix: int = 24) -> str:
103
+ try:
104
+ net = ipaddress.ip_network(f"{ip}/{prefix}", strict=False)
105
+ except ValueError:
106
+ return ""
107
+ return str(net)
108
+
109
+
110
+ def local_subnets(prefix: int = 24, extra: Iterable[str] = ()) -> list[str]:
111
+ """本机所在子网列表。
112
+
113
+ 扫描范围默认是每个本机网卡的 /24;用户也可以在配置里追加子网(比如
114
+ 设备在 /16 网段时,按 /24 一个个扫太慢,可以显式加 ``192.168.0.0/16``)。
115
+ """
116
+ nets: set[str] = set()
117
+ for ip in own_ipv4_addresses():
118
+ net = subnet_for(ip, prefix)
119
+ if net:
120
+ nets.add(net)
121
+ for item in extra:
122
+ item = str(item).strip()
123
+ if item and "/" in item:
124
+ nets.add(item)
125
+ return sorted(nets)
126
+
127
+
128
+ def ip_in_subnets(ip: str, subnets: Iterable[str]) -> bool:
129
+ try:
130
+ addr = ipaddress.ip_address(ip)
131
+ except ValueError:
132
+ return False
133
+ for net in subnets:
134
+ try:
135
+ if addr in ipaddress.ip_network(net, strict=False):
136
+ return True
137
+ except ValueError:
138
+ continue
139
+ return False
140
+
141
+
142
+ def is_private(ip: str) -> bool:
143
+ try:
144
+ return ipaddress.ip_address(ip).is_private
145
+ except ValueError:
146
+ return False
147
+
148
+
149
+ # ------------------------------------------------------------------ 存活探测
150
+
151
+
152
+ def arp_table() -> dict[str, str]:
153
+ """ARP 表 -> {ip: mac}。
154
+
155
+ ARP 是最快的存活判断:不需要逐主机发包,系统里已有的表项直接拿来用。
156
+ 扫描前先读它,能覆盖大部分常在线设备。
157
+ """
158
+ text = _run(["arp", "-a"]) if os.name == "nt" else _run(["arp", "-an"])
159
+ table: dict[str, str] = {}
160
+ for line in text.splitlines():
161
+ match = re.search(r"(\d{1,3}(?:\.\d{1,3}){3})", line)
162
+ if not match:
163
+ continue
164
+ mac = re.search(r"([0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F]{2}", line)
165
+ table[match.group(1)] = (mac.group(0).replace(":", "").replace("-", "").lower() if mac else "")
166
+ return table
167
+
168
+
169
+ def ping(ip: str, timeout: float = 0.6) -> bool:
170
+ """单主机存活探测。失败返回 False,不抛异常。"""
171
+ if os.name == "nt":
172
+ cmd = ["ping", "-n", "1", "-w", str(int(timeout * 1000)), ip]
173
+ else:
174
+ cmd = ["ping", "-c", "1", "-W", str(max(1, int(timeout))), ip]
175
+ out = _run(cmd, timeout=timeout + 2.0)
176
+ # Windows 成功时输出 "TTL=",Linux 成功时输出 "bytes from"
177
+ return bool(re.search(r"TTL=|bytes from", out))
178
+
179
+
180
+ async def tcp_open(ip: str, port: int, timeout: float = DEFAULT_PROBE_TIMEOUT) -> bool:
181
+ """异步 TCP 连接探测。超时即视为未开放。"""
182
+ try:
183
+ fut = asyncio.open_connection(ip, port)
184
+ reader, writer = await asyncio.wait_for(fut, timeout=timeout)
185
+ writer.close()
186
+ try:
187
+ await writer.wait_closed()
188
+ except OSError:
189
+ pass
190
+ return True
191
+ except (OSError, asyncio.TimeoutError):
192
+ return False
193
+
194
+
195
+ async def scan_ports(
196
+ ip: str,
197
+ ports: Iterable[int] = DEFAULT_PORTS,
198
+ timeout: float = DEFAULT_PROBE_TIMEOUT,
199
+ concurrency: int = 16,
200
+ ) -> list[int]:
201
+ """探测一台主机开放的端口。并发受限,避免把本机网卡打满。"""
202
+ ports = list(ports)
203
+ if not ports:
204
+ return []
205
+ sem = asyncio.Semaphore(max(1, concurrency))
206
+
207
+ async def one(port: int) -> int | None:
208
+ async with sem:
209
+ if await tcp_open(ip, port, timeout):
210
+ return port
211
+ return None
212
+
213
+ results = await asyncio.gather(*(one(p) for p in ports))
214
+ return [p for p in results if p is not None]
215
+
216
+
217
+ def ping_sweep(ips: Iterable[str], timeout: float = 0.6, concurrency: int = 64) -> set[str]:
218
+ """并行 ping 网段内主机。只用于没有 ARP 表项时的兜底。"""
219
+ import concurrent.futures
220
+
221
+ alive: set[str] = set()
222
+ ips = list(ips)
223
+ with concurrent.futures.ThreadPoolExecutor(max_workers=max(1, concurrency)) as pool:
224
+ futures = {pool.submit(ping, ip, timeout): ip for ip in ips}
225
+ for fut in concurrent.futures.as_completed(futures):
226
+ if fut.result():
227
+ alive.add(futures[fut])
228
+ return alive
229
+
230
+
231
+ # ------------------------------------------------------------------ HTTP
232
+
233
+
234
+ def http_get(url: str, timeout: float = 2.5, headers: dict | None = None, allow_redirects: bool = True):
235
+ """同步 GET。失败返回 None(调用方按「不可达」处理,不抛)。"""
236
+ import requests
237
+
238
+ try:
239
+ resp = requests.get(
240
+ url,
241
+ timeout=timeout,
242
+ headers={"User-Agent": "dsh-mihome/2.0", **(headers or {})},
243
+ allow_redirects=allow_redirects,
244
+ )
245
+ return resp
246
+ except Exception: # noqa: BLE001 - 网络设备五花八门,任何异常都按不可达
247
+ return None
248
+
249
+
250
+ def http_post(url: str, data=None, json_body=None, timeout: float = 3.0, headers: dict | None = None):
251
+ """同步 POST。失败返回 None。"""
252
+ import requests
253
+
254
+ try:
255
+ resp = requests.post(
256
+ url,
257
+ data=data,
258
+ json=json_body,
259
+ timeout=timeout,
260
+ headers={"User-Agent": "dsh-mihome/2.0", **(headers or {})},
261
+ )
262
+ return resp
263
+ except Exception: # noqa: BLE001
264
+ return None
265
+
266
+
267
+ async def http_get_async(url: str, timeout: float = 2.5, headers: dict | None = None):
268
+ """把同步 GET 放到线程里,供异步扫描使用,避免阻塞事件循环。"""
269
+ return await asyncio.to_thread(http_get, url, timeout, headers)
270
+
271
+
272
+ async def http_post_async(url: str, data=None, json_body=None, timeout: float = 3.0, headers: dict | None = None):
273
+ return await asyncio.to_thread(http_post, url, data, json_body, timeout, headers)
274
+
275
+
276
+ def safe_text(value: object, limit: int = 4000) -> str:
277
+ """把任意响应内容压成可读文本,截断超长内容。"""
278
+ if value is None:
279
+ return ""
280
+ if hasattr(value, "text"):
281
+ text = value.text or ""
282
+ elif isinstance(value, bytes):
283
+ text = value.decode("utf-8", errors="replace")
284
+ else:
285
+ text = str(value)
286
+ text = text.strip()
287
+ if len(text) > limit:
288
+ text = text[:limit] + f"…(截断,共 {len(text)} 字符)"
289
+ return text
290
+
291
+
292
+ def strip_html(text: str) -> str:
293
+ """粗略去 HTML 标签,用于把管理页面正文转成可读文本。"""
294
+ text = re.sub(r"(?is)<(script|style)[^>]*>.*?</\1>", " ", text)
295
+ text = re.sub(r"(?s)<[^>]+>", " ", text)
296
+ text = re.sub(r"\s+", " ", text)
297
+ return text.strip()
298
+
299
+
300
+ def mac_vendor(mac: str) -> str:
301
+ """返回全球单播 MAC 的 IEEE MA-L 注册组织;未知或本地地址返回空串。
302
+
303
+ OUI 只能说明地址块的注册组织,不能证明设备品牌、类别或控制协议。
304
+ 支持完整的冒号、连字符、Cisco 点分和 12 位十六进制格式。
305
+ """
306
+ from .oui_table import OUI_TABLE
307
+
308
+ raw = str(mac or "").strip()
309
+ if not any(re.fullmatch(pattern, raw) for pattern in (
310
+ r"[0-9A-Fa-f]{12}",
311
+ r"(?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}",
312
+ r"(?:[0-9A-Fa-f]{2}-){5}[0-9A-Fa-f]{2}",
313
+ r"(?:[0-9A-Fa-f]{4}\.){2}[0-9A-Fa-f]{4}",
314
+ )):
315
+ return ""
316
+ compact = re.sub(r"[:.\-]", "", raw).upper()
317
+ # I/G 与 U/L 位分别排除组播及随机/本地管理地址;全零也不是设备身份。
318
+ if int(compact[:2], 16) & 0x03 or int(compact, 16) == 0:
319
+ return ""
320
+ return OUI_TABLE.get(compact[:6], "")