I've written this process many times, and finally I came up with the idea of reusing it. The image looks like the figure below, with Subscribe for Topic A on the left and Publish for Topic B on the right.

In the script, the Topic on the left is expressed as "SUB_TOPIC" and the Topic on the right is expressed as "PUB_TOPIC". By the way, the host may be different on the SUB side and the PUB side, so I tried to have the connection information on the SUB side and the PUB side respectively.
Like this.
sample.py
#!/usr/bin/python
# encoding:utf-8
import paho.mqtt.client as mqtt
import re
import sys
#Topic-related settings that this script subscribes to
SUB_TOPIC = "subtopic"
SUB_USERNAME = 'username'
SUB_PASSWORD = 'password'
SUB_HOST = 'localhost'
SUB_PORT = 1883
#Topic-related settings that this script publishes
PUB_TOPIC = "pubtopic"
PUB_USERNAME = 'username'
PUB_PASSWORD = 'password'
PUB_HOST = 'localhost'
PUB_PORT = 1883
#When this keyword appears in the Sub side topic, output to the Pub side topic
KEYWORD = "TEST"
#Flags for debug output control
ISDEBUG = True
def sub_on_connect(client, userdata, flags, rc):
    client.subscribe(SUB_TOPIC)
def sub_on_message(client, userdata, msg):
    #The received message is msg.Stored in payload
    debug_echo(msg.payload)
    match = re.match(KEYWORD, msg.payload)
    if match is None:
        debug_echo("Not Match")
    else:
        debug_echo("Match")
        publish("OK")
def publish(msg):
    pub_client.publish(PUB_TOPIC, msg)
    pass
def debug_echo(msg):
    if ISDEBUG :
        print msg
        sys.stderr.write(msg+"\n")
if __name__ == '__main__':
    #Preparing the sending client
    pub_client = mqtt.Client(protocol=mqtt.MQTTv311)
    pub_client.username_pw_set(PUB_USERNAME, password=PUB_PASSWORD)
    pub_client.connect(PUB_HOST, port=PUB_PORT, keepalive=60)
    #Recipient client preparation
    sub_client = mqtt.Client(protocol=mqtt.MQTTv311)
    sub_client.on_connect = sub_on_connect
    sub_client.on_message = sub_on_message
    sub_client.username_pw_set(SUB_USERNAME, password=SUB_PASSWORD)
    sub_client.connect(SUB_HOST, port=SUB_PORT, keepalive=60)
    #Start receive loop
    sub_client.loop_forever()
Addendum: Changed to output debug contents to standard error output.
Recommended Posts