Python MQTT connection to Azure Iot Hub

后端 未结 4 707
粉色の甜心
粉色の甜心 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:33

    There is now an official Python SDK to connect devices to Azure IoT Hub: https://github.com/Azure/azure-iot-sdks/tree/master/python/device

    This sample demonstrates how to connect using the MQTT protocol.

    Basically, here's how it works:

    1. create a device client and specifies MQTT for the protocol
    2. set the callback that will be called when a message is received
    3. use send_event_async to send messages to your Azure IoT Hub instance.
    from iothub_client import *
    
    def send_confirmation_callback(message, result, userContext):
        print "Confirmation[%d] received for message with result = %s" % (userContext, result)
    
    def receive_message_callback(message, counter):
        buffer = message.get_bytearray()
        size = len(buffer)
        print "Received Message"
        print "    Data: <<<%s>>> & Size=%d" % (buffer[:size], size)
        return IoTHubMessageDispositionResult.ACCEPTED
    
    iotHubClient = IoTHubClient(connectionString, IoTHubTransportProvider.MQTT)
    iotHubClient.set_message_callback(receive_message_callback, 0)
    iotHubClient.send_event_async(message, send_confirmation_callback, 0)
    

提交回复
热议问题