ライブラリーのインストール
sudo apt install python3-paho-mqtt
Subscribe のプログラム
host と、topic を Broker に合わせて下さい。
subscribe.py
# ! /usr/bin/python
# -*- coding: utf-8 -*-
#
# subscribe.py
#
# Dec/04/2017
#
# ------------------------------------------------------------------
import sys
from time import sleep
import paho.mqtt.client as mqtt
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
host = '192.168.8.101'
port = 1883
topic = 'topic_1'
def on_connect(client, userdata, flags, respons_code):
print('status {0}'.format(respons_code))
client.subscribe(topic)
def on_message(client, userdata, msg):
print(msg.topic + ' ' + str(msg.payload,'utf-8'))
if __name__ == '__main__':
client = mqtt.Client(protocol=mqtt.MQTTv311)
client.on_connect = on_connect
client.on_message = on_message
client.connect(host, port=port, keepalive=60)
client.loop_forever()
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------
Publish のプログラム
host と、topic を Broker に合わせて下さい。
publish.py
# ! /usr/bin/python
# -*- coding: utf-8 -*-
#
# publish.py
#
# Dec/04/2017
#
# ------------------------------------------------------------------
import sys
from time import sleep
import paho.mqtt.client as mqtt
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
host = '192.168.8.101'
port = 1883
topic = 'topic_1'
client = mqtt.Client(protocol=mqtt.MQTTv311)
client.connect(host, port=port, keepalive=60)
client.publish(topic, 'Good Afternoon')
sleep(0.5)
client.publish(topic, 'こんにちは')
client.disconnect()
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------
Broker (サーバー) の立て方は、こちら
Raspberry Pi で mosquitto を使う
次のバージョンで動作を確認しました。
$ uname -a
inux lotus 6.12.34+rpt-rpi-v8 #1 SMP PREEMPT Debian 1:6.12.34-1+rpt1~bookworm (2025-06-26) aarch64 GNU/Linux