mqtt-launcher.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. #!/usr/bin/env python
  2. # Copyright (c) 2014 Jan-Piet Mens <jpmens()gmail.com>
  3. # All rights reserved.
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are met:
  7. #
  8. # 1. Redistributions of source code must retain the above copyright notice,
  9. # this list of conditions and the following disclaimer.
  10. # 2. Redistributions in binary form must reproduce the above copyright
  11. # notice, this list of conditions and the following disclaimer in the
  12. # documentation and/or other materials provided with the distribution.
  13. # 3. Neither the name of mosquitto nor the names of its
  14. # contributors may be used to endorse or promote products derived from
  15. # this software without specific prior written permission.
  16. #
  17. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  18. # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  19. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  20. # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  21. # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  22. # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  23. # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  24. # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  25. # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  26. # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  27. # POSSIBILITY OF SUCH DAMAGE.
  28. __author__ = 'Jan-Piet Mens <jpmens()gmail.com>'
  29. __copyright__ = 'Copyright 2014 Jan-Piet Mens'
  30. import os
  31. import sys
  32. import subprocess
  33. import logging
  34. import paho.mqtt.client as paho # pip install paho-mqtt
  35. import time
  36. import socket
  37. import string
  38. qos=2
  39. CONFIG=os.getenv('MQTTLAUNCHERCONFIG', 'launcher.conf')
  40. class Config(object):
  41. def __init__(self, filename=CONFIG):
  42. self.config = {}
  43. execfile(filename, self.config)
  44. def get(self, key, default=None):
  45. return self.config.get(key, default)
  46. try:
  47. cf = Config()
  48. except Exception, e:
  49. print "Cannot load configuration from file %s: %s" % (CONFIG, str(e))
  50. sys.exit(2)
  51. LOGFILE = cf.get('logfile', 'logfile')
  52. LOGFORMAT = '%(asctime)-15s %(message)s'
  53. DEBUG=True
  54. if DEBUG:
  55. logging.basicConfig(filename=LOGFILE, level=logging.DEBUG, format=LOGFORMAT)
  56. else:
  57. logging.basicConfig(filename=LOGFILE, level=logging.INFO, format=LOGFORMAT)
  58. logging.info("Starting")
  59. logging.debug("DEBUG MODE")
  60. def runprog(topic, param=None):
  61. publish = "%s/report" % topic
  62. if param is not None and all(c in string.printable for c in param) == False:
  63. logging.debug("Param for topic %s is not printable; skipping" % (topic))
  64. return
  65. if not topic in topiclist:
  66. logging.info("Topic %s isn't configured" % topic)
  67. return
  68. if param is not None and param in topiclist[topic]:
  69. cmd = topiclist[topic].get(param)
  70. else:
  71. if None in topiclist[topic]: ### and topiclist[topic][None] is not None:
  72. cmd = []
  73. for p in topiclist[topic][None]:
  74. if p == '@!@':
  75. p = param
  76. cmd.append(p)
  77. else:
  78. logging.info("No matching param (%s) for %s" % (param, topic))
  79. return
  80. logging.debug("Running t=%s: %s" % (topic, cmd))
  81. try:
  82. res = subprocess.check_output(cmd, stdin=None, stderr=subprocess.STDOUT, shell=False, universal_newlines=True, cwd='/tmp')
  83. except Exception, e:
  84. res = "*****> %s" % str(e)
  85. payload = res.rstrip('\n')
  86. (res, mid) = mqttc.publish(publish, payload, qos=qos, retain=False)
  87. def on_message(mosq, userdata, msg):
  88. logging.debug(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))
  89. runprog(msg.topic, str(msg.payload))
  90. def on_connect(mosq, userdata, flags, result_code):
  91. logging.debug("Connected to MQTT broker, subscribing to topics...")
  92. for topic in topiclist:
  93. mqttc.subscribe(topic, qos)
  94. def on_disconnect(mosq, userdata, rc):
  95. logging.debug("OOOOPS! launcher disconnects")
  96. time.sleep(10)
  97. if __name__ == '__main__':
  98. userdata = {
  99. }
  100. topiclist = cf.get('topiclist')
  101. if topiclist is None:
  102. logging.info("No topic list. Aborting")
  103. sys.exit(2)
  104. clientid = cf.get('mqtt_clientid', 'mqtt-launcher-%s' % os.getpid())
  105. # initialise MQTT broker connection
  106. mqttc = paho.Client(clientid, clean_session=False)
  107. mqttc.on_message = on_message
  108. mqttc.on_connect = on_connect
  109. mqttc.on_disconnect = on_disconnect
  110. mqttc.will_set('clients/mqtt-launcher', payload="Adios!", qos=0, retain=False)
  111. # Delays will be: 3, 6, 12, 24, 30, 30, ...
  112. #mqttc.reconnect_delay_set(delay=3, delay_max=30, exponential_backoff=True)
  113. mqttc.username_pw_set(cf.get('mqtt_username'), cf.get('mqtt_password'))
  114. mqttc.connect(cf.get('mqtt_broker', 'localhost'), int(cf.get('mqtt_port', '1883')), 60)
  115. for topic in topiclist:
  116. mqttc.subscribe(topic, qos)
  117. while True:
  118. try:
  119. mqttc.loop_forever()
  120. except socket.error:
  121. time.sleep(5)
  122. except KeyboardInterrupt:
  123. sys.exit(0)