Mercury
Mercury

Reputation: 1965

Running a process on MQTT message

I would like to start a task (e.g. play audio file) on my RP when a receiving an MQTT packet. What is the best way to approach it? I'm thinking either writing a c++ script or python. I'm not very sharp in Linux shell, and it could be that there is an even simpler way to do it. Any suggestions?

Upvotes: 2

Views: 8088

Answers (4)

weberjn
weberjn

Reputation: 1985

using Don Libes' expect:


#!/usr/local/bin/expect

spawn mosquitto_sub -t mytop

while 1 {
    expect {
                "hello" {
                        puts "got hello"
                }
                "world" {
                        exec sh -c "touch world"
                }
                "bye" {
                        break
                }
    }
}

Upvotes: 1

Heath Raftery
Heath Raftery

Reputation: 4169

Accepted answer does not work on ash (the default shell on Busybox, as used on the Onion Omega for example). For an ash compatible solution:

#!/bin/sh

mosquitto_sub -R -h your.mqtt.host -t topic | while read RAW_DATA
do
  echo "Got msg" # replace with your task of choice
done

The -R flag prevents "stale" messages from being processed.

Upvotes: 6

Diego Torres Milano
Diego Torres Milano

Reputation: 69368

You can use mosquitto_sub to play a sound file (considering you have the sound file somewhere):

while read msg;
do
   aplay $msg;
done < <(mosquitto_sub -t topic -q 1)

Upvotes: 3

hardillb
hardillb

Reputation: 59751

You can do that with Node-RED, it has a MQTT input node that will listen to a given topic (or wildcard topic) and an exec node that will run an arbitrary command, in this case something like mpg123 or aplay

enter image description here

Upvotes: 3

Related Questions