微信小程序藍牙連接 uniApp藍牙連接設備

?藍牙列表期待效果

?代碼

<template><view class="bluetooth-list"><view class="align-items option" style="justify-content: space-between;" v-for="item in bluetoothList" :key="item.deviceId"><view class=""><view class="title">{{item.name || item.localName}}</view><view class="desc">{{item.deviceId}}</view></view><view class="bind-btn" @click="onBind(item)">綁定設備</view></view></view>
</template>

?js里面注意getBLEDeviceCharacteristics獲取特征值的時候,極個別設備參數write,read,notify是亂來的,需要自己打單獨處理,通過對應write,read,notify 為true的時候拿到對應的uuid,

<script>export default {data() {return {bluetoothObj:{},bluetoothList:[],services: [],serviceId: 0,writeCharacter: false,readCharacter: false,notifyCharacter: false};},onLoad() {this.init()},onUnload() {//停止搜索藍牙設備if (this.isSearching) {uni.stopBluetoothDevicesDiscovery();}},methods: {// 初始化init(){let that = this;uni.openBluetoothAdapter({success(res) {uni.getBluetoothAdapterState({success(res2) {if (res2.available) {if (res2.discovering) {uni.showToast({title: '正在搜索附近打印機設備',icon: "none"})return;}//獲取藍牙設備信息that.getBluetoothDevices()} else {uni.showModal({title: '提示',content: '本機藍牙不可用',})}}});},fail() {uni.showModal({title: '提示',content: '藍牙初始化失敗,請打開藍牙',})}})},//獲取藍牙設備信息getBluetoothDevices() {let that = thisthat.bluetoothList = [];uni.startBluetoothDevicesDiscovery({success(res) {//藍牙設備監聽 uni.onBluetoothDeviceFounduni.onBluetoothDeviceFound((result) => {let arr = that.bluetoothList;let devices = [];let list = result.devices;for (let i = 0; i < list.length; ++i) {if (list[i].name && list[i].name != "未知設備") {let arrNew = arr.filter((item) => {return item.deviceId == list[i].deviceId;});// console.log('arrNew:',arrNew.length)if (arrNew.length == 0) {devices.push(list[i]);}}}that.bluetoothList = arr.concat(devices);console.log("bluetoothList",that.bluetoothList)});that.time = setTimeout(() => {// uni.getBluetoothDevicesuni.getBluetoothDevices({success(res2) {let devices = [];let list = res2.devices;for (let i = 0; i < list.length; ++i) {if (list[i].name && list[i].name != "未知設備") {devices.push(list[i]);}}that.bluetoothList = devices;},})clearTimeout(that.time);}, 3000);}});},// 綁定藍牙onBind(item){uni.stopBluetoothDevicesDiscovery();let that = this;let { deviceId } = item;console.log('item',item)that.bluetoothObj.deviceId = deviceId;that.serviceId = 0;that.writeCharacter = false;that.readCharacter = false;that.notifyCharacter = false;// uni.showLoading({// 	title: '正在連接',// })uni.openBluetoothAdapter({success: function () {uni.createBLEConnection({deviceId,success(res) {console.log('createBLEConnection success', res)uni.hideLoading()that.getSeviceId()},fail(e) {console.log('createBLEConnection fail', e)uni.hideLoading()}})},fail: function (error) {console.log("openBluetoothAdapter")}})},//獲取藍牙設備所有服務(service)。getSeviceId() {let that = this;let t=setTimeout(()=>{uni.getBLEDeviceServices({deviceId: that.bluetoothObj.deviceId,success(res) {console.log('getBLEDeviceServices success', res)that.services = res.services;that.getCharacteristics()},fail: function(e) {}})clearTimeout(t);},1500)},getCharacteristics() {var that = thislet {services: list,serviceId: num,writeCharacter: write,readCharacter: read,notifyCharacter: notify} = that;// uni.getBLEDeviceCharacteristicsuni.getBLEDeviceCharacteristics({deviceId: that.bluetoothObj.deviceId,serviceId: list[num].uuid,success(res) {console.log('getBLEDeviceCharacteristics success', res)// console.log(res)for (var i = 0; i < res.characteristics.length; ++i) {var properties = res.characteristics[i].propertiesvar item = res.characteristics[i].uuidif (!notify) {if (properties.notify) {that.bluetoothObj.notifyCharaterId = item;that.bluetoothObj.notifyServiceId = list[num].uuid;notify = true}}if (!write) {if (properties.write) {that.bluetoothObj.writeCharaterId = item;that.bluetoothObj.writeServiceId = list[num].uuid;write = true}}if (!read) {if (properties.read) {that.bluetoothObj.readCharaterId = item;that.bluetoothObj.readServiceId = list[num].uuid;read = true}}}if (!write || !notify || !read) {num++that.writeCharacter = write;that.readCharacter = read;that.notifyCharacter = notify;that.serviceId = num;if (num == list.length) {uni.showModal({title: '提示',content: '找不到該讀寫的特征值',})} else {that.getCharacteristics()}} else {// ok // wx.writeBLECharacteristicValueuni.notifyBLECharacteristicValueChange({state: true, // 啟用 notify 功能// 這里的 deviceId 需要已經通過 createBLEConnection 與對應設備建立鏈接deviceId:that.bluetoothObj.deviceId,// 這里的 serviceId 需要在 getBLEDeviceServices 接口中獲取serviceId:that.bluetoothObj.serviceId,// 這里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中獲取characteristicId:that.bluetoothObj.notifyServiceId,success (res) {console.log('notifyBLECharacteristicValueChange success', res.errMsg)uni.onBLECharacteristicValueChange(function (e) {/**對設備發送過來的參數進行解密 */let str = that.ab2hex(e.value);console.log("解密str",str)})}})console.log("that.bluetoothObj",that.bluetoothObj)uni.setStorageSync("bluetoothObj", that.bluetoothObj)uni.showToast({icon:"none",title:"綁定成功"})setTimeout(()=>{uni.navigateBack({delta:1})},1000)}},fail: function(e) {console.log("getBLEDeviceCharacteristics fail:",e);}})},ab2hex: (buffer) => {const hexArr = Array.prototype.map.call(new Uint8Array(buffer),function (bit) {return ('00' + bit.toString(16)).slice(-2)})return hexArr.join('')},str2ab:(str) => {var buf = new ArrayBuffer(str.length / 2);var bufView = new Uint8Array(buf);for (var i = 0, strLen = str.length; i < strLen; i++) {bufView[i] = parseInt(str.slice(i * 2, i * 2 + 2), 16);}return buf;}}}
</script>

<style lang="less" scoped>.bluetooth-list{background-color: #F3F3F3;.option{margin: 20rpx;padding: 20rpx 32rpx;background-color: #fff;border-radius: 20rpx;.title{font-weight: 600;font-size: 32rpx;}.desc{font-size: 28rpx;color: #999;margin-top: 12rpx;}.bind-btn{background-color: #3F96DB;color: #fff;width: 200rpx;height: 70rpx;line-height: 70rpx;border-radius: 35rpx;text-align: center;font-size: 30rpx;}}}
</style>

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

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

相關文章

游戲開發團隊配置與協作流程

游戲開發技術圖譜 - 知乎 游戲制作的流程是什么啊&#xff1f; - 知乎 系統策劃&#xff1a;一張圖梳理游戲系統的生產流程 - 知乎 游戲開發入門&#xff08;十一&#xff09;游戲引擎架構-CSDN博客

全局定制序列化

作用:將返回實體類中的屬性如果為null 變成"" package com.example.micrweb.config;import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.f…

linux驅動——原子操作

linux驅動——原子操作 原子操作 API Linux 內核定義了叫做 atomic_t 的結構體來完成整型數據的原操作&#xff0c;在使用是使用原子變量來代替整型變量。此結構體定義在 include/linux/types.h 文件中&#xff0c;定義如下&#xff1a; typedef struct {int counter; }atom…

websocket與node.js實現

什么是 websocket&#xff1f; websoket 是一種網絡通信協議&#xff0c;基于 tcp 連接的全雙工通信協議&#xff08;客戶端和服務器可以同時收發信息&#xff09;&#xff0c;值得注意的是他不基于 http 協議&#xff0c;websocket 只有在建立連接的時候使用到 http 協議進行…

Kubernetes(k8s)之Pod詳解

文章目錄 Kubernetes之Pod詳解一、Pod介紹pod結構pod定義 二、Pod配置pod基本配置鏡像拉取策略啟動命令環境變量端口設置資源配額 三、Pod生命周期創建和終止初始化容器鉤子函數容器探測重啟策略 四、Pod調度定向調度NodeNameNodeSelector 親和性調度NodeAffinityPodAffinityPo…

風電場葉片運輸車模型-FBX格式-帶動畫-數字孿生場景搭建

FBX格式的風電場中葉片運輸車輛模型&#xff0c;按照真實尺寸建模&#xff0c;車輛多個部位帶動畫效果&#xff0c;適用于風電場三維數字化場景和風電場數字孿生使用&#xff0c;也可以用來作為各種三維平臺的測試模型。 模型效果圖 下載地址 葉片運輸車模型下載地址

php生成xml數據

在PHP中&#xff0c;你可以使用以下幾種方法生成XML數據&#xff1a; 使用DOM擴展&#xff1a; $xml new DOMDocument(1.0, UTF-8); $root $xml->createElement(root); $xml->appendChild($root); $child $xml->createElement(child); $root->appendChild($ch…

使用 Raspberry Pi、Golang 和 HERE XYZ 制作實時地圖

到目前為止&#xff0c;您可能已經看過我的一些與 Raspberry Pi 和位置數據相關的教程。我是這些小型物聯網 (IoT) 設備的忠實粉絲&#xff0c;并編寫了有關使用 Golang 進行 WLAN 定位 和 使用 Node.js 進行 GPS 定位的教程。 我想繼續沿著 Golang 路線&#xff0c;做一個關于…

目標檢測YOLO實戰應用案例100講-基于YOLO的小目標檢測改進算法

目錄 前言 國內外研究現狀 常規尺寸目標檢測算法 小目標的檢測算法

stm32定時器輸入捕獲模式

頻率測量 頻率測量有兩種方法 測頻法&#xff1a;在閘門時間T內&#xff0c;對上升沿或下降沿計次&#xff0c;得到N&#xff0c;則評率fxN/T測周法&#xff1a;兩個上升沿內&#xff0c;以標準頻率fc計次得到N&#xff0c;則頻率fx fc/N中界頻率&#xff1a;測頻法和測周法誤…

Spark的通用運行流程與Spark YARN Cluster 模式的運行流程

Spark的通用運行流程 集群啟動后Worker節點會向Master節點心跳匯報資源Client向Driver提交APP&#xff0c;根據不同的運行模式在不同的地方創建Driver。Driver以粗粒度的方式向Master注冊應用并申請資源&#xff08;在Application執行之前&#xff0c;將所有的資源申請完畢&…

助力企業前行——ScalaSpark最佳實踐課程

時間飛逝&#xff0c;轉眼間我們的Scala&Spark培訓課程已經圓滿結束&#xff01;在這段精彩的學習旅程中&#xff0c;你們展現了堅韌、決心和追求卓越的品質。 scala(Scalable Language)是一種多范式的編程語言&#xff0c;其設計的初衷是要集成面向對象編程和函數式編程的…

Cookie與Session知識

目錄 一.Cookie與Session的發展史 1.Cookie的發展史 2.Session的發展史 3.Cookie和Session的關系 4.總結 二.Cookie與Session詳解 1.Cookie 2.Session 3.token 4.總結 三.Django操作Cookie 1.設置Cookie 2.獲取Cookie 3.設置超時時間 4.注銷Cookie 5.登錄功能實…

【機器學習】On the Identifiability of Nonlinear ICA: Sparsity and Beyond

前言 本文是對On the Identifiability of Nonlinear ICA: Sparsity and Beyond (NIPS 2022)中兩個結構稀疏假設的總結。原文鏈接在Reference中。 什么是ICA(Independent component analysis)&#xff1f; 獨立成分分析簡單來說&#xff0c;就是給定很多的樣本X&#xff0c;通…

Springboot-熱部署-IDEA2023

方式一&#xff1a;jrebel 方式二&#xff1a; 1、導入依賴 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> <…

C++ DAY08 異常

概念 異常事件&#xff08;如&#xff1a;除 0 溢出&#xff0c;數組下標越界&#xff0c;所要讀取的文件不存在 , 空指針&#xff0c;內存不足 等等&#xff09; 在 C 語言對錯誤的處理是兩種方法&#xff1a; 一是使用整型的返回值標識錯誤&#xff1b; 二是使用 errn…

自動解決IP沖突的問題 利用批處理更改末位IP循環+1直到網絡暢通為止 解放雙手 事半功倍

好久沒出來寫點什么了&#xff0c;難道今天有點時間&#xff0c;順便把這兩天碰到的問題出個解決方法吧。 這幾天去客戶那兒解決網絡問題&#xff0c;因為客戶的網絡是固定的靜態IP&#xff0c;因為沒做MAC綁定&#xff0c;IP固定在本地電腦上&#xff0c;只要上不了網&#xf…

PDF轉Word,1行Python代碼就夠了,免費用

大家好&#xff0c;這里是程序員晚楓。 今年十一假期沒出去旅游&#xff0c;在家里更新一套原創課程&#xff0c;&#x1f449;給小白的《50講Python自動化辦公》。 所有功能&#xff0c;都只需要1行代碼&#xff0c;非常適合非程序員入門Python使用。 目前全網播放量直逼100…

RK3588平臺開發系列講解(嵌入式AI篇)RKNPU詳解

文章目錄 一、CPU、GPU、FPGA和NPU介紹二、CPU、GPU、FPGA和NPU區別三、NPU 應用四、RKNPU沉淀、分享、成長,讓自己和他人都能有所收獲!?? ?? 本篇將給大家介紹什么是RKNPU。 一、CPU、GPU、FPGA和NPU介紹 二、CPU、GPU、FPGA和NPU區別 若考慮成本、功耗、計算能力以及體…

探秘開發app與小程序:一場技術與創新的博弈

app與小程序&#xff1a;一場技術與創新的博弈隨著科技的飛速發展&#xff0c;移動應用程序已經成為我們日常生活中不可或缺的一部分。在這個充滿競爭的時代&#xff0c;企業紛紛投身于開發各類移動應用&#xff0c;以期在市場中占據一席之地。然而&#xff0c;面對多樣化的應用…