Iam trying to figure out a way to subscribe to multiple topics, and then after receiving a message the function should publish it to a different broker depending on the topic.

I've thought of implementing a function that goes like this: when a publisher publishes a message the value of the topic published get stored in a variable called "topic" and the message get stored in a variable called "message". here is my code:

#!/bin/bash
SOURCE_BROKER="192.168.1.37"
DEST_BROKER="192.168.1.25"
while true
do
#Subscribe to both topics ("0_0" and "0_1")
  mosquitto_sub -h $SOURCE_BROKER -t "0_0" -t "0_1" -u pi -P Pass123 | while read -r topic message
  do
    # This is a callback to be executed every time a client subscribes to a topic
    echo "Client subscribed to ${topic}"
    # Check the topic and redirect the subscription
    if [ "$topic" == "0_0" ]; then
      # Publish the message to the broker (SOURCE_BROKER)
      mosquitto_pub -h $SOURCE_BROKER -t "$topic" -m "$message" -u pi -P Pass123
    elif [ "$topic" == "0_1" ]; then
      # Publish the message to the new broker (DEST_BROKER)
      mosquitto_pub -h $DEST_BROKER -t "$topic" -m "$message" -u pi -P Pass123
    fi
  done
  sleep 10 # Wait 10 seconds until reconnection
done

then I've discovered that it would not work because mosquitto_sub does not return the topic name when subscribing to more than one topic at the same time. Is there is any other way to implement this function?

1

There are 1 best solutions below

5
Freeman On BEST ANSWER

As you see, I subscribe to each topic separately using separate mosquitto_sub and the received messages are then passed to the handle_message function, which handles the logic based on the topic and I also use the & operator to run the first mosquitto_sub in the background, so that both subscriptions can be active simultaneously!

#!/bin/bash

SOURCE_BROKER="192.168.1.37"
DEST_BROKER="192.168.1.25"

# Function to handle the received message
handle_message() {
    topic="$1"
    message="$2"

    # This is a callback to be executed every time a client subscribes to a topic
    echo "Client subscribed to ${topic}"

    # Check the topic and redirect the subscription
    if [ "$topic" == "0_0" ]; then
        # Publish the message to the broker (SOURCE_BROKER)
        mosquitto_pub -h "$SOURCE_BROKER" -t "$topic" -m "$message" -u pi -P Pass123
    elif [ "$topic" == "0_1" ]; then
        # Publish the message to the new broker (DEST_BROKER)
        mosquitto_pub -h "$DEST_BROKER" -t "$topic" -m "$message" -u pi -P Pass123
    fi

    #exit the loop after forwarding the message
    exit
}

# Subscribe to both topics ("0_0" and "0_1")
mosquitto_sub -h "$SOURCE_BROKER" -t "0_0" -u pi -P Pass123 | while read -r message
do
    handle_message "0_0" "$message"
done &

mosquitto_sub -h "$SOURCE_BROKER" -t "0_1" -u pi -P Pass123 | while read -r message
do
    handle_message "0_1" "$message"
done