uniapp打开、搜索蓝牙,通过蓝牙发送、接收数据
生活随笔
收集整理的這篇文章主要介紹了
uniapp打开、搜索蓝牙,通过蓝牙发送、接收数据
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
html
<view><button @click="open">1.是否開啟藍牙</button><button @click="search">2.搜索藍牙</button><button @click="initBlue">3.連接藍牙</button><button @click="getInfo">4.獲取藍牙信息</button><button @click="updateNotify">5.開啟消息監聽點擊之后可以監聽發送過來的數據</button><button @click="stop">6.關閉藍牙搜索</button><button @click="disconnect">7.關閉藍牙連接</button><button @click="getBluetoothDevices">8.獲取藍牙信息</button><button @click="writeBLECharacteristicValue">9.發送數據</button><button @click="readBLECharacteristicValue">10.讀取RFID數據</button></view>js(運行步驟,1,2,3,5,9)
<script> export default {data() {return {deviceId: "",message: null,messageHex: null,uuid: "",characteristics: "",readCode: "",readCodeMsg: "",renwu:'1',};},created() {},methods: {open() {uni.openBluetoothAdapter({success: function (res) {console.log("是否開啟藍牙", res);},fail: function (msg) {console.log(msg);},});},stop() {uni.stopBluetoothDevicesDiscovery({success(res) {console.log("停止搜索---", res);},});},search() {let that = this;uni.startBluetoothDevicesDiscovery({success: function (res) {console.log("搜索設備---", res);uni.onBluetoothDeviceFound(function (el) {console.log("new device list has founded");console.log(el);// console.log(that.ab2hex(el.devices[0].advertisData));//找到對應藍牙設備名字if (el.devices[0].name == "xxxxxxx") {// if (el.devices[0].name == "zhaogpnov") {console.log("成功-------", el);//成功后存儲設備idthat.deviceId = el.devices[0].deviceId;that.stop(); //關閉搜索 第三步方法名}});},});},initBlue() {let that = this;uni.createBLEConnection({deviceId: this.deviceId,success: (res) => {console.log("連接成功---", JSON.stringify(res));//需延時連接,不然會報錯setTimeout(function () {uni.getBLEDeviceServices({deviceId: that.deviceId,success: (res) => {console.log("獲取藍牙設備所有服務", res);// that.uuid = res.services[0].uuid;that.uuid = res.services[2].uuid;that.huoqu(); //第五步方法名},});}, 1000);},});},huoqu() {let that = this;let deviceId = this.deviceId;uni.getBLEDeviceCharacteristics({deviceId: that.deviceId,serviceId: that.uuid,success: (res) => {console.log(res);that.characteristics = res.characteristics[0].uuid;console.log("獲取--------", res);},fail: (res) => {console.log("失敗1--------", res);},});},getInfo() {let that = this;let deviceId = this.deviceId;uni.getBLEDeviceCharacteristics({deviceId: that.deviceId,serviceId: that.uuid,success: (res) => {that.characteristics = res.characteristics[0].uuid;console.log("獲取--------", res);},fail: (res) => {console.log("失敗1--------", res);},});},// 啟用低功耗藍牙設備特征值變化時的notify功能updateNotify() {uni.notifyBLECharacteristicValueChange({deviceId: this.deviceId,serviceId: this.uuid,characteristicId: this.characteristics,state: true,success: (res) => {console.log(res);if (res.errMsg == "notifyBLECharacteristicValueChange:ok") {console.log("開啟消息監聽------", res);// uni.hideLoading();// this.cut = false;// this.BLEValue();this.listenMessage();}},fail: (res) => {console.log("失敗1--------", res);},});},// 將16進制的內容轉成我們看得懂的字符串內容hexCharCodeToStr(hexCharCodeStr) {var trimedStr = hexCharCodeStr.trim();var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;var len = rawStr.length;if (len % 2 !== 0) {alert("存在非法字符!");return "";}var curCharCode;var resultStr = [];for (var i = 0; i < len; i = i + 2) {curCharCode = parseInt(rawStr.substr(i, 2), 16);resultStr.push(String.fromCharCode(curCharCode));}return resultStr.join("");},//監聽發送過來的消息listenMessage() {let that = thisuni.onBLECharacteristicValueChange((res) => {console.log("發送過來的數據---------", res);// 結果里有個value值,該值為 ArrayBuffer 類型,所以在控制臺無法用肉眼觀察到,必須將該值轉換為16進制let resHex = that.ab2hex(res.value)console.log(resHex);// 最后將16進制轉換為ascii碼,就能看到對應的結果let result = that.hexCharCodeToStr(resHex)console.log(result)})},disconnect() {let that = this;uni.closeBLEConnection({deviceId: that.deviceId,success: (res) => {console.log(res, "斷開連接");},});},getBluetoothDevices() {console.log("獲取藍牙設備");uni.getBluetoothDevices({success: (res) => {console.log("獲取藍牙設備成功:" + res);this.bluetooth = res.devices;this.bluetooth.forEach((item) => {this.isLink.push(0);});},});},// ascll轉換strtoascii(str, fix = "&#") {if (str.length < 1) {return false;}var arr = str.split("");var txt = "";arr.forEach(function (v, i) {txt += fix + v.charCodeAt();txt = Number(txt);});return txt;},// 二進制轉換strToBinary(str) {var result = [];var list = str.split("");console.log(list)for (var i = 0; i < list.length; i++) {if (i != 0) {// result.push("");}var item = list[i];var binaryStr = item.charCodeAt().toString(2);result.push(binaryStr);}return result;},// 發送二進制數據writeBLECharacteristicValue() {let that = this;let msg = '>y t s 1 \r'// 向藍牙設備發送一個0x00的16進制數據const buffer = new ArrayBuffer(msg.length)const dataView = new DataView(buffer)// dataView.setUint8(0, 0)for (var i = 0; i < msg.length; i++) {dataView.setUint8(i, msg.charAt(i).charCodeAt())}uni.writeBLECharacteristicValue({// 這里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中獲取deviceId: that.deviceId,// 這里的 serviceId 需要在 getBLEDeviceServices 接口中獲取serviceId: that.uuid,// 這里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中獲取characteristicId: that.characteristics,// 這里的value是ArrayBuffer類型// value: buffer,value: buffer,writeType:'writeNoResponse',success: (res) => {that.returnMessage = res.errMsg;console.log("發送成功-----", res);},fail: (res) => {that.returnMessage = res.errMsg;console.log("發送失敗-----", res);},complete:(res)=>{console.log("發送消息結束----",res)}});},// ArrayBuffer轉16進度字符串示例ab2hex(buffer) {const hexArr = Array.prototype.map.call(new Uint8Array(buffer),function (bit) {return ('00' + bit.toString(16)).slice(-2)})return hexArr.join('')},//獲取buffergetBuffer(str) {if (!str) {return new ArrayBuffer(str.length);}let buffer = new ArrayBuffer(str.length);let dataView = new DataView(buffer);let ind = 0;for (var i = 0, len = str.length; i < len; i += 2) {let code = parseInt(str.substr(i, 2), 16);dataView.setUint8(ind, code);ind++;}return buffer;},// 讀取設備二進制數據readBLECharacteristicValue() {// console.log('進入讀取');// setTimeout(()=>{uni.readBLECharacteristicValue({// 這里的 deviceId 需要已經通過 createBLEConnection 與對應設備建立鏈接deviceId: this.deviceId,// 這里的 serviceId 需要在 getBLEDeviceServices 接口中獲取serviceId: this.uuid,// 這里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中獲取characteristicId: this.characteristics,success: (res) => {console.log("讀取成功:", res);},fail: (res) => {console.log("讀取失敗:", res);},});},}, }; </script>總結
以上是生活随笔為你收集整理的uniapp打开、搜索蓝牙,通过蓝牙发送、接收数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 黎明的颜色
- 下一篇: 【windows系统】插入移动硬盘后,有