0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

MQTT: Paho の使い方

Last updated at Posted at 2025-03-31

こちらを参考にしました。
paho-mqtt 2.1.0

必要なライブラリーのインストール

sudo apt install python3-paho-mqtt

Publish

publish.py
#! /usr/bin/python
#
#	publish.py
#
#					Mar/31/2025
#
# ------------------------------------------------------------------
import paho.mqtt.publish as publish
import	sys

sys.stderr.write("*** 開始 ***\n")
message = "Good Afternoon"
topic = "/paho/test/topic"
publish.single(topic, message, hostname="localhost")
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

Subscribe

subscribe_callback.py
#! /usr/bin/python
#
#	subscribe_callback.py
#
#					Mar/31/2025
#
# ------------------------------------------------------------------
import paho.mqtt.subscribe as subscribe
import sys
# ------------------------------------------------------------------
def on_message_print(client, userdata, message):
    print("%s %s" % (message.topic, message.payload))
    userdata["message_count"] += 1
    if userdata["message_count"] >= 5:
        # it's possible to stop the program by disconnecting
        client.disconnect()

# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
topic = "/paho/test/topic"
subscribe.callback(on_message_print, topic, hostname="localhost", userdata={"message_count": 0})
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

確認したバージョン

$ python --version
Python 3.12.7

テストに使ったスクリプト

go_pub.sh
BROKER="localhost"
TOPIC="/paho/test/topic"
#
echo $BROKER
message="{\"key\": \"A1B2C3D4\",\"version\": \"2025-3-31 AM 11:09\"}"
mosquitto_pub -d -t orz -m "${message}" \
    -h  $BROKER \
    --topic $TOPIC
go_sub.sh
BROKER="localhost"
TOPIC="/paho/test/topic"
#
mosquitto_sub -d -h $BROKER --topic $TOPIC
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?