LoginSignup
26
29

More than 5 years have passed since last update.

Paho(MQTT Client Library) -Python-

Posted at

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

$ sudo pip install paho-mqtt

サンプル

下記の例は、クライアント証明書によるクライアント認証を行うサンプルコードです。
パスワード認証をするときはusernamepasswordが絡む行を有効にしてださい。

ファイル・ディレクトリ構造

 current directory/
   + pub.py
   + sub.py
   + cert/
      + ca.crt              # 認証局の証明書
      + client.crt          # クライアント証明書
      + client_nopass.key   # クライアント証明書の秘密鍵

コードを実行する度にパスワード入力が面倒なのでクライアント証明書の秘密鍵のパスワードを解除したファイルで動作確認しています。パスワードを解除していない秘密鍵を指定すると、コード実行時に秘密鍵のパスワードの入力を促されるはずです。

サンプルコード

pub.py
#!/usr/bin/python
# -*- coding: utf-8 -*-

import paho.mqtt.client as mqtt
import ssl

host = 'Server証明書のFQDN'
port = 1883
### パスワード認証を使用する時に使用する
#username = 'mqtt'
#password = 'mqtt'
### SSL
port = 8883
cacert = './cert/ca.crt'
clientCert = './cert/client.crt'
clientKey = './cert/client_nopass.key'

topic = 'paho/mqtt'
message = 'test message'

def on_connect(client, userdata, flags, respons_code):
    """broker接続時のcallback関数
    """
    print('status {0}'.format(respons_code))
    client.publish(topic, message)

def on_publish(client, userdata, mid):
    """メッセージをpublishした後のcallback関数
    """
    client.disconnect()

if __name__ == '__main__':
    ### インスタンス作成時にprotocol v3.1.1を指定
    client = mqtt.Client(protocol=mqtt.MQTTv311)
    ### パスワード認証を使用する時に使用する
    #client.username_pw_set(username, password=password)
    ### SSL
    client.tls_set(cacert,
        certfile = clientCert,
        keyfile = clientKey,
        tls_version = ssl.PROTOCOL_TLSv1_2)
    client.tls_insecure_set(True)

    ### callback function
    client.on_connect = on_connect
    client.on_publish = on_publish

    client.connect(host, port=port, keepalive=60)
    client.loop_forever()
sub.py
#!/usr/bin/python
# -*- coding: utf-8 -*-

import paho.mqtt.client as mqtt
import ssl

host = 'Server証明書のFQDN'
port = 1883
### パスワード認証を使用する時に使用する
#username = 'mqtt'
#password = 'mqtt'
# SSL
port = 8883
cacert = './cert/ca.crt'
clientCert = './cert/client.crt'
clientKey = './cert/client_nopass.key'

topic = 'paho/mqtt'

def on_connect(client, userdata, flags, respons_code):
    """broker接続時のcallback関数
    """
    print('status {0}'.format(respons_code))
    client.subscribe(topic)

def on_message(client, userdata, msg):
    """メッセージ受信時のcallback関数
    """
    print(msg.topic + ' ' + str(msg.payload))

if __name__ == '__main__':
    ### インスタンス作成時にprotocol v3.1.1を指定
    client = mqtt.Client(protocol=mqtt.MQTTv311)

    ### パスワード認証を使用する時に使用する
    #client.username_pw_set(username, password=password)
    ### SSL
    client.tls_set(cacert,
        certfile = clientCert,
        keyfile = clientKey,
        tls_version = ssl.PROTOCOL_TLSv1_2)
    client.tls_insecure_set(True)

    ### callback function
    client.on_connect = on_connect
    client.on_message = on_message

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

参考サイト

26
29
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
26
29