@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.
- package/README.md +141 -78
- package/client.js +1149 -19
- package/cordis.patch.yml +2 -2
- package/docs/REPAIR-VALIDATION.md +62 -0
- package/lib/bridge.js +126 -44
- package/lib/connections.js +46 -0
- package/lib/format.js +148 -0
- package/lib/index.js +274 -31
- package/lib/panel.js +138 -7
- package/locale/en.json +3 -3
- package/locale/zh.json +2 -2
- package/package.json +13 -4
- package/python/app/core/service.py +62 -31
- package/python/mihome_bridge.py +211 -9
- package/python/smart_home/__init__.py +24 -0
- package/python/smart_home/adapters/__init__.py +50 -0
- package/python/smart_home/adapters/base.py +143 -0
- package/python/smart_home/adapters/ble.py +100 -0
- package/python/smart_home/adapters/dlna.py +227 -0
- package/python/smart_home/adapters/home_assistant.py +454 -0
- package/python/smart_home/adapters/hue.py +225 -0
- package/python/smart_home/adapters/kasa.py +239 -0
- package/python/smart_home/adapters/mihome.py +342 -0
- package/python/smart_home/adapters/network.py +250 -0
- package/python/smart_home/adapters/shelly.py +289 -0
- package/python/smart_home/adapters/tuya.py +95 -0
- package/python/smart_home/adapters/tv.py +26 -0
- package/python/smart_home/catalog.py +336 -0
- package/python/smart_home/cloud.py +85 -0
- package/python/smart_home/discovery.py +934 -0
- package/python/smart_home/localize.py +787 -0
- package/python/smart_home/manager.py +672 -0
- package/python/smart_home/oui_table.py +40550 -0
- package/python/smart_home/scan.py +73 -0
- package/python/smart_home/test_discovery_repairs.py +186 -0
- package/python/smart_home/test_localization_repairs.py +229 -0
- package/python/smart_home/test_offline.py +195 -0
- package/python/smart_home/test_repairs.py +107 -0
- package/python/smart_home/util.py +320 -0
- package/python/tests/test_bridge_integration.py +108 -0
- package/python/tests/test_ha_discovery.py +260 -0
- package/python/tests/test_home_assistant.py +365 -0
- package/python/tests/test_manager_integration.py +150 -0
- package/python/tests/test_mihome_repairs.py +117 -0
- package/python/tests/test_network_read_contract.py +50 -0
- package/python/tests/test_power_confirmation.py +95 -0
- package/python/tests/test_protocol_repairs.py +369 -0
- package/python/tests/test_yeelight_repairs.py +70 -0
- package/requirements-optional.txt +4 -0
- package/requirements.txt +5 -0
- package/scripts/update-oui.py +108 -0
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
# SPDX-License-Identifier: GPL-3.0-or-other
|
|
2
|
+
"""适配器基类与注册表。
|
|
3
|
+
|
|
4
|
+
每个适配器负责一种协议的「读状态 + 控制」,统一输出**能力项**(capability),
|
|
5
|
+
上层 ``manager`` 不关心具体协议。能力项的名字来自 ``catalog.py``,保证
|
|
6
|
+
中文叫法一致。
|
|
7
|
+
|
|
8
|
+
适配器需要实现的接口(其余可留空,表示不支持):
|
|
9
|
+
|
|
10
|
+
- ``list_capabilities()``:本设备支持哪些控制项,返回 ``catalog`` 里的能力项。
|
|
11
|
+
- ``read_capability(cap)``:读某个能力项的当前值。
|
|
12
|
+
- ``write_capability(cap, value)``:写某个能力项。
|
|
13
|
+
- ``run_action(name, params)``:执行动作(如回充、定位)。
|
|
14
|
+
- ``read_all()``:一次性读出所有可读值(面板首屏用)。
|
|
15
|
+
- ``scrape()``:管理类设备(路由器/交换机/光猫/NAS)扒设置页。
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
from .. import catalog
|
|
21
|
+
|
|
22
|
+
# 所有能力项的默认取值类型
|
|
23
|
+
CAPABILITY_KIND = {key: info.get("kind", "bool") for key, info in catalog.CAPABILITY_LABELS.items()}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class BaseAdapter:
|
|
27
|
+
"""适配器基类。"""
|
|
28
|
+
|
|
29
|
+
protocol: str = "base"
|
|
30
|
+
platform: str = ""
|
|
31
|
+
|
|
32
|
+
def __init__(self, device, config: dict | None = None):
|
|
33
|
+
self.device = device
|
|
34
|
+
self.config = config or {}
|
|
35
|
+
self.ip = getattr(device, "ip", "") or ""
|
|
36
|
+
self.mac = getattr(device, "mac", "") or ""
|
|
37
|
+
self.log = print
|
|
38
|
+
|
|
39
|
+
# ---- 可选实现 ----
|
|
40
|
+
|
|
41
|
+
def is_supported(self) -> bool:
|
|
42
|
+
return True
|
|
43
|
+
|
|
44
|
+
async def probe(self) -> dict:
|
|
45
|
+
"""补一次协议级探测,返回要合并进 device.fields 的信息。"""
|
|
46
|
+
return {}
|
|
47
|
+
|
|
48
|
+
async def list_capabilities(self) -> list[dict]:
|
|
49
|
+
"""能力必须由具体协议确认;类别只是标签,不代表支持控制。"""
|
|
50
|
+
return []
|
|
51
|
+
|
|
52
|
+
async def read_capability(self, capability: str):
|
|
53
|
+
"""默认:能力项不在可读集合里,返回 None。"""
|
|
54
|
+
return None
|
|
55
|
+
|
|
56
|
+
async def write_capability(self, capability: str, value) -> dict:
|
|
57
|
+
raise NotImplementedError(f"{self.protocol} 不支持写入 {capability}")
|
|
58
|
+
|
|
59
|
+
async def run_action(self, name: str, params: dict | None = None) -> dict:
|
|
60
|
+
raise NotImplementedError(f"{self.protocol} 不支持动作 {name}")
|
|
61
|
+
|
|
62
|
+
async def read_all(self) -> dict:
|
|
63
|
+
"""默认:逐个读可读能力项。"""
|
|
64
|
+
out: dict = {}
|
|
65
|
+
for cap in await self.list_capabilities():
|
|
66
|
+
key = cap.get("key")
|
|
67
|
+
if cap.get("kind") == "action" or cap.get("readable") is False:
|
|
68
|
+
continue
|
|
69
|
+
try:
|
|
70
|
+
value = await self.read_capability(key)
|
|
71
|
+
except Exception as exc: # noqa: BLE001
|
|
72
|
+
self.log(f"[smart-home] 读取 {self.ip} {key} 失败:{exc}")
|
|
73
|
+
continue
|
|
74
|
+
if value is not None:
|
|
75
|
+
out[key] = value
|
|
76
|
+
return out
|
|
77
|
+
|
|
78
|
+
async def scrape(self) -> dict:
|
|
79
|
+
"""管理类设备的设置页扒取,默认不支持。"""
|
|
80
|
+
raise NotImplementedError(f"{self.protocol} 不支持设置页扒取")
|
|
81
|
+
|
|
82
|
+
async def close(self) -> None:
|
|
83
|
+
"""释放资源(长连接等),默认无需处理。"""
|
|
84
|
+
|
|
85
|
+
# ---- 工具 ----
|
|
86
|
+
|
|
87
|
+
def device_id(self) -> str:
|
|
88
|
+
"""统一设备标识:优先用设备自带 id,否则用协议 + 地址。"""
|
|
89
|
+
explicit = getattr(self.device, "did", "") or getattr(self.device, "id", "")
|
|
90
|
+
if explicit:
|
|
91
|
+
return str(explicit)
|
|
92
|
+
return f"{self.protocol}:{self.ip}"
|
|
93
|
+
|
|
94
|
+
def device_name(self) -> str:
|
|
95
|
+
return getattr(self.device, "name", "") or self.device_id()
|
|
96
|
+
|
|
97
|
+
def category(self) -> str:
|
|
98
|
+
return getattr(self.device, "category", "other") or "other"
|
|
99
|
+
|
|
100
|
+
def capability_info(self, capability: str) -> dict:
|
|
101
|
+
return catalog.capability_info(capability)
|
|
102
|
+
|
|
103
|
+
def _value_for_capability(self, capability: str, value):
|
|
104
|
+
"""把统一能力项的取值按类型归一化。"""
|
|
105
|
+
info = catalog.CAPABILITY_LABELS.get(capability, {})
|
|
106
|
+
kind = info.get("kind", "bool")
|
|
107
|
+
if kind == "bool":
|
|
108
|
+
if isinstance(value, bool):
|
|
109
|
+
return value
|
|
110
|
+
if isinstance(value, (int, float)) and value in (0, 1):
|
|
111
|
+
return bool(value)
|
|
112
|
+
if isinstance(value, str):
|
|
113
|
+
normalized = value.strip().casefold()
|
|
114
|
+
if normalized in {"1", "true", "on", "yes", "enabled", "开", "开启", "打开"}:
|
|
115
|
+
return True
|
|
116
|
+
if normalized in {"0", "false", "off", "no", "disabled", "关", "关闭"}:
|
|
117
|
+
return False
|
|
118
|
+
raise ValueError(f"{capability} 需要布尔值,收到 {value!r}")
|
|
119
|
+
if kind == "range":
|
|
120
|
+
try:
|
|
121
|
+
return float(value)
|
|
122
|
+
except (TypeError, ValueError):
|
|
123
|
+
raise ValueError(f"{capability} 需要数值,收到 {value!r}")
|
|
124
|
+
return value
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
# ------------------------------------------------------------------ 注册表
|
|
128
|
+
|
|
129
|
+
_REGISTRY: dict[str, type[BaseAdapter]] = {}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def register(cls: type[BaseAdapter]) -> type[BaseAdapter]:
|
|
133
|
+
"""把适配器注册进协议名表。"""
|
|
134
|
+
_REGISTRY[cls.protocol] = cls
|
|
135
|
+
return cls
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def get_adapter_class(protocol: str) -> type[BaseAdapter] | None:
|
|
139
|
+
return _REGISTRY.get(protocol)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def all_protocols() -> list[str]:
|
|
143
|
+
return sorted(_REGISTRY)
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
2
|
+
"""蓝牙(BLE)适配器。
|
|
3
|
+
|
|
4
|
+
Wi-Fi 不是唯一的发现手段:智能手表、部分灯具、门锁、传感器走蓝牙。
|
|
5
|
+
这类设备的控制协议高度私有,插件**只做识别与状态展示**,不做猜测;
|
|
6
|
+
需要控制时,由用户提供设备的 GATT 特征(在配置里声明)后再扩展。
|
|
7
|
+
|
|
8
|
+
依赖 ``bleak``(可选)。未安装时扫描返回空,不影响其它协议。
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from .. import catalog
|
|
14
|
+
from .base import BaseAdapter, register
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
async def ble_scan(timeout: float = 4.0) -> list[dict]:
|
|
18
|
+
"""扫描附近的 BLE 设备。
|
|
19
|
+
|
|
20
|
+
返回 ``[{"ip"/"address", "name", "mac", "rssi", "uuids"}]``。
|
|
21
|
+
没有 ``bleak`` 或平台不支持时返回空列表。
|
|
22
|
+
"""
|
|
23
|
+
try:
|
|
24
|
+
from bleak import BleakScanner # type: ignore
|
|
25
|
+
except Exception: # noqa: BLE001
|
|
26
|
+
return []
|
|
27
|
+
out: list[dict] = []
|
|
28
|
+
try:
|
|
29
|
+
devices = await BleakScanner.discover(timeout=timeout, return_adv=True)
|
|
30
|
+
except Exception as exc: # noqa: BLE001
|
|
31
|
+
print(f"[smart-home] BLE 扫描失败:{exc}")
|
|
32
|
+
return []
|
|
33
|
+
if isinstance(devices, dict):
|
|
34
|
+
entries = devices.values()
|
|
35
|
+
else:
|
|
36
|
+
entries = devices or []
|
|
37
|
+
for entry in entries:
|
|
38
|
+
try:
|
|
39
|
+
if isinstance(entry, (tuple, list)) and len(entry) == 2:
|
|
40
|
+
device, adv = entry
|
|
41
|
+
else:
|
|
42
|
+
device, adv = entry, None
|
|
43
|
+
name = (
|
|
44
|
+
getattr(adv, "local_name", "") if adv is not None else ""
|
|
45
|
+
) or getattr(device, "name", "") or ""
|
|
46
|
+
address = str(getattr(device, "address", "") or "")
|
|
47
|
+
rssi = (getattr(adv, "rssi", None) if adv is not None else None) or 0
|
|
48
|
+
uuids = (
|
|
49
|
+
getattr(adv, "service_uuids", None) if adv is not None else None
|
|
50
|
+
) or getattr(device, "uuids", []) or []
|
|
51
|
+
out.append({
|
|
52
|
+
"address": address,
|
|
53
|
+
"mac": address,
|
|
54
|
+
"name": name,
|
|
55
|
+
"rssi": rssi,
|
|
56
|
+
"uuids": list(uuids),
|
|
57
|
+
"protocol": "ble",
|
|
58
|
+
"category": catalog.guess_category(name, address),
|
|
59
|
+
"confidence": 0.6,
|
|
60
|
+
"source": "ble",
|
|
61
|
+
})
|
|
62
|
+
except Exception: # noqa: BLE001
|
|
63
|
+
continue
|
|
64
|
+
return out
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@register
|
|
68
|
+
class BleAdapter(BaseAdapter):
|
|
69
|
+
"""蓝牙设备:识别与状态展示。"""
|
|
70
|
+
|
|
71
|
+
protocol = "ble"
|
|
72
|
+
platform = ""
|
|
73
|
+
|
|
74
|
+
def __init__(self, device, config=None):
|
|
75
|
+
super().__init__(device, config)
|
|
76
|
+
# BLE 用地址而非 IP
|
|
77
|
+
self.address = getattr(device, "ip", "") or getattr(device, "mac", "")
|
|
78
|
+
|
|
79
|
+
def device_id(self) -> str:
|
|
80
|
+
return f"{self.protocol}:{self.address}"
|
|
81
|
+
|
|
82
|
+
async def list_capabilities(self) -> list[dict]:
|
|
83
|
+
return [
|
|
84
|
+
{"key": "status", "name": "device_info", "zh": catalog.capability_zh("status"),
|
|
85
|
+
"en": catalog.capability_en("status"), "kind": "bool", "writable": False},
|
|
86
|
+
]
|
|
87
|
+
|
|
88
|
+
async def read_capability(self, capability: str):
|
|
89
|
+
if capability == "status":
|
|
90
|
+
return await self.scrape()
|
|
91
|
+
return None
|
|
92
|
+
|
|
93
|
+
async def scrape(self) -> dict:
|
|
94
|
+
return {
|
|
95
|
+
"protocol": "ble",
|
|
96
|
+
"name": getattr(self.device, "name", ""),
|
|
97
|
+
"mac": self.address,
|
|
98
|
+
"rssi": getattr(self.device, "fields", {}).get("rssi"),
|
|
99
|
+
"note": "蓝牙设备的控制协议私有,插件暂只做识别与状态展示",
|
|
100
|
+
}
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
2
|
+
"""DLNA / ONVIF / 投屏(Cast)适配器。
|
|
3
|
+
|
|
4
|
+
这三类是「媒体与摄像头」方向的设备:
|
|
5
|
+
|
|
6
|
+
- **DLNA**:读设备描述,展示能力;控制走 UPnP SOAP,仅在渲染器上支持
|
|
7
|
+
播放 / 停止等基础动作。
|
|
8
|
+
- **ONVIF**:摄像头。先做 WS-Discovery 探测拿到设备服务地址,再读系统
|
|
9
|
+
信息、执行重启;控制能力以设备支持的 ONVIF 服务为准。
|
|
10
|
+
- **Cast**:Chromecast / 投屏设备。本地控制需要 Cast 私有协议(protobuf),
|
|
11
|
+
这里只做识别与状态展示,不猜测控制接口。
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import re
|
|
17
|
+
import uuid
|
|
18
|
+
import xml.etree.ElementTree as ET
|
|
19
|
+
from urllib.parse import urlparse
|
|
20
|
+
|
|
21
|
+
from .. import catalog
|
|
22
|
+
from .base import BaseAdapter, register
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
# ------------------------------------------------------------------ DLNA
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _soap_action(service: str, action: str, body: str) -> str:
|
|
29
|
+
return (
|
|
30
|
+
'<?xml version="1.0" encoding="utf-8"?>'
|
|
31
|
+
'<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" '
|
|
32
|
+
'xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">'
|
|
33
|
+
f'<s:Header><u:Security><wsse:UsernameToken xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">'
|
|
34
|
+
f'<wsse:Username>anonymous</wsse:Username></wsse:UsernameToken></u:Security></s:Header>'
|
|
35
|
+
f'<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">{body}</s:Body></s:Envelope>'
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@register
|
|
40
|
+
class DlnaAdapter(BaseAdapter):
|
|
41
|
+
"""DLNA 媒体设备。"""
|
|
42
|
+
|
|
43
|
+
protocol = "dlna"
|
|
44
|
+
platform = ""
|
|
45
|
+
|
|
46
|
+
def _location(self) -> str:
|
|
47
|
+
return str(self.device.fields.get("location") or f"http://{self.ip}/")
|
|
48
|
+
|
|
49
|
+
async def list_capabilities(self) -> list[dict]:
|
|
50
|
+
return [
|
|
51
|
+
{"key": "status", "name": "device_info", "zh": catalog.capability_zh("status"),
|
|
52
|
+
"en": catalog.capability_en("status"), "kind": "bool", "writable": False},
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
async def read_capability(self, capability: str):
|
|
56
|
+
if capability == "status":
|
|
57
|
+
return await self.scrape()
|
|
58
|
+
return None
|
|
59
|
+
|
|
60
|
+
async def scrape(self) -> dict:
|
|
61
|
+
"""读 UPnP 设备描述,给出设备名、型号、服务列表。"""
|
|
62
|
+
from .. import util
|
|
63
|
+
|
|
64
|
+
resp = await util.http_get_async(self._location(), timeout=3)
|
|
65
|
+
if resp is None:
|
|
66
|
+
return {"protocol": "dlna", "note": "DLNA 描述文件不可达"}
|
|
67
|
+
text = resp.text or ""
|
|
68
|
+
friendly = re.search(r'<friendlyName>(.*?)</friendlyName>', text, re.I)
|
|
69
|
+
model = re.search(r'<modelName>(.*?)</modelName>', text, re.I)
|
|
70
|
+
manufacturer = re.search(r'<manufacturer>(.*?)</manufacturer>', text, re.I)
|
|
71
|
+
services = re.findall(r'<serviceType>(.*?)</serviceType>', text, re.I)
|
|
72
|
+
return {
|
|
73
|
+
"protocol": "dlna",
|
|
74
|
+
"name": friendly.group(1).strip() if friendly else "",
|
|
75
|
+
"model": model.group(1).strip() if model else "",
|
|
76
|
+
"manufacturer": manufacturer.group(1).strip() if manufacturer else "",
|
|
77
|
+
"services": services,
|
|
78
|
+
"location": self._location(),
|
|
79
|
+
"note": "DLNA 控制能力取决于设备支持的服务",
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
# ------------------------------------------------------------------ ONVIF
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
_PROBE = (
|
|
87
|
+
'<?xml version="1.0" encoding="utf-8"?>'
|
|
88
|
+
'<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" '
|
|
89
|
+
'xmlns:d="http://schemas.xmlsoap.org/ws/2005/04/discovery" '
|
|
90
|
+
'xmlns:td="http://www.onvif.org/ver10/device/wsdl" '
|
|
91
|
+
'xmlns:wsa="http://www.w3.org/2005/08/addressing">'
|
|
92
|
+
'<s:Header><wsa:MessageID>uuid</wsa:MessageID>'
|
|
93
|
+
'<wsa:To>urn:schemas-onvif-org:ddi:discovery</wsa:To>'
|
|
94
|
+
'<wsa:Action>http://schemas.xmlsoap.org/ws/2004/10/discovery/Probe</wsa:Action></s:Header>'
|
|
95
|
+
'<s:Body><d:Probe><d:Types>td:NetworkVideoTransmitter</d:Types></d:Probe></s:Body></s:Envelope>'
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
async def _onvif_probe(ip: str, timeout: float = 3.0) -> dict:
|
|
100
|
+
"""WS-Discovery 探测 ONVIF 设备,返回设备服务地址。"""
|
|
101
|
+
import socket
|
|
102
|
+
|
|
103
|
+
envelope = _PROBE.replace(">uuid<", ">urn:uuid:" + str(uuid.uuid4()) + "<")
|
|
104
|
+
results: dict = {}
|
|
105
|
+
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
|
|
106
|
+
try:
|
|
107
|
+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
108
|
+
sock.bind(("", 0))
|
|
109
|
+
sock.sendto(envelope.encode("utf-8"), ("239.255.255.250", 3702))
|
|
110
|
+
sock.settimeout(timeout)
|
|
111
|
+
while True:
|
|
112
|
+
try:
|
|
113
|
+
data, addr = sock.recvfrom(8192)
|
|
114
|
+
except (socket.timeout, OSError):
|
|
115
|
+
break
|
|
116
|
+
if addr[0] != ip:
|
|
117
|
+
continue
|
|
118
|
+
try:
|
|
119
|
+
root = ET.fromstring(data)
|
|
120
|
+
except ET.ParseError:
|
|
121
|
+
continue
|
|
122
|
+
for node in root.iter():
|
|
123
|
+
if node.tag.rsplit('}', 1)[-1] != 'XAddrs':
|
|
124
|
+
continue
|
|
125
|
+
for service in (node.text or '').split():
|
|
126
|
+
parsed = urlparse(service)
|
|
127
|
+
if parsed.scheme in ('http', 'https') and parsed.hostname == ip and not parsed.username and not parsed.password:
|
|
128
|
+
return {'service': service, 'ip': ip}
|
|
129
|
+
except OSError:
|
|
130
|
+
pass
|
|
131
|
+
finally:
|
|
132
|
+
sock.close()
|
|
133
|
+
return results
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@register
|
|
137
|
+
class OnvifAdapter(BaseAdapter):
|
|
138
|
+
"""ONVIF 摄像头。"""
|
|
139
|
+
|
|
140
|
+
protocol = "onvif"
|
|
141
|
+
platform = ""
|
|
142
|
+
|
|
143
|
+
async def list_capabilities(self) -> list[dict]:
|
|
144
|
+
return [
|
|
145
|
+
{"key": "status", "name": "device_info", "zh": catalog.capability_zh("status"),
|
|
146
|
+
"en": catalog.capability_en("status"), "kind": "bool", "writable": False},
|
|
147
|
+
]
|
|
148
|
+
|
|
149
|
+
async def read_capability(self, capability: str):
|
|
150
|
+
if capability == "status":
|
|
151
|
+
return await self.scrape()
|
|
152
|
+
return None
|
|
153
|
+
|
|
154
|
+
async def _soap(self, service: str, action: str, body: str, timeout: float = 4.0):
|
|
155
|
+
from .. import util
|
|
156
|
+
|
|
157
|
+
envelope = (
|
|
158
|
+
'<?xml version="1.0" encoding="utf-8"?>'
|
|
159
|
+
'<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope">'
|
|
160
|
+
f'<s:Header><wsa:MessageID xmlns:wsa="http://www.w3.org/2005/08/addressing">{uuid.uuid4()}</wsa:MessageID>'
|
|
161
|
+
f'<wsa:Action xmlns:wsa="http://www.w3.org/2005/08/addressing">{action}</wsa:Action></s:Header>'
|
|
162
|
+
f'<s:Body>{body}</s:Body></s:Envelope>'
|
|
163
|
+
)
|
|
164
|
+
resp = await util.http_post_async(
|
|
165
|
+
service,
|
|
166
|
+
data=envelope.encode("utf-8"),
|
|
167
|
+
headers={"Content-Type": "application/soap+xml; charset=utf-8"},
|
|
168
|
+
timeout=timeout,
|
|
169
|
+
)
|
|
170
|
+
if resp is None or not 200 <= resp.status_code < 300:
|
|
171
|
+
raise RuntimeError('ONVIF SOAP request failed')
|
|
172
|
+
return resp.text or ""
|
|
173
|
+
|
|
174
|
+
async def reboot(self) -> dict:
|
|
175
|
+
raise NotImplementedError('ONVIF reboot is not implemented')
|
|
176
|
+
|
|
177
|
+
async def scrape(self) -> dict:
|
|
178
|
+
probe = await _onvif_probe(self.ip)
|
|
179
|
+
service = probe.get('service')
|
|
180
|
+
if not service:
|
|
181
|
+
raise RuntimeError('ONVIF device service not discovered')
|
|
182
|
+
parsed = urlparse(service)
|
|
183
|
+
if parsed.scheme not in ('http', 'https') or parsed.hostname != self.ip or parsed.username or parsed.password:
|
|
184
|
+
raise ValueError('ONVIF service address does not match target')
|
|
185
|
+
body = '<tds:GetDeviceInformation xmlns:tds="http://www.onvif.org/ver10/device/wsdl"/>'
|
|
186
|
+
text = await self._soap(service, 'http://www.onvif.org/ver10/device/wsdl/GetDeviceInformation', body)
|
|
187
|
+
try:
|
|
188
|
+
root = ET.fromstring(text)
|
|
189
|
+
except (ET.ParseError, TypeError) as exc:
|
|
190
|
+
raise RuntimeError('Invalid ONVIF SOAP response') from exc
|
|
191
|
+
if any(node.tag.rsplit('}',1)[-1] == 'Fault' for node in root.iter()):
|
|
192
|
+
raise RuntimeError('ONVIF SOAP fault')
|
|
193
|
+
response = next((n for n in root.iter() if n.tag == '{http://www.onvif.org/ver10/device/wsdl}GetDeviceInformationResponse'), None)
|
|
194
|
+
if response is None:
|
|
195
|
+
raise RuntimeError('Missing ONVIF device information')
|
|
196
|
+
fields = {n.tag.rsplit('}',1)[-1]: n.text or '' for n in response}
|
|
197
|
+
return {'protocol':'onvif','service':service,'model':fields.get('Model',''),
|
|
198
|
+
'manufacturer':fields.get('Manufacturer',''), 'serial':fields.get('SerialNumber','')}
|
|
199
|
+
|
|
200
|
+
# ------------------------------------------------------------------ Cast
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
@register
|
|
204
|
+
class CastAdapter(BaseAdapter):
|
|
205
|
+
"""Chromecast / 投屏设备。"""
|
|
206
|
+
|
|
207
|
+
protocol = "cast"
|
|
208
|
+
platform = ""
|
|
209
|
+
|
|
210
|
+
async def list_capabilities(self) -> list[dict]:
|
|
211
|
+
return [
|
|
212
|
+
{"key": "status", "name": "device_info", "zh": catalog.capability_zh("status"),
|
|
213
|
+
"en": catalog.capability_en("status"), "kind": "bool", "writable": False},
|
|
214
|
+
]
|
|
215
|
+
|
|
216
|
+
async def read_capability(self, capability: str):
|
|
217
|
+
if capability == "status":
|
|
218
|
+
return await self.scrape()
|
|
219
|
+
return None
|
|
220
|
+
|
|
221
|
+
async def scrape(self) -> dict:
|
|
222
|
+
return {
|
|
223
|
+
"protocol": "cast",
|
|
224
|
+
"name": getattr(self.device, "name", ""),
|
|
225
|
+
"model": getattr(self.device, "model", ""),
|
|
226
|
+
"note": "投屏设备的本地控制需要 Cast 私有协议(protobuf),插件暂只做识别与状态展示",
|
|
227
|
+
}
|