A simple Pub / Sub program note in Python

Reference site

MQTT specifications The basic part was explained, and the understanding of MQTT was deepened.

I referred to the program. https://www.sunbit.co.jp/blog/2019/11/21802/ https://qiita.com/rui0930/items/1d139248b440650dc952

Preparation for use

To use mosquitto broker with python, use pho-mqtt.

pip install pho-mqtt

This time, the broker, subscriber, and publisher all run on the same terminal.

Terminal information
Linux mqtt-test 4.15.0-43-generic #46~16.04.1-Ubuntu SMP Fri Dec 7 13:31:08 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

** Launch broker ** This time, to check the operation on localhost, it will start with the port and IP address by default. Since it is not necessary to change the settings or create the config, start the broker with the following command.

mosquitto

** Explanation of operation program ** Both publisher and subscriber operate in an infinite loop. "Hello" is sent to "Topic1" four times in a loop as the transmission data of the publisher. After that, the content is that the information such as the memory usage acquired by executing the free command is continuously sent to "Topic / Mem" every minute. You can send or change it to the subscriber by changing the hierarchical structure of the topic.

The subscriber program keeps getting the subscribed topic data in an infinite loop.

** subscriber program **

 #!/usr/bin/env python
 # -*- coding: utf-8 -*-

#Subscriber
import paho.mqtt.client as mqtt

#mqtt broker
MQTT_HOST = 'localhost'
MQTT_PORT = 1883
MQTT_KEEP_ALIVE = 60

#broker connection
def on_connect(mqttc, obj, flags, rc):
    print("rc:" + str(rc))

#receve message
def on_message(mqttc, obj, msg):
    print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))

mqttc = mqtt.Client()
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEP_ALIVE)


#Subscribe to topic1
mqttc.subscribe("Topic1/#")

#loop
mqttc.loop_forever()

** publisher program **

 #!/usr/bin/env python
 # -*- coding: utf-8 -*-

#Publisher
from time import sleep
import subprocess
import paho.mqtt.client as mqtt

#MQTT Broker
MQTT_HOST = 'localhost'
MQTT_PORT = 1883
MQTT_KEEP_ALIVE = 60
MQTT_TOPIC = 'Topic1'
MQTT_SUB_TOPIC_MEM='Topic1/Mem'

def on_connect(mqttc, obj, flags, rc):
    print("rc:" + str(rc))

def res_cmd(cmd):
    return subprocess.Popen(cmd, stdout=subprocess.PIPE,shell=True).communicate()[0]

mqttc = mqtt.Client()
mqttc.on_connect = on_connect

#Broker connection
mqttc.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEP_ALIVE)
#Start processing
mqttc.loop_start()
for i in range(3):
    mqttc.publish(MQTT_TOPIC, 'hello')
    sleep(1)

cmd = 'free'
ans_str = res_cmd(cmd)
while True:
    mqttc.publish(MQTT_SUB_TOPIC_MEM, ans_str)
    sleep(60)

mqttc.disconnect()

Execution result

subscriber スクリーンショット 2020-06-25 20.10.55.png

publisher スクリーンショット 2020-06-25 20.10.39.png

Recommended Posts

A simple Pub / Sub program note in Python
Write a super simple molecular dynamics program in python
Implementing a simple algorithm in Python 2
Run a simple algorithm in Python
When writing a program in Python
[MQTT / Python] Implemented a class that does MQTT Pub / Sub in Python
A simple HTTP client implemented in Python
I made a payroll program in Python!
Try drawing a simple animation in Python
Create a simple GUI app in Python
Write a Caesar cipher program in Python
Write a simple greedy algorithm in Python
Write a simple Vim Plugin in Python 3
Set up a simple HTTPS server in Python 3
Simple gRPC in Python
A program that removes duplicate statements in Python
A note on optimizing blackbox functions in Python
Data analysis in Python: A note about line_profiler
Create a simple momentum investment model in Python
Set up a simple SMTP server in Python
I made a Caesar cryptographic program in Python.
I made a prime number generation program in Python
Receive dictionary data from a Python program in AppleScript
Make a simple Slackbot with interactive button in python
Things to note when initializing a list in Python
A note on handling variables in Python recursive functions
I made a prime number generation program in Python 2
Create a function in Python
Create a dictionary in Python
Python Input Note in AtCoder
Make a bookmarklet in Python
Simple regression analysis in Python
Draw a heart in Python
Simple IRC client in python
A note about [python] __debug__
A note that runs an external program in Python and parses the resulting line
A Python program in "A book that gently teaches difficult programming"
I made a simple typing game with tkinter in Python
A simple way to avoid multiple for loops in Python
A note on touching Microsoft's face recognition API in Python
I tried "a program that removes duplicate statements in Python"
[Note] Import of a file in the parent directory in Python
Maybe in a python (original title: Maybe in Python)
[python] Manage functions in a list
First simple regression analysis in Python
[Note] Project Euler in Python (Problem 1-22)
Simple OAuth 2 in Python (urllib + oauthlib)
Create a DI Container in Python
Python: A Note About Classes 1 "Abstract"
Draw a scatterplot matrix in python
A note about get_scorer in sklearn
ABC166 in Python A ~ C problem
Write A * (A-star) algorithm in Python
Compatibility diagnosis program written in python
Create a binary file in Python
Solve ABC036 A ~ C in Python
Write a pie chart in Python
Write a vim plugin in Python
Write a depth-first search in Python
Foreign Key in Python SQLite [Note]
Create a Kubernetes Operator in Python