__init__.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. import argparse
  2. import json
  3. import logging
  4. import pathlib
  5. import typing
  6. import paho.mqtt.client
  7. import intertechno_cc1101
  8. _LOGGER = logging.getLogger(__name__)
  9. Aliases = typing.Dict[str, typing.Dict[str, int]]
  10. def _parse_topic(
  11. topic: str, aliases: Aliases
  12. ) -> typing.Tuple[typing.Optional[int], typing.Optional[int]]:
  13. topic_split = topic.split("/")
  14. if len(topic_split) == 3:
  15. try:
  16. alias_attrs = aliases[topic_split[1]]
  17. except KeyError:
  18. _LOGGER.warning("unknown alias %r; ignoring message", topic_split[1])
  19. return None, None
  20. try:
  21. return int(alias_attrs["address"]), int(alias_attrs["button-index"])
  22. except KeyError:
  23. _LOGGER.error(
  24. "alias file must provide fields 'address' and 'button-index' for each alias"
  25. )
  26. return None, None
  27. try:
  28. address = int(topic_split[1])
  29. except ValueError:
  30. _LOGGER.warning(
  31. "failed to parse address %r, expected integer; ignoring message",
  32. topic_split[1],
  33. )
  34. return None, None
  35. try:
  36. button_index = int(topic_split[2])
  37. except ValueError:
  38. _LOGGER.warning(
  39. "failed to parse button index %r, expected integer; ignoring message",
  40. topic_split[2],
  41. )
  42. return None, None
  43. return address, button_index
  44. def _mqtt_on_message(
  45. mqtt_client: paho.mqtt.client.Client,
  46. aliases: Aliases,
  47. message: paho.mqtt.client.MQTTMessage,
  48. ):
  49. # pylint: disable=unused-argument; callback
  50. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L469
  51. _LOGGER.debug("received topic=%s payload=%r", message.topic, message.payload)
  52. if message.retain: # TODO remove
  53. _LOGGER.warning("ignoring retained message")
  54. return
  55. address, button_index = _parse_topic(topic=message.topic, aliases=aliases)
  56. if not address:
  57. return
  58. try:
  59. remote_control = intertechno_cc1101.RemoteControl(address=address)
  60. except AssertionError:
  61. _LOGGER.warning(
  62. "failed to initialize remote control, invalid address? ignoring message",
  63. exc_info=True,
  64. )
  65. return
  66. # https://www.home-assistant.io/integrations/switch.mqtt/#payload_on
  67. try:
  68. if message.payload.upper() == b"ON":
  69. remote_control.turn_on(button_index=button_index)
  70. elif message.payload.upper() == b"OFF":
  71. remote_control.turn_off(button_index=button_index)
  72. else:
  73. _LOGGER.warning(
  74. "unexpected payload %r; expected 'ON' or 'OFF'", message.payload
  75. )
  76. except Exception: # pylint: disable=broad-except; invalid perms? spi error? invalid button index?
  77. _LOGGER.error("failed to send signal", exc_info=True)
  78. def _mqtt_on_connect(
  79. mqtt_client: paho.mqtt.client.Client,
  80. aliases: Aliases,
  81. flags: typing.Dict,
  82. return_code: int,
  83. ) -> None:
  84. # pylint: disable=unused-argument; callback
  85. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L441
  86. assert return_code == 0, return_code # connection accepted
  87. mqtt_broker_host, mqtt_broker_port = mqtt_client.socket().getpeername()
  88. _LOGGER.debug("connected to MQTT broker %s:%d", mqtt_broker_host, mqtt_broker_port)
  89. # alternative: .message_callback_add
  90. mqtt_client.on_message = _mqtt_on_message
  91. set_topic = "intertechno-cc1101/+/+/set"
  92. _LOGGER.info("subscribing to MQTT topic %r (address & button index)", set_topic)
  93. mqtt_client.subscribe(set_topic)
  94. if aliases:
  95. set_alias_topic = "intertechno-cc1101/+/set"
  96. _LOGGER.info("subscribing to MQTT topic %r (alias)", set_alias_topic)
  97. mqtt_client.subscribe(set_alias_topic)
  98. def _run(
  99. mqtt_host: str,
  100. mqtt_port: int,
  101. mqtt_username: typing.Optional[str],
  102. mqtt_password: typing.Optional[str],
  103. alias_file_path: typing.Optional[pathlib.Path],
  104. ) -> None:
  105. if alias_file_path:
  106. with alias_file_path.open("r") as alias_file:
  107. aliases = json.load(alias_file)
  108. else:
  109. aliases = {}
  110. # https://pypi.org/project/paho-mqtt/
  111. mqtt_client = paho.mqtt.client.Client(userdata=aliases)
  112. mqtt_client.on_connect = _mqtt_on_connect
  113. _LOGGER.info("connecting to MQTT broker %s:%d", mqtt_host, mqtt_port)
  114. if mqtt_username:
  115. mqtt_client.username_pw_set(username=mqtt_username, password=mqtt_password)
  116. elif mqtt_password:
  117. raise ValueError("Missing MQTT username")
  118. mqtt_client.connect(host=mqtt_host, port=mqtt_port)
  119. mqtt_client.loop_forever()
  120. def _main() -> None:
  121. logging.basicConfig(
  122. level=logging.DEBUG,
  123. format="%(asctime)s:%(levelname)s:%(name)s:%(message)s",
  124. datefmt="%Y-%m-%dT%H:%M:%S%z",
  125. )
  126. logging.getLogger("cc1101").setLevel(logging.INFO)
  127. argparser = argparse.ArgumentParser(
  128. description="MQTT client controlling Intertechno smart outlets via a CC1101 transceiver, "
  129. "compatible with home-assistant.io's MQTT Switch platform",
  130. allow_abbrev=False,
  131. )
  132. argparser.add_argument("--mqtt-host", type=str, required=True)
  133. argparser.add_argument("--mqtt-port", type=int, default=1883)
  134. argparser.add_argument("--mqtt-username", type=str)
  135. password_argument_group = argparser.add_mutually_exclusive_group()
  136. password_argument_group.add_argument("--mqtt-password", type=str)
  137. password_argument_group.add_argument(
  138. "--mqtt-password-file",
  139. type=pathlib.Path,
  140. metavar="PATH",
  141. dest="mqtt_password_path",
  142. help="stripping trailing newline",
  143. )
  144. argparser.add_argument(
  145. "--alias-file",
  146. metavar="PATH",
  147. dest="alias_file_path",
  148. type=pathlib.Path,
  149. help="json: {}".format(
  150. json.dumps(
  151. {
  152. "some-alias": {"address": 12345678, "button-index": 0},
  153. "another-alias": {"address": 12345678, "button-index": 0},
  154. }
  155. )
  156. ),
  157. )
  158. args = argparser.parse_args()
  159. if args.mqtt_password_path:
  160. # .read_text() replaces \r\n with \n
  161. mqtt_password = args.mqtt_password_path.read_bytes().decode()
  162. if mqtt_password.endswith("\r\n"):
  163. mqtt_password = mqtt_password[:-2]
  164. elif mqtt_password.endswith("\n"):
  165. mqtt_password = mqtt_password[:-1]
  166. else:
  167. mqtt_password = args.mqtt_password
  168. _run(
  169. mqtt_host=args.mqtt_host,
  170. mqtt_port=args.mqtt_port,
  171. mqtt_username=args.mqtt_username,
  172. mqtt_password=mqtt_password,
  173. alias_file_path=args.alias_file_path,
  174. )