mqtt-wrapper - brcon2024-hackathons - Bitreichcon 2024 Hackathons
 (HTM) git clone git://bitreich.org/brcon2024-hackathons git://enlrupgkhuxnvlhsf6lc3fziv5h2hhfrinws65d7roiv6bfj7d652fid.onion/brcon2024-hackathons
 (DIR) Log
 (DIR) Files
 (DIR) Refs
 (DIR) Tags
 (DIR) Submodules
       ---
       mqtt-wrapper (1664B)
       ---
            1 #!/bin/sh
            2 set -x
            3 #
            4 # $input_topic | $runtime $runtime_args | $output_topic
            5 #                 2>$error_topic
            6 #
            7 # application to run
            8 runtime="${RUNTIME:-cat}"
            9 # arguments to $runtime
           10 runtime_args="${ARGS}"
           11 # stdin for $runtime; where others send to
           12 input_topics="${INPUT_TOPICS:-$$/in}"
           13 # stdout of $runtime; where others need to subscribe
           14 output_topic="${OUTPUT_TOPIC:-$$/out}"
           15 # stderr of $runtime; where others can subscribe
           16 error_topic="${ERROR_TOPIC:-$$/err}"
           17 
           18 mqtt_broker="${MQTT_BROKER:-mx2.adamsgaard.dk}"
           19 mqtt_port="${MQTT_BROKER:-65431}"
           20 mqtt_user="${MQTT_USER:-bitreich}"
           21 mqtt_password="${MQTT_PASSWORD:-bitreich}"
           22 mosquitto_args="-h ${mqtt_broker} -p ${mqtt_port} -u ${mqtt_user} -P ${mqtt_password}"
           23 
           24 cleanup() {
           25         kill -TERM -- -$$
           26         rm -f "$fin" "$fout" "$ferr"
           27         rmdir "$fifodir"
           28         exit 1
           29 }
           30 
           31 die() {
           32         printf '%s: %s\n' "${0##*/}" "${1}" >&2
           33         cleanup
           34         exit "${2:-1}"
           35 }
           36 
           37 fifodir="$(mktemp -d)" || die 'mktemp'
           38 fin="${fifodir}/in"
           39 fout="${fifodir}/out"
           40 ferr="${fifodir}/err"
           41 mkfifo "$fin" "$fout" "$ferr" || die 'mkfifo'
           42 
           43 # split multiple input topics separated by "," into separate args
           44 subscribe_args="$(printf '%s' "$input_topics" | sed 's/,/ -t /g')"
           45 
           46 # subscribe to input topic(s), add -v option if you want message topic as first field
           47 mosquitto_sub ${mosquitto_args} -t $subscribe_args >"${fin}" &
           48 
           49 # create named pipes for output streams
           50 mosquitto_pub ${mosquitto_args} -t "${output_topic}" -l <"${fout}" &
           51 mosquitto_pub ${mosquitto_args} -t "${error_topic}" -l <"${ferr}" &
           52 trap -- 'cleanup' ERR INT HUP EXIT CHLD
           53 
           54 # run the program (lossy restart if it fails), connecting to named pipes
           55 while :
           56 do
           57         $runtime $runtime_args <"${fin}" >"${fout}" 2>"${ferr}"
           58 done
           59