当前位置: 首页 > news >正文

微信小程序蓝牙连接 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.lryc.cn/news/239712.html

相关文章:

  • 启动Dubbo项目注册Zookeeper时提示zookeeper not connected异常原理解析
  • 我在Vscode学OpenCV 几何变换(缩放、翻转、仿射变换、透视、重映射)
  • MATLAB算法实战应用案例精讲-【图像处理】图像缩放
  • Doris的PROPERTIES与ENGINE(九)
  • 华为云数据库 RDS 下载全量备份文件 wget
  • C#使用whisper.net实现语音识别(语音转文本)
  • 从零开始学习typescript——运算符(算术运算符、赋值运算符、比较运算符)
  • likeshop单商户商城系统 任意文件上传漏洞复现
  • CentOS 7 使用pugixml 库
  • 深度学习 loss 是nan的可能原因
  • [ 云计算 | AWS 实践 ] 基于 Amazon S3 协议搭建个人云存储服务
  • 第二十章:多线程
  • CentOS 7启动时报“Started Crash recovery kernel arming.....shutdown....”问题处理过程
  • Android 13 - Media框架(14)- OpenMax(二)
  • 【Python大数据笔记_day11_Hadoop进阶之MR和YARNZooKeeper】
  • 飞桨——总结PPOCRLabel中遇到的坑
  • LeetCode(30)长度最小的子数组【滑动窗口】【中等】
  • Niushop 开源商城 v5.1.7:支持PC、手机、小程序和APP多端电商的源码
  • Navmesh 寻路
  • YOLOv5 分类模型 数据集加载 3
  • 『亚马逊云科技产品测评』活动征文|AWS 存储产品类别及其适用场景详细说明
  • Mac | Vmware Fusion | 分辨率自动还原问题解决
  • SQL知多少?这篇文章让你从小白到入门
  • centos7安装MySQL—以MySQL5.7.30为例
  • 3.计算机网络补充
  • 【云原生】Spring Cloud Alibaba 之 Gateway 服务网关实战开发
  • opencv-直方图均衡化
  • npm install安装报错
  • Spring Boot创建和使用(重要)
  • python 基于gdal,richdem,pysheds实现 实现洼填、D8流向,汇流累计量计算,河网连接,分水岭及其水文分析与斜坡单元生成