Instantly share code, notes, and snippets.

Embed
What would you like to do?

Publisher

送信

from time import sleep
import paho.mqtt.client as mqtt

host = 'v157-7-84-147.z1d11.static.cnode.jp'
port = 1883
topic = 'pycon/tutorial/iot'

# インスタンス作成時にprotocol v3.1.1を指定します
client = mqtt.Client(protocol=mqtt.MQTTv311)

client.connect(host, port=port, keepalive=60)

for i in range(10):
    client.publish(topic, 'ham')
    sleep(0.2)

client.disconnect()

will の利用

from time import sleep
import paho.mqtt.client as mqtt

host = 'v157-7-84-147.z1d11.static.cnode.jp'
port = 1883
topic = 'pycon/tutorial/iot'

# インスタンス作成時にprotocol v3.1.1を指定します
client = mqtt.Client(protocol=mqtt.MQTTv311)

# connect() の利用前に will_set() を使用します
client.will_set('system/message', 'Publisher Down')
client.connect(host, port=port, keepalive=60)

for i in range(3):
    client.publish(topic, 'ham')
    sleep(0.2)

raise Exception

Retain の利用

# 送付時に retain=True を利用する
client.publish(topic, 'This is Retain message.', 0, retain=True)
# 送付時に retain=True を利用する
client.publish(topic, 'This is Retain message.', 0, retain=True)
client.publish('pycon/tutorial/iot', 'This is fist Retain message.', 0, retain=True)
client.publish('pycon/tutorial/ml', 'This is first Retain message.', 0, retain=True)
# 既に Retain の設定のある Topic に再び Retain を登録すると? 
client.publish('pycon/tutorial/iot', 'This is second Retain message.', 0, retain=True)

Subscriber

特定のトピックの情報を取得

import paho.mqtt.client as mqtt

topic = 'pycon/tutorial/iot'

# topic にはワイルドカードも利用できます
## 'pycon/#'
## 'pycon/+/iot'

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

if __name__ == '__main__':

    host = 'v157-7-84-147.z1d11.static.cnode.jp'
    port = 1883

    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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment