当前位置: 移动技术网 > IT编程>开发语言>Java > MQTT进阶篇

MQTT进阶篇

2019年05月11日  | 移动技术网IT编程  | 我要评论
        我们介绍了最流行的物联网协议mqtt的背景以及基本使用方法。在这篇文章中,我们会继续考察mqtt的高级玩法——与网页应用的交互。mqtt是基于tcp协议实现,基于http的网页应用便无法与之交互了。为了解决这个问题,许多mqtt代理加上了对websockets的支持,可以方便地实现如下场景:
  • 显示设备的实时信息
  • 接收报警等推送信息
  • 查看设备的历史消息
目前ubuntu 14.04.1 lts自带的mosquitto版本比较低,所以我们将使用ppa上的新版本:
1
2
3
4
apt-add-repository ppa:mosquitto-dev/mosquitto-ppa
apt-get update
apt-get install mosquitto
apt-get install mosquitto-clients
以下实验是基于已经支持websockets的1.4.5版本的mosquitto。打开websockets很简单,只需要在/etc/mosquitto/mosquitto.conf中添加:
1
2
listener 8001
protocol websockets
指定以上配置文件重启mosquitto服务之后,便可以通过任意mqtt over websockets的界面,比如hivemq websockets client showcase或者mqtt client sample来把玩了:

 

浏览器其实是以websockets协议与mqtt代理交互的,不但可以完成mosquitto_pub和mosquitto_sub的功能,还可以结合html5的特性完成很多有意思的场景。下面我们就来实现温度感知器的图形界面。
下面是网页应用的源代码,其中用到了paho javascript client实现了mqtt over websockets:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!doctype html>
<html>
<head>
<title>start page</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<script src="mqttws31.js"></script>
</head>
<body>
<label>当前温度</label>
<meter max="100" low="60" high="80" value="30" id="meter"></meter>
 
<script>
var client = new paho.mqtt.client("host", 8001, "clientid");
 
client.onmessagearrived = function (msg) {
document.queryselector("#meter").value = msg.payloadstring;
};
 
client.connect({
onsuccess: function () {
client.subscribe("floor-5/temperature");
}
});
</script>
</body>
</html>
代码非常直观,在连接到mqtt代理之后便订阅五楼温度的主题。当后台感知器发送温度信息后,比如用中提到的命令模拟:
1
mosquitto_pub -d -q 2 -t 'floor-5/temperature' -m '95'
 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网