MQTT读取温湿度(WEB)
# FastWeb之MQTT-WebSocket读取温湿度
- 适用平台:WEB(桌面)
# 1. 说明
采用MQTT通讯协议,读取驳接在Arduino上的DHT22温湿度传感器的数据。MQTT是由IBM开发的通讯协议,为传感器提供一个轻量可靠的二进制通信设定,使得开发MQTT与物联网,机器之间的通信变得非常简单。
在网页端可以使用WebSocket实现对MQTT协议的连接以及消息的传输,该种传输方式不需要经过FastWeb所在服务器的中转,直接由MQTT Broker向网页客户端传输,与传统的MQTT传输相比响应速度更快,性能更好。在范例中Arduino开发板与Ethernet W5100网络扩展板,组装方式与前述章节相同。温湿度传感器DHT22,负极接Ethernet W5100扩展板的GND针脚,正极接扩展板5V针脚,信号线接扩展板D8针脚。DHT22的特性如下表所示。
名称 | 取值 |
---|---|
工作电压 | 3V–5.5V |
温度测量范围 | -40℃–80℃ |
温度测量精度 | 0.5℃ |
湿度测量范围 | 0–100% RH |
湿度测量精度 | 2% RH |
通过本范例学习,可以掌握UgMQTTws控件的基本使用,并结合arduino开发板通过MQTT进行温湿度采集。
Arduino开发板与Ethernet W5100网络扩展板的连接方式如下图所示。

# 2. 零件连接图

# 3. 使用零件
序 | 零件名称 | 数量 |
---|---|---|
1 | Arduino UNO R3 开发板 | 1 |
2 | Arduino Ethernet W5100 网络扩展板 | 1 |
3 | DHT22温湿度 模块 | 1 |
4 | USB数据线 | 1 |
5 | 面包板 | 1 |
6 | 杜邦线 | 3 |
# 4. Arduino流程图

# 5. Arduino程序
使用Arduino IDE 编译并上传以下Arduino程序。
// pubsubclient MQTT 链接库网址 https://github.com/knolleary/pubsubclient
// 使用温湿度传感器之链接库 https://github.com/adafruit/DHT-sensor-library
#include <DHT.h>
#define dhtPin 8 //读取DHT22 Data
#define dhtType DHT22 //选用DHT22
DHT dht(dhtPin, dhtType); // Initialize DHT sensor
#include <SPI.h>
#include <Ethernet.h>
// MQTT 宣告 ========================================================
#include <PubSubClient.h>
EthernetClient ethClient;
PubSubClient client(ethClient);
// 设置网络IP地址 (网络扩充卡 MAC 可自行修改 +1 避免冲突)
byte mac[] = {0x90, 0xA2, 0xDA, 0x0E, 0x94, 0xB9 };
IPAddress ip(192, 168, 0, 165);
IPAddress gateway(192, 168, 0, 1);
IPAddress subnet(255, 255, 255, 0);
void setup() {
Serial.begin(9600); //设定鲍率9600
dht.begin(); //启动DHT
//设置 MQTT ========================================================
client.setServer("192.168.0.113", 1883); // 连接 MQTT Broker
client.setCallback(subscribeReceive); // 设置从 MQTT Broker读取主题之后,自动运行之副程序
Ethernet.begin(mac, ip, gateway, subnet); // 启动网络
Serial.println("网络已经开通");
delay(1500);
}
void loop() {
float h = dht.readHumidity(); //读取湿度
float t = dht.readTemperature(); //读取摄氏温度
if (isnan(h) || isnan(t)) {
Serial.println(" 无法从DHT传感器读取!");
return;
}
if (!client.connected()) { // 如果未联机 MQTT Broker 将重新联机
reconnect();
}
client.loop();
// MQTT 开始运作发送主题 传送温湿度到 MQTT Broker
char tmp[20];
char hum[20];
dtostrf(t,3,2,tmp); // 将Float 转换为 char[]
dtostrf(h,3,2,hum);
Serial.println(tmp);
Serial.println(hum);
// MQTT 发送主题(温湿度) =================
client.publish("TMP", tmp);
client.publish("HUM", hum);
delay(5000);
}
void reconnect() {
// 一直循环直到连上 MQTT Broker
while (!client.connected()) {
Serial.print("正在连接 MQTT Broker...");
if (client.connect("arduinoClientMQTTDHT","username","password")) {
Serial.println("MQTT Broker 已经连接上");
client.subscribe("TMP");
client.subscribe("HUM");
} else {
Serial.print("联机失败, rc=");
Serial.print(client.state());
Serial.println("五秒钟之后再联机");
delay(5000);
}
}
}
void subscribeReceive(char* topic, byte* payload, unsigned int length)
{
// Print the topic
Serial.print("Topic: ");
Serial.println(topic);
// Print the message
Serial.print("Message: ");
for(int i = 0; i < length; i ++)
{
Serial.print(char(payload[i]));
}
// Print a newline
Serial.println("");
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# 6. 设计明细
开启FastWeb设计器,分别加入下插图之控件。或者通过点击[导入]
按钮选择模板文件来打开模板。

①:TUgImage组件,控件名称为UgImage01
。
②:TUgSwitchImage组件,控件名称为ugSwitchImage01
。
③:TUgLabel组件,控件名称为UgLabel05
。
④:TUgLabel组件,控件名称为UgLabel06
。
fxRunFrame属性设置
Height
:设置页面高度=800
。Width
:设置页面宽度=400
。
UgWebRunFrame属性设置
Height
:设置窗体高度=360
。Width
:设置窗体宽度=480
。
UgMQTTws01属性设置
Visible
:设置控件是否可见。设置为False
。MQTTOptions
:设置MQTT选项。CleanSession
:设置为True
。ClientID
:设置客户端ID号,与已连接的客户端ID不能重复。HostName
:设置MQTT Broker的地址。Password
:设置MQTT Broker的账号密码。Port
:设置WebSocket服务的端口号,默认为9001
。Topic
:设置MQTT的主题,启动时自动订阅该主题。UserName
:设置MQTT Broker的连接用户名。
①UgImage01属性设置
Align
:设置对齐方式=alClient
。Stretch
:设置画面拉伸=True
。Picture
:设置图像(背景)。点击Picture
属性右侧的[√]
,打开图像编辑器,点击[Load]
按钮打开文件上传界面,点击右侧的[Browse...]
打开图像浏览界面,选择图像后,点击[确定]
按钮返回到文件上传界面,点击[Upload]
将文件上传至编辑器中,待图片显示后,点击[Save]
按钮即可。
②ugSwitchImage01属性设置
Height
:设置控件高度=128
。Width
:设置控件宽度=128
。- 双击该控件打开图片编辑界面。点击添加按钮打开文件上传界面。点击
[Load]
按钮打开文件上传界面,点击右侧的[Browse...]
打开图像浏览界面,选择图像后,点击[确定]
按钮返回到文件上传界面,点击[Upload]
将文件上传至编辑器中,待图片显示后,点击[Save]
按钮即可。
③UgLabel05属性设置
Caption
:设置标签字幕内容=℃
。Font.Color
:设置字幕的颜色=clWhite
。Font.Size
:设置字幕的大小=24
。Font.Style.fsBold
:设置字体加粗=True
。
④UgLabel06属性设置
Caption
:设置标签字幕内容=%RH
。Font.Color
:设置字幕的颜色=clWhite
。Font.Size
:设置字幕的大小=24
。Font.Style.fsBold
:设置字体加粗=True
。
# 7. 程序设计
# 7.1. 程序初始设置
该程式无程序初始设置。
# 7.2. 事件设置
- UgMQTTws01-OnMessage事件
当接收到订阅信息时,显示内容。
//JScript
function ugMQTTws01OnMessage(atopic,apayload)
{
if (atopic == "TMP")
{
UgLabel05.Caption = apayload + "℃";
}
else if (atopic == "HUM")
{
UgLabel06.Caption = apayload + "%RH";
}
}
2
3
4
5
6
7
8
9
10
11
12
//PasScript
procedure ugMQTTws01OnMessage(const atopic: string;apayload: string);
begin
if atopic = 'TMP' Then
begin
UgLabel05.Caption := apayload + '℃';
end
else if atopic = 'HUM' Then
Begin
UgLabel06.Caption := apayload + '%RH';
End;
end;
2
3
4
5
6
7
8
9
10
11
12
// Make sure to add code blocks to your code group
- ②ugSwitchImage01-OnSwitch事件
点击以开启/关闭温湿度订阅。
//JScript
function ugSwitchImage01OnSwitch(sender)
//开启、关闭计数器
{
if (ugSwitchImage01.IsChecked){
ugMQTTws01.Subscribe("HUM");
ugMQTTws01.Subscribe("TMP");
}
else{
ugMQTTws01.Unsubscribe("HUM");
ugMQTTws01.Subscribe("TMP");
UgLabel05.Caption = "0.0℃";
UgLabel06.Caption = "0.0%RH";
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//PasScript
procedure ugSwitchImage01OnSwitch(sender: tobject);
//开启、关闭计数器
begin
if ugSwitchImage01.IsChecked Then
Begin
ugMQTTws01.Subscribe('HUM');
ugMQTTws01.Subscribe('TMP');
End
else If ugSwitchImage01.IsChecked = False Then
Begin
ugMQTTws01.Unsubscribe('HUM');
ugMQTTws01.Subscribe('TMP');
UgLabel05.Caption := '0.0℃';
UgLabel06.Caption := '0.0%RH';
End;
end;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Make sure to add code blocks to your code group
# 8. 运行结果
使用鼠标点击工具栏保存到数据库,然后点击运行(Run),测试运行结果。将图中的拨杆拨向“开”,数值显示屏中的温湿度数据每隔五秒更新一次。
