Middleware: Front-end JS integrates MQTT communication

MQTT official front-end call example: https://github.com/moscajs/mosca/wiki/MQTT-over-Websockets

MQTT-NPM:mqtt - npm

MQTT information reference: MQTT learning record (1, Windows)

HTML MQTT DHT11 use record reference:

HTML Echarts graphic statistics display DHT11 temperature in real time (4)

HTML Echarts graphic statistics display DHT11 temperature in real time (3)

HTML Echarts graphic statistics display DHT11 temperature in real time (2)

HTML Echarts graphic statistics display DHT11 temperature in real time (1)

1. EMQX server construction

 And environment reference: Middleware: SpringBoot-JAVA integrates MQTT communication_I don't know blog-CSDN blog

2. The front end refers to mqtt.min.js for direct MQTT communication

<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
<script>
var options = {
	//mqtt客户端的id,这里面应该还可以加上其他参数,具体看官方文档
	clientId: 'esp8266-client'
}
//console.log(options.clientId);
//浏览器采用websocket协议,host主机地址为127.0.0.1,端口为8083,路径为/mqtt
var client = mqtt.connect("ws://127.0.0.1:8083/mqtt",options) // you add a ws:// url here

//建立连接
client.on('connect', function () {
	console.log("connect success!")
	//订阅主题名称 publishTopic
	client.subscribe('publishTopic', function (err) {
		if (!err) {
			console.log("订阅成功!")
			//发布主题名称subscribeTopic,消息内容为Hello mqtt
			client.publish('subscribeTopic', 'Hello mqtt')
		}else{
			//打印错误
			console.log(err)
		}
	})
})

//如果连接错误,打印错误
client.on('error', function (err) {
	console.log(err)
	client.end()
})

//如果client订阅主题成功,那么这里就是当接收到自己订阅主题的处理逻辑
client.on('message', function (topic, message) {
	// message is Buffer,此处就是打印消息的具体内容
	console.log('json-> ' + message.toString());
	var jsonMsg = JSON.parse(message);
	console.log('temperature-> ' + jsonMsg.temperature);
})

</script>

Guess you like

Origin blog.csdn.net/chenyang_wei/article/details/128446022