「paho-mqtt」ライブラリを使って、Raspberry PiでMQTT通信を行います。「PC上でMQTT通信」で作成したBrokerを使用します。
ライブラリのインストール
PythonでMQTTを取り扱うために、次のコマンドで「paho-mqtt」ライブラリをインストールします。
pip install paho-mqtt
ValueError: Unsupported callback API version: version 2.0 added a callback_api_version, see docs/migrations.rst for details
このエラーメッセージは、paho-mqttのVer2に対応できていないときに発生します。変更が必要な個所については、「Change between version 1.x and 2.0」を参照します。
Publisherの作成
次のPublisher コード「publisher.py」を作成します。
publisher.py
import paho.mqtt.client as mqtt
import time
def on_connect(client, userdata, flags, reason_code, properties):
print(f"Connected with result code {reason_code}")
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
for i in range(5):
# The four parameters are topic, sending content, QoS and whether retaining the message respectively
client.publish('raspberry/topic', payload=i, qos=0, retain=False)
print(f"send {i} to raspberry/topic")
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.on_connect = on_connect
client.connect("192.168.10.105", 1883, 60)
client.loop_forever()
Subscriber の作成
次のSubscriber コード「subscriber_v2.py」を作成します。
subscriber_v2.py
import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, reason_code, properties):
print(f"Connected with result code {reason_code}")
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("raspberry/topic")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
mqttc.on_connect = on_connect
mqttc.on_message = on_message
mqttc.connect("192.168.10.105", 1883, 60)
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
mqttc.loop_forever()
MQTT通信の実行
Subscriberの実行後にPublisherを実行します。


