构建实用的 IoT 应用程序 - 一个空气质量监视器(2)
 
- UID
- 1066743
|

构建实用的 IoT 应用程序 - 一个空气质量监视器(2)
第 3 步:将 IoT 设备连接到 Watson IoT Platform在中,介绍了如何在 Watson IoT Platform 上设置 MQTT 项目。请按照那篇文章中的说明,用您的 Bluemix 帐户设置一个 MQTT 项目,并创建您的设备的授权凭证。
在设备端,必须首先确保 NodeMCU 固件是使用 MQTT 支持模块构建的。请按照中的说明进行操作。
在 init.lua 应用程序中,首先将从 Watson IoT Platform 创建的设备 ID 和访问令牌分配给此设备。必须针对每个设备自定义此代码段。所以,对于涉及许多设备的大型项目,需要一个自动化代码生成和部署工具(一个 devops 解决方案)。
-- 1.Setup the device ID and access credential.
-- Device ID.It is a random string for each device.
-- But, it should match the device ID set up on Watson IoTP.
device_id = "random_string"
-- The access token Watson IoTP assigned for the device.
access_token = "assigned_by_Watson"
|
接下来,在建立 WiFi 网络连接后,该设备应连接到 MQTT 服务。这是第二个占位符。使用下面的代码段更新 init.lua 应用程序,我在该代码段中还创建了一条“last will”消息,以便在设备断开网络时 MQTT 服务能保留一条记录。
-- 2.Connect to the MQTT service.
-- Init MQTT client with keepalive timer 120s
m = mqtt.Client(device_id, 120, "use-token-auth", access_token)
-- setup Last Will and Testament (optional)
-- Broker will publish a message "offline" to topic "dw/lwt"
-- if client doesn't send keepalive packet
m:lwt("dw/lwt", "offline", 0, 0)
|
第 4 步:将数据发送到 Watson IoT Platform 并分析数据设备建立连接后,可以向 MQTT 服务发送消息。在本例中,更新 init.lua 应用程序中的第三个占位符,使其将测量的值发送到某个主题。在此设置中,有一个聚合所有传感器读数的共享主题。然后 Watson IoT Platform 可以通过设备 ID 区分每个传感器设备的数据点。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| -- 3.Send data to the MQTT server.
m:connect("host.iotp.mqtt.bluemix.com", 1883, 0,
function(client)
print("connected")
-- subscribe topic with QoS = 0
client:subscribe("dw/air", 0, function(client)
print("subscribe success")
end)
-- publish a message with QoS = 0, retain = 0
client:publish("dw/air", pm25, 0, 0, function(client)
print("sent")
end)
end,
function(client, reason)
print("failed reason: " .. reason)
end
)
m:close();
|
将数据发送到 Watson IoT Platform 服务器后,可以根据需要来可视化和处理数据。此外,MQTT 协议的一个关键特性是,它允许代理(服务器)向设备回发消息,以便潜在控制设备的行为。例如,我们应在服务器上设置一个所有设备都订阅的特殊主题。然后服务器可以向该主题发出一条消息,以控制单个设备的采样频率。该消息需要以设备 ID 开头,后跟一个空格,并以一个整数结尾,该整数指定了设备对空气质量数据进行采样的间隔(在我们的代码示例中,目前将它设置为 10 分钟)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| -- In the m:connect loop
client:subscribe("dw/control", 0)
-- ......
m n("message", function(client, topic, data)
if topic == "dw/control" then
print(data)
t = {}
for k, v in string.gmatch(data, "[^%s]+") do
t[k] = v
end
if t[0] == device_id then
-- Change the main loop interval to t[1]
end
end)
|
通过创造性地使用 MQTT 主题,我们甚至可以设计传感器设备来相互通信。可在中了解相关内容。
结束语在本文中,讨论了如何使用 NodeMCU 硬件开发板和开发工具包构建一个 IoT 空气质量传感器,然后将该设备连接到 IBM Watson IoT Platform 的 MQTT 服务。可选的 MQTT 支持模块对 NodeMCU 平台上的 IoT 设备非常有用。IBM Watson IoT Platform 提供了一个易于使用的托管服务,用于聚合和管理来自启用了 MQTT 的 IoT 设备的数据。 |
|
|
|
|
|