uniapp 連接mqtt

1:下載插件

npm install mqtt
2:創建 mqtt.js
/* main.js 項目主入口注入實例 */
// import mqttTool from './lib/mqttTool.js'
// Vue.prototype.$mqttTool = mqttTool/* 使用范例見 /pages/index/index.vue */
// mqtt協議:H5使用ws/wss APP-PLUS使用wx/wxsvar mqtt = require('mqtt/dist/mqtt.js')let mqttTool = {client: null
}mqttTool.connect = function(params){let options = {clientId: params.clientId,username: params.username,password: params.password,clean: params.clean,connectTimeout: 600000, cleanSession: false}let client = mqtt.connect(params.url, options);mqttTool.client = clientreturn client;
}mqttTool.end = function(){return new Promise((resolve, reject) => {if(mqttTool.client == null){resolve('未連接')console.log('App_text' + ":end 未連接")return;}mqttTool.client.end()mqttTool.client = nullresolve('連接終止')})
}mqttTool.reconnect = function(){return new Promise((resolve, reject) => {if(mqttTool.client == null){resolve('未連接')console.log('App_text' + ":reconnect 未連接")return;}mqttTool.client.reconnect()})
}mqttTool.subscribe = function(params){return new Promise((resolve, reject) => {if(mqttTool.client == null){resolve('未連接')console.log('App_text' + ":unconnect 未連接")return;}mqttTool.client.subscribe(params.topic, {qos:params.qos}, function(err,res) {console.log(err,res)if (!err && res.length>0) {resolve('訂閱成功')console.log('App_text' + ":subscribe success 訂閱成功")}else{resolve('訂閱失敗')console.log('App_text' + ":subscribe failed 訂閱失敗")return;} })  })
}mqttTool.unsubscribe = function(params){return new Promise((resolve, reject) => {if(mqttTool.client == null){resolve('未連接')console.log('App_text' + ":unconnect 未連接")return;}mqttTool.client.unsubscribe(params.topic, function(err) {if (!err) {resolve('取消訂閱成功')console.log('App_text' + ":unsubscribe success 取消訂閱成功")}else{resolve('取消訂閱失敗')console.log('App_text' + ":unsubscribe failed 取消訂閱失敗")return;} })  })
}mqttTool.publish = function(params){return new Promise((resolve, reject) => {if(mqttTool.client == null){resolve('未連接')console.log('App_text' + ":unconnect 未連接")return;}mqttTool.client.publish(params.topic, params.message, function(err){if (!err) {resolve(params.topic + '-' + params.message + '-發送成功')console.log('App_text' + ":publish success 發送成功")}else{resolve(params.topic + '-' + params.message + '-發送失敗')console.log('App_text' + ":publish failed 發送失敗")return;} })})
}export default mqttTool

3:創建mqtt.vue 并引入mqtt.js

