2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Summary:This article introduces the core concepts of IoT, cloud platform, MQTT, HTTP, data visualization, etc., and combines mainstream tools such as EMQX, Flask, InfluxDB, Grafana, etc. to teach you how to build an IoT cloud platform that supports multiple protocols. The article has a clear structure, rich pictures and texts, and detailed and easy-to-understand codes, aiming to help readers quickly master the core technologies of building an IoT cloud platform.
Key words:IoT, cloud platform, MQTT, HTTP, data visualization, EMQX, Flask, InfluxDB, Grafana
The Internet of Things (IoT) refers to the use of various information sensors, radio frequency identification technology, global positioning systems, etc. to collect real-time data on any object or process that needs to be monitored, connected, and interacted with, thereby achieving ubiquitous connection between objects and objects, and objects and people, and further realizing intelligent perception, identification, and management of objects and processes.
The IoT system architecture is usually divided into three layers:
Cloud platform refers to the increase, use and delivery model of Internet-based related services, which usually involves providing dynamic, scalable and often virtualized resources through the Internet. Cloud platform can provide powerful computing, storage and network resources for IoT applications, reducing the cost of IoT application development and deployment.
Data visualization refers to the display of data in visual forms such as graphics and charts to help users understand the data more intuitively and gain insight into the patterns and trends behind the data.
MQTT (Message Queuing Telemetry Transport) is a lightweight message publish/subscribe protocol designed for low-bandwidth, low-power devices and networks. MQTT is widely used in the field of Internet of Things, especially for resource-constrained devices and unreliable network environments.
HTTP (Hypertext Transfer Protocol) is an application layer protocol used to transfer information between web browsers and web servers. The HTTP protocol is simple and easy to use and is widely used in various network applications, including the field of Internet of Things.
EMQX is an open source, high-performance, and scalable MQTT message server that supports millions of concurrent connections and message throughput.
Flask is a lightweight web application framework written in Python. It is easy to learn and use and suitable for quickly building web applications and API interfaces.
InfluxDB is an open source time series database designed for storing and querying time series data. It is suitable for storing IoT sensor data, monitoring data, etc.
Grafana is an open source data visualization tool that can connect to multiple data sources to create beautiful and powerful dashboards to display data in real time.
This project will build an IoT cloud platform that supports MQTT and HTTP protocols to achieve the following functions:
1. HTTP server setup (Flask)
- # 导入 Flask 库
- from flask import Flask, request, jsonify
-
- # 创建 Flask 应用
- app = Flask(__name__)
-
- # 定义 HTTP 接口,接收 POST 请求
- @app.route('/data', methods=['POST'])
- def receive_data():
- # 获取请求数据
- data = request.get_json()
-
- # 数据处理逻辑,例如数据校验、格式转换等
- # ...
-
- # 将数据写入 InfluxDB (示例)
- from influxdb import InfluxDBClient
- client = InfluxDBClient('localhost', 8086, 'user', 'password', 'iot_data')
- json_body = [
- {
- "measurement": "sensor_data",
- "tags": {
- "sensor_id": data.get("sensor_id")
- },
- "fields": {
- "temperature": data.get("temperature"),
- "humidity": data.get("humidity")
- }
- }
- ]
- client.write_points(json_body)
-
- # 返回响应
- return jsonify({'message': 'Data received successfully!'}), 200
-
- # 启动 Flask 应用
- if __name__ == '__main__':
- app.run(debug=True)
Code Description:
Flask
The framework creates an HTTP server and defines/data
The interface receives POST requests.request.get_json()
Get the JSON data in the HTTP request.InfluxDBClient
Connect to the InfluxDB database and write data to the database.2. MQTT message processing (Python)
- # 导入必要的库
- import paho.mqtt.client as mqtt
- from influxdb import InfluxDBClient
- import json
-
- # MQTT Broker 配置
- MQTT_BROKER = "localhost"
- MQTT_PORT = 1883
- MQTT_TOPIC = "sensor/data"
-
- # InfluxDB 配置
- INFLUXDB_HOST = "localhost"
- INFLUXDB_PORT = 8086
- INFLUXDB_USER = "user"
- INFLUXDB_PASSWORD = "password"
- INFLUXDB_DATABASE = "iot_data"
-
- # 创建 InfluxDB 客户端
- influxdb_client = InfluxDBClient(
- host=INFLUXDB_HOST,
- port=INFLUXDB_PORT,
- username=INFLUXDB_USER,
- password=INFLUXDB_PASSWORD,
- database=INFLUXDB_DATABASE
- )
-
- # 连接到 MQTT Broker
- def on_connect(client, userdata, flags, rc):
- print("Connected to MQTT Broker with result code " + str(rc))
- client.subscribe(MQTT_TOPIC)
-
- # 接收 MQTT 消息
- def on_message(client, userdata, msg):
- # 解析数据
- data = json.loads(msg.payload.decode())
-
- # 构建 InfluxDB 数据点
- influxdb_data = [
- {
- "measurement": "sensor_data",
- "tags": {
- "sensor_id": data.get("sensor_id"),
- },
- "fields": {
- "temperature": data.get("temperature"),
- "humidity": data.get("humidity"),
- }
- }
- ]
-
- # 写入 InfluxDB
- influxdb_client.write_points(influxdb_data)
- print("Data written to InfluxDB: " + str(influxdb_data))
-
- # 创建 MQTT 客户端
- mqtt_client = mqtt.Client()
- mqtt_client.on_connect = on_connect
- mqtt_client.on_message = on_message
- mqtt_client.connect(MQTT_BROKER, MQTT_PORT, 60)
-
- # 启动 MQTT 客户端
- mqtt_client.loop_start()
-
- # 保持程序运行
- while True:
- pass
Code Description:
paho.mqtt.client
Connect to the MQTT Broker and subscribe to the specified topic.json.loads()
Parse the message content.influxdb_client.write_points()
Write data to the InfluxDB database.3. Data Visualization (Grafana)
Example Grafana query:
SELECT "temperature", "humidity" FROM "sensor_data" WHERE time > now() - 1h
The query will besensor_data
Query the temperature and humidity data of the last hour in measurement.
This project combines tools such as Flask, EMQX, InfluxDB and Grafana to build an IoT cloud platform that supports MQTT and HTTP protocols, and realizes data collection, storage and visualization. The platform can be flexibly expanded to support more types of devices and protocol access, and can be customized according to actual needs.
Notice:
paho-mqtt
,influxdb
,flask
wait.If you want specific codes and ideas, you can send me a private message! ! !