[PYTHON] Publish to another topic when a keyword appears in a topic subscribed to in MQTT

【Overview】

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.

Kobito.jocseL.png

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.

【script】

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

Publish to another topic when a keyword appears in a topic subscribed to in MQTT
What to do when a warning appears around Python integration in Neovim's CheckHealth
[openpyxl] What to do when IllegalCharacterError appears in pandas.DataFrame.to_excel
Things to note when initializing a list in Python
When you want to plt.save in a for statement
Publish / upload a library created in Python to PyPI
What to do when "SSL: CERTIFICATE_VERIFY_FAILED _ssl.c: 1056" appears in Python
What to do when "Invalid HTTP_HOST header" appears in Django
[Subprocess] When you want to execute another Python program in Python code
Timezone specification when converting a string to datetime type in python
[Python] When you want to use all variables in another file
When creating a matrix in a list
When writing a program in Python
[Memorandum] What to do when a warning appears after executing pip list
How to write a string when there are multiple lines in python
What to do when a warning message is displayed in pip list