Long day at work! Sorry for the delay.
My setup is as follow:
On the RPI I want the python script to execute, I made a first script which listens to a specific MQTT topic (/home/dashboard/entrance) and evaluate the messages it receives. It uses the Paho library (pip install paho-mqtt). If the message received is “movement”, then it executes another script called anotherScript.py.
#!/usr/bin/env python3
import paho.mqtt.client as mqtt
import anotherScript #That the script you want to execute without .py
def on_connect(client, userdata, flags, rc):
print("Connected to MQTT broker")
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))
if msg.payload.decode() == "movement":
print("Movement detected - turning the Dashboard screen on for 30 seconds ")
anotherScript.myFunction()
def on_subscribe(client, userdata, mid, granted_qos):
print("Subscribed to topic : " + str(mid) +" with QoS" + str(granted_qos))
client = mqtt.Client()
client.username_pw_set( "<YourMQTTBrokerUsername>" , "<YourMQTTBrokerPassword>" )
client.connect( "<YourMQTTBrokerIP>", 1883, 60)
client.subscribe( "/home/dashboard/entrance" , qos=1)
client.on_connect = on_connect
client.on_message = on_message
client.loop_forever()
Here is the anotherScript.py
def myFunction ():
print ( "Hello World!" )
myFunction()
From here you need to execute the main script and you can test from HASS.IO developer tools (yourHASSIOURL:8123/dev-mqtt) and publish the payload on the defined topic and the second script python should execute.
To integrate further with Home Assistant, I added an automation to publish an MQTT payload (movement in my case) to the pre-defined topic (/home/dashboard/entrance in my case).
- id: '1978423740934'
alias: Turn Dashboard screen on when movement is detected
initial_state: True
trigger:
- entity_id: sensor.aeotec_zw100_multisensor_6_burglar
platform: state
to: '8'
action:
- service: mqtt.publish
data:
topic: "/home/dashboard/entrance"
payload: "movement"