Skip to content

Instantly share code, notes, and snippets.

@David-Lor
Created July 11, 2019 12:29
Show Gist options
  • Star 29 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save David-Lor/63fb0be80b67359c8de6230c6b1dafa2 to your computer and use it in GitHub Desktop.
Save David-Lor/63fb0be80b67359c8de6230c6b1dafa2 to your computer and use it in GitHub Desktop.
Shell Script to subscribe to MQTT and execute a callback
#!/bin/bash
# This script subscribes to a MQTT topic using mosquitto_sub.
# On each message received, you can execute whatever you want.
while true # Keep an infinite loop to reconnect when connection lost/broker unavailable
do
mosquitto_sub -h "127.0.0.1" -t "test" | while read -r payload
do
# Here is the callback to execute whenever you receive a message:
echo "Rx MQTT: ${payload}"
done
sleep 10 # Wait 10 seconds until reconnection
done # & # Discomment the & to run in background (but you should rather run THIS script in background)
@rwb196884
Copy link

#!/bin/sh

# https://gist.github.com/David-Lor/63fb0be80b67359c8de6230c6b1dafa2

while true  # Keep an infinite loop to reconnect when connection lost/broker unavailable
do
    mosquitto_sub -h localhost -t zigbee2mqtt/things/\# -F "%t %p" | while read -r payload
    do
        # Here is the callback to execute whenever you receive a message:
        topic=$(echo "$payload" | cut -d ' ' -f 1)
        msg=$(echo "$payload" | cut -d ' ' -f 2-)
        echo "Rx MQTT: $topic: ${payload}"
        p=$(echo "$msg" | jq '.property')
        echo "Extracted property: $p for $topic"
    done
    sleep 10  # Wait 10 seconds until reconnection
done # &  # Discomment the & to run in background (but you should rather run THIS script in background)

@smithj33
Copy link

smithj33 commented Mar 9, 2023

Thank you for this script. Saved me a lot of time trying to figure out how to do this.

@suedwestlicht
Copy link

Thanks, that's a nice script to start with. Saved me a lot of time, too.

@jeanrocco
Copy link

Smart script, very useful with "Docker Homeassistant" to interface with MQTT mosquitto on other machines (satellites for Rhasspy). Great teaching too ! Thanks a lot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment