7
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Raspberry Pi で paho-mqtt を使う

Last updated at Posted at 2017-12-04

ライブラリーのインストール

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
7
20
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
7
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?