__init__.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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. import intertechno_cc1101_mqtt._homeassistant
  9. _LOGGER = logging.getLogger(__name__)
  10. Aliases = typing.Dict[str, typing.Dict[str, int]]
  11. def _parse_topic(
  12. topic: str, aliases: Aliases
  13. ) -> typing.Tuple[typing.Optional[int], typing.Optional[int]]:
  14. topic_split = topic.split("/")
  15. if len(topic_split) == 3:
  16. try:
  17. alias_attrs = aliases[topic_split[1]]
  18. except KeyError:
  19. _LOGGER.warning("unknown alias %r; ignoring message", topic_split[1])
  20. return None, None
  21. try:
  22. return int(alias_attrs["address"]), int(alias_attrs["button-index"])
  23. except KeyError:
  24. _LOGGER.error(
  25. "alias file must provide fields 'address' and 'button-index' for each alias"
  26. )
  27. return None, None
  28. try:
  29. address = int(topic_split[1])
  30. except ValueError:
  31. _LOGGER.warning(
  32. "failed to parse address %r, expected integer; ignoring message",
  33. topic_split[1],
  34. )
  35. return None, None
  36. try:
  37. button_index = int(topic_split[2])
  38. except ValueError:
  39. _LOGGER.warning(
  40. "failed to parse button index %r, expected integer; ignoring message",
  41. topic_split[2],
  42. )
  43. return None, None
  44. return address, button_index
  45. def _mqtt_on_message(
  46. mqtt_client: paho.mqtt.client.Client,
  47. aliases: Aliases,
  48. message: paho.mqtt.client.MQTTMessage,
  49. ):
  50. # pylint: disable=unused-argument; callback
  51. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L469
  52. _LOGGER.debug("received topic=%s payload=%r", message.topic, message.payload)
  53. address, button_index = _parse_topic(topic=message.topic, aliases=aliases)
  54. if not address:
  55. return
  56. try:
  57. remote_control = intertechno_cc1101.RemoteControl(address=address)
  58. except AssertionError:
  59. _LOGGER.warning(
  60. "failed to initialize remote control, invalid address? ignoring message",
  61. exc_info=True,
  62. )
  63. return
  64. # https://www.home-assistant.io/integrations/switch.mqtt/#payload_on
  65. try:
  66. if message.payload.upper() == b"ON":
  67. remote_control.turn_on(button_index=button_index)
  68. elif message.payload.upper() == b"OFF":
  69. remote_control.turn_off(button_index=button_index)
  70. else:
  71. _LOGGER.warning(
  72. "unexpected payload %r; expected 'ON' or 'OFF'", message.payload
  73. )
  74. except Exception: # pylint: disable=broad-except; invalid perms? spi error? invalid button index?
  75. _LOGGER.error("failed to send signal", exc_info=True)
  76. def _publish_homeassistant_discovery_configs(
  77. mqtt_client: paho.mqtt.client.Client, aliases: Aliases
  78. ) -> None:
  79. # <discovery_prefix>/<component>/[<node_id>/]<object_id>/config
  80. # https://www.home-assistant.io/docs/mqtt/discovery/
  81. # https://www.home-assistant.io/integrations/switch.mqtt/#configuration-variables
  82. # https://github.com/fphammerle/systemctl-mqtt/blob/v0.5.0/systemctl_mqtt/__init__.py#L163
  83. # https://github.com/fphammerle/wireless-sensor-mqtt/blob/v0.3.0/wireless_sensor_mqtt/__init__.py#L153
  84. for alias in aliases.keys():
  85. # pylint: disable=protected-access; internal
  86. if not intertechno_cc1101_mqtt._homeassistant.validate_object_id(alias):
  87. if len(alias) == 0:
  88. _LOGGER.warning(
  89. "empty alias; skipping publishing of discovery config for home assistant"
  90. )
  91. continue
  92. _LOGGER.warning(
  93. "alias %r contains characters unsupported by home assistant"
  94. " (supported characters: %s); skipping publishing of discovery config",
  95. alias,
  96. intertechno_cc1101_mqtt._homeassistant.OBJECT_ID_ALLOWED_CHARS,
  97. )
  98. continue
  99. discovery_topic = "homeassistant/switch/{}/config".format(alias)
  100. _LOGGER.debug(
  101. "publishing home assistant discovery config on topic %s", discovery_topic
  102. )
  103. mqtt_client.publish(
  104. topic="homeassistant/switch/{}/config".format(alias),
  105. payload=json.dumps(
  106. {
  107. "unique_id": "intertechno-cc1101-mqtt/aliases/{}".format(alias),
  108. "command_topic": "intertechno-cc1101/{}/set".format(alias),
  109. "payload_on": "ON", # default
  110. "payload_off": "OFF", # default
  111. "retain": "true",
  112. # friendly_name & template for default entity_id
  113. "name": alias,
  114. }
  115. ),
  116. retain=True,
  117. )
  118. def _mqtt_on_connect(
  119. mqtt_client: paho.mqtt.client.Client,
  120. aliases: Aliases,
  121. flags: typing.Dict,
  122. return_code: int,
  123. ) -> None:
  124. # pylint: disable=unused-argument; callback
  125. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L441
  126. assert return_code == 0, return_code # connection accepted
  127. mqtt_broker_host, mqtt_broker_port = mqtt_client.socket().getpeername()
  128. _LOGGER.debug("connected to MQTT broker %s:%d", mqtt_broker_host, mqtt_broker_port)
  129. # alternative: .message_callback_add
  130. mqtt_client.on_message = _mqtt_on_message
  131. set_topic = "intertechno-cc1101/+/+/set"
  132. _LOGGER.info("subscribing to MQTT topic %r (address & button index)", set_topic)
  133. mqtt_client.subscribe(set_topic)
  134. if aliases:
  135. set_alias_topic = "intertechno-cc1101/+/set"
  136. _LOGGER.info("subscribing to MQTT topic %r (alias)", set_alias_topic)
  137. mqtt_client.subscribe(set_alias_topic)
  138. _publish_homeassistant_discovery_configs(
  139. mqtt_client=mqtt_client, aliases=aliases
  140. )
  141. def _run(
  142. mqtt_host: str,
  143. mqtt_port: int,
  144. mqtt_username: typing.Optional[str],
  145. mqtt_password: typing.Optional[str],
  146. alias_file_path: typing.Optional[pathlib.Path],
  147. ) -> None:
  148. if alias_file_path:
  149. with alias_file_path.open("r") as alias_file:
  150. aliases = json.load(alias_file)
  151. else:
  152. aliases = {}
  153. # https://pypi.org/project/paho-mqtt/
  154. mqtt_client = paho.mqtt.client.Client(userdata=aliases)
  155. mqtt_client.on_connect = _mqtt_on_connect
  156. _LOGGER.info("connecting to MQTT broker %s:%d", mqtt_host, mqtt_port)
  157. if mqtt_username:
  158. mqtt_client.username_pw_set(username=mqtt_username, password=mqtt_password)
  159. elif mqtt_password:
  160. raise ValueError("Missing MQTT username")
  161. mqtt_client.connect(host=mqtt_host, port=mqtt_port)
  162. mqtt_client.loop_forever()
  163. def _main() -> None:
  164. logging.basicConfig(
  165. level=logging.DEBUG,
  166. format="%(asctime)s:%(levelname)s:%(name)s:%(message)s",
  167. datefmt="%Y-%m-%dT%H:%M:%S%z",
  168. )
  169. logging.getLogger("cc1101").setLevel(logging.INFO)
  170. argparser = argparse.ArgumentParser(
  171. description="MQTT client controlling Intertechno smart outlets via a CC1101 transceiver, "
  172. "compatible with home-assistant.io's MQTT Switch platform",
  173. allow_abbrev=False,
  174. )
  175. argparser.add_argument("--mqtt-host", type=str, required=True)
  176. argparser.add_argument("--mqtt-port", type=int, default=1883)
  177. argparser.add_argument("--mqtt-username", type=str)
  178. password_argument_group = argparser.add_mutually_exclusive_group()
  179. password_argument_group.add_argument("--mqtt-password", type=str)
  180. password_argument_group.add_argument(
  181. "--mqtt-password-file",
  182. type=pathlib.Path,
  183. metavar="PATH",
  184. dest="mqtt_password_path",
  185. help="stripping trailing newline",
  186. )
  187. argparser.add_argument(
  188. "--alias-file",
  189. metavar="PATH",
  190. dest="alias_file_path",
  191. type=pathlib.Path,
  192. help="json: {}".format(
  193. json.dumps(
  194. {
  195. "some-alias": {"address": 12345678, "button-index": 0},
  196. "another-alias": {"address": 12345678, "button-index": 0},
  197. }
  198. )
  199. ),
  200. )
  201. args = argparser.parse_args()
  202. if args.mqtt_password_path:
  203. # .read_text() replaces \r\n with \n
  204. mqtt_password = args.mqtt_password_path.read_bytes().decode()
  205. if mqtt_password.endswith("\r\n"):
  206. mqtt_password = mqtt_password[:-2]
  207. elif mqtt_password.endswith("\n"):
  208. mqtt_password = mqtt_password[:-1]
  209. else:
  210. mqtt_password = args.mqtt_password
  211. _run(
  212. mqtt_host=args.mqtt_host,
  213. mqtt_port=args.mqtt_port,
  214. mqtt_username=args.mqtt_username,
  215. mqtt_password=mqtt_password,
  216. alias_file_path=args.alias_file_path,
  217. )