_cli.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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 argparse
  19. import json
  20. import logging
  21. import os
  22. import pathlib
  23. import warnings
  24. import switchbot
  25. import switchbot_mqtt
  26. from switchbot_mqtt._actors import _ButtonAutomator, _CurtainMotor
  27. _MQTT_DEFAULT_PORT = 1883
  28. _MQTT_DEFAULT_TLS_PORT = 8883
  29. _LOGGER = logging.getLogger(__name__)
  30. def _main() -> None:
  31. argparser = argparse.ArgumentParser(
  32. description="MQTT client controlling SwitchBot button automators, "
  33. "compatible with home-assistant.io's MQTT Switch platform"
  34. )
  35. argparser.add_argument("--mqtt-host", type=str, required=True)
  36. argparser.add_argument(
  37. "--mqtt-port",
  38. type=int,
  39. help=f"default {_MQTT_DEFAULT_PORT} ({_MQTT_DEFAULT_TLS_PORT} with --mqtt-enable-tls)",
  40. )
  41. mqtt_tls_argument_group = argparser.add_mutually_exclusive_group()
  42. mqtt_tls_argument_group.add_argument(
  43. "--mqtt-enable-tls",
  44. action="store_true",
  45. help="TLS will be enabled by default in the next major release",
  46. )
  47. mqtt_tls_argument_group.add_argument( # for upward compatibility
  48. "--mqtt-disable-tls", action="store_true", help="Currently enabled by default"
  49. )
  50. argparser.add_argument("--mqtt-username", type=str)
  51. password_argument_group = argparser.add_mutually_exclusive_group()
  52. password_argument_group.add_argument("--mqtt-password", type=str)
  53. password_argument_group.add_argument(
  54. "--mqtt-password-file",
  55. type=pathlib.Path,
  56. metavar="PATH",
  57. dest="mqtt_password_path",
  58. help="stripping trailing newline",
  59. )
  60. argparser.add_argument(
  61. "--device-password-file",
  62. type=pathlib.Path,
  63. metavar="PATH",
  64. dest="device_password_path",
  65. help="path to json file mapping mac addresses of switchbot devices to passwords, e.g. "
  66. + json.dumps({"11:22:33:44:55:66": "password", "aa:bb:cc:dd:ee:ff": "secret"}),
  67. )
  68. argparser.add_argument(
  69. "--retries",
  70. dest="retry_count",
  71. type=int,
  72. default=switchbot.DEFAULT_RETRY_COUNT,
  73. help="Maximum number of attempts to send a command to a SwitchBot device"
  74. " (default: %(default)d)",
  75. )
  76. argparser.add_argument(
  77. "--fetch-device-info",
  78. action="store_true",
  79. help="Report devices' battery level on topic"
  80. # pylint: disable=protected-access; internal
  81. f" {_ButtonAutomator.get_mqtt_battery_percentage_topic(mac_address='MAC_ADDRESS')}"
  82. " or, respectively,"
  83. f" {_CurtainMotor.get_mqtt_battery_percentage_topic(mac_address='MAC_ADDRESS')}"
  84. " after every command. Additionally report curtain motors' position on"
  85. f" topic {_CurtainMotor.get_mqtt_position_topic(mac_address='MAC_ADDRESS')}"
  86. " after executing stop commands."
  87. " When this option is enabled, the mentioned reports may also be requested"
  88. " by sending a MQTT message to the topic"
  89. f" {_ButtonAutomator.get_mqtt_update_device_info_topic(mac_address='MAC_ADDRESS')}"
  90. f" or {_CurtainMotor.get_mqtt_update_device_info_topic(mac_address='MAC_ADDRESS')}."
  91. " This option can also be enabled by assigning a non-empty value to the"
  92. " environment variable FETCH_DEVICE_INFO.",
  93. )
  94. argparser.add_argument("--debug", action="store_true")
  95. args = argparser.parse_args()
  96. # https://github.com/fphammerle/python-cc1101/blob/26d8122661fc4587ecc7c73df55b92d05cf98fe8/cc1101/_cli.py#L51
  97. logging.basicConfig(
  98. level=logging.DEBUG if args.debug else logging.INFO,
  99. format="%(asctime)s:%(levelname)s:%(name)s:%(funcName)s:%(message)s"
  100. if args.debug
  101. else "%(message)s",
  102. datefmt="%Y-%m-%dT%H:%M:%S%z",
  103. )
  104. _LOGGER.debug("args=%r", args)
  105. if args.mqtt_port:
  106. mqtt_port = args.mqtt_port
  107. elif args.mqtt_enable_tls:
  108. mqtt_port = _MQTT_DEFAULT_TLS_PORT
  109. else:
  110. mqtt_port = _MQTT_DEFAULT_PORT
  111. if not args.mqtt_enable_tls and not args.mqtt_disable_tls:
  112. warnings.warn(
  113. "In switchbot-mqtt's next major release, TLS will be enabled by default"
  114. " (--mqtt-enable-tls)."
  115. " Please add --mqtt-disable-tls to your command for upward compatibility.",
  116. UserWarning, # DeprecationWarning ignored by default
  117. )
  118. if args.mqtt_password_path:
  119. # .read_text() replaces \r\n with \n
  120. mqtt_password = args.mqtt_password_path.read_bytes().decode()
  121. if mqtt_password.endswith("\r\n"):
  122. mqtt_password = mqtt_password[:-2]
  123. elif mqtt_password.endswith("\n"):
  124. mqtt_password = mqtt_password[:-1]
  125. else:
  126. mqtt_password = args.mqtt_password
  127. if args.device_password_path:
  128. device_passwords = json.loads(args.device_password_path.read_text())
  129. else:
  130. device_passwords = {}
  131. switchbot_mqtt._run( # pylint: disable=protected-access; internal
  132. mqtt_host=args.mqtt_host,
  133. mqtt_port=mqtt_port,
  134. mqtt_username=args.mqtt_username,
  135. mqtt_password=mqtt_password,
  136. mqtt_disable_tls=not args.mqtt_enable_tls,
  137. retry_count=args.retry_count,
  138. device_passwords=device_passwords,
  139. fetch_device_info=args.fetch_device_info
  140. # > In formal language theory, the empty string, [...], is the unique string of length zero.
  141. # https://en.wikipedia.org/wiki/Empty_string
  142. or bool(os.environ.get("FETCH_DEVICE_INFO")),
  143. )