Home > Net >  Subscribe a bash script to run when MQTT message is received
Subscribe a bash script to run when MQTT message is received

Time:09-02

I would like to subscribe a bash script to run when an MQTT message arrives in a topic.

The basic mosquitto_sub -d -t Topic -u user -p password is not enough to do this.

For context I am using an esp8266 that needs to query an SQL database (look for an item) on a computer via MQTT protocol. The esp is already programmed to send the request in the payload and waits for a reply (item exist/not_exist).

Desired behavior:

  • MQTT message arrives on desired topic
  • message triggers a bash script (process_message.sh) to run and passes the payload to it as an argument.
  • script interprets payload and sends a reply (already know how to do)

I am looking for any solutions that work and are simple to implement. Could be demon, bash magic, extra tool to install or convince me to use python/other code.

CodePudding user response:

You should be able to use a little bash script like this:

#!/usr/bin/env bash

mosquitto_sub ... |
   while read payload ; do
      echo Received $payload
      ... process and produce response
      mosquitto_pub ... $response
   done

Save as responder.sh, and make it executable with:

chmod  x responder.sh

Then run it with:

./responder 
  • Related