Python MQTT connection to Azure Iot Hub

2019-01-27 05:51发布

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 mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("$SYS/#")

def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.username_pw_set("myHub.azure-devices.net/device1", "mySASToken")

client.connect("myHub.azure-devices.net", 1883, 60)

client.loop_forever()

But after running for a while, this exception is thrown:

TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

Does somebody know why I can't connect to the Iot Hub?

4条回答
Explosion°爆炸
2楼-- · 2019-01-27 06:31

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/<YOUR DEVICE ID>/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/<YOUR DEVICE ID>/messages/events", "REPLY", qos=1)


def on_publish(client, userdata, mid):
    print "Sent message"


client = mqtt.Client(cleint_id=<YOUR DEVICE 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="<YOUR NAMESPACE>.azure-devices.net/<YOUR DEVICE ID>",
                       password="<YOUR SHARED ACCESS SIGNATURE FOR THE DEVICE>")
client.tls_insecure_set(True) # You can also set the proper certificate using client.tls_set()
client.connect("<YOUR NAMESPACE>.azure-devices.net", port=8883)
client.loop_forever()
查看更多
狗以群分
3楼-- · 2019-01-27 06:37

As @FarukCelik said, there was no Azure IoT SDK for Python.

However, per my experience, I think there are four practicable ways using the existing SDK for Azure IoTHub in Python.

  1. Using Azure IoT SDK for C to extending Python, you can try to refer to https://docs.python.org/2/extending/extending.html to implement it.
  2. Using Azure IoT SDK for Java as Jython package imported, you can try to refer to http://www.jython.org/jythonbook/en/1.0/JythonAndJavaIntegration.html to know how to do it.
  3. The similar to the second way, integrating IronPython with Azure IoT SDK for C#/.Net, please refer to http://ironpython.net/documentation/dotnet/.
  4. The Azure IoT SDK for NodeJS support MQTT via the same Eclipse project Paho for JavaScript Client, so I think you can try to refer to the source code of Azure NodeJS IoT SDK on GitHub to know how to correctly using paho Python client for Azure IoTHub.

Meanwhile, there is a unoffical Python library for Azure IoTHub Device on GitHub https://github.com/bechynsky/AzureIoTDeviceClientPY. That you can concern about this project repository, but it's still on the deveploment stage by now.

Hope it helps. Best Regards.

查看更多
Luminary・发光体
5楼-- · 2019-01-27 06:44

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)
查看更多
登录 后发表回答