Difference between revisions of "MQTT monitoring Daemon"
Jump to navigation
Jump to search
Line 11: | Line 11: | ||
<p class="mwt-heading" >An example of what's possible...</p> | <p class="mwt-heading" >An example of what's possible...</p> | ||
= Requirements: = | = Requirements: = | ||
* <code>apt install mosquitto-clients</code> | * <code>sudo apt install mosquitto-clients</code> | ||
* <code>apt install jq</code> | * <code>sudo apt install jq</code> | ||
= The systemd Service Unit = | = The systemd Service Unit = |
Revision as of 18:52, 14 April 2023
11 (bullseye) |
|
An example of what's possible...
Requirements:
sudo apt install mosquitto-clients
sudo apt install jq
The systemd Service Unit
/etc/systemd/system/MQTTmon.service
[Unit]
Description=MQTT Monitoring Daemon
After=network.target
Requires=network.target
[Service]
Type=simple
User=root
ExecStart=/usr/bin/MQTTmon
Restart=always
[Install]
WantedBy=multi-user.target
- Any time you create or edit a service unit:
systemctl daemon-reload
systemctl restart MQTTmon.service
- Check on how it's going...
systemctl status MQTTmon.service
The Script
/usr/bin/MQTTmon
#!/bin/bash
BROKER="LXC-Mosquitto"
TOPIC="turd"
MQTT=`/usr/bin/mosquitto_sub -C 1 -h $BROKER -t $TOPIC`
TARGET=`echo $MQTT {{!}} jq '.Target'`
MESSAGE=`echo $MQTT {{!}} jq '.Message'`
COMMAND=`echo ${MQTT} {{!}} jq '.Command'`
HOST=\"`hostname`\"
if [[ $TARGET == $HOST ]]
then
/root/Logit $TARGET , $COMMAND , $MESSAGE
if [[ $COMMAND == "\"MSG\"" ]] ; then
/root/Logit "Message is: " $MESSAGE
fi
if [[ $COMMAND == "\"WALL\"" ]] ; then
wall -n $MESSAGE
fi
if [[ $COMMAND == "\"DIE\"" ]] ; then
shutdown
fi
else
/root/Logit $TARGET " got a message too, but this is " $HOST " so we don't GAF."
fi
Sending it messages
In these examples, the machine (an LXC) used for testng is named poop2
- Telling it to shut down...
mosquitto_pub -h LXC-Mosquitto -t turd -m '{"Target":"poop2","Message": "It is time to DIE","Command":"DIE"}'
- Send a message to all logged-in users terminals
mosquitto_pub -h LXC-Mosquitto -t turd -m '{"Target":"poop2","Message": "This is a TURD","Command":"WALL"}'
- Just log a message (using random logger for testing)
mosquitto_pub -h LXC-Mosquitto -t turd -m '{"Target":"poop2","Message": "This is another TURD","Command":"MSG"}'
- Send a message to a different machine
mosquitto_pub -h LXC-Mosquitto -t turd -m '{"Target":"poop1","Message": "This is a TURD too","Command":"DoIt"}'