Possibility for multiple topics, keys, data and commands implemented
Tento commit je obsažen v:
rodič
299917736d
revize
5736a42f6e
@ -9,11 +9,18 @@ MQTT_USER = "user"
|
||||
MQTT_PASS = "pass"
|
||||
MQTT_SERVER = "host"
|
||||
|
||||
TOPIC = 'topic'
|
||||
PAYLOAD_KEY = 'key' # Give a key or None to compare plain DATA
|
||||
PAYLOAD_DATA = 'data' # Give data to compare or None if no comparison is needed
|
||||
|
||||
COMMAND = "aplay %s/ring.wav -D plughw:UACDemoV10,0" % __BASEPATH__
|
||||
EXEC_LIST = {
|
||||
'topic_1': {
|
||||
'key': 'key', # Give a key or None to compare plain DATA
|
||||
'data': 'data', # Give data to compare or None if no comparison is needed
|
||||
'command': 'echo 123'
|
||||
},
|
||||
'topic_2': {
|
||||
'key': None, # Give a key or None to compare plain DATA
|
||||
'data': 'data', # Give data to compare or None if no comparison is needed
|
||||
'command': 'echo 321'
|
||||
}
|
||||
}
|
||||
|
||||
#
|
||||
# Logging
|
||||
|
@ -17,18 +17,21 @@ class exec_command(mqtt.mqtt_client):
|
||||
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)
|
||||
self.add_callback(config.TOPIC, self.mqtt_rx)
|
||||
for topic in config.EXEC_LIST:
|
||||
self.add_callback(topic, self.mqtt_rx)
|
||||
# Start a pseudo process
|
||||
self.process = subprocess.Popen(["sleep", "0"])
|
||||
|
||||
def exec_command(self):
|
||||
self.process = subprocess.Popen(config.COMMAND.split(" "))
|
||||
def exec_command(self, cmd):
|
||||
self.process = subprocess.Popen(cmd.split(" "))
|
||||
|
||||
def mqtt_rx(self, client, userdate, message):
|
||||
data = None
|
||||
if config.PAYLOAD_KEY is None:
|
||||
payload = None
|
||||
key = config.EXEC_LIST[message.topic].get('key')
|
||||
data = config.EXEC_LIST[message.topic].get('data')
|
||||
if key is None:
|
||||
try:
|
||||
data = message.payload.decode('utf-8')
|
||||
payload = message.payload.decode('utf-8')
|
||||
except:
|
||||
logger.exception("Error decoding mqtt message")
|
||||
else:
|
||||
@ -37,12 +40,15 @@ class exec_command(mqtt.mqtt_client):
|
||||
except:
|
||||
logger.exception("Error decoding json mqtt message")
|
||||
else:
|
||||
data = payload.get(config.PAYLOAD_KEY)
|
||||
if config.PAYLOAD_DATA is None or data == config.PAYLOAD_DATA:
|
||||
try:
|
||||
payload = payload.get(key)
|
||||
except AttributeError:
|
||||
logger.exception("payload seems to be no dictionary")
|
||||
if data is None or payload == data:
|
||||
if self.process.poll() is None:
|
||||
self.process.kill()
|
||||
logger.debug("Starting execution in background...")
|
||||
self.exec_command()
|
||||
self.exec_command(config.EXEC_LIST[message.topic]['command'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
1
ring.wav
1
ring.wav
@ -1 +0,0 @@
|
||||
sounds/door-bell.wav
|
Načítá se…
x
Odkázat v novém úkolu
Zablokovat Uživatele