_utils.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 collections.abc
  19. import enum
  20. import logging
  21. import queue # pylint: disable=unused-import; in type hint
  22. import re
  23. import typing
  24. _MAC_ADDRESS_REGEX = re.compile(r"^[0-9a-f]{2}(:[0-9a-f]{2}){5}$")
  25. def _mac_address_valid(mac_address: str) -> bool:
  26. return _MAC_ADDRESS_REGEX.match(mac_address.lower()) is not None
  27. class _MQTTTopicPlaceholder(enum.Enum):
  28. MAC_ADDRESS = "MAC_ADDRESS"
  29. _MQTTTopicLevel = typing.Union[str, _MQTTTopicPlaceholder]
  30. def _join_mqtt_topic_levels(
  31. topic_levels: typing.Iterable[_MQTTTopicLevel], mac_address: str
  32. ) -> str:
  33. return "/".join(
  34. mac_address if l == _MQTTTopicPlaceholder.MAC_ADDRESS else typing.cast(str, l)
  35. for l in topic_levels
  36. )
  37. def _parse_mqtt_topic(
  38. topic: str, expected_levels: collections.abc.Collection[_MQTTTopicLevel]
  39. ) -> typing.Dict[_MQTTTopicPlaceholder, str]:
  40. attrs: typing.Dict[_MQTTTopicPlaceholder, str] = {}
  41. topic_split = topic.split("/")
  42. if len(topic_split) != len(expected_levels):
  43. raise ValueError(f"unexpected topic {topic}")
  44. for given_part, expected_part in zip(topic_split, expected_levels):
  45. if expected_part == _MQTTTopicPlaceholder.MAC_ADDRESS:
  46. attrs[_MQTTTopicPlaceholder(expected_part)] = given_part
  47. elif expected_part != given_part:
  48. raise ValueError(f"unexpected topic {topic}")
  49. return attrs
  50. class _QueueLogHandler(logging.Handler):
  51. """
  52. logging.handlers.QueueHandler drops exc_info
  53. """
  54. # TypeError: 'type' object is not subscriptable
  55. def __init__(self, log_queue: "queue.Queue[logging.LogRecord]") -> None:
  56. self.log_queue = log_queue
  57. super().__init__()
  58. def emit(self, record: logging.LogRecord) -> None:
  59. self.log_queue.put(record)