@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,50 @@
|
|
|
1
|
+
"""Public management-page reads must report transport failures honestly."""
|
|
2
|
+
import tempfile
|
|
3
|
+
import unittest
|
|
4
|
+
from types import SimpleNamespace
|
|
5
|
+
from unittest.mock import AsyncMock, patch
|
|
6
|
+
|
|
7
|
+
from smart_home.manager import SmartHomeManager
|
|
8
|
+
from smart_home.adapters.network import RouterAdapter
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class NetworkReadTests(unittest.IsolatedAsyncioTestCase):
|
|
12
|
+
async def test_manager_scrape_distinguishes_page_read_from_settings_access(self):
|
|
13
|
+
with tempfile.TemporaryDirectory() as folder:
|
|
14
|
+
manager = SmartHomeManager({'data_dir': folder})
|
|
15
|
+
manager._scan = {'devices': [{'id': 'router:192.0.2.1', 'protocol': 'router',
|
|
16
|
+
'ip': '192.0.2.1', 'ports': [80], 'fields': {}}]}
|
|
17
|
+
page = {'url': 'http://192.0.2.1:80/', 'status': 200, 'server': 'test',
|
|
18
|
+
'text': '<title>Router Login</title><form><input name="password" value="secret"></form>'}
|
|
19
|
+
try:
|
|
20
|
+
with patch('smart_home.adapters.network._page', new=AsyncMock(return_value=page)):
|
|
21
|
+
result = await manager.control('router:192.0.2.1', 'scrape')
|
|
22
|
+
self.assertIs(result.get('ok'), True)
|
|
23
|
+
self.assertIs(result.get('public_only'), True)
|
|
24
|
+
self.assertEqual(result['http_status'], 200)
|
|
25
|
+
self.assertEqual(result['title'], 'Router Login')
|
|
26
|
+
self.assertNotIn('secret', str(result))
|
|
27
|
+
finally:
|
|
28
|
+
await manager.close()
|
|
29
|
+
|
|
30
|
+
async def test_unreachable_or_auth_required_is_not_success(self):
|
|
31
|
+
adapter = RouterAdapter(SimpleNamespace(ip='192.0.2.1', ports=[80]))
|
|
32
|
+
for status in (None, 401, 403, 503):
|
|
33
|
+
with self.subTest(status=status):
|
|
34
|
+
page = None if status is None else {
|
|
35
|
+
'url': 'http://192.0.2.1:80/', 'status': status, 'server': '', 'text': 'Login required'}
|
|
36
|
+
with patch('smart_home.adapters.network._page', new=AsyncMock(return_value=page)):
|
|
37
|
+
result = await adapter.scrape()
|
|
38
|
+
self.assertIs(result.get('ok'), False)
|
|
39
|
+
self.assertTrue(result.get('error'))
|
|
40
|
+
self.assertIs(result.get('public_only'), True)
|
|
41
|
+
|
|
42
|
+
async def test_page_capability_is_readable_structured_data(self):
|
|
43
|
+
caps = await RouterAdapter(SimpleNamespace(ip='192.0.2.1', ports=[80])).list_capabilities()
|
|
44
|
+
self.assertEqual(caps[0]['kind'], 'json')
|
|
45
|
+
self.assertIs(caps[0].get('readable'), True)
|
|
46
|
+
self.assertIs(caps[0]['writable'], False)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
if __name__ == '__main__':
|
|
50
|
+
unittest.main()
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Cloud response confirmation must not manufacture device state (offline)."""
|
|
2
|
+
import sys
|
|
3
|
+
import unittest
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from types import SimpleNamespace
|
|
6
|
+
from unittest.mock import Mock, patch
|
|
7
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
8
|
+
import mihome_bridge as bridge
|
|
9
|
+
from app.core.service import MijiaService, ServiceError
|
|
10
|
+
from mijiaAPI import mijiaDevice
|
|
11
|
+
from mijiaAPI.devices import DevProp, DevAction
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def cloud_service(response):
|
|
15
|
+
"""Keep upstream validation real; replace only the cloud transport."""
|
|
16
|
+
calls = []
|
|
17
|
+
api = SimpleNamespace(
|
|
18
|
+
set_devices_prop=lambda data: (calls.append(data), response)[1],
|
|
19
|
+
run_action=lambda data: (calls.append(data), response)[1],
|
|
20
|
+
)
|
|
21
|
+
dev = mijiaDevice.__new__(mijiaDevice)
|
|
22
|
+
dev.api = api
|
|
23
|
+
dev.did, dev.name, dev.sleep_time = 'lamp', 'Desk lamp', 0
|
|
24
|
+
dev.prop_list = {'brightness': DevProp({
|
|
25
|
+
'name': 'brightness', 'description': 'Brightness', 'type': 'uint',
|
|
26
|
+
'rw': 'rw', 'range': [1, 100, 1], 'method': {'siid': 2, 'piid': 2},
|
|
27
|
+
})}
|
|
28
|
+
dev.action_list = {'toggle': DevAction({
|
|
29
|
+
'name': 'toggle', 'description': 'Toggle', 'method': {'siid': 2, 'aiid': 1},
|
|
30
|
+
})}
|
|
31
|
+
svc = MijiaService.__new__(MijiaService)
|
|
32
|
+
svc._get_device = lambda did: dev
|
|
33
|
+
return svc, dev, api, calls
|
|
34
|
+
|
|
35
|
+
class PowerConfirmationTests(unittest.TestCase):
|
|
36
|
+
def test_unknown_power_state_stays_unknown(self):
|
|
37
|
+
svc = SimpleNamespace(power_state=lambda did: None)
|
|
38
|
+
with patch.object(bridge, 'service', return_value=svc):
|
|
39
|
+
self.assertEqual(bridge.op_power_states({'dids':['lamp']})['states'], {'lamp':None})
|
|
40
|
+
|
|
41
|
+
def test_power_write_requires_nonempty_success_confirmation(self):
|
|
42
|
+
for response in ([], None, [None], {}, [{'code':1}], [{'code':False}]):
|
|
43
|
+
with self.subTest(response=response):
|
|
44
|
+
svc = MijiaService.__new__(MijiaService)
|
|
45
|
+
svc._api = SimpleNamespace(set_devices_prop=lambda data:response)
|
|
46
|
+
with self.assertRaises(ServiceError):
|
|
47
|
+
svc._write_power('lamp', {'siid':2,'piid':1}, True)
|
|
48
|
+
svc._api = SimpleNamespace(set_devices_prop=lambda data:[{'did':'lamp','siid':2,'piid':1,'code':0}])
|
|
49
|
+
self.assertIsNone(svc._write_power('lamp', {'siid':2,'piid':1}, True))
|
|
50
|
+
|
|
51
|
+
def test_property_and_action_require_device_confirmation(self):
|
|
52
|
+
for operation in ('property', 'action'):
|
|
53
|
+
for response in ({'code': 1}, {'code': False}, {}, [], None):
|
|
54
|
+
with self.subTest(operation=operation, response=response):
|
|
55
|
+
svc, dev, api, calls = cloud_service(response)
|
|
56
|
+
with self.assertRaises(ServiceError):
|
|
57
|
+
if operation == 'property':
|
|
58
|
+
svc.write_prop('lamp', 'brightness', 42)
|
|
59
|
+
else:
|
|
60
|
+
svc.run_action('lamp', 'toggle')
|
|
61
|
+
self.assertEqual(len(calls), 1)
|
|
62
|
+
self.assertIs(dev.api, api)
|
|
63
|
+
|
|
64
|
+
def test_property_validation_and_action_payload_are_preserved(self):
|
|
65
|
+
svc, dev, api, calls = cloud_service({'code': 0})
|
|
66
|
+
svc.write_prop('lamp', 'brightness', '42')
|
|
67
|
+
self.assertEqual(calls, [{'did': 'lamp', 'siid': 2, 'piid': 2, 'value': 42}])
|
|
68
|
+
with self.assertRaises(ServiceError):
|
|
69
|
+
svc.write_prop('lamp', 'brightness', 101)
|
|
70
|
+
self.assertEqual(len(calls), 1)
|
|
71
|
+
svc.run_action('lamp', 'toggle', [3, False])
|
|
72
|
+
self.assertEqual(calls[-1], {'did': 'lamp', 'siid': 2, 'aiid': 1, 'value': [3, False]})
|
|
73
|
+
self.assertIs(dev.api, api)
|
|
74
|
+
|
|
75
|
+
def test_power_toggle_reports_the_state_confirmed_by_service(self):
|
|
76
|
+
svc = MijiaService.__new__(MijiaService)
|
|
77
|
+
svc.power_state = Mock(side_effect=[None, True])
|
|
78
|
+
svc.set_power_state = Mock()
|
|
79
|
+
with patch.object(bridge, 'service', return_value=svc):
|
|
80
|
+
result = bridge.op_power({'did': 'lamp'})
|
|
81
|
+
self.assertEqual(result, {'on': False})
|
|
82
|
+
svc.set_power_state.assert_called_once_with('lamp', False)
|
|
83
|
+
|
|
84
|
+
def test_explicit_power_state_must_be_boolean(self):
|
|
85
|
+
for state in ('off', None, 0, {}, []):
|
|
86
|
+
with self.subTest(state=state):
|
|
87
|
+
svc = Mock()
|
|
88
|
+
with patch.object(bridge, 'service', return_value=svc):
|
|
89
|
+
with self.assertRaises(ValueError):
|
|
90
|
+
bridge.op_power({'did': 'lamp', 'state': state})
|
|
91
|
+
svc.set_power_state.assert_not_called()
|
|
92
|
+
svc.toggle_power.assert_not_called()
|
|
93
|
+
svc.power_state.assert_not_called()
|
|
94
|
+
|
|
95
|
+
if __name__ == '__main__': unittest.main()
|
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
"""Offline regression tests for smart-home protocol adapters."""
|
|
2
|
+
import asyncio
|
|
3
|
+
import unittest
|
|
4
|
+
from types import SimpleNamespace
|
|
5
|
+
from unittest.mock import patch
|
|
6
|
+
|
|
7
|
+
from smart_home.adapters.kasa import _kasa_encode, _kasa_decode, _kasa_call, _yeelight_call, YeelightAdapter
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ProtocolTests(unittest.IsolatedAsyncioTestCase):
|
|
11
|
+
def test_kasa_rolling_xor_packet(self):
|
|
12
|
+
self.assertEqual(_kasa_encode(b'{}'), bytes.fromhex('00000002d0ad'))
|
|
13
|
+
self.assertEqual(_kasa_decode(bytes.fromhex('00000002d0ad')), b'{}')
|
|
14
|
+
|
|
15
|
+
async def test_kasa_split_response(self):
|
|
16
|
+
response = b'{"system":{"get_sysinfo":{"err_code":0}}}'
|
|
17
|
+
packet = bytearray(len(response).to_bytes(4, 'big'))
|
|
18
|
+
key = 0xab
|
|
19
|
+
for byte in response:
|
|
20
|
+
key ^= byte
|
|
21
|
+
packet.append(key)
|
|
22
|
+
async def handle(reader, writer):
|
|
23
|
+
await reader.read(4096)
|
|
24
|
+
for chunk in (packet[:2], packet[2:5], packet[5:]):
|
|
25
|
+
writer.write(chunk)
|
|
26
|
+
await writer.drain()
|
|
27
|
+
await asyncio.sleep(0.005)
|
|
28
|
+
writer.close()
|
|
29
|
+
server = await asyncio.start_server(handle, '127.0.0.1', 0)
|
|
30
|
+
port = server.sockets[0].getsockname()[1]
|
|
31
|
+
original = asyncio.open_connection
|
|
32
|
+
async def connect(ip, ignored):
|
|
33
|
+
return await original(ip, port)
|
|
34
|
+
try:
|
|
35
|
+
with patch('smart_home.adapters.kasa.asyncio.open_connection', connect):
|
|
36
|
+
result = await _kasa_call('127.0.0.1', {'system': {'get_sysinfo': {}}})
|
|
37
|
+
self.assertEqual(result['system']['get_sysinfo']['err_code'], 0)
|
|
38
|
+
finally:
|
|
39
|
+
server.close()
|
|
40
|
+
await server.wait_closed()
|
|
41
|
+
|
|
42
|
+
async def test_yeelight_notification_and_error(self):
|
|
43
|
+
async def handle(reader, writer):
|
|
44
|
+
await reader.readline()
|
|
45
|
+
writer.write(b'{"method":"props","params":{"power":"on"}}\r\n')
|
|
46
|
+
writer.write(b'{"id":1,"error":{"code":-1,"message":"bad"}}\r\n')
|
|
47
|
+
await writer.drain()
|
|
48
|
+
writer.close()
|
|
49
|
+
server = await asyncio.start_server(handle, '127.0.0.1', 0)
|
|
50
|
+
port = server.sockets[0].getsockname()[1]
|
|
51
|
+
original = asyncio.open_connection
|
|
52
|
+
async def connect(ip, ignored):
|
|
53
|
+
return await original(ip, port)
|
|
54
|
+
try:
|
|
55
|
+
with patch('smart_home.adapters.kasa.asyncio.open_connection', connect):
|
|
56
|
+
with self.assertRaises(RuntimeError):
|
|
57
|
+
await _yeelight_call('127.0.0.1', 'set_power', ['on', 'smooth', 300])
|
|
58
|
+
finally:
|
|
59
|
+
server.close()
|
|
60
|
+
await server.wait_closed()
|
|
61
|
+
|
|
62
|
+
async def test_yeelight_color_temperature_payload(self):
|
|
63
|
+
calls = []
|
|
64
|
+
async def fake(ip, method, params):
|
|
65
|
+
calls.append((method, params))
|
|
66
|
+
return {'id': 1, 'result': ['on', '50', '4000', '1'] if method == 'get_prop' else ['ok']}
|
|
67
|
+
adapter = YeelightAdapter(SimpleNamespace(ip='127.0.0.1', fields={'support': 'get_prop set_ct_abx'}), {'color_temp_range': [2000, 6000]})
|
|
68
|
+
with patch('smart_home.adapters.kasa._yeelight_call', fake):
|
|
69
|
+
await adapter.write_capability('color_temp', 4000)
|
|
70
|
+
self.assertEqual(calls[-1], ('set_ct_abx', [4000, 'smooth', 300]))
|
|
71
|
+
|
|
72
|
+
class TuyaTests(unittest.IsolatedAsyncioTestCase):
|
|
73
|
+
async def test_unknown_schema_never_assumes_dp1(self):
|
|
74
|
+
from smart_home.adapters.tuya import TuyaAdapter
|
|
75
|
+
adapter = TuyaAdapter(SimpleNamespace(ip='127.0.0.1', credentials={}))
|
|
76
|
+
self.assertEqual(await adapter.list_capabilities(), [])
|
|
77
|
+
with self.assertRaises((ValueError, RuntimeError)):
|
|
78
|
+
await adapter.write_capability('power', True)
|
|
79
|
+
|
|
80
|
+
async def test_explicit_schema_and_private_credentials(self):
|
|
81
|
+
from smart_home.adapters.tuya import TuyaAdapter
|
|
82
|
+
class Device:
|
|
83
|
+
def status(self):
|
|
84
|
+
return {'dps': {'20': True}}
|
|
85
|
+
def set_value(self, dp, value):
|
|
86
|
+
self.sent = (dp, value)
|
|
87
|
+
return {'dps': {dp: value}}
|
|
88
|
+
fake = Device()
|
|
89
|
+
dev = SimpleNamespace(ip='127.0.0.1', credentials={'local_key':'secret','device_id':'did'})
|
|
90
|
+
adapter = TuyaAdapter(dev, {'dps': {'20': {'key': 'power', 'kind': 'bool', 'writable': True}}})
|
|
91
|
+
with patch('smart_home.adapters.tuya._make_device', return_value=fake) as factory:
|
|
92
|
+
self.assertTrue(await adapter.read_capability('power'))
|
|
93
|
+
await adapter.write_capability('power', False)
|
|
94
|
+
self.assertEqual(fake.sent, ('20', False))
|
|
95
|
+
self.assertEqual(factory.call_args.args[:3], ('127.0.0.1', 'secret', '3.3'))
|
|
96
|
+
self.assertEqual(factory.call_args.args[3], 'did')
|
|
97
|
+
|
|
98
|
+
async def test_tuya_error_is_not_success(self):
|
|
99
|
+
from smart_home.adapters.tuya import TuyaAdapter
|
|
100
|
+
fake = SimpleNamespace(set_value=lambda dp, value: {'Error': 'offline', 'Err': '905'})
|
|
101
|
+
adapter = TuyaAdapter(SimpleNamespace(ip='127.0.0.1'), {'dps': {'20': {'key':'power', 'kind':'bool', 'writable':True}}})
|
|
102
|
+
adapter._dev = fake
|
|
103
|
+
with self.assertRaises(RuntimeError):
|
|
104
|
+
await adapter.write_capability('power', True)
|
|
105
|
+
|
|
106
|
+
class HttpFirmwareTests(unittest.IsolatedAsyncioTestCase):
|
|
107
|
+
async def test_shelly_gen2_switch_and_position(self):
|
|
108
|
+
from smart_home.adapters.shelly import ShellyAdapter
|
|
109
|
+
class Response:
|
|
110
|
+
status_code = 200
|
|
111
|
+
def __init__(self, data): self.data = data
|
|
112
|
+
def json(self): return self.data
|
|
113
|
+
sent = []
|
|
114
|
+
def post(url, payload):
|
|
115
|
+
sent.append(payload)
|
|
116
|
+
return Response({'id': 1, 'result': {'switch:0': {'output': True}, 'cover:0': {'current_pos': 50}} if payload['method'] == 'Shelly.GetStatus' else {}})
|
|
117
|
+
a = ShellyAdapter(SimpleNamespace(ip='127.0.0.1'))
|
|
118
|
+
with patch('smart_home.adapters.shelly._post_json', post):
|
|
119
|
+
self.assertTrue(await a.read_capability('power'))
|
|
120
|
+
await a.write_capability('position', 50)
|
|
121
|
+
self.assertEqual(sent[-1]['params'], {'id': 0, 'pos': 50})
|
|
122
|
+
|
|
123
|
+
async def test_wled_brightness_and_color(self):
|
|
124
|
+
from smart_home.adapters.shelly import WledAdapter
|
|
125
|
+
class Response:
|
|
126
|
+
status_code = 200
|
|
127
|
+
def json(self): return {'on': True, 'bri': 255, 'seg': [{'col': [[255,160,0,0], [0,0,0]]}]}
|
|
128
|
+
sent = []
|
|
129
|
+
def post(url, payload): sent.append(payload); return Response()
|
|
130
|
+
a = WledAdapter(SimpleNamespace(ip='127.0.0.1'))
|
|
131
|
+
with patch('smart_home.adapters.shelly._get', return_value=Response()), patch('smart_home.adapters.shelly._post_json', post):
|
|
132
|
+
self.assertEqual(await a.read_capability('brightness'), 100)
|
|
133
|
+
self.assertEqual(await a.read_capability('color'), '#ffa000')
|
|
134
|
+
await a.write_capability('brightness', 100)
|
|
135
|
+
self.assertEqual(sent[-1], {'bri': 255})
|
|
136
|
+
|
|
137
|
+
async def test_tasmota_status_sts(self):
|
|
138
|
+
from smart_home.adapters.shelly import TasmotaAdapter
|
|
139
|
+
a = TasmotaAdapter(SimpleNamespace(ip='127.0.0.1'))
|
|
140
|
+
async def cmd(command):
|
|
141
|
+
self.assertEqual(command, 'Status 11')
|
|
142
|
+
return {'StatusSTS': {'POWER': 'ON', 'Dimmer': 50}}
|
|
143
|
+
with patch.object(a, '_cmd', cmd):
|
|
144
|
+
self.assertEqual(await a.read_all(), {'power': True, 'brightness': 50})
|
|
145
|
+
|
|
146
|
+
class NetworkSafetyTests(unittest.IsolatedAsyncioTestCase):
|
|
147
|
+
async def test_unknown_router_and_nas_never_guess_reboot(self):
|
|
148
|
+
from smart_home.adapters.network import RouterAdapter, NasAdapter
|
|
149
|
+
for cls in (RouterAdapter, NasAdapter):
|
|
150
|
+
adapter = cls(SimpleNamespace(ip='127.0.0.1'))
|
|
151
|
+
caps = await adapter.list_capabilities()
|
|
152
|
+
self.assertFalse(any(c['key'] == 'reboot' and c['writable'] for c in caps))
|
|
153
|
+
with self.assertRaises((NotImplementedError, ValueError, RuntimeError)):
|
|
154
|
+
await adapter.write_capability('reboot', True)
|
|
155
|
+
|
|
156
|
+
def test_hidden_values_and_passwords_are_not_exposed(self):
|
|
157
|
+
from smart_home.adapters.network import _parse_html
|
|
158
|
+
data = _parse_html('<form><input name="password" type="password" value="secret"><input type="hidden" name="csrf" value="private"></form>')
|
|
159
|
+
self.assertNotIn('secret', str(data))
|
|
160
|
+
self.assertNotIn('private', str(data))
|
|
161
|
+
|
|
162
|
+
async def test_onu_does_not_submit_unknown_login(self):
|
|
163
|
+
from smart_home.adapters.network import OnuAdapter
|
|
164
|
+
a = OnuAdapter(SimpleNamespace(ip='127.0.0.1'), {'onu_credentials': {'username':'name','password':'secret'}})
|
|
165
|
+
async def scrape(): return {'status': 200}
|
|
166
|
+
calls = []
|
|
167
|
+
def post(*args, **kwargs):
|
|
168
|
+
calls.append(args)
|
|
169
|
+
return SimpleNamespace(status_code=200)
|
|
170
|
+
with patch.object(a, '_scrape', scrape), patch.dict('sys.modules', {'requests': SimpleNamespace(post=post)}):
|
|
171
|
+
result = await a.scrape()
|
|
172
|
+
self.assertEqual(calls, [])
|
|
173
|
+
self.assertNotIn('logged_in', result)
|
|
174
|
+
|
|
175
|
+
class UnsupportedTests(unittest.IsolatedAsyncioTestCase):
|
|
176
|
+
async def test_televisions_do_not_expose_unimplemented_writes(self):
|
|
177
|
+
from smart_home.adapters.tv import SamsungTvAdapter, LgTvAdapter, VizioTvAdapter
|
|
178
|
+
for cls in (SamsungTvAdapter, LgTvAdapter, VizioTvAdapter):
|
|
179
|
+
adapter = cls(SimpleNamespace(ip='127.0.0.1'))
|
|
180
|
+
self.assertFalse(any(c.get('writable') for c in await adapter.list_capabilities()))
|
|
181
|
+
with self.assertRaises((ValueError, NotImplementedError)):
|
|
182
|
+
await adapter.write_capability('power', True)
|
|
183
|
+
|
|
184
|
+
async def test_lifx_does_not_send_unverified_packet(self):
|
|
185
|
+
from smart_home.adapters.hue import LifxAdapter
|
|
186
|
+
adapter = LifxAdapter(SimpleNamespace(ip='127.0.0.1'))
|
|
187
|
+
self.assertFalse(any(c.get('writable') for c in await adapter.list_capabilities()))
|
|
188
|
+
with self.assertRaises((ValueError, NotImplementedError)):
|
|
189
|
+
await adapter.write_capability('power', True)
|
|
190
|
+
|
|
191
|
+
async def test_onvif_unverified_reboot_unavailable(self):
|
|
192
|
+
from smart_home.adapters.dlna import OnvifAdapter
|
|
193
|
+
adapter = OnvifAdapter(SimpleNamespace(ip='127.0.0.1', fields={}))
|
|
194
|
+
self.assertFalse(any(c['key'] == 'reboot' for c in await adapter.list_capabilities()))
|
|
195
|
+
with self.assertRaises((ValueError, NotImplementedError)):
|
|
196
|
+
await adapter.reboot()
|
|
197
|
+
|
|
198
|
+
class HueTests(unittest.IsolatedAsyncioTestCase):
|
|
199
|
+
async def test_pair_generated_username_and_api_error(self):
|
|
200
|
+
from smart_home.adapters.hue import HueAdapter
|
|
201
|
+
class Response:
|
|
202
|
+
status_code = 200
|
|
203
|
+
text = ''
|
|
204
|
+
def __init__(self, data): self.data = data
|
|
205
|
+
def json(self): return self.data
|
|
206
|
+
sent = []
|
|
207
|
+
def post(url, json, **kwargs):
|
|
208
|
+
sent.append(json)
|
|
209
|
+
return Response([{'success': {'username': 'generated'}}])
|
|
210
|
+
def put(url, json, **kwargs): return Response([{'error': {'type': 7}}])
|
|
211
|
+
a = HueAdapter(SimpleNamespace(ip='127.0.0.1'), {'hue_light_id': '1'})
|
|
212
|
+
with patch.dict('sys.modules', {'requests': SimpleNamespace(post=post, put=put, get=lambda *args, **kwargs: Response({'1': {'state': {'on': False}}}))}):
|
|
213
|
+
with self.assertRaises(RuntimeError):
|
|
214
|
+
await a.write_capability('power', True)
|
|
215
|
+
self.assertEqual(a.config['hue_username'], 'generated')
|
|
216
|
+
self.assertNotIn('username', sent[0])
|
|
217
|
+
|
|
218
|
+
class ContractTests(unittest.IsolatedAsyncioTestCase):
|
|
219
|
+
async def test_hue_reads_and_writes_same_configured_light(self):
|
|
220
|
+
from smart_home.adapters.hue import HueAdapter
|
|
221
|
+
a = HueAdapter(SimpleNamespace(ip='127.0.0.1'), {'hue_light_id':'7'})
|
|
222
|
+
calls = []
|
|
223
|
+
async def api(method, path, payload=None):
|
|
224
|
+
calls.append((method, path, payload))
|
|
225
|
+
if method == 'GET': return {'1': {'state': {'on': False}}, '7': {'state': {'on': True}}}
|
|
226
|
+
return [{'success': {'/lights/7/state/on': False}}]
|
|
227
|
+
with patch.object(a, '_api', api):
|
|
228
|
+
self.assertTrue(await a.read_capability('power'))
|
|
229
|
+
await a.write_capability('power', False)
|
|
230
|
+
self.assertEqual(calls[-1][1], '/lights/7/state')
|
|
231
|
+
self.assertEqual(calls[-1][2], {'on': False})
|
|
232
|
+
|
|
233
|
+
async def test_wled_color_text_write(self):
|
|
234
|
+
from smart_home.adapters.shelly import WledAdapter
|
|
235
|
+
class Response:
|
|
236
|
+
status_code=200
|
|
237
|
+
captured=[]
|
|
238
|
+
def post(url, payload): captured.append(payload); return Response()
|
|
239
|
+
a=WledAdapter(SimpleNamespace(ip='127.0.0.1'))
|
|
240
|
+
with patch('smart_home.adapters.shelly._post_json', post):
|
|
241
|
+
await a.write_capability('color', '#ffa000')
|
|
242
|
+
self.assertEqual(captured[0], {'seg':[{'col':[[255,160,0]]}]})
|
|
243
|
+
|
|
244
|
+
async def test_tasmota_read_capability_status(self):
|
|
245
|
+
from smart_home.adapters.shelly import TasmotaAdapter
|
|
246
|
+
a=TasmotaAdapter(SimpleNamespace(ip='127.0.0.1'))
|
|
247
|
+
async def cmd(command): return {'StatusSTS': {'POWER':'ON', 'Dimmer':50}}
|
|
248
|
+
with patch.object(a, '_cmd', cmd):
|
|
249
|
+
self.assertTrue(await a.read_capability('power'))
|
|
250
|
+
self.assertEqual(await a.read_capability('brightness'), 50)
|
|
251
|
+
|
|
252
|
+
class HueContractTests(unittest.IsolatedAsyncioTestCase):
|
|
253
|
+
async def test_hue_selects_same_discovered_light_and_validates_xy(self):
|
|
254
|
+
from smart_home.adapters.hue import HueAdapter
|
|
255
|
+
a=HueAdapter(SimpleNamespace(ip='127.0.0.1'))
|
|
256
|
+
calls=[]
|
|
257
|
+
async def api(method, path, payload=None):
|
|
258
|
+
calls.append((method,path,payload))
|
|
259
|
+
return {'7': {'state': {'on': True, 'xy': [0.2, 0.3]}}} if method == 'GET' else [{'success': {path: True}}]
|
|
260
|
+
with patch.object(a, '_api', api):
|
|
261
|
+
await a.write_capability('color', '0.2,0.3')
|
|
262
|
+
self.assertEqual(calls[-1], ('PUT','/lights/7/state',{'xy':[0.2,0.3]}))
|
|
263
|
+
|
|
264
|
+
class MetadataTests(unittest.IsolatedAsyncioTestCase):
|
|
265
|
+
async def test_wled_capabilities_match_values(self):
|
|
266
|
+
from smart_home.adapters.shelly import WledAdapter
|
|
267
|
+
class Response:
|
|
268
|
+
status_code=200
|
|
269
|
+
def json(self): return {'on':True,'bri':255,'seg':[{'col':[[255,160,0]]}]}
|
|
270
|
+
a=WledAdapter(SimpleNamespace(ip='127.0.0.1'))
|
|
271
|
+
with patch('smart_home.adapters.shelly._get', return_value=Response()):
|
|
272
|
+
caps={c['key']: c for c in await a.list_capabilities()}
|
|
273
|
+
result=await a.read_all()
|
|
274
|
+
self.assertEqual(caps['brightness']['range'], [0,100,1])
|
|
275
|
+
self.assertEqual(caps['color']['kind'], 'text')
|
|
276
|
+
self.assertEqual(result, {'power':True,'brightness':100,'color':'#ffa000'})
|
|
277
|
+
|
|
278
|
+
async def test_shelly_gen1_relay_write(self):
|
|
279
|
+
from smart_home.adapters.shelly import ShellyAdapter
|
|
280
|
+
class Response:
|
|
281
|
+
status_code=200
|
|
282
|
+
def json(self): return {'ison': False}
|
|
283
|
+
sent=[]
|
|
284
|
+
async def rpc(*args): raise RuntimeError('RPC unavailable')
|
|
285
|
+
def get(url): sent.append(url); return Response()
|
|
286
|
+
a=ShellyAdapter(SimpleNamespace(ip='127.0.0.1'), {'shelly_gen':1})
|
|
287
|
+
with patch.object(a, '_rpc', rpc), patch('smart_home.adapters.shelly._get', get):
|
|
288
|
+
await a.write_capability('power', False)
|
|
289
|
+
self.assertEqual(sent, ['http://127.0.0.1/relay/0?turn=off'])
|
|
290
|
+
|
|
291
|
+
async def test_kasa_read_all_uses_capability_keys(self):
|
|
292
|
+
from smart_home.adapters.kasa import KasaAdapter
|
|
293
|
+
a=KasaAdapter(SimpleNamespace(ip='127.0.0.1'))
|
|
294
|
+
async def sysinfo(): return {'relay_state':1}
|
|
295
|
+
with patch.object(a, '_sysinfo', sysinfo):
|
|
296
|
+
self.assertEqual(await a.read_all(), {'power':True})
|
|
297
|
+
|
|
298
|
+
class FinalContractTests(unittest.IsolatedAsyncioTestCase):
|
|
299
|
+
async def test_shelly_gen2_advertises_observed_components_and_reads(self):
|
|
300
|
+
from smart_home.adapters.shelly import ShellyAdapter
|
|
301
|
+
a=ShellyAdapter(SimpleNamespace(ip='127.0.0.1'))
|
|
302
|
+
async def rpc(method, params=None): return {'switch:0': {'output': True}, 'cover:0': {'current_pos': 73}}
|
|
303
|
+
with patch.object(a, '_rpc', rpc):
|
|
304
|
+
caps={c['key']:c for c in await a.list_capabilities()}
|
|
305
|
+
values=await a.read_all()
|
|
306
|
+
self.assertEqual(set(caps), {'power','position'})
|
|
307
|
+
self.assertEqual(values, {'power':True,'position':73})
|
|
308
|
+
|
|
309
|
+
async def test_shelly_action_sends_dict(self):
|
|
310
|
+
from smart_home.adapters.shelly import ShellyAdapter
|
|
311
|
+
a=ShellyAdapter(SimpleNamespace(ip='127.0.0.1')); calls=[]
|
|
312
|
+
async def rpc(method, params=None): calls.append((method, params))
|
|
313
|
+
with patch.object(a, '_rpc', rpc): await a.run_action('Switch.Set', {'id':0,'on':True})
|
|
314
|
+
self.assertEqual(calls, [('Switch.Set', {'id':0,'on':True})])
|
|
315
|
+
|
|
316
|
+
async def test_tasmota_only_advertises_observed(self):
|
|
317
|
+
from smart_home.adapters.shelly import TasmotaAdapter
|
|
318
|
+
a=TasmotaAdapter(SimpleNamespace(ip='127.0.0.1'))
|
|
319
|
+
async def cmd(command): return {'StatusSTS': {'POWER':'ON', 'Dimmer':50}}
|
|
320
|
+
with patch.object(a, '_cmd', cmd):
|
|
321
|
+
caps={c['key']:c for c in await a.list_capabilities()}
|
|
322
|
+
self.assertEqual(set(caps), {'power','brightness'})
|
|
323
|
+
self.assertTrue(caps['brightness']['writable'])
|
|
324
|
+
|
|
325
|
+
async def test_hue_light_only_advertises_supported_state(self):
|
|
326
|
+
from smart_home.adapters.hue import HueAdapter
|
|
327
|
+
a=HueAdapter(SimpleNamespace(ip='127.0.0.1'), {'hue_light_id':'2'})
|
|
328
|
+
async def api(method,path,payload=None):
|
|
329
|
+
return {'2': {'state': {'on':True}, 'type':'On/Off plug-in unit'}}
|
|
330
|
+
with patch.object(a,'_api',api):
|
|
331
|
+
self.assertEqual([c['key'] for c in await a.list_capabilities()],['power'])
|
|
332
|
+
with self.assertRaises(ValueError): await a.write_capability('brightness',10)
|
|
333
|
+
|
|
334
|
+
async def test_tasmota_rejects_unconfirmed_write(self):
|
|
335
|
+
from smart_home.adapters.shelly import TasmotaAdapter
|
|
336
|
+
a=TasmotaAdapter(SimpleNamespace(ip='127.0.0.1'))
|
|
337
|
+
async def cmd(command): return {}
|
|
338
|
+
with patch.object(a,'_cmd',cmd):
|
|
339
|
+
with self.assertRaises(RuntimeError): await a.write_capability('power',True)
|
|
340
|
+
|
|
341
|
+
async def test_tuya_close_closes_client(self):
|
|
342
|
+
from smart_home.adapters.tuya import TuyaAdapter
|
|
343
|
+
a=TuyaAdapter(SimpleNamespace(ip='127.0.0.1'))
|
|
344
|
+
class Dev:
|
|
345
|
+
closed=False
|
|
346
|
+
def close(self): self.closed=True
|
|
347
|
+
dev=Dev(); a._dev=dev
|
|
348
|
+
await a.close()
|
|
349
|
+
self.assertTrue(dev.closed)
|
|
350
|
+
self.assertIsNone(a._dev)
|
|
351
|
+
|
|
352
|
+
async def test_esphome_is_explicitly_unsupported(self):
|
|
353
|
+
from smart_home.adapters.shelly import EspHomeAdapter
|
|
354
|
+
a=EspHomeAdapter(SimpleNamespace(ip='127.0.0.1', category='light'))
|
|
355
|
+
self.assertEqual(await a.list_capabilities(), [])
|
|
356
|
+
with self.assertRaises((ValueError, NotImplementedError)): await a.write_capability('power',True)
|
|
357
|
+
|
|
358
|
+
async def test_onvif_uses_discovered_address_and_detects_fault(self):
|
|
359
|
+
from smart_home.adapters.dlna import OnvifAdapter
|
|
360
|
+
a=OnvifAdapter(SimpleNamespace(ip='127.0.0.1'))
|
|
361
|
+
async def probe(ip): return {'service':'http://127.0.0.1/onvif/device_service'}
|
|
362
|
+
async def soap(service, action, body):
|
|
363
|
+
self.assertIn('GetDeviceInformation', body)
|
|
364
|
+
return '<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"><s:Body><s:Fault/></s:Body></s:Envelope>'
|
|
365
|
+
with patch('smart_home.adapters.dlna._onvif_probe',probe), patch.object(a,'_soap',soap):
|
|
366
|
+
with self.assertRaises(RuntimeError): await a.scrape()
|
|
367
|
+
|
|
368
|
+
if __name__ == '__main__':
|
|
369
|
+
unittest.main()
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import unittest
|
|
3
|
+
from types import SimpleNamespace
|
|
4
|
+
from unittest.mock import patch
|
|
5
|
+
from smart_home.adapters.kasa import YeelightAdapter, KasaAdapter, _yeelight_call, _kasa_call
|
|
6
|
+
|
|
7
|
+
class YeelightTests(unittest.IsolatedAsyncioTestCase):
|
|
8
|
+
async def test_read_and_metadata(self):
|
|
9
|
+
async def call(ip,method,params):
|
|
10
|
+
self.assertEqual(method,'get_prop')
|
|
11
|
+
return {'result':['on','50','4000','16711680']}
|
|
12
|
+
a=YeelightAdapter(SimpleNamespace(ip='test',fields={'support':'get_prop set_power set_bright set_ct_abx set_rgb'}), {'color_temp_range':[2700,6500]})
|
|
13
|
+
with patch('smart_home.adapters.kasa._yeelight_call',call):
|
|
14
|
+
caps={c['key']:c for c in await a.list_capabilities()}
|
|
15
|
+
values=await a.read_all()
|
|
16
|
+
self.assertEqual(values,{'power':True,'brightness':50,'color_temp':4000,'color':16711680})
|
|
17
|
+
self.assertEqual(caps['brightness']['range'],[1,100,1]); self.assertEqual(caps['color']['range'],[0,16777215,1]); self.assertEqual(caps['color_temp']['range'],[2700,6500,1])
|
|
18
|
+
self.assertTrue(all(c['writable'] for c in caps.values()))
|
|
19
|
+
|
|
20
|
+
async def test_unknown_properties_and_no_guessed_writes(self):
|
|
21
|
+
async def call(ip,method,params): return {'result':['on','', '', '']}
|
|
22
|
+
a=YeelightAdapter(SimpleNamespace(ip='test',fields={}))
|
|
23
|
+
with patch('smart_home.adapters.kasa._yeelight_call',call):
|
|
24
|
+
caps=await a.list_capabilities()
|
|
25
|
+
self.assertEqual([x['key'] for x in caps],['power']); self.assertFalse(caps[0]['writable'])
|
|
26
|
+
with patch('smart_home.adapters.kasa._yeelight_call',call):
|
|
27
|
+
with self.assertRaises(ValueError): await a.write_capability('power',True)
|
|
28
|
+
|
|
29
|
+
async def test_ct_success_payload(self):
|
|
30
|
+
a=YeelightAdapter(SimpleNamespace(ip='test', fields={'support':'get_prop set_ct_abx'}), {'color_temp_range':[2000,6000]})
|
|
31
|
+
calls=[]
|
|
32
|
+
async def call(ip,method,params):
|
|
33
|
+
calls.append((method,params))
|
|
34
|
+
return {'result':['on','50','4000','1']} if method == 'get_prop' else {'result':['ok']}
|
|
35
|
+
with patch('smart_home.adapters.kasa._yeelight_call',call):
|
|
36
|
+
await a.write_capability('color_temp',4000)
|
|
37
|
+
self.assertEqual(calls[-1],('set_ct_abx',[4000,'smooth',300]))
|
|
38
|
+
|
|
39
|
+
async def test_reject_invalid_values_and_bad_ack(self):
|
|
40
|
+
a=YeelightAdapter(SimpleNamespace(ip='test',fields={'support':'get_prop set_power set_bright set_ct_abx set_rgb'}), {'color_temp_range':[2700,6500]})
|
|
41
|
+
async def call(ip,method,params): return {'result':['on','50','4000','1']} if method=='get_prop' else {'result':['bad']}
|
|
42
|
+
with patch('smart_home.adapters.kasa._yeelight_call',call):
|
|
43
|
+
for key,value in [('color',-1),('color',16777216),('color','bad'),('brightness',0),('brightness',1.5),('color_temp',2000)]:
|
|
44
|
+
with self.assertRaises(ValueError): await a.write_capability(key,value)
|
|
45
|
+
with self.assertRaises(RuntimeError): await a.write_capability('power',True)
|
|
46
|
+
with self.assertRaises((NotImplementedError, ValueError)): await a.run_action('arbitrary')
|
|
47
|
+
|
|
48
|
+
class KasaTests(unittest.IsolatedAsyncioTestCase):
|
|
49
|
+
async def test_no_relay_no_fake_power(self):
|
|
50
|
+
a=KasaAdapter(SimpleNamespace(ip='test'))
|
|
51
|
+
async def info(): return {'model':'strip'}
|
|
52
|
+
with patch.object(a,'_sysinfo',info):
|
|
53
|
+
self.assertEqual(await a.list_capabilities(),[])
|
|
54
|
+
self.assertIsNone(await a.read_capability('power'))
|
|
55
|
+
with self.assertRaises(ValueError): await a.write_capability('power',True)
|
|
56
|
+
|
|
57
|
+
async def test_missing_or_error_ack_rejected(self):
|
|
58
|
+
a=KasaAdapter(SimpleNamespace(ip='test'))
|
|
59
|
+
async def info(): return {'relay_state':0}
|
|
60
|
+
async def call(ip,payload): return {'system': {'set_relay_state': {}}}
|
|
61
|
+
with patch.object(a,'_sysinfo',info), patch('smart_home.adapters.kasa._kasa_call',call):
|
|
62
|
+
with self.assertRaises(RuntimeError): await a.write_capability('power',True)
|
|
63
|
+
|
|
64
|
+
async def test_connection_timeout(self):
|
|
65
|
+
async def blocked(*args): await asyncio.Future()
|
|
66
|
+
with patch('smart_home.adapters.kasa.asyncio.open_connection',blocked):
|
|
67
|
+
with self.assertRaises(TimeoutError): await _kasa_call('test',{},timeout=.01)
|
|
68
|
+
with self.assertRaises(TimeoutError): await _yeelight_call('test','get_prop',[],timeout=.01)
|
|
69
|
+
|
|
70
|
+
if __name__=='__main__': unittest.main()
|