Ultima attività 1747055737

Simple script listens to a MQTT value change and shutdown the machine

santiago's Avatar santiago ha revisionato questo gist 1747055737. Vai alla revisione

Nessuna modifica

santiago's Avatar santiago ha revisionato questo gist 1747055704. Vai alla revisione

1 file changed, 50 insertions

mqtt_shutdown_listen.sh(file creato)

@@ -0,0 +1,50 @@
1 + #!/usr/bin/env zsh
2 +
3 +
4 + if [ -z "$RASPISTUFF_DIR" ];then
5 + export RASPISTUFF_DIR="$(cd "$(dirname "$(readlink -f "${(%):-%x}")")" && pwd)"
6 + fi
7 +
8 +
9 + cd $RASPISTUFF_DIR
10 +
11 +
12 + if [ ! -f "$RASPISTUFF_DIR/secret/credentials_mqtt.sh" ]; then
13 + echo "$RASPISTUFF_DIR/secret/credentials_mqtt.sh not found. Will NOT listen for MQTT."
14 + exit 1
15 + fi
16 +
17 + source $RASPISTUFF_DIR/secret/credentials_mqtt.sh
18 +
19 + shutdown_if_needed() {
20 +
21 + local payload=$1
22 + echo "TOPIC $MQTT_TOPIC is now = $1"
23 + if [ "$payload" = "1" ]; then
24 + echo "Shutdown command received. Shutting down the system..."
25 +
26 + MSG_TITLE="✋ Shutdown $(hostname)"
27 + MSG_TEXT="MQTT Shutdown requested in $MQTT_TOPIC"
28 +
29 + NOTIFY_SCRIPT="$RASPISTUFF_DIR/notify.sh"
30 + #Requires MSG_TITLE and $MSG_TEXT to be defined!
31 + source "$NOTIFY_SCRIPT"
32 +
33 + echo "Will shutdown in 5 seconds..."
34 + sleep 5
35 + sudo shutdown -h now "MQTT requested shutdown in topic $MQTT_TOPIC"
36 + fi
37 + }
38 +
39 + while true; do
40 +
41 + echo "listening to topic $MQTT_TOPIC "
42 + mosquitto_sub -h "$MQTT_BROKER" -p "$MQTT_PORT" -t "$MQTT_TOPIC" -u "$MQTT_USER" -P "$MQTT_PASSWORD" | while read -r payload
43 + do
44 + shutdown_if_needed "$payload"
45 + done
46 +
47 + echo "mosquitto client EXITEDi will try again in 5 minute"
48 +
49 + sleep 300
50 + done
Più nuovi Più vecchi