10000 Catch exceptions raised on unknown devices during discovery (#240) · python-kasa/python-kasa@9cda529 · GitHub
[go: up one dir, main page]

Skip to content

Commit 9cda529

Browse files
authored
Catch exceptions raised on unknown devices during discovery (#240)
1 parent 8a4068c commit 9cda529

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

kasa/discover.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,12 @@ def datagram_received(self, data, addr) -> None:
7373
info = json.loads(TPLinkSmartHomeProtocol.decrypt(data))
7474
_LOGGER.debug("[DISCOVERY] %s << %s", ip, info)
7575

76-
device_class = Discover._get_device_class(info)
76+
try:
77+
device_class = Discover._get_device_class(info)
78+
except SmartDeviceException as ex:
79+
_LOGGER.debug("Unable to find device type from %s: %s", info, ex)
80+
return
81+
7782
device = device_class(ip)
7883
device.update_from_discover_info(info)
7984

kasa/tests/test_discovery.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,9 +85,9 @@ async def test_discover_send(mocker):
8585
proto = _DiscoverProtocol()
8686
assert proto.discovery_packets == 3
8787
assert proto.target == ("255.255.255.255", 9999)
88-
sendto = mocker.patch.object(proto, "transport")
88+
transport = mocker.patch.object(proto, "transport")
8989
proto.do_discover()
90-
assert sendto.sendto.call_count == proto.discovery_packets
90+
assert transport.sendto.call_count == proto.discovery_packets
9191

9292

9393
async def test_discover_datagram_received(mocker, discovery_data):
@@ -105,3 +105,15 @@ async def test_discover_datagram_received(mocker, discovery_data):
105105
dev = proto.discovered_devices[addr]
106106
assert issubclass(dev.__class__, SmartDevice)
107107
assert dev.host == addr
108+
109+
110+
@pytest.mark.parametrize("msg, data", INVALIDS)
111+
async def test_discover_invalid_responses(msg, data, mocker):
112+
"""Verify that we don't crash whole discovery if some devices in the network are sending unexpected data."""
113+
proto = _DiscoverProtocol()
114+
mocker.patch("json.loads", return_value=data)
115+
mocker.patch.object(protocol.TPLinkSmartHomeProtocol, "encrypt")
116+
mocker.patch.object(protocol.TPLinkSmartHomeProtocol, "decrypt")
117+
118+
proto.datagram_received(data, ("127.0.0.1", 1234))
119+
assert len(proto.discovered_devices) == 0

0 commit comments

Comments
 (0)
0