1
0

_utils.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # switchbot-mqtt - MQTT client controlling SwitchBot button & curtain automators,
  2. # compatible with home-assistant.io's MQTT Switch & Cover platform
  3. #
  4. # Copyright (C) 2020 Fabian Peter Hammerle <fabian@hammerle.me>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. import enum
  19. import queue # pylint: disable=unused-import; in type hint
  20. import re
  21. import typing
  22. _MAC_ADDRESS_REGEX = re.compile(r"^[0-9a-f]{2}(:[0-9a-f]{2}){5}$")
  23. def _mac_address_valid(mac_address: str) -> bool:
  24. return _MAC_ADDRESS_REGEX.match(mac_address.lower()) is not None
  25. class _MQTTTopicPlaceholder(enum.Enum):
  26. MAC_ADDRESS = "MAC_ADDRESS"
  27. _MQTTTopicLevel = typing.Union[str, _MQTTTopicPlaceholder]
  28. def _join_mqtt_topic_levels(
  29. *,
  30. topic_prefix: str,
  31. topic_levels: typing.Iterable[_MQTTTopicLevel],
  32. mac_address: str,
  33. ) -> str:
  34. return topic_prefix + "/".join(
  35. mac_address if l == _MQTTTopicPlaceholder.MAC_ADDRESS else l
  36. for l in topic_levels
  37. )
  38. def _parse_mqtt_topic(
  39. *,
  40. topic: str,
  41. expected_prefix: str,
  42. expected_levels: typing.Collection[_MQTTTopicLevel],
  43. ) -> typing.Dict[_MQTTTopicPlaceholder, str]:
  44. if not topic.startswith(expected_prefix):
  45. raise ValueError(f"expected topic prefix {expected_prefix}, got topic {topic}")
  46. attrs: typing.Dict[_MQTTTopicPlaceholder, str] = {}
  47. topic_split = topic[len(expected_prefix) :].split("/")
  48. if len(topic_split) != len(expected_levels):
  49. raise ValueError(f"unexpected topic {topic}")
  50. for given_part, expected_part in zip(topic_split, expected_levels):
  51. if expected_part == _MQTTTopicPlaceholder.MAC_ADDRESS:
  52. attrs[_MQTTTopicPlaceholder(expected_part)] = given_part
  53. elif expected_part != given_part:
  54. raise ValueError(f"unexpected topic {topic}")
  55. return attrs