@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,108 @@
|
|
|
1
|
+
"""Offline checks for bridge cancellation and private connection handoff."""
|
|
2
|
+
import asyncio
|
|
3
|
+
import sys
|
|
4
|
+
import threading
|
|
5
|
+
import unittest
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from tempfile import TemporaryDirectory
|
|
8
|
+
from types import SimpleNamespace
|
|
9
|
+
from unittest.mock import patch, AsyncMock
|
|
10
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
11
|
+
import mihome_bridge as bridge
|
|
12
|
+
from smart_home.manager import SmartHomeManager
|
|
13
|
+
|
|
14
|
+
class BridgeTests(unittest.TestCase):
|
|
15
|
+
def test_timeout_cancels_pending_coroutine_before_delayed_write(self):
|
|
16
|
+
completed = threading.Event()
|
|
17
|
+
cancelled = threading.Event()
|
|
18
|
+
async def delayed():
|
|
19
|
+
try:
|
|
20
|
+
await asyncio.sleep(.12)
|
|
21
|
+
completed.set()
|
|
22
|
+
finally:
|
|
23
|
+
cancelled.set()
|
|
24
|
+
with self.assertRaises(TimeoutError):
|
|
25
|
+
bridge._run_async(delayed(), timeout=.01)
|
|
26
|
+
self.assertTrue(cancelled.wait(.3))
|
|
27
|
+
self.assertFalse(completed.is_set())
|
|
28
|
+
def test_smart_operations_apply_private_connections_and_scene_contract(self):
|
|
29
|
+
with TemporaryDirectory() as folder:
|
|
30
|
+
manager = SmartHomeManager({'data_dir':folder})
|
|
31
|
+
with patch.object(bridge, 'smart_home_manager', return_value=manager):
|
|
32
|
+
result = bridge.handle({'id':1,'op':'smart_home_scenes','args':{
|
|
33
|
+
'mode':'save','scene':{'name':'demo','actions':[{'device':'x','mode':'power','state':True}]},
|
|
34
|
+
'_connections':{'contract:manual':{'token':'hidden'}}}})
|
|
35
|
+
self.assertIs(result['result']['ok'], True)
|
|
36
|
+
self.assertEqual(manager._connections['contract:manual']['token'], 'hidden')
|
|
37
|
+
self.assertNotIn('hidden', str(result))
|
|
38
|
+
def test_cold_start_device_operations_allow_a_full_scan_budget(self):
|
|
39
|
+
manager = SimpleNamespace(device=AsyncMock(), control=AsyncMock(), scrape=AsyncMock())
|
|
40
|
+
budgets = []
|
|
41
|
+
def run(coro, timeout):
|
|
42
|
+
budgets.append(timeout)
|
|
43
|
+
coro.close()
|
|
44
|
+
return {}
|
|
45
|
+
with patch.object(bridge, 'smart_home_manager', return_value=manager), patch.object(bridge, '_run_async', side_effect=run):
|
|
46
|
+
bridge.op_smart_home_device({'id':'contract:one'})
|
|
47
|
+
bridge.op_smart_home_control({'device_id':'contract:one'})
|
|
48
|
+
bridge.op_smart_home_scrape({'device_id':'contract:one'})
|
|
49
|
+
self.assertEqual(budgets, [180, 180, 180])
|
|
50
|
+
|
|
51
|
+
def test_action_keeps_explicit_empty_parameter_containers(self):
|
|
52
|
+
from smart_home.adapters.base import BaseAdapter, register
|
|
53
|
+
@register
|
|
54
|
+
class ParamsAdapter(BaseAdapter):
|
|
55
|
+
protocol = 'bridge-params-contract'
|
|
56
|
+
async def run_action(self, name, params=None):
|
|
57
|
+
return {'ok': True, 'received': params}
|
|
58
|
+
with TemporaryDirectory() as folder:
|
|
59
|
+
manager = SmartHomeManager({'data_dir': folder})
|
|
60
|
+
manager._scan = {'devices': [{'id': 'bridge-params-contract:one',
|
|
61
|
+
'protocol': ParamsAdapter.protocol, 'fields': {}}]}
|
|
62
|
+
with patch.object(bridge, 'smart_home_manager', return_value=manager):
|
|
63
|
+
for supplied in ({}, [], False, 0):
|
|
64
|
+
with self.subTest(params=supplied):
|
|
65
|
+
result = bridge.handle({'id': 1, 'op': 'smart_home_control', 'args': {
|
|
66
|
+
'device_id': 'bridge-params-contract:one', 'mode': 'action',
|
|
67
|
+
'name': 'run', 'params': supplied}})
|
|
68
|
+
self.assertIs(result['ok'], True)
|
|
69
|
+
self.assertEqual(result['result']['received'], supplied)
|
|
70
|
+
self.assertIs(type(result['result']['received']), type(supplied))
|
|
71
|
+
bridge._run_async(manager.close(), timeout=1)
|
|
72
|
+
|
|
73
|
+
def test_power_distinguishes_omitted_state_from_explicit_null(self):
|
|
74
|
+
from smart_home.adapters.base import BaseAdapter, register
|
|
75
|
+
writes = []
|
|
76
|
+
@register
|
|
77
|
+
class PowerAdapter(BaseAdapter):
|
|
78
|
+
protocol = 'bridge-state-contract'
|
|
79
|
+
async def read_capability(self, key):
|
|
80
|
+
return False
|
|
81
|
+
async def write_capability(self, key, value):
|
|
82
|
+
writes.append((key, value))
|
|
83
|
+
return {'ok':True, 'on':value}
|
|
84
|
+
with TemporaryDirectory() as folder:
|
|
85
|
+
manager = SmartHomeManager({'data_dir':folder})
|
|
86
|
+
manager._scan = {'devices':[{'id':'bridge-state-contract:one', 'protocol':PowerAdapter.protocol, 'fields':{}}]}
|
|
87
|
+
with patch.object(bridge, 'smart_home_manager', return_value=manager):
|
|
88
|
+
result = bridge.op_smart_home_control({'device_id':'bridge-state-contract:one', 'mode':'power'})
|
|
89
|
+
self.assertIs(result['on'], True)
|
|
90
|
+
self.assertEqual(writes, [('power',True)])
|
|
91
|
+
with self.assertRaises(ValueError):
|
|
92
|
+
bridge.op_smart_home_control({'device_id':'bridge-state-contract:one', 'mode':'power', 'state':None})
|
|
93
|
+
self.assertEqual(writes, [('power',True)])
|
|
94
|
+
bridge._run_async(manager.close(), timeout=1)
|
|
95
|
+
|
|
96
|
+
def test_manager_cloud_proxy_updates_when_service_changes(self):
|
|
97
|
+
old = bridge._manager
|
|
98
|
+
bridge._manager = None
|
|
99
|
+
try:
|
|
100
|
+
with TemporaryDirectory() as folder, patch.dict('os.environ', {'MIHOME_DATA_DIR':folder}), patch.object(bridge, 'service', side_effect=[SimpleNamespace(), SimpleNamespace()]):
|
|
101
|
+
manager = bridge.smart_home_manager()
|
|
102
|
+
original = manager.cloud._svc
|
|
103
|
+
self.assertIs(bridge.smart_home_manager(), manager)
|
|
104
|
+
self.assertIsNot(manager.cloud._svc, original)
|
|
105
|
+
finally:
|
|
106
|
+
bridge._manager = old
|
|
107
|
+
|
|
108
|
+
if __name__ == '__main__': unittest.main()
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
"""HA mDNS/HTTP and miIO hello regressions; network boundaries are always mocked."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import socket
|
|
7
|
+
import struct
|
|
8
|
+
import sys
|
|
9
|
+
import types
|
|
10
|
+
import unittest
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from unittest.mock import AsyncMock, Mock, patch
|
|
13
|
+
|
|
14
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
15
|
+
from smart_home import discovery, util
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
HA_TYPE = '_home-assistant._tcp.local.'
|
|
19
|
+
HA_UUID = '0123456789abcdef0123456789abcdef'
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def mdns_modules(port=8123):
|
|
23
|
+
class Info:
|
|
24
|
+
server = HA_UUID + '.local.'
|
|
25
|
+
name = 'Test Home.' + HA_TYPE
|
|
26
|
+
properties = {
|
|
27
|
+
b'location_name': b'Test Home', b'uuid': HA_UUID.encode(), b'version': b'2026.11.0',
|
|
28
|
+
b'internal_url': b'http://user:private@wrong.example:9999', b'token': b'must-not-leak',
|
|
29
|
+
}
|
|
30
|
+
def parsed_addresses(self):
|
|
31
|
+
return ['192.0.2.20']
|
|
32
|
+
Info.port = port
|
|
33
|
+
|
|
34
|
+
class Zeroconf:
|
|
35
|
+
closed = 0
|
|
36
|
+
def __init__(self, **kwargs):
|
|
37
|
+
self.zeroconf = object()
|
|
38
|
+
async def async_get_service_info(self, type_, name, timeout=3000):
|
|
39
|
+
assert type_ == HA_TYPE and name == Info.name
|
|
40
|
+
return Info()
|
|
41
|
+
async def async_close(self):
|
|
42
|
+
Zeroconf.closed += 1
|
|
43
|
+
|
|
44
|
+
class Browser:
|
|
45
|
+
seen = []
|
|
46
|
+
cancelled = 0
|
|
47
|
+
def __init__(self, zc, type_, listener=None, **kwargs):
|
|
48
|
+
Browser.seen.append(type_)
|
|
49
|
+
if type_ == HA_TYPE:
|
|
50
|
+
listener.add_service(zc, type_, Info.name)
|
|
51
|
+
async def async_cancel(self):
|
|
52
|
+
Browser.cancelled += 1
|
|
53
|
+
|
|
54
|
+
return {
|
|
55
|
+
'zeroconf': types.SimpleNamespace(IPVersion=types.SimpleNamespace(V4Only='v4')),
|
|
56
|
+
'zeroconf.asyncio': types.SimpleNamespace(AsyncZeroconf=Zeroconf, AsyncServiceBrowser=Browser),
|
|
57
|
+
}, Browser, Zeroconf
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class HaDiscoveryTests(unittest.IsolatedAsyncioTestCase):
|
|
61
|
+
async def test_official_mdns_type_preserves_resolved_ip_port_uuid(self):
|
|
62
|
+
modules, browser, zc = mdns_modules()
|
|
63
|
+
with patch.dict(sys.modules, modules):
|
|
64
|
+
rows = await discovery.mdns_discover(timeout=0.1)
|
|
65
|
+
self.assertIn(HA_TYPE, browser.seen)
|
|
66
|
+
self.assertEqual(zc.closed, 1)
|
|
67
|
+
self.assertEqual(browser.cancelled, len(browser.seen))
|
|
68
|
+
self.assertEqual(len(rows), 1)
|
|
69
|
+
self.assertEqual(rows[0]['ip'], '192.0.2.20')
|
|
70
|
+
self.assertEqual(rows[0]['port'], 8123)
|
|
71
|
+
self.assertEqual(rows[0]['uuid'], HA_UUID)
|
|
72
|
+
self.assertEqual(rows[0]['version'], '2026.11.0')
|
|
73
|
+
self.assertEqual(rows[0]['location_name'], 'Test Home')
|
|
74
|
+
self.assertNotIn('private', repr(rows))
|
|
75
|
+
self.assertNotIn('must-not-leak', repr(rows))
|
|
76
|
+
|
|
77
|
+
async def test_empty_arp_and_ssdp_still_find_ha_without_tcp(self):
|
|
78
|
+
modules, _, _ = mdns_modules()
|
|
79
|
+
with patch.dict(sys.modules, modules), \
|
|
80
|
+
patch.object(util, 'arp_table', return_value={}), \
|
|
81
|
+
patch.object(util, 'ping_sweep', return_value=[]), \
|
|
82
|
+
patch.object(util, 'scan_ports', AsyncMock(return_value=[])) as scan_ports, \
|
|
83
|
+
patch.object(discovery, 'ssdp_discover', AsyncMock(return_value=[])), \
|
|
84
|
+
patch.object(discovery, 'tuya_discover', AsyncMock(return_value=[])), \
|
|
85
|
+
patch('smart_home.adapters.ble.ble_scan', AsyncMock(return_value=[])):
|
|
86
|
+
rows = await discovery.scan_subnet('192.0.2.0/24', scan_ping=False)
|
|
87
|
+
self.assertEqual(len(rows), 1)
|
|
88
|
+
row = rows[0]
|
|
89
|
+
self.assertEqual((row.ip, row.protocol, row.category), ('192.0.2.20', 'home_assistant', 'gateway'))
|
|
90
|
+
self.assertEqual(row.name, 'Test Home')
|
|
91
|
+
self.assertEqual(row.ports, [8123])
|
|
92
|
+
self.assertEqual(row.fields['uuid'], HA_UUID)
|
|
93
|
+
self.assertEqual(row.fields['base_url'], 'http://192.0.2.20:8123')
|
|
94
|
+
self.assertEqual(row.fields['port'], 8123)
|
|
95
|
+
self.assertTrue(row.requires_credentials)
|
|
96
|
+
self.assertNotIn('private', repr(row.to_dict()))
|
|
97
|
+
scan_ports.assert_not_awaited()
|
|
98
|
+
|
|
99
|
+
async def test_default_ports_and_http_fingerprint_include_8123(self):
|
|
100
|
+
self.assertIn(8123, util.DEFAULT_PORTS)
|
|
101
|
+
row = discovery.ScannedDevice(ip='192.0.2.20', ports=[8123])
|
|
102
|
+
get = AsyncMock(return_value=('Home Assistant', 'aiohttp', '<title>Home Assistant</title>', 'http://192.0.2.20:8123/'))
|
|
103
|
+
with patch.object(discovery, 'fetch_http', get):
|
|
104
|
+
await discovery._fingerprint(row)
|
|
105
|
+
get.assert_awaited_once_with('192.0.2.20', 8123, use_tls=False)
|
|
106
|
+
self.assertEqual((row.protocol, row.category), ('home_assistant', 'gateway'))
|
|
107
|
+
self.assertEqual(row.fields['base_url'], 'http://192.0.2.20:8123')
|
|
108
|
+
self.assertEqual(row.fields['port'], 8123)
|
|
109
|
+
self.assertTrue(row.requires_credentials)
|
|
110
|
+
|
|
111
|
+
async def test_http_tls_keeps_actual_scheme_and_non_ha_is_not_guessed(self):
|
|
112
|
+
row = discovery.ScannedDevice(ip='192.0.2.20', ports=[8123])
|
|
113
|
+
get = AsyncMock(side_effect=[None, ('Home Assistant', '', '', 'https://192.0.2.20:8123/')])
|
|
114
|
+
with patch.object(discovery, 'fetch_http', get):
|
|
115
|
+
await discovery._fingerprint(row)
|
|
116
|
+
self.assertEqual(row.protocol, 'home_assistant')
|
|
117
|
+
self.assertEqual(row.fields['base_url'], 'https://192.0.2.20:8123')
|
|
118
|
+
other = discovery.fingerprint_http('Example Dashboard', 'aiohttp', '', '192.0.2.20', 8123)
|
|
119
|
+
self.assertNotEqual(other.protocol, 'home_assistant')
|
|
120
|
+
|
|
121
|
+
async def test_invalid_ha_srv_port_never_creates_endpoint(self):
|
|
122
|
+
mdns = AsyncMock(return_value=[
|
|
123
|
+
{'ip': '192.0.2.20', 'port': port, 'service': HA_TYPE.rstrip('.')}
|
|
124
|
+
for port in (0, 65536, 'invalid', None)
|
|
125
|
+
])
|
|
126
|
+
with patch.object(discovery, 'mdns_discover', mdns), \
|
|
127
|
+
patch.object(discovery, 'ssdp_discover', AsyncMock(return_value=[])), \
|
|
128
|
+
patch.object(discovery, 'tuya_discover', AsyncMock(return_value=[])), \
|
|
129
|
+
patch('smart_home.adapters.ble.ble_scan', AsyncMock(return_value=[])):
|
|
130
|
+
rows = await discovery._extra_discovery('192.0.2.0/24')
|
|
131
|
+
self.assertEqual(rows, [])
|
|
132
|
+
|
|
133
|
+
async def test_mdns_does_not_downgrade_confirmed_https_endpoint(self):
|
|
134
|
+
row = discovery.ScannedDevice(ip='192.0.2.20', protocol='home_assistant',
|
|
135
|
+
confidence=.95, fields={'base_url': 'https://192.0.2.20:8123'})
|
|
136
|
+
discovery._merge_item(row, {
|
|
137
|
+
'protocol': 'home_assistant', 'source': 'mdns', 'confidence': .95,
|
|
138
|
+
'fields': {'base_url': 'http://192.0.2.20:8123', 'uuid': HA_UUID},
|
|
139
|
+
})
|
|
140
|
+
self.assertEqual(row.fields['base_url'], 'https://192.0.2.20:8123')
|
|
141
|
+
self.assertEqual(row.fields['uuid'], HA_UUID)
|
|
142
|
+
|
|
143
|
+
async def test_ha_os_port80_and_subnet_boundary(self):
|
|
144
|
+
mdns = AsyncMock(return_value=[
|
|
145
|
+
{'ip': '192.0.2.20', 'port': 80, 'service': HA_TYPE.rstrip('.'), 'uuid': HA_UUID,
|
|
146
|
+
'location_name': 'HA OS', 'name': 'HA OS.' + HA_TYPE, 'version': '2026.11.0'},
|
|
147
|
+
{'ip': '198.51.100.9', 'port': 8123, 'service': HA_TYPE.rstrip('.'), 'uuid': 'other'},
|
|
148
|
+
])
|
|
149
|
+
with patch.object(discovery, 'mdns_discover', mdns), \
|
|
150
|
+
patch.object(discovery, 'ssdp_discover', AsyncMock(return_value=[])), \
|
|
151
|
+
patch.object(discovery, 'tuya_discover', AsyncMock(return_value=[])), \
|
|
152
|
+
patch('smart_home.adapters.ble.ble_scan', AsyncMock(return_value=[])):
|
|
153
|
+
rows = await discovery._extra_discovery('192.0.2.0/24')
|
|
154
|
+
self.assertEqual(len(rows), 1)
|
|
155
|
+
self.assertEqual(rows[0]['protocol'], 'home_assistant')
|
|
156
|
+
self.assertEqual(rows[0]['fields']['base_url'], 'http://192.0.2.20:80')
|
|
157
|
+
self.assertEqual(rows[0]['ports'], [80])
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class MiioHelloTests(unittest.IsolatedAsyncioTestCase):
|
|
161
|
+
def packet(self, magic=0x2131, length=32, unknown=0, did=0x12345678, stamp=1234567):
|
|
162
|
+
return struct.pack('>HHIII', magic, length, unknown, did, stamp) + b'secret-token1234'
|
|
163
|
+
|
|
164
|
+
async def hello(self, data=None, error=None, ip='192.0.2.30', timeout=0.2):
|
|
165
|
+
sock = Mock()
|
|
166
|
+
# Handshake checksum/token is exactly 16 bytes and must never be exposed.
|
|
167
|
+
sock.recv.return_value = data if data is not None else self.packet()
|
|
168
|
+
if error:
|
|
169
|
+
sock.recv.side_effect = error
|
|
170
|
+
fake_socket = types.SimpleNamespace(AF_INET=socket.AF_INET, SOCK_DGRAM=socket.SOCK_DGRAM,
|
|
171
|
+
socket=Mock(return_value=sock))
|
|
172
|
+
# Replacing the global socket.socket type breaks Windows Proactor's own
|
|
173
|
+
# isinstance checks; inject only the module imported by the function.
|
|
174
|
+
with patch.dict(sys.modules, {'socket': fake_socket}), \
|
|
175
|
+
patch('asyncio.open_connection', AsyncMock(side_effect=OSError('TCP forbidden'))) as tcp:
|
|
176
|
+
result = await discovery.miio_hello(ip, timeout=timeout)
|
|
177
|
+
create = fake_socket.socket
|
|
178
|
+
return result, sock, create, tcp
|
|
179
|
+
|
|
180
|
+
async def test_hello_uses_udp_big_endian_header_without_leaking_token(self):
|
|
181
|
+
result, sock, create, tcp = await self.hello()
|
|
182
|
+
create.assert_called_once_with(socket.AF_INET, socket.SOCK_DGRAM)
|
|
183
|
+
tcp.assert_not_awaited()
|
|
184
|
+
sock.connect.assert_called_once_with(('192.0.2.30', 54321))
|
|
185
|
+
sock.send.assert_called_once_with(discovery.MIIO_HELLO)
|
|
186
|
+
sock.settimeout.assert_called_once_with(0.2)
|
|
187
|
+
sock.close.assert_called_once()
|
|
188
|
+
self.assertEqual(result, {'device_id': str(0x12345678), 'timestamp': 1234567})
|
|
189
|
+
self.assertNotIn('secret', repr(result))
|
|
190
|
+
self.assertNotIn('model', result)
|
|
191
|
+
|
|
192
|
+
async def test_malformed_and_echoed_hello_never_identify_device(self):
|
|
193
|
+
for data in (b'bad', self.packet(magic=0x3121), self.packet(length=33),
|
|
194
|
+
self.packet() + b'{}', discovery.MIIO_HELLO,
|
|
195
|
+
self.packet(did=0xffffffff), self.packet(stamp=0xffffffff)):
|
|
196
|
+
with self.subTest(data=data[:16].hex()):
|
|
197
|
+
result, sock, _, _ = await self.hello(data=data)
|
|
198
|
+
self.assertEqual(result, {})
|
|
199
|
+
sock.close.assert_called_once()
|
|
200
|
+
|
|
201
|
+
async def test_udp_timeout_and_oserror_close_socket(self):
|
|
202
|
+
for error in (socket.timeout(), OSError('unreachable')):
|
|
203
|
+
result, sock, _, _ = await self.hello(error=error)
|
|
204
|
+
self.assertEqual(result, {})
|
|
205
|
+
sock.close.assert_called_once()
|
|
206
|
+
|
|
207
|
+
async def test_invalid_address_or_timeout_creates_no_socket(self):
|
|
208
|
+
for ip, timeout in (('not-a-host', .2), ('::1', .2), ('192.0.2.30', 0), ('192.0.2.30', -1)):
|
|
209
|
+
result, _, create, _ = await self.hello(ip=ip, timeout=timeout)
|
|
210
|
+
self.assertEqual(result, {})
|
|
211
|
+
create.assert_not_called()
|
|
212
|
+
|
|
213
|
+
async def test_udp_only_arp_candidate_does_not_require_open_tcp54321(self):
|
|
214
|
+
hello = AsyncMock(return_value={'device_id': '12345', 'timestamp': 10})
|
|
215
|
+
with patch.object(util, 'arp_table', return_value={'192.0.2.30': ''}), \
|
|
216
|
+
patch.object(util, 'scan_ports', AsyncMock(return_value=[])), \
|
|
217
|
+
patch.object(discovery, '_extra_discovery', AsyncMock(return_value=[])), \
|
|
218
|
+
patch.object(discovery, 'miio_hello', hello):
|
|
219
|
+
rows = await discovery.scan_subnet('192.0.2.0/24', ports=[54321], scan_ping=False)
|
|
220
|
+
hello.assert_awaited_once_with('192.0.2.30', timeout=1.2)
|
|
221
|
+
self.assertEqual(rows[0].protocol, 'miio')
|
|
222
|
+
self.assertEqual(rows[0].fields['miio'], {'device_id': '12345', 'timestamp': 10})
|
|
223
|
+
self.assertEqual(rows[0].ports, [])
|
|
224
|
+
|
|
225
|
+
async def test_udp_candidates_use_bounded_concurrency(self):
|
|
226
|
+
started = 0
|
|
227
|
+
active = 0
|
|
228
|
+
peak = 0
|
|
229
|
+
ready = asyncio.Event()
|
|
230
|
+
async def hello(*args, **kwargs):
|
|
231
|
+
nonlocal started, active, peak
|
|
232
|
+
started += 1
|
|
233
|
+
active += 1
|
|
234
|
+
peak = max(peak, active)
|
|
235
|
+
if started >= 2:
|
|
236
|
+
ready.set()
|
|
237
|
+
try:
|
|
238
|
+
await asyncio.wait_for(ready.wait(), .1)
|
|
239
|
+
return {'device_id': args[0].split('.')[-1], 'timestamp': 10}
|
|
240
|
+
finally:
|
|
241
|
+
active -= 1
|
|
242
|
+
with patch.object(util, 'arp_table', return_value={f'192.0.2.{n}': '' for n in range(1, 5)}), \
|
|
243
|
+
patch.object(util, 'scan_ports', AsyncMock(return_value=[])), \
|
|
244
|
+
patch.object(discovery, '_extra_discovery', AsyncMock(return_value=[])), \
|
|
245
|
+
patch.object(discovery, 'miio_hello', hello):
|
|
246
|
+
rows = await discovery.scan_subnet('192.0.2.0/24', ports=[54321], scan_ping=False, concurrency=2)
|
|
247
|
+
self.assertEqual(len(rows), 4)
|
|
248
|
+
self.assertEqual(peak, 2)
|
|
249
|
+
|
|
250
|
+
async def test_explicit_port_selection_can_skip_udp_probe(self):
|
|
251
|
+
with patch.object(util, 'arp_table', return_value={'192.0.2.30': ''}), \
|
|
252
|
+
patch.object(util, 'scan_ports', AsyncMock(return_value=[])), \
|
|
253
|
+
patch.object(discovery, '_extra_discovery', AsyncMock(return_value=[])), \
|
|
254
|
+
patch.object(discovery, 'miio_hello', AsyncMock()) as hello:
|
|
255
|
+
await discovery.scan_subnet('192.0.2.0/24', ports=[80], scan_ping=False)
|
|
256
|
+
hello.assert_not_awaited()
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
if __name__ == '__main__':
|
|
260
|
+
unittest.main(verbosity=2)
|