首页 > 解决方案 > 如何将 django 连接到 mqtt 代理?

问题描述

我需要使用 MQTT 协议将一些数据从 django wed 服务器发送到板(esp8266)。我在查找有关如何连接 django 和 mqtt-broker 的信息时遇到问题。我该如何实施?

标签: djangomqtt

解决方案


对于您的MQTT 代理,您可以选择使用云提供商或运行本地代理。云提供商包括:

这些服务有关于如何配置您的主板以与代理通信的分步指南,您可以使用 Web 控制台测试这种通信。大多数云提供商都有免费套餐,因此您可以免费测试服务。

如果您更喜欢运营本地代理,Mosquitto ( https://mosquitto.org/ ) 是一个非常好的选择,在线提供大量文档和教程。这里还有一个测试服务器:https ://test.mosquitto.org/

为了让您的django 应用程序与开发板通信,您需要运行 MQTT 客户端,例如 paho-mqtt ( https://pypi.org/project/paho-mqtt/ )。以下是 paho-mqtt 文档中有关如何使用客户端的示例:

import paho.mqtt.client as mqtt

# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe("$SYS/#")

# The callback for when a PUBLISH message is received from the server.
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.connect("mqtt.eclipse.org", 1883, 60)

# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()

推荐阅读