Last active
April 16, 2024 20:53
-
-
Save dayne/eda80fcfce2f8239047702e55a3a91c9 to your computer and use it in GitHub Desktop.
simple wrapper around mosquitto_pub to make a line based pipe to a server+topic easier. Example usage: `fortune-loop | mlpub`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/bash | |
DELAY_DEFAULT=5 | |
DELAY=${DELAY:-$DELAY_DEFAULT} | |
if ! command -v fortune > /dev/null; then | |
echo "missing fortune" | |
echo " fix: sudo apt install fortune-mod" | |
exit 1 | |
fi | |
while(true); do | |
fortune | |
echo | |
sleep $DELAY | |
done |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/bash | |
# Dayne Broderson 2024 | |
CMD_NAME=$(basename $0) | |
MQTT_HOST_DEFAULT="localhost" | |
MQTT_TOPIC_DEFAULT="${1:-"/$CMD_NAME"}" | |
MQTT_HOST="${MQTT_HOST:-$MQTT_HOST_DEFAULT}" | |
MQTT_TOPIC="${MQTT_TOPIC:-$MQTT_TOPIC_DEFAULT}" | |
if ! command -v mosquitto_pub > /dev/null; then | |
echo "missing command: mosquitto_pub" | |
echo " fix: sudo apt install mosquitto-clients" | |
exit 1 | |
fi | |
if ! command -v nc > /dev/null; then | |
echo "missing command: nc" | |
echo " fix: sudo apt install" | |
sleep 3 | |
else | |
if ! $(nc $MQTT_HOST 1883); then | |
echo "Warning: Unable to connec to $MQTT_HOST on 1883" | |
echo " possible fix: sudo apt install mosquitto" | |
echo " sudo /etc/init.d/mosquitto start" | |
sleep 3 | |
fi | |
fi | |
display_help() { | |
echo "Usage: $CMD_NAME" | |
echo " This script is intended to b e used in a pipeline" | |
echo " It reads from STDIN and publishes each line as a message to MQTT" | |
echo "MQTT server & topic set via environment vairables" | |
echo " MQTT_HOST=$MQTT_HOST" | |
echo " MQTT_TOPIC=$MQTT_TOPIC" | |
echo "Examples:" | |
echo " echo 'hi' | $CMD_NAME" | |
echo " cat file.txt | $CMD_NAME" | |
echo " MQTT_TOPIC='/new/topic' cat file.txt | $CMD_NAME" | |
echo " MQTT_HOST='127.0.0.1' cat file.txt | $CMD_NAME '/new/topic'" | |
} | |
# interactive script run check | |
if [ -t 0 ]; then | |
display_help | |
exit 1 | |
else | |
echo "Reading from STDIN and pushing to $MQTT_HOST at $MQTT_TOPIC" | |
echo " watch: mosquitto_sub -h ${MQTT_HOST} -t ${MQTT_TOPIC}" | |
fi | |
while IFS= read -r line; do | |
mosquitto_pub -h "$MQTT_HOST" -t "$MQTT_TOPIC" -m "$line" | |
if [ $? -eq 0 ]; then | |
echo "published: $line" | |
else | |
echo "Error: mosquitto_pub failed" | |
exit 1 | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment