exec_command/exec_command.py

65 lines
2.1 KiB
Python
Raw Normal View History

2022-09-21 14:38:35 +01:00
import config
2022-09-22 09:32:43 +01:00
import json
2022-09-21 14:38:35 +01:00
import logging
import mqtt
import report
2022-09-22 10:19:04 +01:00
import subprocess
2022-09-21 14:38:35 +01:00
import time
try:
from config import APP_NAME as ROOT_LOGGER_NAME
except ImportError:
ROOT_LOGGER_NAME = 'root'
logger = logging.getLogger(ROOT_LOGGER_NAME).getChild('main')
2022-09-22 10:19:04 +01:00
class exec_command(mqtt.mqtt_client):
2022-09-21 14:38:35 +01:00
def __init__(self):
self.__block_execution__ = False
mqtt.mqtt_client.__init__(self, config.APP_NAME, config.MQTT_SERVER, 1883, config.MQTT_USER, config.MQTT_PASS)
for topic in config.EXEC_LIST:
self.add_callback(topic, self.mqtt_rx)
2022-09-22 10:19:04 +01:00
# Start a pseudo process
self.process = subprocess.Popen(["sleep", "0"])
2022-09-21 14:38:35 +01:00
def exec_command(self, cmd):
self.process = subprocess.Popen(cmd.split(" "))
2022-09-21 14:38:35 +01:00
def mqtt_rx(self, client, userdate, message):
payload = None
key = config.EXEC_LIST[message.topic].get('key')
data = config.EXEC_LIST[message.topic].get('data')
if key is None:
2022-09-22 10:19:04 +01:00
try:
payload = message.payload.decode('utf-8')
2022-09-22 10:19:04 +01:00
except:
logger.exception("Error decoding mqtt message")
2022-09-21 14:38:35 +01:00
else:
2022-09-22 10:19:04 +01:00
try:
payload = json.loads(message.payload)
except:
logger.exception("Error decoding json mqtt message")
else:
try:
payload = payload.get(key)
except AttributeError:
logger.exception("payload seems to be no dictionary")
if data is None or payload == data:
2022-09-22 10:19:04 +01:00
if self.process.poll() is None:
self.process.kill()
logger.debug("Starting execution in background...")
self.exec_command(config.EXEC_LIST[message.topic]['command'])
2022-09-21 14:38:35 +01:00
if __name__ == '__main__':
report.appLoggingConfigure(config.__BASEPATH__, config.LOGTARGET, ((config.APP_NAME, config.LOGLVL), ), fmt=config.formatter, host=config.LOGHOST, port=config.LOGPORT)
#
ec = exec_command()
#
while True:
time.sleep(30)
try:
ec.join()
finally:
ec.stop()