_utils.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. topic_levels: typing.List[_MQTTTopicLevel], mac_address: str
  31. ) -> str:
  32. return "/".join(
  33. mac_address if l == _MQTTTopicPlaceholder.MAC_ADDRESS else typing.cast(str, l)
  34. for l in topic_levels
  35. )
  36. def _parse_mqtt_topic(
  37. topic: str, expected_levels: typing.List[_MQTTTopicLevel]
  38. ) -> typing.Dict[_MQTTTopicPlaceholder, str]:
  39. attrs: typing.Dict[_MQTTTopicPlaceholder, str] = {}
  40. topic_split = topic.split("/")
  41. if len(topic_split) != len(expected_levels):
  42. raise ValueError(f"unexpected topic {topic}")
  43. for given_part, expected_part in zip(topic_split, expected_levels):
  44. if expected_part == _MQTTTopicPlaceholder.MAC_ADDRESS:
  45. attrs[_MQTTTopicPlaceholder(expected_part)] = given_part
  46. elif expected_part != given_part:
  47. raise ValueError(f"unexpected topic {topic}")
  48. return attrs
  49. class _QueueLogHandler(logging.Handler):
  50. """
  51. logging.handlers.QueueHandler drops exc_info
  52. """
  53. # TypeError: 'type' object is not subscriptable
  54. def __init__(self, log_queue: "queue.Queue[logging.LogRecord]") -> None:
  55. self.log_queue = log_queue
  56. super().__init__()
  57. def emit(self, record: logging.LogRecord) -> None:
  58. self.log_queue.put(record)