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.

exec_command.py 1.8KB

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