A frequent question on the forum has been how Raspberry Pi users can run any code on their Pi, triggered from a Cayenne action or widget. This is possible with your Pi connected through our ‘Bring Your Own Thing’ MQTT API, so I’ve made a quick guide to show how to do this.
Setup
For this example to work, your Pi must be connected to Cayenne via the MQTT API rather than via the original Cayenne Pi Agent software. To do this, follow the ‘Installation’ and ‘Cayenne Setup’ instructions for the Cayenne-MQTT-Python library.
I’ll be using the Example-03-CayenneClient.py Python script for the rest of this example. It should be present in the /Cayenne-MQTT-Python/examples
folder after running the install steps mentioned above.
Steps
-
Edit the example script to enter your MQTT Username / Password / Client ID, obtained from the Cayenne Dashboard, so it can make a connection to your account.
-
Edit the block of code labeled “The callback for when a message is received from Cayenne.” to add two new lines at the bottom:
# The callback for when a message is received from Cayenne.
def on_message(message):
print("message received: " + str(message))
if (message.channel == 4) and (message.value == "1"):
execfile("test.py")
These lines check for a value of ‘1’ on MQTT channel 4. You can edit message.value
and message.channel
to anything you’d like. Once the value of 1 is received and the if
statement is true, it will execute the python script test.py
in same folder as the example client.
In my case test.py
just prints “Hello World” to the terminal, but you can run any python code you’d like using this same concept.
- In order to send the value of 1 to trigger the python script, we need an actuator on the Cayenne dashboard. Go to Add New > Device/Widget > Custom Widgets > Button, and set it as follows:
- Device: Your MQTT-connected Pi
- Data: Digital Actuator
- Unit: Digital (0/1)
- Channel: The MQTT channel that your script is monitoring to run custom code – in my example, 4
- With the button widget created, toggle it while
Example-03-CayenneClient.py
is running on your Pi. Notice that when it is an ON (1) state, it will execute the script specified in theexecfile()
statement. If you want to run it again, you’ll need to toggle the button back to OFF (0), and then to ON again for the client to receive the next 1 value. This could be accomplished with a Cayenne trigger to automatically set it back to 0 so it behaves like a momentary switch.
Conclusion
Using this base logic, you can then use Cayenne triggers and scheduled events to interact with button widgets like this on your dashboard, and thus run arbitrary code on your Pi in response to Cayenne dashboard activity / widgets!