Pythonシミュレーションデバイスを使用してアリクラウドネットワークのMQTTサーバにアクセス

6430 ワード

前言
アリクラウドネットワークキットの設備認証に関するドキュメントが詳細ではないため、筆者は数日でMQTTに接続することを模索した.以下はPythonシミュレータを用いてアリクラウドにアクセスするMQTTです.
概要
アリクラウドネットワークキットには、2つのアクセス方法があります.
  • MQTTクライアントドメイン名直結(リソース制限デバイス推奨)
  • HTTPSから権限を送信してからMQTTに接続する(デバイスレベルのストリーミングなどの特殊付加価値サービス)
  • 本明細書では、主に第1のアクセス方式、TCP直結を紹介し、Pythonコードの例を提供する.
    しゅパラメータ
    ドメイン名の接続
    .iot-as-mqtt.cn-shanghai.aliyuncs.com:1883

    MQTT Connectメッセージパラメータ
    1、mqttClientId
    mqttClientId = ""+"|securemode=3,signmethod=hmacsha1,timestamp=132323232|"

    2、mqttUsername
    使用&パッチおよび.
    mqttUsername = "&"

    3、mqttPassword
    以下のパラメータを辞書のキー名で並べ替え、キー名をつなぎ合わせてcontentを生成し、DeviceSecretを塩としてcontentをhma_sha 1は暗号化され、最後にバイナリは16進数文字列表現に変換される.
  • clientId
  • deviceName
  • productKey
  • timestamp
  • mqttPassword = hmac_sha1(DeviceSecret, content).toHexString();


    仮定
  • clientId = 12345
  • deviceName = device
  • productKey = pk
  • timestamp = 789
  • signmethod = hmacsha1

  • content接合結果:clientId12345deviceNamedeviceproductKeypktimestamp789注意:signmethodパラメータを接合する必要はありません.
    contentをDeviceSecretを塩としてhmacsha 1にサインした後、16進文字列に変換し、最終結果:FAFD82A3D602B37FB0FA8B7892F24A477F851A14注意:base 64は必要ありません.
    最後に、生成されたパラメータをまとめます.
  • mqttHost = pk.iot-as-mqtt.cn-shanghai.aliyuncs.com
  • mqttPort = 1883
  • mqttClientId = 12345|securemode=3,signmethod=hmacsha1,timestamp=789|
  • mqttUsername = device&pk
  • mqttPassword = FAFD82A3D602B37FB0FA8B7892F24A477F851A14

  • パラメータの説明
    パラメータ
    説明
    ProductKey
    製品キー.iotスイートコンソールから取得
    DeviceName
    デバイス名.iotスイートコンソールから取得
    DeviceSecret
    パスワードを設定しiotスイートコンソールから取得
    signmethod
    アルゴリズムタイプ、hmacmd 5またはhmacsha 1
    clientId
    クライアントはidを自己表示し、macまたはsnを推奨する
    timestamp
    現在のミリ秒値(オプション)
    securemode
    現在のセキュリティモードは、オプション値が2(TLS直結モード)、3(TCP直結モード)
    サンプルコード
    自分のProductKeyClientIdDeviceNameDeviceSecret・.
    # coding=utf-8
    # !/usr/bin/python3
    
    import datetime
    import time
    import hmac
    import hashlib
    import math
    
    TEST = 0
    
    ProductKey = ""
    ClientId = "12345"  #    clientId
    DeviceName = ""
    DeviceSecret = ""
    
    # signmethod
    signmethod = "hmacsha1"
    # signmethod = "hmacmd5"
    
    #        
    us = math.modf(time.time())[0]
    ms = int(round(us * 1000))
    timestamp = str(ms)
    
    data = "".join(("clientId", ClientId, "deviceName", DeviceName,
                    "productKey", ProductKey, "timestamp", timestamp
                    ))
    # print(round((time.time() * 1000)))
    print("data:", data)
    
    if "hmacsha1" == signmethod:
        ret = hmac.new(bytes(DeviceSecret, encoding="utf-8"),
                       bytes(data, encoding="utf-8"),
                       hashlib.sha1).hexdigest()
    elif "hmacmd5" == signmethod:
        ret = hmac.new(bytes(DeviceSecret, encoding="utf-8"),
                       bytes(data, encoding="utf-8"),
                       hashlib.md5).hexdigest()
    else:
        raise ValueError
    
    sign = ret
    print("sign:", sign)
    
    # ======================================================
    
    strBroker = ProductKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com"
    port = 1883
    
    client_id = "".join((ClientId,
                         "|securemode=3",
                         ",signmethod=", signmethod,
                         ",timestamp=", timestamp,
                         "|"))
    username = "".join((DeviceName, "&", ProductKey))
    password = sign
    
    print("="*30)
    print("client_id:", client_id)
    print("username:", username)
    print("password:", password)
    print("="*30)
    
    def secret_test():
        DeviceSecret = "secret"
        data = "clientId12345deviceNamedeviceproductKeypktimestamp789"
        ret = hmac.new(bytes(DeviceSecret, encoding="utf-8"),
                       bytes(data, encoding="utf-8"),
                       hashlib.sha1).hexdigest()
        print("test:", ret)
    
    
    # ======================================================
    # MQTT Initialize.--------------------------------------
    
    try:
        import paho.mqtt.client as mqtt
    except ImportError:
        print("MQTT client not find. Please install as follow:")
        print("git clone http://git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.python.git")
        print("cd org.eclipse.paho.mqtt.python")
        print("sudo python setup.py install")
    
    
    # ======================================================
    def on_connect(mqttc, obj, rc):
        print("OnConnetc, rc: " + str(rc))
    
        mqttc.subscribe("test", 0)
    
    
    def on_publish(mqttc, obj, mid):
        print("OnPublish, mid: " + str(mid))
    
    
    def on_subscribe(mqttc, obj, mid, granted_qos):
        print("Subscribed: " + str(mid) + " " + str(granted_qos))
    
    
    def on_log(mqttc, obj, level, string):
        print("Log:" + string)
    
    
    def on_message(mqttc, obj, msg):
        curtime = datetime.datetime.now()
        strcurtime = curtime.strftime("%Y-%m-%d %H:%M:%S")
        print(strcurtime + ": " + msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
        on_exec(str(msg.payload))
    
    
    def on_exec(strcmd):
        print("Exec:", strcmd)
        strExec = strcmd
    
    
    # =====================================================
    if __name__ == '__main__':
        if TEST:
            secret_test()
            exit(0)
    
        mqttc = mqtt.Client(client_id)
        mqttc.username_pw_set(username, password)
        mqttc.on_message = on_message
        mqttc.on_connect = on_connect
        mqttc.on_publish = on_publish
        mqttc.on_subscribe = on_subscribe
        mqttc.on_log = on_log
    
        mqttc.connect(strBroker, port, 120)
        mqttc.loop_forever()
    

    参考資料
  • アリクラウドネットワークキット>デバイス側アクセスマニュアル>デバイスMQTTアクセスに基づく>デバイス認証
  • やっと前にどうしていつもつながっていないことを知っています!!!以前のドキュメントのpassword暗号化フィールドは「signmethodhmacsha 1」文字列が多くなりました!