Skip to content

Commit 7c6360d

Browse files
authored
switch: tolerate missing 'type' in device info for legacy v1 firmware; use .get for version/mac/type; add test; update changelog (refs home-assistant/core#150264) (#60)
1 parent 9d80905 commit 7c6360d

File tree

3 files changed

+43
-3
lines changed

3 files changed

+43
-3
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
- Add boot_id, energy_since_boot and time_since_boot to switch (thanks @slyoldfox)
66
- Expose `device_type` property on switches
7+
- Fix: Tolerate missing 'type' in device info for legacy myStrom v1 switches, preventing KeyError during get_state (related to home-assistant/core#150264)
8+
79

810
## 2.2.0 (2023-05-21)
911

pymystrom/switch.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,9 +87,10 @@ async def get_state(self) -> None:
8787
url = URL(self.uri).join(URL("info.json"))
8888
response = await request(self, uri=url)
8989

90-
self._firmware = response["version"]
91-
self._mac = response["mac"]
92-
self._device_type = response["type"]
90+
# Tolerate missing keys on legacy firmware (e.g., v1 devices)
91+
self._firmware = response.get("version")
92+
self._mac = response.get("mac")
93+
self._device_type = response.get("type")
9394

9495
@property
9596
def device_type(self) -> Optional[str]:

tests/test_switch_missing_type.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import asyncio
2+
3+
from pymystrom.switch import MyStromSwitch
4+
import pymystrom.switch as switch_module
5+
6+
7+
async def _fake_request(self, uri, method="GET", data=None, json_data=None, params=None):
8+
uri_str = str(uri)
9+
if uri_str.endswith("/report"):
10+
return {"relay": True, "power": 1.23, "Ws": 0.5}
11+
if uri_str.endswith("/api/v1/info"):
12+
# Legacy v1 firmware without 'type'
13+
return {"version": "2.68.10", "mac": "AA:BB:CC:DD:EE:FF"}
14+
if uri_str.endswith("/info.json"):
15+
return {"version": "2.68.10", "mac": "AA:BB:CC:DD:EE:FF"}
16+
return {}
17+
18+
19+
def test_get_state_missing_type():
20+
# Patch the request function used by MyStromSwitch
21+
original_request = switch_module.request
22+
switch_module.request = _fake_request
23+
try:
24+
sw = MyStromSwitch("127.0.0.1")
25+
asyncio.run(sw.get_state())
26+
27+
assert sw.relay is True
28+
assert sw.consumption == 1.2
29+
assert sw.consumedWs == 0.5
30+
assert sw.firmware == "2.68.10"
31+
assert sw.mac == "AA:BB:CC:DD:EE:FF"
32+
# Missing 'type' should be tolerated and map to None
33+
assert sw.device_type is None
34+
finally:
35+
# Restore original request function
36+
switch_module.request = original_request
37+

0 commit comments

Comments
 (0)