Skip to content

Commit dde60cd

Browse files
bieniufrenck
authored andcommitted
Improve mac_address_from_name() function to avoid double discovery of Shelly devices (home-assistant#153343)
1 parent f03b16b commit dde60cd

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

homeassistant/components/shelly/utils.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -552,8 +552,15 @@ def percentage_to_brightness(percentage: int) -> int:
552552

553553
def mac_address_from_name(name: str) -> str | None:
554554
"""Convert a name to a mac address."""
555-
mac = name.partition(".")[0].partition("-")[-1]
556-
return mac.upper() if len(mac) == 12 else None
555+
base = name.split(".", 1)[0]
556+
if "-" not in base:
557+
return None
558+
559+
mac = base.rsplit("-", 1)[-1]
560+
if len(mac) != 12 or not all(char in "0123456789abcdefABCDEF" for char in mac):
561+
return None
562+
563+
return mac.upper()
557564

558565

559566
def get_release_url(gen: int, model: str, beta: bool) -> str | None:

tests/components/shelly/test_utils.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
get_rpc_channel_name,
3535
get_rpc_input_triggers,
3636
is_block_momentary_input,
37+
mac_address_from_name,
3738
)
3839
from homeassistant.util import dt as dt_util
3940

@@ -327,3 +328,17 @@ def test_get_release_url(
327328
def test_get_host(host: str, expected: str) -> None:
328329
"""Test get_host function."""
329330
assert get_host(host) == expected
331+
332+
333+
@pytest.mark.parametrize(
334+
("name", "result"),
335+
[
336+
("shelly1pm-AABBCCDDEEFF", "AABBCCDDEEFF"),
337+
("Shelly Plus 1 [DDEEFF]", None),
338+
("S11-Schlafzimmer", None),
339+
("22-Kueche-links", None),
340+
],
341+
)
342+
def test_mac_address_from_name(name: str, result: str | None) -> None:
343+
"""Test mac_address_from_name() function."""
344+
assert mac_address_from_name(name) == result

0 commit comments

Comments
 (0)