<template><view class="mqtt"><u-navbar title='MQTT調試' autoBack bgColor="#fff" placeholder></u-navbar><view class="options"><view class="info"><view class="bar"><text class="label">clientId:</text><input v-model="connectInfo.clientId" class="value" style="width:70%" :adjust-position="false" placeholder=""/></view><view class="flex-between"><view class="bar"><text class="label">username:</text><input v-model="connectInfo.username" class="value" :adjust-position="false" placeholder=""/></view><view class="bar" style="margin-left:4px;"><text class="label">password:</text><input v-model="connectInfo.password" class="value" :adjust-position="false" placeholder=""/></view></view><view class="flex-between"><view class="btn" @click="startConnect">連接</view><view class="btn" @click="endConnect">終止</view><view class="btn" @click="reConnect">重新連接</view></view><view class="flex-between"><view class="bar" style="width:40%;"><text class="label">topic</text><input v-model="subscribeInfo.topic" class="value" :adjust-position="false" placeholder=""/></view><view class="bar" @click="changeQos"><text class="label">qos</text><text class="value">{{subscribeInfo.qos}}</text></view><view class="bar" @click="connectInfo.clean = !connectInfo.clean"><text class="label">clean</text><text class="value">{{connectInfo.clean}}</text></view></view><view class="flex-row"><view class="btn" @click="startSubscribe">訂閱</view><view class="btn" style="margin-left:6px;" @click="endSubscribe">取消訂閱</view></view><view class="tips"><text class="tips-lab">操作日志:</text><text class="tips-reset" @click="clearConfig">清空配置</text><text class="tips-buffer" :style="isBuffer?'':'opacity:0.5'" @click="isBuffer=!isBuffer">打印Buffer</text><text class="tips-clear" @click="cealrLog">清空日志</text></view></view></view><scroll-view class="logs" scroll-y><view class="logs-list" v-for="(item,index) in logs" :key="index">{{item.option + item.log}}</view></scroll-view><view class="feet" :style="'bottom:' + (isSending?sendInfo.keyboard:0) + 'px;'"><view class="inpbar"><input v-model="sendInfo.msg" @focus="focusSend(true)" @blur="focusSend(false)" :adjust-position="false" :cursor-spacing="12" class="inp" type="text" placeholder="請輸入內容" placeholder-style="color:#cccccc;"/><view v-if="sendInfo.msg==''" class="send send-dark">發送q</view><view v-else @click="publish()" class="send">發送</view></view></view></view>
</template><script>export default{data(){return{/* 連接信息 */connectInfo: {clientId: '隨機客戶id',username: '你的用戶名',password: '用戶密碼',clean: false},/* 訂閱信息 */subscribeInfo: {topic: '你訂閱的topic',qos: 1},/* 日志信息 */isBuffer: false,logs: [{option:'環境配置:', log:'配置成功'},],/* 發送信息 */isSending: false,sendInfo: {msg: '',keyboard: 0}}},computed:{/* system */systemInfo(){return uni.getSystemInfoSync()},},onLoad(){/* 即時通訊類鍵盤元素高度處理 */uni.onKeyboardHeightChange(res => {this.sendInfo.keyboard = res.height})},onUnload(){uni.offKeyboardHeightChange();},methods:{/* 連接 */startConnect(){var _this = thislet opts = {url: 'wx://你的服務器域名:8083/mqtt',clientId: this.connectInfo.clientId,username: this.connectInfo.username,password: this.connectInfo.password,clean: this.connectInfo.clean}var client =  this.$mqttTool.connect(opts);client.on('connect', function(res) {_this.logs.unshift({option:'mqtt:', log:'連接成功'})})client.on('reconnect', function(res) {_this.logs.unshift({option:'mqtt:', log:'重新連接'})})client.on('error', function(res) {_this.logs.unshift({option:'mqtt:', log:'連接失敗'})})client.on('close', function(res) {_this.logs.unshift({option:'mqtt:', log:'關閉成功'})})client.on('message', function(topic, message, buffer) {if(_this.isBuffer){_this.logs.unshift({option:topic+' buffer:', log: JSON.stringify(buffer)})}_this.logs.unshift({option:topic+' message:', log: message.toString()})})},/* 終止連接 */endConnect(){var _this = thisthis.$mqttTool.end().then(res =>{_this.logs.unshift({option:'終止:', log:res})})},/* 重新連接 */reConnect(){var _this = thisthis.$mqttTool.reconnect().then(res =>{_this.logs.unshift({option:'重連:', log:res})})},/* 更改Qos */changeQos(){var _this = thisif(this.subscribeInfo.qos >= 2){this.subscribeInfo.qos = 0this.logs.unshift({option:'Qos:', log:this.subscribeInfo.qos + ' Qos變更,訂閱已取消,請重新發起訂閱'})this.endSubscribe();}else{this.subscribeInfo.qos += 1this.logs.unshift({option:'Qos:', log:this.subscribeInfo.qos + ' Qos變更,訂閱已取消,請重新發起訂閱'})this.endSubscribe();}},/* 訂閱 */startSubscribe(){if(this.subscribeInfo.topic == ''){uni.showToast({icon: 'none',title: '輸入topic'})return;}var _this = thislet opts = {topic: this.subscribeInfo.topic,qos: this.subscribeInfo.qos,}this.$mqttTool.subscribe(opts).then(res =>{_this.logs.unshift({option:'訂閱' + opts.topic + ':', log:res})})},/* 取消訂閱 */endSubscribe(){var _this = thislet opts = {topic: this.subscribeInfo.topic}this.$mqttTool.unsubscribe(opts).then(res =>{_this.logs.unshift({option:'取消訂閱:', log:res})})},/* 發送消息 */publish(){var _this = thislet opts = {topic: this.subscribeInfo.topic,message: this.sendInfo.msg,}this.$mqttTool.publish(opts).then(res =>{_this.sendInfo.msg = ''_this.logs.unshift({option:'發送:', log:res})}).catch(err=>{_this.logs.unshift({option:'發送失敗:', log:err})})},/* 清空配置 */clearConfig(){this.endConnect();this.connectInfo = {clientId: '',username: '',password: ''}this.subscribeInfo = {topic: '',qos: 1,sendMsg: ''}this.isBuffer = false},/* 清空日志 */cealrLog(){this.logs = [{option:'環境配置:', log:'配置成功'}]},/* 聚焦 */focusSend(val){this.isSending = val},}}
</script><style lang="less" scoped>.flex-row{display: flex;flex-direction: row;align-items: center;justify-content: flex-start;}.flex-between{display: flex;flex-direction: row;align-items: center;justify-content: space-between;}.mqtt{width: 100vw;height: 100vh;background-color: #f8f8f8;.options{width: 100%;height: 316px;background-color: #ffffff;box-shadow: 0px 0px 8px rgba(0, 0, 0, 0.1);font-size: 13px;color: #666666;.title{width: 710upx;margin: 0 auto;font-size: 15px;font-weight: 500;color: #333333;text-align: center;padding-bottom: 8px;display: flex;flex-direction: row;align-items: center;justify-content: space-between;.title-btn{font-size: 14px;font-weight: 400;color: #3F536E;}}.info{width: 710upx;margin: 0 auto;.bar{min-width: 160upx;margin-bottom: 8px;height: 30px;border-radius: 8px;box-shadow: inset 0px 0px 6px rgba(0, 0, 0, 0.1);border: 1px solid #cccccc;display: flex;flex-direction: row;align-items: center;justify-content: flex-start;font-size: 14px;.label{height: 30px;background-color: #f8f8f8;padding: 0px 10px;line-height: 30px;border-right: 1px solid #eeeeee;border-radius: 15px 0px 0px 15px;}.value{height: 30px;padding: 0px 12px;line-height: 30px;font-size: 14px;color: #3F536E;}}.btn{width: 30%;height: 32px;background-color: #3F536E;color: #ffffff;border-radius: 8px;margin-bottom: 8px;text-align: center;line-height: 32px;}.tips{width: 100%;height: 30px;margin-top: 6px;display: flex;flex-direction: row;align-items: center;position: relative;.tips-lab{font-size: 14px;color: #333333;}.tips-reset{font-size: 14px;font-weight: 500;color: #3F536E;position: absolute;right: 150px;}.tips-buffer{font-size: 14px;font-weight: 500;color: #3F536E;position: absolute;right: 70px;}.tips-clear{font-size: 14px;font-weight: 500;color: #3F536E;position: absolute;right: 0px;}}}}.logs{width: 100%;height: calc(100% - 396px);.logs-list{padding: 14upx 20upx;border-bottom: 1px solid #eeeeee;font-size: 13px;color: #3e3d3e;word-break: break-all;}}.feet{width: 100%;height: 80px;background-color: #ffffff;position: absolute;bottom: 0px;transition: all 0.35s;-webkit-transition: all 0.35s;&::before{position: absolute;content: '';top: 0px;background: rgba(0,0,0,0.2);width: 100%;height: 1px;transform: scaleY(0.5);transform-origin: 0 0;-webkit-transform: scaleY(0.5);-webkit-transform-origin: 0 0;}.inpbar{width: 710upx;height: 44px;background-color: #eeeeee;border-radius: 10px;position: absolute;left: 20upx;top: 10px;display: flex;flex-direction: row;align-items: center;justify-content: space-between;.img{width: 30px;height: 30px;margin-left: 12px;}.inp{width: calc(100% - 138px);height: 40px;margin: 0px 12px;font-size: 14px;color: #000000;}.send-dark{opacity: 0.7;}.send{width: 60px;height: 32px;background-color: #3F536E;border-radius: 6px;font-size: 14px;color: #ffffff;display: flex;align-items: center;justify-content: center;margin-right: 12px;}}}}
</style>

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/895787.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/895787.shtml
英文地址,請注明出處:http://en.pswp.cn/news/895787.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

shell腳本備份PostgreSQL數據庫和庫下表

注意&#xff1a; 以下為對PostgreSQL13.16版本數據庫備份shell腳本參考請確認備份節點上psql和pgdump的版本不至于太低&#xff0c;建議>13.16該腳本目前是對于整庫、&#xff08;默認針對public這個schema&#xff0c;如果有其他schema&#xff0c;請自行添加一層循環&am…

EXCEL解決IF函數“您已為此函數輸入太多個參數”的報錯

IF函數的基本結構是IF(條件, 值為真時的結果, 值為假時的結果)&#xff0c;所以標準的IF函數最多只能有三個參數。當用戶輸入的參數超過三個時&#xff0c;Excel就會報這個錯誤。比如多個IF語句疊加&#xff0c;但可能在嵌套的過程中沒有正確關閉每個IF函數的括號&#xff0c;導…

圖像質量評價指標-UCIQE-UIQM

一、評價指標UCIQE 在文章《An underwater color image quality evaluation metric》中&#xff0c;提到的了評價指標UCIQE&#xff08;Underwater Colour Image Quality Evaluation&#xff09;&#xff0c;是一種無參考圖像質量評價指標&#xff0c;主要用于評估水下圖像的質…

Vue 前端開發中的路由知識:從入門到精通

文章目錄 引言1. Vue Router 簡介1.1 安裝 Vue Router1.2 配置 Vue Router1.3 在 Vue 實例中使用 Vue Router 2. 路由的基本用法2.1 路由映射2.2 路由視圖2.3 路由鏈接 3. 動態路由3.1 動態路徑參數3.2 訪問動態參數3.3 響應路由參數的變化 4. 嵌套路由4.1 定義嵌套路由4.2 渲染…

基于Springboot+微信小程序調用文心一言大模型實現AI聊天

一、文章前言 此文主要實現基于Springboot微信小程序調用文心一言大模型實現AI聊天對話功能&#xff0c;使用Java作為后端語言進行支持&#xff0c;界面友好&#xff0c;開發簡單。 二、開發流程及工具準備 2.1、登錄百度智能云平臺&#xff0c;獲取 API Key 和 Secret Key兩個…

leaflet前端初始化項目

1、通過npm安裝leaflet包&#xff0c;或者直接在項目中引入leaflet.js庫文件。 npm 安裝&#xff1a;npm i leaflet 如果在index.html中引入leaflet.js,在項目中可以直接使用變量L. 注意:盡量要么使用npm包&#xff0c;要么使用leaflet.js庫&#xff0c;兩者一起使用容易發生…

Deepseek官網接口文檔

API 接口 生成完成 生成聊天完成 創建模型 列出本地模型 顯示模型信息 復制模型 刪除模型 拉取模型 推送模型 生成嵌入 列出運行中的模型 版本 約定 模型名稱 模型名稱遵循 model:tag 格式&#xff0c;其中 model 可以有一個可選的命名空間&#xff0c;例如 ex…

容器運行常見數據庫

一.涉及鏡像壓縮包 均為amd架構版本&#xff1a;mysql:5.7.42、postgres:13.16、dm8:20250206_rev257733_x86_rh6_64、oceanbase-ce:v4.0、opengauss:5.0.2 通過網盤分享的文件&#xff1a;db.tgz 鏈接: https://pan.baidu.com/s/1EBbFPZj1FxCA4_GxjVunWg?pwd563s 提取碼: 5…

python爬蟲系列課程2:如何下載Xpath Helper

python爬蟲系列課程2:如何下載Xpath Helper 一、訪問極簡插件官網二、點擊搜索按鈕三、輸入xpath并點擊搜索四、點擊推薦下載五、將下載下來的文件解壓縮六、打開擴展程序界面七、將xpath.crx文件拖入擴展程序界面一、訪問極簡插件官網 極簡插件官網地址:https://chrome.zzz…

PHP支付寶--轉賬到支付寶賬戶

官方參考文檔&#xff1a; ?https://opendocs.alipay.com/open/62987723_alipay.fund.trans.uni.transfer?sceneca56bca529e64125a2786703c6192d41&pathHash66064890? 可以使用默認應用&#xff0c;也可以自建新應用&#xff0c;此處以默認應用來講解【默認應用默認支持…

前端開發崗模擬面試題套卷A答案及解析(一)技術面部分

前端開發崗模擬面試題套卷A答案及解析(一)技術面部分 (一)技術面 一、JavaScript核心技術(ES6+) 1-1、實現防抖函數 function debounce(fn, delay) {let timer = null;return function(...args) {clearTimeout(timer); // 清除已有定時器timer = setTimeout(() =>…

對稱加密算法——IDEA加密算法

Java IDEA算法詳解 1. 理論背景 IDEA&#xff08;International Data Encryption Algorithm&#xff09;是一種對稱密鑰加密算法&#xff0c;由Xuejia Lai和James Massey于1991年提出。它被設計用于替代DES&#xff08;Data Encryption Standard&#xff09;算法&#xff0c;…

單例模式、構造函數、左值右值

拷貝構造函數 簡單的說就是——用一個對象構造另外一個對象 class Myclass {public:int d0;Myclass(int d_){d d_}; //常用的構造函數Myclass(Myclass c) //拷貝構造函數{d c.d;} }; //對比 class Myclass {public:int d0;Myclass(int d_){d d_}; //常用的構造函數Myclass…

rustdesk遠程桌面自建服務器

首先&#xff0c;我這里用到的是阿里云服務器 centos7版本&#xff0c;win版客戶端。 準備工作 centos7 服務器端文件&#xff1a; https://github.com/rustdesk/rustdesk-server/releases/download/1.1.11-1/rustdesk-server-linux-amd64.zip win版客戶端安裝包&#xff1…

【深度學習】Transformer入門:通俗易懂的介紹

【深度學習】Transformer入門&#xff1a;通俗易懂的介紹 一、引言二、從前的“讀句子”方式三、Transformer的“超級閱讀能力”四、Transformer是怎么做到的&#xff1f;五、Transformer的“多視角”能力六、Transformer的“位置記憶”七、Transformer的“翻譯流程”八、Trans…

用deepseek學大模型03-數學基礎 概率論 最大似然估計(MLE)最大后驗估計(MAP)

https://metaso.cn/s/r4kq4Ni 什么是最大似然估計&#xff08;MLE&#xff09;最大后驗估計&#xff08;MAP&#xff09;&#xff1f;深度學習中如何應用&#xff0c;舉例說明。 好的&#xff0c;我現在需要回答關于最大似然估計&#xff08;MLE&#xff09;和最大后驗估計&…

Socket通訊協議理解及客戶端服務器程序流程

Socket通訊我們可以從以下幾個方面簡單理解 1.Socket是網絡通信中的一項重要技術&#xff0c;它提供了在網絡上進行數據交換的接口。用C#、Java、C等開發語言&#xff0c;都可以開發Socket網絡通信程序。 2.Socket(套接字)是計算機網絡編程中的一種抽象&#xff0c;它允許不同…

《Stable Diffusion繪畫完全指南:從入門到精通的Prompt設計藝術》-配套代碼示例

第一章&#xff1a;模型加載與基礎生成 1.1 基礎模型加載 from diffusers import StableDiffusionPipeline import torch# 加載SD 1.5基礎模型&#xff08;FP32精度&#xff09; pipe StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5",…

【DL】淺談深度學習中的知識蒸餾 | 輸出層知識蒸餾

目錄 一 核心概念與背景 二 輸出層知識蒸餾 1 教師模型訓練 2 軟標簽生成&#xff08;Soft Targets&#xff09; 3 學生模型訓練 三 擴展 1 有效性分析 2 關鍵影響因素 3 變體 一 核心概念與背景 知識蒸餾&#xff08;Knowledge Distillation, KD&#xff09;是一種模…

嵌入式學習第十六天--stdio(二)

文件打開 open函數 #include <fcntl.h> int open(const char *pathname&#xff0c;int flags); int open(const char *pathname&#xff0c;int flags&#xff0c;mode_t mode); 功能: 打開或創建文件 參數: pathname //打開的文件名 flags //操作…