LoginSignup
6
4

More than 5 years have passed since last update.

Orange Pi ZeroからRaspberry PiにMQTTで通信する

Posted at

Raspberry PiにMosquitto Brokerをインストールしたので、Orange PiからMQTTを用いてpublishし、Raspberry Piでsubscribeしてみます。今回はPythonのMQTT Python client libraryであるpaho-mqttを利用します。

Raspberry Pi (Subscriber) 側の準備

Subscriber側のコード (mqtt_subscriber.py) は以下のようになります:

#!/usr/bin/env python

import paho.mqtt.client as mqtt

host = '127.0.0.1'
port = 1883
keepalive = 60
topic = 'mqtt/test'

def on_connect(client, userdata, flags, rc):
    print('Connected with result code ' + str(rc))
    client.subscribe(topic)

def on_message(client, userdata, msg):
    print(msg.topic + ' ' + str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect(host, port, keepalive)

client.loop_forever()

on_connectはBrokerとの接続確立時に呼ばれるコールバック関数です。また、on_messageはBrokerからメッセージを受信した際に呼ばれるコールバック関数です。

あとは、このコードを任意のディレクトリで実行します:

$ virtualenv venv
$ source venv/bin/activate
$ pip install paho-mqtt
$ python mqtt_subscriber.py
Connected with result code 0

Orange Pi (Publisher) 側の準備

Publisher側のコード (mqtt_publisher.py) は以下のようになります:

#!/usr/bin/env python

import time
import paho.mqtt.client as mqtt

host = 'xxx.xxx.xxx.xxx'
port = 1883
keepalive = 60
topic = 'mqtt/test'

client = mqtt.Client()
client.connect(host, port, keepalive)

for i in range(3):
    client.publish(topic, 'hello from orangepi')
    time.sleep(1)

client.disconnect()

1秒間隔で三回、"hello from orangepi"というメッセージをBrokerにpublishしています。hostにはRaspberry PiのIPアドレスを指定します。

Subscriber側が実行されていることを確認した上で、こちらのコードも実行します:

$ virtualenv venv
$ source venv/bin/activate
$ pip install paho-mqtt
$ python mqtt_publisher.py

実行結果

$ python mqtt_subscriber.py
Connected with result code 0
mqtt/test hello from orangepi
mqtt/test hello from orangepi
mqtt/test hello from orangepi

無事MQTTによってOrange Pi ZeroからRaspberry Piへと通信することができました:thumbsup:

6
4
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
6
4