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
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()
subscriber
publisher
Recommended Posts