7
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Raspberry Pi で paho-mqtt を使う

Last updated at Posted at 2017-12-04

リンクを切り替えて python3 を、ディフォールトにします。

sudo cd /usr/bin
sudo rm python
sudo ln -s python3 python

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

sudo pip3 install 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
Linux pansy 5.4.72-v7+ #1356 SMP Thu Oct 22 13:56:54 BST 2020 armv7l GNU/Linux
7
19
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
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?