本文重點是JavaScript實現的MQTT,智能門鎖是基於此的擴展應用demo。
簡介
JavaScript實現的MQTT Demo,可通過Hbuilder IDE進行App打包,也可直接部署到Web服務器上。
Demo內容是以MQTT實現的智能門鎖應用,包括基礎的訂閱、發佈功能。
APP端如下圖所示:
硬件端爲集藍牙與WiFi與一體的物聯網開發板ESP32,如下圖所示:
將SG90舵機與ESP32的IO腳相連,通過控制舵機的轉動,帶動門把手的轉動。
還可引入LED燈,作爲工作狀態的指示:
正文
其中MQTT庫使用的是mqttws31。
Eclipse Paho項目提供了MQTT和MQTT-SN消息傳遞協議的開源客戶端實現,這些實現針對物聯網(IoT)的新的,現有的和新興的應用程序。
HTML與CSS部分不講解,直接上JavaScript部分。
<script>
var hostname = 'api.easylink.io',
port = 1983,
clientId = 'client-' + Math.ceil(Math.random() * 1000),
timeout = 5,
keepAlive = 100,
cleanSession = false,
ssl = false,
client,
topic_send = 'CMD',
topic_sub = 'CALLBACK',
s = "";
$(document).ready(function(){
$(".host").val("api.easylink.io:1983");
$(".subTop").val('CALLBACK');
$(".sendTop").val('CMD');
});
function onFailure() {
console.log(e);
}
//連接服務器並註冊連接成功處理事件
function onConnect() {
innerHTMl(">> 連接成功!");
client.subscribe(topic_sub);
}
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:" + responseObject.errorMessage);
innerHTMl(">> 連接出錯!");
}else{
innerHTMl(">> 結束連接!");
}
}
//消息接收處理
function onMessageArrived(message) {
innerHTMl(">> 收到消息:" + message.payloadString);
}
function getSubTopic(){
if($(".subTop").val()){
return $(".subTop").val();
}else{
innerHTMl(">> 請輸入訂閱主題");
return null;
}
}
function btnConnect(){
if($(".host").val()){
var temp = $(".host").val().split(":");
hostname = temp[0];
port = Number(temp[1]);
innerHTMl(">> 使用自定義BROKER: "+temp)
}else{
innerHTMl(">>使用默認BROKER: "+hostname)
}
if($(".subTop").val()){
topic_sub = $(".subTop").val();
innerHTMl(">> 自定義訂閱主題: "+topic_sub)
}
if($(".sendTop").val()){
topic_send = $(".sendTop").val();
innerHTMl(">> 自定義發佈主題: "+topic_sub)
}
client = new Paho.MQTT.Client(hostname, port, clientId)
//建立客戶端實例
var options = {
invocationContext: {
host: hostname,
port: port,
path: client.path,
clientId: clientId
},
timeout: timeout,
keepAliveInterval: keepAlive,
cleanSession: cleanSession,
useSSL: ssl,
onSuccess: onConnect,
onFailure: onFailure,
};
//註冊連接斷開處理事件
client.onConnectionLost = onConnectionLost;
//註冊消息接收處理事件
client.onMessageArrived = onMessageArrived;
client.connect(options);
}
function btnEnd() {
if(client.isConnected){
client.disconnect();
}else{
//console.log(">> 當前未連接!");
innerHTMl(">> 當前未連接!");
}
}
function btnOpen() {
message = new Paho.MQTT.Message("Open");
message.destinationName = topic_send;
client.send(message);
innerHTMl(">> 已發送!");
}
function btnSub(){
if($(".subTop").val()){
client.subscribe($(".subTop").val());
innerHTMl(">> 已訂閱!");
}else{
innerHTMl(">> 請先輸入訂閱主題!");
}
}
function btnSend(){
if($(".sendMsg").val()){
if($(".sendTop").val()){
message = new Paho.MQTT.Message($(".sendMsg").val());
message.destinationName = $(".sendTop").val();
client.send(message);
innerHTMl(">> 已發送!");
}else{
innerHTMl(">> 請先輸入訂閱主題!");
}
}else{
innerHTMl(">> 請先輸入發佈內容!");
}
}
///////////////////////////////////////////////////////////////////////////
//刪除當前數據
function btnClear(){
$(".msgBox").remove()
}
//渲染html
function innerHTMl(msg) {
let str =
`<div class='msgBox'>
<div class='msgTxt'>
[${new Date().Format("yyyy-MM-dd hh:mm:ss")}] ${msg}
</div>
</div>`
$(".msgCon").append(str);
}
</script>
最終完成後,可以使用Hbuilder IDE免費打包爲手機端APP:
附錄
項目已開源:
https://github.com/1061700625/JavaScript_MQTT