_utils.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. class _QueueLogHandler(logging.Handler):
  37. """
  38. logging.handlers.QueueHandler drops exc_info
  39. """
  40. # TypeError: 'type' object is not subscriptable
  41. def __init__(self, log_queue: "queue.Queue[logging.LogRecord]") -> None:
  42. self.log_queue = log_queue
  43. super().__init__()
  44. def emit(self, record: logging.LogRecord) -> None:
  45. self.log_queue.put(record)