__init__.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. # systemctl-mqtt - MQTT client triggering shutdown on systemd-based systems
  2. #
  3. # Copyright (C) 2020 Fabian Peter Hammerle <fabian@hammerle.me>
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. import argparse
  18. import datetime
  19. import functools
  20. import logging
  21. import pathlib
  22. import socket
  23. import typing
  24. import dbus
  25. import paho.mqtt.client
  26. _LOGGER = logging.getLogger(__name__)
  27. _SHUTDOWN_DELAY = datetime.timedelta(seconds=4)
  28. def _get_login_manager() -> dbus.proxies.Interface:
  29. # https://dbus.freedesktop.org/doc/dbus-python/tutorial.html
  30. bus = dbus.SystemBus()
  31. proxy: dbus.proxies.ProxyObject = bus.get_object(
  32. bus_name="org.freedesktop.login1", object_path="/org/freedesktop/login1"
  33. )
  34. # https://freedesktop.org/wiki/Software/systemd/logind/
  35. return dbus.Interface(object=proxy, dbus_interface="org.freedesktop.login1.Manager")
  36. def _schedule_shutdown(action: str) -> None:
  37. # https://github.com/systemd/systemd/blob/v237/src/systemctl/systemctl.c#L8553
  38. assert action in ["poweroff", "reboot"], action
  39. shutdown_datetime = datetime.datetime.now() + _SHUTDOWN_DELAY
  40. _LOGGER.info(
  41. "scheduling %s for %s",
  42. action,
  43. shutdown_datetime.isoformat(sep=" ", timespec="seconds"),
  44. )
  45. shutdown_epoch_usec = int(shutdown_datetime.timestamp() * 10 ** 6)
  46. _get_login_manager().ScheduleShutdown(action, shutdown_epoch_usec)
  47. _MQTT_TOPIC_SUFFIX_ACTION_MAPPING = {
  48. "poweroff": functools.partial(_schedule_shutdown, action="poweroff"),
  49. }
  50. class _Settings:
  51. # pylint: disable=too-few-public-methods
  52. def __init__(self, mqtt_topic_prefix: str) -> None:
  53. self.mqtt_topic_action_mapping: typing.Dict[str, typing.Callable] = {}
  54. for topic_suffix, action in _MQTT_TOPIC_SUFFIX_ACTION_MAPPING.items():
  55. topic = mqtt_topic_prefix + "/" + topic_suffix
  56. self.mqtt_topic_action_mapping[topic] = action
  57. def _mqtt_on_connect(
  58. mqtt_client: paho.mqtt.client.Client,
  59. settings: _Settings,
  60. flags: typing.Dict,
  61. return_code: int,
  62. ) -> None:
  63. # pylint: disable=unused-argument; callback
  64. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L441
  65. assert return_code == 0, return_code # connection accepted
  66. mqtt_broker_host, mqtt_broker_port = mqtt_client.socket().getpeername()
  67. _LOGGER.debug("connected to MQTT broker %s:%d", mqtt_broker_host, mqtt_broker_port)
  68. for topic in settings.mqtt_topic_action_mapping.keys():
  69. _LOGGER.debug("subscribing to %s", topic)
  70. mqtt_client.subscribe(topic)
  71. def _mqtt_on_message(
  72. mqtt_client: paho.mqtt.client.Client,
  73. settings: _Settings,
  74. message: paho.mqtt.client.MQTTMessage,
  75. ) -> None:
  76. # pylint: disable=unused-argument; callback
  77. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L469
  78. _LOGGER.debug("received topic=%s payload=%r", message.topic, message.payload)
  79. if message.retain:
  80. _LOGGER.info("ignoring retained message")
  81. return
  82. try:
  83. action = settings.mqtt_topic_action_mapping[message.topic]
  84. except KeyError:
  85. _LOGGER.warning("unexpected topic %s", message.topic)
  86. return
  87. action()
  88. def _run(
  89. mqtt_host: str,
  90. mqtt_port: int,
  91. mqtt_username: typing.Optional[str],
  92. mqtt_password: typing.Optional[str],
  93. mqtt_topic_prefix: str,
  94. ) -> None:
  95. # https://pypi.org/project/paho-mqtt/
  96. mqtt_client = paho.mqtt.client.Client(
  97. userdata=_Settings(mqtt_topic_prefix=mqtt_topic_prefix)
  98. )
  99. mqtt_client.on_connect = _mqtt_on_connect
  100. mqtt_client.on_message = _mqtt_on_message
  101. _LOGGER.info(
  102. "connecting to MQTT broker %s:%d", mqtt_host, mqtt_port,
  103. )
  104. if mqtt_username:
  105. mqtt_client.username_pw_set(username=mqtt_username, password=mqtt_password)
  106. elif mqtt_password:
  107. raise ValueError("Missing MQTT username")
  108. mqtt_client.connect(host=mqtt_host, port=mqtt_port)
  109. mqtt_client.loop_forever()
  110. def _get_hostname() -> str:
  111. return socket.gethostname()
  112. def _main() -> None:
  113. logging.basicConfig(
  114. level=logging.DEBUG,
  115. format="%(asctime)s:%(levelname)s:%(message)s",
  116. datefmt="%Y-%m-%dT%H:%M:%S%z",
  117. )
  118. argparser = argparse.ArgumentParser(
  119. description="MQTT client triggering shutdown on systemd-based systems",
  120. formatter_class=argparse.ArgumentDefaultsHelpFormatter,
  121. )
  122. argparser.add_argument("--mqtt-host", type=str, required=True)
  123. argparser.add_argument("--mqtt-port", type=int, default=1883)
  124. argparser.add_argument("--mqtt-username", type=str)
  125. password_argument_group = argparser.add_mutually_exclusive_group()
  126. password_argument_group.add_argument("--mqtt-password", type=str)
  127. password_argument_group.add_argument(
  128. "--mqtt-password-file",
  129. type=pathlib.Path,
  130. metavar="PATH",
  131. dest="mqtt_password_path",
  132. help="stripping trailing newline",
  133. )
  134. # https://www.home-assistant.io/docs/mqtt/discovery/#discovery_prefix
  135. argparser.add_argument(
  136. "--mqtt-topic-prefix",
  137. type=str,
  138. default="systemctl/" + _get_hostname(),
  139. help="test",
  140. )
  141. args = argparser.parse_args()
  142. if args.mqtt_password_path:
  143. # .read_text() replaces \r\n with \n
  144. mqtt_password = args.mqtt_password_path.read_bytes().decode()
  145. if mqtt_password.endswith("\r\n"):
  146. mqtt_password = mqtt_password[:-2]
  147. elif mqtt_password.endswith("\n"):
  148. mqtt_password = mqtt_password[:-1]
  149. else:
  150. mqtt_password = args.mqtt_password
  151. _run(
  152. mqtt_host=args.mqtt_host,
  153. mqtt_port=args.mqtt_port,
  154. mqtt_username=args.mqtt_username,
  155. mqtt_password=mqtt_password,
  156. mqtt_topic_prefix=args.mqtt_topic_prefix,
  157. )