diss带码

diss带码

马上订阅 diss带码 RSS 更新: https://dumplingbao.github.io/atom.xml

小程序:mqtt+webview控制显示内容

2021年7月22日 23:48

看到mqtt+webview似乎不知道能做什么,mqtt微消息服务更适用iot物联网,这个应该熟悉,但是似乎还是得从webview说起。webview的场景不仅仅是手机端的APP或者小程序用到,好多基于android主板显示的设备、大屏等webview都发挥了很大的作用。这里我们一是验证小程序的mqtt,二是通过mqtt控制设备自动切换显示内容,这样试想一下,其实就是远程操控设备显示内容的一种很好的方式。

效果

01

mqtt小程序端

需要mqtt.js客户端库:https://github.com/mqttjs/MQTT.js

小程序配置:

1
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
const app = getApp()
var mqtt = require('../../../utils/mqtt.min')
var client = null

Page({

/**
* 页面的初始数据
*/
data: {
webUrl: 'https://www.baidu.com'
},

/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.connnectMqtt()
},

connnectMqtt: function (){
var that = this
const options = {
connectTimeout: 4000, // 超时时间
clientId: 'mqtt_' + Math.random().toString(16).substr(2, 8),
port: 8083, //重点注意这个坑
}

client = mqtt.connect("wx://xx.xx.xx.xx/mqtt", options);
client.on('reconnect', (error) => {
console.log('正在重连:', error)
})

client.on('error', (error) => {
console.log('连接失败:', error)
})
client.on('connect', (e) => {
console.log('成功连接服务器')
       //订阅一个主题
client.subscribe('test', {
qos: 0
}, function(err) {
if (!err) {
console.log("订阅成功")
}
})
})
client.on('message', function (topic, message) {
console.log('received msg:' + message.toString());
that.setData({
webUrl: message.toString()
})
console.log(that.data.webUrl)
})
}
})
1
<web-view src="{{webUrl}}" bindmessage="getmessage"></web-view>

mqtt服务端安装

EMQ X 是一款完全开源,高度可伸缩,高可用的分布式 MQTT 消息服务器

git地址:https://gitee.com/emqx/emqx

docker安装步骤

1
$ docker search emqx // 查看版本
1
$ docker pull emqx/emqx // 拉取镜像...

剩余内容已隐藏

查看完整文章以阅读更多