django - 如何将 django 连接到 mqtt 代理?
问题描述
我需要使用 MQTT 协议将一些数据从 django wed 服务器发送到板(esp8266)。我在查找有关如何连接 django 和 mqtt-broker 的信息时遇到问题。我该如何实施?
解决方案
对于您的MQTT 代理,您可以选择使用云提供商或运行本地代理。云提供商包括:
- AWS IoT ( https://aws.amazon.com/iot-core/getting-started/ )
- 谷歌云物联网代理 ( https://cloud.google.com/iot/docs/quickstart )
这些服务有关于如何配置您的主板以与代理通信的分步指南,您可以使用 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()
推荐阅读
- cloud-sql-proxy - zsh 命令未找到 cloud_sql_proxy
- asp.net-core-webapi - 如何从 Blazor 服务器端登录 WebApi 并检索 cookie 并将其传递给应用程序?
- python - python NameError:名称'Z'未定义,但仅在某些执行中
- docker - 无法从 Azure Devops 将 docker 映像推送到 AzureContainer Registry
- maven - 没有 Spring Boot 的 Vaadin Flow 18/19?
- python - 使用 Selenium 验证表单输入停止几秒钟
- winapi - SetWindowsHookEx Hook into Explorer 拦截 Win32API 调用
- javascript - 向 redux 状态添加计数器
- c# - 加载带有部分响应的 DataGrid,同时仍在获取请求中下载
- sharepoint - 分享点 - 使用数据/报告