@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,365 @@
|
|
|
1
|
+
"""Offline Home Assistant REST contract tests; no Home Assistant is contacted."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import copy
|
|
5
|
+
import importlib
|
|
6
|
+
import json
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import sys
|
|
9
|
+
import threading
|
|
10
|
+
from types import SimpleNamespace
|
|
11
|
+
import unittest
|
|
12
|
+
from unittest.mock import AsyncMock, patch
|
|
13
|
+
|
|
14
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
15
|
+
try:
|
|
16
|
+
HA = importlib.import_module('smart_home.adapters.home_assistant').HomeAssistantAdapter
|
|
17
|
+
except ModuleNotFoundError:
|
|
18
|
+
HA = None
|
|
19
|
+
|
|
20
|
+
TOKEN = 'offline-test-secret-never-echo'
|
|
21
|
+
SERVICE_NAMES = {
|
|
22
|
+
'light': ['turn_on', 'turn_off'], 'switch': ['turn_on', 'turn_off'],
|
|
23
|
+
'fan': ['turn_on', 'turn_off', 'set_percentage', 'oscillate', 'set_direction', 'set_preset_mode'],
|
|
24
|
+
'climate': ['turn_on', 'turn_off', 'set_temperature', 'set_hvac_mode', 'set_humidity', 'set_fan_mode', 'set_preset_mode', 'set_swing_mode', 'set_swing_horizontal_mode'],
|
|
25
|
+
'cover': ['open_cover', 'close_cover', 'stop_cover', 'set_cover_position', 'set_cover_tilt_position'],
|
|
26
|
+
'media_player': ['turn_on', 'turn_off', 'volume_set', 'volume_mute', 'select_source', 'media_play', 'media_pause', 'media_stop', 'media_next_track', 'media_previous_track', 'play_media'],
|
|
27
|
+
'vacuum': ['start', 'pause', 'stop', 'return_to_base', 'locate', 'clean_spot', 'set_fan_speed'],
|
|
28
|
+
'lock': ['lock', 'unlock', 'open'], 'humidifier': ['turn_on', 'turn_off', 'set_humidity', 'set_mode'],
|
|
29
|
+
'select': ['select_option'], 'number': ['set_value'], 'button': ['press'],
|
|
30
|
+
'scene': ['turn_on'], 'script': ['turn_on', 'turn_off'],
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def services():
|
|
35
|
+
data = [{'domain': domain, 'services': {name: {} for name in names}} for domain, names in SERVICE_NAMES.items()]
|
|
36
|
+
next(x for x in data if x['domain'] == 'lock')['services']['unlock'] = {'fields': {'code': {'selector': {'text': {}}, 'required': False}}}
|
|
37
|
+
next(x for x in data if x['domain'] == 'media_player')['services']['play_media'] = {'fields': {
|
|
38
|
+
'media_content_id': {'required': True, 'selector': {'text': {}}},
|
|
39
|
+
'media_content_type': {'required': True, 'selector': {'text': {}}},
|
|
40
|
+
}}
|
|
41
|
+
return data
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def state(entity_id, value='on', **attributes):
|
|
45
|
+
return {'entity_id': entity_id, 'state': value, 'attributes': attributes}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class AdapterTests(unittest.IsolatedAsyncioTestCase):
|
|
49
|
+
def setUp(self):
|
|
50
|
+
self.assertIsNotNone(HA, 'Home Assistant adapter has not been implemented')
|
|
51
|
+
|
|
52
|
+
def make(self, item=None, service_data=None):
|
|
53
|
+
entity = item['entity_id'] if item else ''
|
|
54
|
+
device = SimpleNamespace(id='home_assistant:' + (entity or 'main'), ip='', mac='',
|
|
55
|
+
fields={'entity_id': entity} if entity else {}, credentials={'token': TOKEN})
|
|
56
|
+
adapter = HA(device, {'base_url': 'http://ha.invalid:8123'})
|
|
57
|
+
async def response(method, path, payload=None):
|
|
58
|
+
if path == '/api/services':
|
|
59
|
+
return copy.deepcopy(service_data if service_data is not None else services())
|
|
60
|
+
if path == '/api/config':
|
|
61
|
+
return {'unit_system': {'temperature': '°F'}}
|
|
62
|
+
if path == '/api/states':
|
|
63
|
+
return [copy.deepcopy(item)] if item else []
|
|
64
|
+
if path.startswith('/api/states/') and item:
|
|
65
|
+
return copy.deepcopy(item)
|
|
66
|
+
if path.startswith('/api/services/') and method == 'POST':
|
|
67
|
+
return []
|
|
68
|
+
raise AssertionError((method, path, payload))
|
|
69
|
+
adapter._request = AsyncMock(side_effect=response)
|
|
70
|
+
return adapter
|
|
71
|
+
|
|
72
|
+
async def caps(self, adapter):
|
|
73
|
+
return {item['key']: item for item in await adapter.list_capabilities()}
|
|
74
|
+
|
|
75
|
+
async def posted(self, adapter):
|
|
76
|
+
calls = [c.args for c in adapter._request.await_args_list if c.args[0] == 'POST']
|
|
77
|
+
return calls[-1]
|
|
78
|
+
|
|
79
|
+
async def test_entity_identity_overrides_inherited_hub_configuration(self):
|
|
80
|
+
a = self.make(state('light.kitchen', supported_color_modes=['onoff']))
|
|
81
|
+
a.config['entity_id'] = 'light.desk'
|
|
82
|
+
self.assertEqual(a._entity_id(), 'light.kitchen')
|
|
83
|
+
await a.write_capability('power', True)
|
|
84
|
+
self.assertEqual((await self.posted(a))[2]['entity_id'], 'light.kitchen')
|
|
85
|
+
|
|
86
|
+
async def test_hub_discovery_has_only_public_identity_and_reads(self):
|
|
87
|
+
adapter = self.make()
|
|
88
|
+
rows = [state('light.desk', friendly_name='Desk', supported_color_modes=['onoff']),
|
|
89
|
+
state('sensor.outdoor', '12.5', friendly_name='Outside', device_class='temperature', unit_of_measurement='°C'),
|
|
90
|
+
state('custom.unknown', 'idle'), state('switch.offline', 'unavailable')]
|
|
91
|
+
async def response(method, path, payload=None):
|
|
92
|
+
self.assertEqual(method, 'GET')
|
|
93
|
+
return services() if path == '/api/services' else rows
|
|
94
|
+
adapter._request.side_effect = response
|
|
95
|
+
self.assertEqual(await adapter.list_capabilities(), [])
|
|
96
|
+
await adapter.probe()
|
|
97
|
+
result = await adapter.discover_entities()
|
|
98
|
+
self.assertEqual({x['entity_id'] for x in result}, {x['entity_id'] for x in rows})
|
|
99
|
+
lamp = next(x for x in result if x['entity_id'] == 'light.desk')
|
|
100
|
+
self.assertEqual(lamp['id'], 'home_assistant:light.desk')
|
|
101
|
+
self.assertEqual(lamp['name'], 'Desk')
|
|
102
|
+
self.assertEqual(lamp['category'], 'light')
|
|
103
|
+
self.assertEqual(lamp['fields']['entity_id'], 'light.desk')
|
|
104
|
+
self.assertFalse(next(x for x in result if x['entity_id'] == 'switch.offline')['online'])
|
|
105
|
+
self.assertNotIn(TOKEN, json.dumps(result))
|
|
106
|
+
self.assertNotIn('base_url', json.dumps(result))
|
|
107
|
+
|
|
108
|
+
async def test_light_percent_kelvin_rgb_and_exact_target(self):
|
|
109
|
+
a = self.make(state('light.desk', supported_color_modes=['rgb', 'color_temp'], brightness=128,
|
|
110
|
+
rgb_color=[1, 2, 3], color_temp_kelvin=3000, min_color_temp_kelvin=2200, max_color_temp_kelvin=6500))
|
|
111
|
+
caps = await self.caps(a)
|
|
112
|
+
self.assertEqual(caps['brightness']['range'], [0, 100, 1])
|
|
113
|
+
self.assertEqual(caps['color_temp']['range'], [2200, 6500, 1])
|
|
114
|
+
self.assertEqual(caps['color_temp']['unit'], 'K')
|
|
115
|
+
values = await a.read_all()
|
|
116
|
+
self.assertAlmostEqual(values['brightness'], 128 / 255 * 100, places=2)
|
|
117
|
+
self.assertEqual(values['color_temp'], 3000)
|
|
118
|
+
self.assertEqual(set(values), {key for key, cap in caps.items() if cap['readable']})
|
|
119
|
+
for percent, raw in [(100, 255), (50, 128), (0, 0)]:
|
|
120
|
+
self.assertTrue((await a.write_capability('brightness', percent))['ok'])
|
|
121
|
+
self.assertEqual(await self.posted(a), ('POST', '/api/services/light/turn_on', {'entity_id': 'light.desk', 'brightness': raw}))
|
|
122
|
+
await a.write_capability('color_temp', 4000)
|
|
123
|
+
self.assertEqual((await self.posted(a))[2]['color_temp_kelvin'], 4000)
|
|
124
|
+
await a.write_capability('color', '10,20,30')
|
|
125
|
+
self.assertEqual((await self.posted(a))[2]['rgb_color'], [10, 20, 30])
|
|
126
|
+
with self.assertRaises(ValueError):
|
|
127
|
+
await a.write_capability('color_temp', 100)
|
|
128
|
+
|
|
129
|
+
async def test_entity_features_and_service_directory_both_gate_writes(self):
|
|
130
|
+
data = [{'domain': 'light', 'services': {'turn_off': {}}}]
|
|
131
|
+
a = self.make(state('light.simple', brightness=100, supported_color_modes=['onoff']), data)
|
|
132
|
+
caps = await self.caps(a)
|
|
133
|
+
self.assertFalse(caps['power']['writable'])
|
|
134
|
+
self.assertFalse(caps['brightness']['writable'])
|
|
135
|
+
with self.assertRaises((ValueError, NotImplementedError)):
|
|
136
|
+
await a.write_capability('brightness', 80)
|
|
137
|
+
self.assertFalse(any(c.args[0] == 'POST' for c in a._request.await_args_list))
|
|
138
|
+
|
|
139
|
+
async def test_fan_percentage_modes_oscillation_and_feature_gate(self):
|
|
140
|
+
a = self.make(state('fan.office', supported_features=63, percentage=50, percentage_step=25,
|
|
141
|
+
oscillating=True, direction='forward', preset_mode='auto', preset_modes=['auto', 'sleep']))
|
|
142
|
+
caps = await self.caps(a)
|
|
143
|
+
self.assertEqual(caps['fan_speed']['range'], [0, 100, 25])
|
|
144
|
+
self.assertEqual((await a.read_all())['swing'], True)
|
|
145
|
+
await a.write_capability('fan_speed', 75)
|
|
146
|
+
self.assertEqual((await self.posted(a))[1:], ('/api/services/fan/set_percentage', {'entity_id': 'fan.office', 'percentage': 75}))
|
|
147
|
+
await a.write_capability('swing', 'false')
|
|
148
|
+
self.assertIs((await self.posted(a))[2]['oscillating'], False)
|
|
149
|
+
await a.write_capability('mode', 'sleep')
|
|
150
|
+
self.assertEqual((await self.posted(a))[2]['preset_mode'], 'sleep')
|
|
151
|
+
b = self.make(state('fan.fixed', supported_features=0, percentage=50))
|
|
152
|
+
self.assertFalse((await self.caps(b))['fan_speed']['writable'])
|
|
153
|
+
|
|
154
|
+
async def test_climate_native_ranges_modes_and_paired_temperature(self):
|
|
155
|
+
a = self.make(state('climate.room', 'heat', supported_features=1 | 2 | 4 | 8 | 16 | 32 | 128 | 256,
|
|
156
|
+
temperature=70, current_temperature=68, min_temp=50, max_temp=90, target_temp_step=0.5,
|
|
157
|
+
temperature_unit='°F', target_temp_low=65, target_temp_high=75,
|
|
158
|
+
hvac_modes=['off', 'heat', 'cool', 'heat_cool'], fan_mode='auto', fan_modes=['auto', 'low'],
|
|
159
|
+
preset_mode='eco', preset_modes=['eco', 'away'], swing_mode='off', swing_modes=['off', 'on'],
|
|
160
|
+
humidity=45, min_humidity=30, max_humidity=80, current_humidity=42))
|
|
161
|
+
caps = await self.caps(a)
|
|
162
|
+
self.assertEqual(caps['target_temp']['range'], [50, 90, 0.5])
|
|
163
|
+
self.assertEqual(caps['target_temp']['unit'], '°F')
|
|
164
|
+
self.assertEqual((await a.read_all())['mode'], 'heat')
|
|
165
|
+
await a.write_capability('target_temp', 72.5)
|
|
166
|
+
self.assertEqual((await self.posted(a))[2]['temperature'], 72.5)
|
|
167
|
+
await a.write_capability('target_temp_low', 66)
|
|
168
|
+
self.assertEqual((await self.posted(a))[2], {'entity_id': 'climate.room', 'target_temp_low': 66, 'target_temp_high': 75})
|
|
169
|
+
with self.assertRaises(ValueError):
|
|
170
|
+
await a.write_capability('mode', 'invented')
|
|
171
|
+
with self.assertRaises(ValueError):
|
|
172
|
+
await a.write_capability('target_temp_low', 80)
|
|
173
|
+
|
|
174
|
+
async def test_cover_position_and_actions_need_features(self):
|
|
175
|
+
a = self.make(state('cover.blind', 'open', supported_features=15, current_position=35))
|
|
176
|
+
caps = await self.caps(a)
|
|
177
|
+
self.assertEqual(caps['position']['range'], [0, 100, 1])
|
|
178
|
+
self.assertEqual(caps['open']['kind'], 'action')
|
|
179
|
+
self.assertFalse(caps['open']['readable'])
|
|
180
|
+
await a.write_capability('position', 80)
|
|
181
|
+
self.assertEqual((await self.posted(a))[2], {'entity_id': 'cover.blind', 'position': 80})
|
|
182
|
+
self.assertTrue((await a.run_action('stop'))['ok'])
|
|
183
|
+
self.assertEqual((await self.posted(a))[1], '/api/services/cover/stop_cover')
|
|
184
|
+
b = self.make(state('cover.basic', supported_features=0, current_position=30))
|
|
185
|
+
self.assertNotIn('open', await self.caps(b))
|
|
186
|
+
self.assertFalse((await self.caps(b))['position']['writable'])
|
|
187
|
+
|
|
188
|
+
async def test_media_player_volume_source_and_parameterized_action(self):
|
|
189
|
+
a = self.make(state('media_player.tv', 'playing', supported_features=4 | 8 | 16 | 32 | 128 | 256 | 512 | 2048 | 4096 | 16384 | 1,
|
|
190
|
+
volume_level=0.25, is_volume_muted=False, source='HDMI 1', source_list=['HDMI 1', 'TV']))
|
|
191
|
+
caps = await self.caps(a)
|
|
192
|
+
self.assertEqual((await a.read_all())['volume'], 25)
|
|
193
|
+
self.assertEqual(caps['play_media']['kind'], 'action')
|
|
194
|
+
self.assertIn('media_content_id', caps['play_media']['params_schema']['properties'])
|
|
195
|
+
await a.write_capability('volume', 50)
|
|
196
|
+
self.assertEqual((await self.posted(a))[2]['volume_level'], 0.5)
|
|
197
|
+
await a.write_capability('input_source', 'TV')
|
|
198
|
+
self.assertEqual((await self.posted(a))[2]['source'], 'TV')
|
|
199
|
+
with self.assertRaises(ValueError):
|
|
200
|
+
await a.run_action('play_media', {})
|
|
201
|
+
await a.run_action('play_media', {'media_content_id': 'demo', 'media_content_type': 'music'})
|
|
202
|
+
self.assertEqual((await self.posted(a))[2]['entity_id'], 'media_player.tv')
|
|
203
|
+
with self.assertRaises(ValueError):
|
|
204
|
+
await a.run_action('play', {'entity_id': 'media_player.other'})
|
|
205
|
+
|
|
206
|
+
async def test_vacuum_actions_and_string_fan_speed(self):
|
|
207
|
+
a = self.make(state('vacuum.robot', 'docked', supported_features=8192 | 4 | 8 | 16 | 32 | 512 | 1024,
|
|
208
|
+
fan_speed='quiet', fan_speed_list=['quiet', 'turbo']))
|
|
209
|
+
caps = await self.caps(a)
|
|
210
|
+
self.assertEqual(caps['clean']['kind'], 'action')
|
|
211
|
+
self.assertEqual(caps['charge']['kind'], 'action')
|
|
212
|
+
self.assertNotIn('power', caps)
|
|
213
|
+
await a.run_action('charge')
|
|
214
|
+
self.assertEqual((await self.posted(a))[1], '/api/services/vacuum/return_to_base')
|
|
215
|
+
await a.write_capability('fan_speed', 'turbo')
|
|
216
|
+
self.assertEqual((await self.posted(a))[2]['fan_speed'], 'turbo')
|
|
217
|
+
|
|
218
|
+
async def test_lock_actions_use_declared_code_without_exposing_it(self):
|
|
219
|
+
a = self.make(state('lock.front', 'locked', supported_features=1, code_format='^\\d{4}$'))
|
|
220
|
+
caps = await self.caps(a)
|
|
221
|
+
self.assertEqual(caps['unlock']['kind'], 'action')
|
|
222
|
+
self.assertEqual((await a.read_all())['status'], 'locked')
|
|
223
|
+
result = await a.run_action('unlock', {'code': '1234'})
|
|
224
|
+
self.assertEqual((await self.posted(a))[2], {'entity_id': 'lock.front', 'code': '1234'})
|
|
225
|
+
self.assertNotIn('1234', json.dumps(result))
|
|
226
|
+
|
|
227
|
+
async def test_humidifier_native_humidity_and_mode(self):
|
|
228
|
+
a = self.make(state('humidifier.room', supported_features=1, humidity=50, current_humidity=45,
|
|
229
|
+
min_humidity=35, max_humidity=75, target_humidity_step=5, mode='auto', available_modes=['auto', 'sleep']))
|
|
230
|
+
caps = await self.caps(a)
|
|
231
|
+
self.assertEqual(caps['target_humidity']['range'], [35, 75, 5])
|
|
232
|
+
await a.write_capability('target_humidity', 60)
|
|
233
|
+
self.assertEqual((await self.posted(a))[1], '/api/services/humidifier/set_humidity')
|
|
234
|
+
await a.write_capability('mode', 'sleep')
|
|
235
|
+
self.assertEqual((await self.posted(a))[2]['mode'], 'sleep')
|
|
236
|
+
|
|
237
|
+
async def test_select_number_and_trigger_entities(self):
|
|
238
|
+
a = self.make(state('select.program', 'eco', options=['eco', 'normal']))
|
|
239
|
+
self.assertEqual((await self.caps(a))['mode']['value_list'][0]['value'], 'eco')
|
|
240
|
+
await a.write_capability('mode', 'normal')
|
|
241
|
+
self.assertEqual((await self.posted(a))[2]['option'], 'normal')
|
|
242
|
+
b = self.make(state('number.setpoint', '12.5', min=5, max=20, step=0.5, unit_of_measurement='V'))
|
|
243
|
+
self.assertEqual((await self.caps(b))['value']['range'], [5, 20, 0.5])
|
|
244
|
+
self.assertEqual((await b.read_all())['value'], 12.5)
|
|
245
|
+
await b.write_capability('value', 15)
|
|
246
|
+
self.assertEqual((await self.posted(b))[1], '/api/services/number/set_value')
|
|
247
|
+
for domain, action, service in [('button', 'press', 'press'), ('scene', 'activate', 'turn_on'), ('script', 'run', 'turn_on')]:
|
|
248
|
+
with self.subTest(domain=domain):
|
|
249
|
+
c = self.make(state(domain + '.test', 'unknown'))
|
|
250
|
+
self.assertEqual((await self.caps(c))[action]['kind'], 'action')
|
|
251
|
+
await c.run_action(action)
|
|
252
|
+
self.assertEqual((await self.posted(c))[1], f'/api/services/{domain}/{service}')
|
|
253
|
+
|
|
254
|
+
async def test_sensors_unknown_and_unavailable_never_guess_writes(self):
|
|
255
|
+
a = self.make(state('sensor.temp', '21.6', device_class='temperature', unit_of_measurement='°C'))
|
|
256
|
+
self.assertEqual((await a.read_all())['temperature'], 21.6)
|
|
257
|
+
self.assertEqual((await self.caps(a))['temperature']['unit'], '°C')
|
|
258
|
+
for item in [state('custom.foo', 'idle', supported_features=65535), state('light.offline', 'unavailable', supported_color_modes=['brightness'])]:
|
|
259
|
+
b = self.make(item)
|
|
260
|
+
self.assertFalse(any(x['writable'] for x in await b.list_capabilities()))
|
|
261
|
+
with self.assertRaises((ValueError, NotImplementedError)):
|
|
262
|
+
await b.write_capability('power', True)
|
|
263
|
+
c = self.make(state('binary_sensor.door', 'off', device_class='door'))
|
|
264
|
+
self.assertIs((await c.read_all())['value'], False)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
async def test_discovery_uses_known_categories_and_unavailable_trigger_is_read_only(self):
|
|
268
|
+
a = self.make()
|
|
269
|
+
a._request.return_value = [state('lock.front'), state('media_player.audio', device_class='speaker')]
|
|
270
|
+
a._request.side_effect = None
|
|
271
|
+
rows = await a.discover_entities()
|
|
272
|
+
self.assertEqual(rows[0]['category'], 'lock')
|
|
273
|
+
self.assertEqual(rows[1]['category'], 'speaker')
|
|
274
|
+
trigger = self.make(state('scene.first', 'unavailable'))
|
|
275
|
+
self.assertNotIn('activate', await self.caps(trigger))
|
|
276
|
+
|
|
277
|
+
async def test_kelvin_bounds_and_step_and_unknown_values_are_not_guessed(self):
|
|
278
|
+
a = self.make(state('light.no_bounds', color_temp_kelvin=3000, supported_color_modes=['color_temp']))
|
|
279
|
+
self.assertFalse((await self.caps(a))['color_temp']['writable'])
|
|
280
|
+
number = self.make(state('number.stepped', '10', min=5, max=20, step=0.5))
|
|
281
|
+
with self.assertRaises(ValueError):
|
|
282
|
+
await number.write_capability('value', 10.3)
|
|
283
|
+
self.assertFalse(any(c.args[0] == 'POST' for c in number._request.await_args_list))
|
|
284
|
+
|
|
285
|
+
async def test_ha_temperature_unit_is_read_from_configuration_when_absent(self):
|
|
286
|
+
a = self.make(state('climate.furnace', 'heat', supported_features=1, temperature=70, min_temp=45, max_temp=95))
|
|
287
|
+
caps = await self.caps(a)
|
|
288
|
+
self.assertEqual(caps['target_temp']['unit'], '°F')
|
|
289
|
+
|
|
290
|
+
async def test_list_style_directory_is_supported_and_invalid_json_service_is_failure(self):
|
|
291
|
+
a = self.make(state('switch.desk'), [{'domain': 'switch', 'services': ['turn_on', 'turn_off']}])
|
|
292
|
+
self.assertTrue((await self.caps(a))['power']['writable'])
|
|
293
|
+
original = a._request.side_effect
|
|
294
|
+
async def response(method, path, payload=None):
|
|
295
|
+
if method == 'POST':
|
|
296
|
+
return [{'error': 'do not claim success'}]
|
|
297
|
+
return await original(method, path, payload)
|
|
298
|
+
a._request.side_effect = response
|
|
299
|
+
with self.assertRaises(RuntimeError):
|
|
300
|
+
await a.write_capability('power', True)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
class HttpTests(unittest.IsolatedAsyncioTestCase):
|
|
304
|
+
def setUp(self):
|
|
305
|
+
self.assertIsNotNone(HA, 'Home Assistant adapter has not been implemented')
|
|
306
|
+
self.device = SimpleNamespace(id='home_assistant:light.desk', fields={'entity_id': 'light.desk'}, credentials={'token': TOKEN})
|
|
307
|
+
self.adapter = HA(self.device, {'base_url': 'http://ha.invalid:8123/'})
|
|
308
|
+
|
|
309
|
+
async def test_request_offloads_blocking_io_and_sets_bearer_once(self):
|
|
310
|
+
thread = threading.get_ident()
|
|
311
|
+
def request(method, url, **kwargs):
|
|
312
|
+
self.assertNotEqual(thread, threading.get_ident())
|
|
313
|
+
self.assertEqual(url, 'http://ha.invalid:8123/api/states')
|
|
314
|
+
self.assertEqual(kwargs['headers']['Authorization'], 'Bearer ' + TOKEN)
|
|
315
|
+
self.assertFalse(kwargs['allow_redirects'])
|
|
316
|
+
return SimpleNamespace(status_code=200, json=lambda: [])
|
|
317
|
+
with patch('requests.request', side_effect=request) as call:
|
|
318
|
+
self.assertEqual(await self.adapter._request('GET', '/api/states'), [])
|
|
319
|
+
self.assertEqual(call.call_count, 1)
|
|
320
|
+
|
|
321
|
+
async def test_http_errors_json_errors_and_transport_errors_are_sanitized(self):
|
|
322
|
+
responses = [SimpleNamespace(status_code=401, json=lambda: {'message': TOKEN}),
|
|
323
|
+
SimpleNamespace(status_code=404, json=lambda: {'error': TOKEN}),
|
|
324
|
+
SimpleNamespace(status_code=200, json=lambda: {'error': TOKEN}),
|
|
325
|
+
SimpleNamespace(status_code=200, json=lambda: (_ for _ in ()).throw(ValueError(TOKEN)))]
|
|
326
|
+
for response in responses:
|
|
327
|
+
with self.subTest(status=response.status_code), patch('requests.request', return_value=response):
|
|
328
|
+
with self.assertRaises(RuntimeError) as caught:
|
|
329
|
+
await self.adapter._request('GET', '/api/states')
|
|
330
|
+
self.assertNotIn(TOKEN, str(caught.exception))
|
|
331
|
+
self.assertNotIn('Bearer', str(caught.exception))
|
|
332
|
+
with patch('requests.request', side_effect=RuntimeError('Authorization: Bearer ' + TOKEN)):
|
|
333
|
+
with self.assertRaises(RuntimeError) as caught:
|
|
334
|
+
await self.adapter._request('GET', '/api/states')
|
|
335
|
+
self.assertNotIn(TOKEN, str(caught.exception))
|
|
336
|
+
self.assertIsNone(caught.exception.__cause__)
|
|
337
|
+
|
|
338
|
+
async def test_configuration_and_entity_validation_never_send_unsafe_requests(self):
|
|
339
|
+
for config in [{}, {'base_url': 'ftp://host'}, {'base_url': 'http://user:secret@host'}, {'base_url': 'http://host?token=secret'}]:
|
|
340
|
+
with self.subTest(config=config), patch('requests.request') as call:
|
|
341
|
+
a = HA(self.device, config)
|
|
342
|
+
with self.assertRaises(ValueError):
|
|
343
|
+
await a._request('GET', '/api/states')
|
|
344
|
+
call.assert_not_called()
|
|
345
|
+
a = HA(SimpleNamespace(id='home_assistant:main', credentials={}), {'base_url': 'http://ha.invalid'})
|
|
346
|
+
with patch('requests.request') as call:
|
|
347
|
+
with self.assertRaises(ValueError):
|
|
348
|
+
await a._request('GET', '/api/states')
|
|
349
|
+
call.assert_not_called()
|
|
350
|
+
|
|
351
|
+
async def test_empty_service_response_success_but_401_never_success(self):
|
|
352
|
+
item = state('light.desk', supported_color_modes=['onoff'])
|
|
353
|
+
def request(method, url, **kwargs):
|
|
354
|
+
if method == 'GET':
|
|
355
|
+
return SimpleNamespace(status_code=200, json=lambda: services() if url.endswith('/services') else item)
|
|
356
|
+
return SimpleNamespace(status_code=200, json=lambda: [])
|
|
357
|
+
with patch('requests.request', side_effect=request):
|
|
358
|
+
self.assertTrue((await self.adapter.write_capability('power', True))['ok'])
|
|
359
|
+
with patch('requests.request', return_value=SimpleNamespace(status_code=401, json=lambda: {'message': TOKEN})):
|
|
360
|
+
with self.assertRaises(RuntimeError):
|
|
361
|
+
await self.adapter.write_capability('power', False)
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
if __name__ == '__main__':
|
|
365
|
+
unittest.main(verbosity=2)
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""Offline integration checks for private connections and honest capabilities."""
|
|
2
|
+
import json
|
|
3
|
+
import sys
|
|
4
|
+
import tempfile
|
|
5
|
+
import unittest
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from unittest.mock import AsyncMock, patch
|
|
8
|
+
from types import SimpleNamespace
|
|
9
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
10
|
+
from smart_home.manager import SmartHomeManager
|
|
11
|
+
from smart_home.adapters.base import BaseAdapter, register
|
|
12
|
+
|
|
13
|
+
@register
|
|
14
|
+
class ContractAdapter(BaseAdapter):
|
|
15
|
+
protocol = 'contract'
|
|
16
|
+
async def list_capabilities(self):
|
|
17
|
+
return [{'key':'power','name':'power','kind':'bool','readable':True,'writable':True}]
|
|
18
|
+
async def read_capability(self, key):
|
|
19
|
+
return None
|
|
20
|
+
async def write_capability(self, key, value):
|
|
21
|
+
return {'ok':'false'}
|
|
22
|
+
|
|
23
|
+
class IntegrationTests(unittest.IsolatedAsyncioTestCase):
|
|
24
|
+
def setUp(self):
|
|
25
|
+
self.temp = tempfile.TemporaryDirectory()
|
|
26
|
+
self.manager = SmartHomeManager({'data_dir':self.temp.name})
|
|
27
|
+
async def asyncTearDown(self):
|
|
28
|
+
await self.manager.close()
|
|
29
|
+
self.temp.cleanup()
|
|
30
|
+
def scanned(self, **kw):
|
|
31
|
+
return SimpleNamespace(protocol='contract',ip='192.0.2.4',name='Lamp',category='light',
|
|
32
|
+
fields={'token':'secret','version':'3.5'},credentials={'local_key':'private'},**kw)
|
|
33
|
+
async def test_private_scan_credentials_and_no_guessed_controls(self):
|
|
34
|
+
device = self.manager._build_device(self.scanned())
|
|
35
|
+
self.assertNotIn('secret', json.dumps(device))
|
|
36
|
+
self.assertEqual(device['controls'], [])
|
|
37
|
+
adapter = self.manager._adapter_for(device)
|
|
38
|
+
self.assertEqual(adapter.device.credentials['local_key'], 'private')
|
|
39
|
+
self.assertEqual(adapter.device.credentials['token'], 'secret')
|
|
40
|
+
async def test_configured_connection_creates_device_and_flattens_config(self):
|
|
41
|
+
await self.manager.set_connections({'contract:manual':{'ip':'192.0.2.8','token':'hidden','name':'Manual'}})
|
|
42
|
+
with patch('smart_home.discovery.discover_all', new=AsyncMock(return_value=[])):
|
|
43
|
+
devices = (await self.manager.scan())['devices']
|
|
44
|
+
self.assertEqual(devices[0]['id'], 'contract:manual')
|
|
45
|
+
self.assertNotIn('hidden', json.dumps(devices))
|
|
46
|
+
self.assertEqual(self.manager._adapter_for(devices[0]).config['token'], 'hidden')
|
|
47
|
+
async def test_string_false_is_not_success_and_unknown_toggle_is_refused(self):
|
|
48
|
+
device = self.manager._build_device(self.scanned())
|
|
49
|
+
self.manager._scan = {'devices':[device]}
|
|
50
|
+
result = await self.manager.control(device['id'], 'write', name='power', value=True)
|
|
51
|
+
self.assertIs(result['ok'], False)
|
|
52
|
+
with self.assertRaisesRegex(ValueError, 'state'):
|
|
53
|
+
await self.manager.control(device['id'], 'power')
|
|
54
|
+
|
|
55
|
+
async def test_explicit_null_power_state_is_rejected_without_dispatch(self):
|
|
56
|
+
device = self.manager._build_device(self.scanned())
|
|
57
|
+
self.manager._scan = {'devices':[device]}
|
|
58
|
+
with patch.object(ContractAdapter, 'read_capability', new=AsyncMock(return_value=False)), patch.object(ContractAdapter, 'write_capability', new=AsyncMock(return_value={'ok': True})) as write:
|
|
59
|
+
with self.assertRaises(ValueError):
|
|
60
|
+
await self.manager.control(device['id'], 'power', state=None)
|
|
61
|
+
write.assert_not_awaited()
|
|
62
|
+
|
|
63
|
+
async def test_scene_rejects_explicit_null_power_state(self):
|
|
64
|
+
with self.assertRaisesRegex(ValueError, 'state'):
|
|
65
|
+
self.manager.scene_save({'name':'null-state', 'actions':[{'device':'contract:lamp','mode':'power','state':None}]})
|
|
66
|
+
|
|
67
|
+
async def test_scene_omitted_state_toggles_and_explicit_false_turns_off(self):
|
|
68
|
+
device = self.manager._build_device(self.scanned())
|
|
69
|
+
self.manager._scan = {'devices':[device]}
|
|
70
|
+
scene = self.manager.scene_save({'name':'power-states', 'actions':[
|
|
71
|
+
{'device':device['id'], 'mode':'power'},
|
|
72
|
+
{'device':device['id'], 'mode':'power', 'state':False},
|
|
73
|
+
]})
|
|
74
|
+
with patch.object(ContractAdapter, 'read_capability', new=AsyncMock(return_value=False)), patch.object(ContractAdapter, 'write_capability', new=AsyncMock(return_value={'ok':True})) as write:
|
|
75
|
+
result = await self.manager.scene_run(scene['id'])
|
|
76
|
+
self.assertIs(result['ok'], True)
|
|
77
|
+
self.assertEqual([step['result']['on'] for step in result['results']], [True, False])
|
|
78
|
+
self.assertEqual([call.args for call in write.await_args_list], [('power',True), ('power',False)])
|
|
79
|
+
async def test_scan_accepts_string_ports_before_cache_key(self):
|
|
80
|
+
with patch('smart_home.discovery.discover_all', new=AsyncMock(return_value=[])) as discover:
|
|
81
|
+
await self.manager.scan(subnets='192.0.2.0/24', ports='80,443', scan_ping='false')
|
|
82
|
+
self.assertEqual(discover.call_args.kwargs['ports'], [80,443])
|
|
83
|
+
self.assertIs(discover.call_args.kwargs['scan_ping'], False)
|
|
84
|
+
async def test_corrupt_scenes_do_not_get_silently_overwritten(self):
|
|
85
|
+
path = self.manager._scenes_path()
|
|
86
|
+
path.write_text('{broken', encoding='utf-8')
|
|
87
|
+
with self.assertRaises(ValueError):
|
|
88
|
+
self.manager.scene_save({'name':'x','actions':[{'device':'x','mode':'power','state':True}]})
|
|
89
|
+
self.assertEqual(path.read_text('utf-8'), '{broken')
|
|
90
|
+
async def test_base_has_no_guessed_writable_controls(self):
|
|
91
|
+
self.assertEqual(await BaseAdapter(self.scanned()).list_capabilities(), [])
|
|
92
|
+
async def test_ha_is_registered_via_normal_entry(self):
|
|
93
|
+
from smart_home.adapters import get_adapter_class
|
|
94
|
+
self.assertIsNotNone(get_adapter_class('home_assistant'))
|
|
95
|
+
async def test_configured_ha_entity_is_not_expanded_as_hub(self):
|
|
96
|
+
from smart_home.adapters.home_assistant import HomeAssistantAdapter
|
|
97
|
+
await self.manager.set_connections({'home_assistant:light.kitchen':{'base_url':'http://192.0.2.3:8123','token':'t','entity_id':'light.kitchen'}})
|
|
98
|
+
with patch('smart_home.discovery.discover_all', new=AsyncMock(return_value=[])), patch.object(HomeAssistantAdapter,'discover_entities',new=AsyncMock(side_effect=AssertionError('entity expanded as hub'))):
|
|
99
|
+
rows = (await self.manager.scan())['devices']
|
|
100
|
+
self.assertEqual(len(rows),1)
|
|
101
|
+
self.assertEqual(rows[0]['id'],'home_assistant:light.kitchen')
|
|
102
|
+
self.assertNotIn('connection_error',rows[0])
|
|
103
|
+
async def test_rescan_drops_expired_discovered_credentials(self):
|
|
104
|
+
first = self.scanned()
|
|
105
|
+
second = self.scanned()
|
|
106
|
+
second.fields = {'version':'3.5'}
|
|
107
|
+
second.credentials = {}
|
|
108
|
+
with patch('smart_home.discovery.discover_all', new=AsyncMock(side_effect=[[first], [second]])):
|
|
109
|
+
row = (await self.manager.scan())['devices'][0]
|
|
110
|
+
self.assertEqual(self.manager._adapter_for(row).device.credentials['local_key'], 'private')
|
|
111
|
+
row = (await self.manager.scan(force=True))['devices'][0]
|
|
112
|
+
self.assertEqual(self.manager._adapter_for(row).device.credentials, {})
|
|
113
|
+
async def test_discovered_ha_connection_is_inherited_by_entities(self):
|
|
114
|
+
from smart_home.adapters.home_assistant import HomeAssistantAdapter
|
|
115
|
+
await self.manager.set_connections({'home_assistant:192.0.2.9':{'token':'private-token'}})
|
|
116
|
+
found = SimpleNamespace(protocol='home_assistant',ip='192.0.2.9',name='HA',category='gateway',
|
|
117
|
+
fields={'base_url':'http://192.0.2.9:8123'},credentials={})
|
|
118
|
+
async def entities(hub):
|
|
119
|
+
self.assertEqual(hub._connection()[:2], ('http://192.0.2.9:8123','private-token'))
|
|
120
|
+
return [{'entity_id':'light.desk','protocol':'home_assistant','category':'light','fields':{'entity_id':'light.desk'}}]
|
|
121
|
+
with patch('smart_home.discovery.discover_all', new=AsyncMock(return_value=[found])), patch.object(HomeAssistantAdapter,'discover_entities',entities):
|
|
122
|
+
rows = (await self.manager.scan())['devices']
|
|
123
|
+
self.assertEqual(len(rows), 2)
|
|
124
|
+
child = rows[1]
|
|
125
|
+
self.assertEqual(self.manager._adapter_for(child)._connection()[:2], ('http://192.0.2.9:8123','private-token'))
|
|
126
|
+
self.assertNotIn('private-token', json.dumps(rows))
|
|
127
|
+
async def test_multiple_ha_hubs_keep_entity_identity_and_target(self):
|
|
128
|
+
from smart_home.adapters.home_assistant import HomeAssistantAdapter
|
|
129
|
+
await self.manager.set_connections({
|
|
130
|
+
'home_assistant:one':{'base_url':'http://192.0.2.1:8123','token':'one'},
|
|
131
|
+
'home_assistant:two':{'base_url':'http://192.0.2.2:8123','token':'two'},
|
|
132
|
+
})
|
|
133
|
+
async def entities(_hub):
|
|
134
|
+
return [{'id':'home_assistant:light.desk','entity_id':'light.desk','protocol':'home_assistant',
|
|
135
|
+
'category':'light','name':'Desk','online':True,'fields':{'entity_id':'light.desk','domain':'light'}}]
|
|
136
|
+
with patch('smart_home.discovery.discover_all', new=AsyncMock(return_value=[])), patch.object(HomeAssistantAdapter,'discover_entities',entities):
|
|
137
|
+
rows = (await self.manager.scan())['devices']
|
|
138
|
+
children = [d for d in rows if d.get('fields',{}).get('entity_id')]
|
|
139
|
+
self.assertEqual(len(children), 2)
|
|
140
|
+
self.assertEqual(len({d['id'] for d in children}), 2)
|
|
141
|
+
self.assertEqual({self.manager._adapter_for(d).config['token'] for d in children}, {'one','two'})
|
|
142
|
+
self.assertTrue(all(d['category_zh']=='灯具' and d['source']=='home_assistant' for d in children))
|
|
143
|
+
for child in children:
|
|
144
|
+
adapter = self.manager._adapter_for(child)
|
|
145
|
+
self.assertEqual(adapter._entity_id(),'light.desk')
|
|
146
|
+
with patch.object(HomeAssistantAdapter,'write_capability', new=AsyncMock(return_value={'ok':True})) as write:
|
|
147
|
+
await self.manager.control(children[0]['id'], 'write', name='power', value=True)
|
|
148
|
+
write.assert_awaited_once_with('power',True)
|
|
149
|
+
|
|
150
|
+
if __name__ == '__main__': unittest.main()
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import hashlib
|
|
3
|
+
import json
|
|
4
|
+
import struct
|
|
5
|
+
import unittest
|
|
6
|
+
from types import SimpleNamespace
|
|
7
|
+
from unittest.mock import patch
|
|
8
|
+
|
|
9
|
+
from smart_home.adapters.mihome import MiHomeCloudAdapter, MiIOAdapter
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class CloudTests(unittest.IsolatedAsyncioTestCase):
|
|
13
|
+
async def test_full_spec_and_dispatch(self):
|
|
14
|
+
class Cloud:
|
|
15
|
+
def device_detail(self, did):
|
|
16
|
+
return {'props': [
|
|
17
|
+
{'name':'a.on','type':'bool','readable':True,'writable':True},
|
|
18
|
+
{'name':'b.on','type':'bool','readable':True,'writable':False},
|
|
19
|
+
{'name':'mode','type':'uint8','readable':True,'writable':True,'range':[1,3,1], 'value_list':[{'value':1,'description':'auto'}], 'unit':'x'},
|
|
20
|
+
{'name':'unknown','type':'float','readable':True,'writable':False,'range':[0,10,0.5]}],
|
|
21
|
+
'actions':[{'name':'fan.start','desc':'start'}]}
|
|
22
|
+
def read_props(self,did,names): return {n:i for i,n in enumerate(names)}
|
|
23
|
+
def write_prop(self,did,name,value): self.write=(name,value)
|
|
24
|
+
def run_action(self,did,name,params): self.action=(name,params)
|
|
25
|
+
svc=Cloud(); a=MiHomeCloudAdapter(SimpleNamespace(did='123'), {'cloud':svc})
|
|
26
|
+
caps=await a.list_capabilities(); by={c['key']:c for c in caps}
|
|
27
|
+
self.assertEqual(set(by), {'a.on','b.on','mode','unknown','fan.start'})
|
|
28
|
+
self.assertEqual(by['mode']['kind'], 'enum')
|
|
29
|
+
self.assertEqual(by['mode']['range'], [1,3,1])
|
|
30
|
+
self.assertEqual(by['mode']['unit'], 'x')
|
|
31
|
+
self.assertEqual(by['fan.start']['kind'], 'action')
|
|
32
|
+
self.assertEqual((await a.read_all())['b.on'],1)
|
|
33
|
+
await a.write_capability('mode', 1)
|
|
34
|
+
self.assertEqual(svc.write, ('mode',1))
|
|
35
|
+
await a.run_action('fan.start', {'v':[1,2]})
|
|
36
|
+
self.assertEqual(svc.action, ('fan.start', {'v':[1,2]}))
|
|
37
|
+
with self.assertRaises(ValueError): await a.write_capability('b.on',True)
|
|
38
|
+
with self.assertRaises(ValueError): await a.run_action('bogus')
|
|
39
|
+
|
|
40
|
+
async def test_manager_power_uses_confirmed_cloud_power_path(self):
|
|
41
|
+
from smart_home.manager import SmartHomeManager
|
|
42
|
+
class Cloud:
|
|
43
|
+
def power_state(self, did):
|
|
44
|
+
self.read_did = did
|
|
45
|
+
return False
|
|
46
|
+
def set_power_state(self, did, state):
|
|
47
|
+
self.write = (did, state)
|
|
48
|
+
cloud = Cloud()
|
|
49
|
+
manager = SmartHomeManager({'cloud': cloud})
|
|
50
|
+
manager._scan = {'devices': [{'id':'mihome:123','did':'123','protocol':'mihome','fields':{}}]}
|
|
51
|
+
result = await manager.control('mihome:123', 'power')
|
|
52
|
+
self.assertIs(result['ok'], True)
|
|
53
|
+
self.assertIs(result['on'], True)
|
|
54
|
+
self.assertEqual(cloud.write, ('123', True))
|
|
55
|
+
cloud.power_state = lambda did: None
|
|
56
|
+
with self.assertRaises(ValueError):
|
|
57
|
+
await manager.control('mihome:123', 'power')
|
|
58
|
+
self.assertEqual(cloud.write, ('123', True))
|
|
59
|
+
|
|
60
|
+
async def test_no_guessed_controls(self):
|
|
61
|
+
a=MiHomeCloudAdapter(SimpleNamespace(did='1',category='light'))
|
|
62
|
+
self.assertEqual(await a.list_capabilities(), [])
|
|
63
|
+
|
|
64
|
+
class LocalTests(unittest.IsolatedAsyncioTestCase):
|
|
65
|
+
async def test_corrupt_checksum_rejected(self):
|
|
66
|
+
from smart_home.adapters.mihome import _miio_unpack
|
|
67
|
+
token=bytes(range(16))
|
|
68
|
+
header=struct.pack('>HHIII',0x2131,48,0,42,10)
|
|
69
|
+
with self.assertRaisesRegex(ValueError, 'checksum'):
|
|
70
|
+
_miio_unpack(header+b'\x00'*16+b'\x00'*16,token,42)
|
|
71
|
+
|
|
72
|
+
async def test_explicit_mappings_only(self):
|
|
73
|
+
device=SimpleNamespace(ip='127.0.0.1', credentials={'token':'00'*16})
|
|
74
|
+
a=MiIOAdapter(device, {'miio_mapping': {'power': {'kind':'bool','readable':True,'writable':True,'read_method':'get_prop','read_params':['power'],'write_method':'set_power','write_params':['$value']}}})
|
|
75
|
+
self.assertEqual([x['key'] for x in await a.list_capabilities()], ['power'])
|
|
76
|
+
calls=[]
|
|
77
|
+
async def call(method,params):
|
|
78
|
+
calls.append((method,params)); return {'id':1,'result':[True]}
|
|
79
|
+
with patch.object(a,'_call',call):
|
|
80
|
+
self.assertTrue(await a.read_capability('power'))
|
|
81
|
+
await a.write_capability('power',False)
|
|
82
|
+
self.assertEqual(calls, [('get_prop',['power']),('set_power',[False])])
|
|
83
|
+
self.assertEqual(await MiIOAdapter(device).list_capabilities(), [])
|
|
84
|
+
with self.assertRaises(ValueError): await a.write_capability('brightness',50)
|
|
85
|
+
|
|
86
|
+
async def test_udp_handshake_encryption_response_validation(self):
|
|
87
|
+
from smart_home.adapters.mihome import _miio_send, _MIIO_NOOP
|
|
88
|
+
from Crypto.Cipher import AES
|
|
89
|
+
from Crypto.Util.Padding import pad, unpad
|
|
90
|
+
token=bytes(range(16)); key=hashlib.md5(token).digest(); iv=hashlib.md5(key+token).digest()
|
|
91
|
+
did=0x12345678; stamp=123
|
|
92
|
+
hello=struct.pack('>HHIII',0x2131,32,0,did,stamp)+b'\xff'*16
|
|
93
|
+
class Socket:
|
|
94
|
+
def __init__(self): self.sent=[]
|
|
95
|
+
def setblocking(self,v): pass
|
|
96
|
+
def connect(self,addr): self.addr=addr
|
|
97
|
+
def close(self): pass
|
|
98
|
+
sock=Socket()
|
|
99
|
+
async def send(s,data):
|
|
100
|
+
s.sent.append(data)
|
|
101
|
+
if len(s.sent)==2:
|
|
102
|
+
p=data; self.assertEqual(hashlib.md5(p[:16]+token+p[32:]).digest(),p[16:32])
|
|
103
|
+
body=unpad(AES.new(key,AES.MODE_CBC,iv).decrypt(p[32:]),16)
|
|
104
|
+
self.assertEqual(json.loads(body), {'id':1,'method':'get_prop','params':['power']})
|
|
105
|
+
async def recv(s,n):
|
|
106
|
+
if len(s.sent)==1: return hello
|
|
107
|
+
body=AES.new(key,AES.MODE_CBC,iv).encrypt(pad(b'{"id":1,"result":["on"]}',16))
|
|
108
|
+
header=struct.pack('>HHIII',0x2131,32+len(body),0,did,stamp)
|
|
109
|
+
return header+hashlib.md5(header+token+body).digest()+body
|
|
110
|
+
loop=asyncio.get_running_loop()
|
|
111
|
+
with patch('smart_home.adapters.mihome.socket.socket',return_value=sock), patch.object(loop,'sock_sendall',side_effect=send), patch.object(loop,'sock_recv',side_effect=recv):
|
|
112
|
+
result=await _miio_send('127.0.0.1',token.hex(),{'id':1,'method':'get_prop','params':['power']})
|
|
113
|
+
self.assertEqual(sock.sent[0],_MIIO_NOOP)
|
|
114
|
+
self.assertEqual(sock.addr,('127.0.0.1',54321))
|
|
115
|
+
self.assertEqual(result['result'],['on'])
|
|
116
|
+
|
|
117
|
+
if __name__=='__main__': unittest.main()
|