_utils.py 2.8 KB

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