Execute a command on receiving a mqtt message
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import config
  2. import json
  3. import logging
  4. import mqtt
  5. import os
  6. import report
  7. import task
  8. import time
  9. try:
  10. from config import APP_NAME as ROOT_LOGGER_NAME
  11. except ImportError:
  12. ROOT_LOGGER_NAME = 'root'
  13. logger = logging.getLogger(ROOT_LOGGER_NAME).getChild('main')
  14. class exec_command(mqtt.mqtt_client, task.threaded_queue):
  15. def __init__(self):
  16. self.__block_execution__ = False
  17. task.threaded_queue.__init__(self)
  18. mqtt.mqtt_client.__init__(self, config.APP_NAME, config.MQTT_SERVER, 1883, config.MQTT_USER, config.MQTT_PASS)
  19. self.add_callback(config.TOPIC, self.mqtt_rx)
  20. def exec_command(self, rt):
  21. os.system(config.COMMAND)
  22. self.__block_execution__ = False
  23. def mqtt_rx(self, client, userdate, message):
  24. if not self.__block_execution__:
  25. data = None
  26. if config.PAYLOAD_KEY is None:
  27. try:
  28. data = message.payload.decode('utf-8')
  29. except:
  30. logger.exception("Error decoding mqtt message")
  31. else:
  32. try:
  33. payload = json.loads(message.payload)
  34. except:
  35. logger.exception("Error decoding json mqtt message")
  36. else:
  37. data = payload.get(config.PAYLOAD_KEY)
  38. if config.PAYLOAD_DATA is None or data == config.PAYLOAD_DATA:
  39. logger.debug("Starting execution in background...")
  40. self.__block_execution__ = True
  41. self.enqueue(5, self.exec_command)
  42. else:
  43. logger.debug("Execution in progress. Ignoring request...")
  44. if __name__ == '__main__':
  45. report.appLoggingConfigure(config.__BASEPATH__, config.LOGTARGET, ((config.APP_NAME, config.LOGLVL), ), fmt=config.formatter, host=config.LOGHOST, port=config.LOGPORT)
  46. #
  47. ec = exec_command()
  48. ec.run()
  49. #
  50. while True:
  51. time.sleep(30)
  52. try:
  53. ec.join()
  54. finally:
  55. ec.stop()