Python MQTT connection to Azure Iot Hub

后端 未结 4 708
粉色の甜心
粉色の甜心 2020-12-20 06:55

I want to connect to Azure Iot Hub, with Python MQTT.

An username and SAS token is required by Iot Hub. This is my code:

import paho.mqtt.client as m         


        
4条回答
  •  悲哀的现实
    2020-12-20 07:49

    Here is how to use paho (mosquitto) to connect to the Azure IoT Hub over standard MQTT:

    from paho.mqtt import client as mqtt
    
    
    def on_connect(client, userdata, flags, rc):
        print "Connected with result code: %s" % rc
        client.subscribe("devices//messages/devicebound/#")
    
    
    def on_disconnect(client, userdata, rc):
        print "Disconnected with result code: %s" % rc
    
    
    def on_message(client, userdata, msg):
        print " - ".join((msg.topic, str(msg.payload)))
        # Do this only if you want to send a reply message every time you receive one
        client.publish("devices//messages/events", "REPLY", qos=1)
    
    
    def on_publish(client, userdata, mid):
        print "Sent message"
    
    
    client = mqtt.Client(cleint_id=, protocol=mqtt.MQTTv311)
    client.on_connect = on_connect
    client.on_disconnect = on_disconnect
    client.on_message = on_message
    client.on_publish = on_publish
    client.username_pw_set(username=".azure-devices.net/",
                           password="")
    client.tls_insecure_set(True) # You can also set the proper certificate using client.tls_set()
    client.connect(".azure-devices.net", port=8883)
    client.loop_forever()
    

提交回复
热议问题