如何使用 Linux shell 命令订阅多个主题(至少 2 个)并将收到的消息重新发布到 Mosquitto MQTT 的单个主题

问题描述 投票:0回答:1

我试图找到一种订阅多个主题的方法,然后在收到消息后,该函数应该根据主题将其发布到不同的代理。

我想过实现一个像这样的函数: 当发布者发布消息时,发布的主题的值存储在名为“topic”的变量中,消息存储在名为“message”的变量中。这是我的代码:

#!/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

然后我发现它不起作用,因为同时订阅多个主题时 mosquitto_sub 不会返回主题名称。还有其他方法可以实现这个功能吗?

bash shell mqtt mosquitto messagebroker
1个回答
0
投票

如您所见,我使用单独的

mosquitto_sub
分别订阅每个主题,然后将收到的消息传递给
handle_message
函数,该函数根据主题处理逻辑,我还使用
&
运算符来运行首先
mosquitto_sub
在后台运行,以便两个订阅可以同时处于活动状态!

#!/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
}

# 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
© www.soinside.com 2019 - 2024. All rights reserved.