微信小程序蓝牙连接 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 = this
				that.bluetoothList = [];
				uni.startBluetoothDevicesDiscovery({
					success(res) {
						//蓝牙设备监听 uni.onBluetoothDeviceFound
						uni.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.getBluetoothDevices
							uni.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 = this
				let {
					services: list,
					serviceId: num,
					writeCharacter: write,
					readCharacter: read,
					notifyCharacter: notify
				} = that;
				// uni.getBLEDeviceCharacteristics
				uni.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].properties
							var item = res.characteristics[i].uuid
							if (!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.writeBLECharacteristicValue
							uni.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.mfbz.cn/a/178611.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

万字解析设计模式之组合模式、亨元模式

一、组合模式 1.1概述 组合模式是一种结构型设计模式&#xff0c;它允许将对象组合成树形结构&#xff0c;以表示“部分-整体”的层次结构。组合模式使得客户端可以一致地对待单个对象和对象组合&#xff0c;从而将复杂的层次结构展现为一个统一的树形结构。 在组合模式中&…

Audition 2024 24.0.0.46(音频剪辑)

Audition 2024是一款非常棒的音频编辑和混合软件&#xff0c;提供了广泛的工具和功能&#xff0c;用于创建、编辑、混合和设计音效。这款软件旨在加速音频和视频制作工作流程&#xff0c;提供具有原始音效的高质量混音。其界面构成清晰&#xff0c;操作简便&#xff0c;适合专业…

【python】python旅游网数据抓取分析(源码+论文)【独一无二】

&#x1f449;博__主&#x1f448;&#xff1a;米码收割机 &#x1f449;技__能&#x1f448;&#xff1a;C/Python语言 &#x1f449;公众号&#x1f448;&#xff1a;测试开发自动化【获取源码商业合作】 &#x1f449;荣__誉&#x1f448;&#xff1a;阿里云博客专家博主、5…

开发上门送桶装水小程序要考虑哪些业务场景

上门送水业务已经有很长一段时间了&#xff0c;但是最开始都是给用户发名片、贴小广告&#xff0c;然后客户电话订水&#xff0c;水站工作人员再上门去送&#xff0c;这种人工记单和派单效率并不高&#xff0c;并且电话沟通中也比较容易出现偏差&#xff0c;那么根据这个情况就…

【Docker】从零开始:6.配置镜像加速器

【Docker】从零开始&#xff1a;5.配置镜像加速器 什么是镜像加速器&#xff1f;为什么要配置docker镜像加速器?常见的Docker镜像加速器有哪些&#xff1f;如何申请Docker镜像加速器如何配置Docker镜像加速器 什么是镜像加速器&#xff1f; 镜像加速器是一个位于Docker Hub之…

UDP中connect的作用

udpclientNoConnect.c里边的内容如下&#xff1a; #include<stdio.h> #include<stdlib.h> #include<string.h> #include<unistd.h> #include<arpa/inet.h> #include<sys/socket.h> #include <errno.h> #include <syslog.h…

七、通过libfdk_aac编解码器实现aac音频和pcm的编解码

前言 测试环境&#xff1a; ffmpeg的4.3.2自行编译版本windows环境qt5.12 AAC编码是MP3格式的后继产品&#xff0c;通常在相同的比特率下可以获得比MP3更高的声音质量&#xff0c;是iPhone、iPod、iPad、iTunes的标准音频格式。 AAC相较于MP3的改进包含&#xff1a; 更多的采…

在AWS VPC中运行Nagios检查时指定自定义DNS解析器的选项

在AWS VPC中运行Nagios检查&#xff0c;并希望能够指定自定义DNS解析器来处理请求。我想使用Python requests库来实现这个目标。 根据问题描述&#xff0c;您想在AWS VPC中运行Nagios检查&#xff0c;并希望使用Python的requests库来指定自定义DNS解析器。 要解决这个问题&…

[开源]Web端的P2P文件传输工具,简单安全高效的P2P文件传输服务

一、开源项目简介 小鹿快传 - 在线P2P文件传输工具 小鹿快传是一款Web端的P2P文件传输工具&#xff0c;使用了WebRTC技术实现P2P连接和文件传输。 二、开源协议 使用MIT开源协议 三、界面展示 产品截图 四、功能概述 简单安全高效的P2P文件传输服务 小鹿快传是一款Web端…

php文件上传例子

目录结构&#xff1a; index.html代码&#xff1a; <!DOCTYPE html> <html><head><title>文件上传</title><meta charset"utf-8"></head><body><form action"./up.php" method"post" encty…

python趣味编程-5分钟实现一个太空大战游戏(含源码、步骤讲解)

飞机战争游戏系统项目是使用Python编程语言开发的,是一个简单的桌面应用程序。 Python 中的飞机战争游戏使用pygame导入和随机导入。 Pygame 是一组跨平台的 Python 模块,专为编写视频游戏而设计。它包括设计用于 Python 编程语言的计算机图形和声音库。

Django(九、cookie与session)

文章目录 一、cookie与session的介绍HTTP四大特性 cookiesession Django操作cookie三板斧基于cookie的登录功能 一、cookie与session的介绍 在讲之前我们先来回忆一下HTTP的四大特性 HTTP四大特性 1.基于请求响应 2.基于TIC、IP作用于应用层上的协议 3.无状态 保存…

Navmesh 寻路

用cocos2dx引擎简单实现了一下navmesh的多边形划分&#xff0c;然后基于划分多边形的a*寻路。以及路径拐点优化算法 用cocos主要是方便使用一些渲染接口和定时器。重点是实现的原理。 首先画了一个带有孔洞的多边形 //多边形的顶点数据Vec2(100, 100),Vec2(300, 200),Vec2(50…

P4 C++ 条件与分支(if)

前言 今天我们来看看条件语句&#xff0c;换句话说&#xff0c;也就是 if 语句、if else 和 else if 等等这写语句。 我知道大家基本上已经非常了解 if 语句和所有 C 中的分支语句&#xff0c;但我还是鼓励你们继续看完这一讲&#xff0c;这里可能包含一些新东西。我们还会深入…

【精选】Ajax技术知识点合集

Ajax技术详解 Ajax简介 Ajax 即“Asynchronous Javascript And XML”&#xff08;异步 JavaScript 和 XML&#xff09;&#xff0c;是指一种创建 交互式、快速动态应用的网页开发技术&#xff0c;无需重新加载整个网页的情况下&#xff0c;能够更新页面局 部数据的技术。通过在…

[ 云计算 | AWS 实践 ] 基于 Amazon S3 协议搭建个人云存储服务

本文收录于【#云计算入门与实践 - AWS】专栏中&#xff0c;收录 AWS 入门与实践相关博文。 本文同步于个人公众号&#xff1a;【云计算洞察】 更多关于云计算技术内容敬请关注&#xff1a;CSDN【#云计算入门与实践 - AWS】专栏。 本系列已更新博文&#xff1a; [ 云计算 | …

世微 dc-dc降压恒流 LED汽车大灯 单灯 14V5A 68W车灯驱动方案 AP5191

产品描述 AP5191是一款PWM工作模式,高效率、外围简单、外置功率MOS管&#xff0c;适用于4.5-150V输入的高精度降压LED恒流驱动芯片。输出最大功率150W&#xff0c;最大电流6A。AP5191可实现线性调光和PWM调光&#xff0c;线性调光脚有效电压范围0.55-2.6V.AP5191 工作频率可以…

Oracle与Redis Enterprise协同,作为企业缓存解决方案

来源&#xff1a;虹科云科技 虹科干货丨Oracle与Redis Enterprise协同&#xff0c;作为企业缓存解决方案 欢迎关注虹科&#xff0c;为您提供最新资讯&#xff01; 单独使用Oracle作为企业缓存数据库时&#xff0c;会出现哪些问题呢&#xff1f;使用Redis Enterprise与Oracle共…

基于STM32的手势识别算法研究与应用

基于STM32的手势识别算法在人机交互和智能设备控制中具有重要的应用价值。本文将介绍基于STM32的手势识别算法的研究原理和实现步骤&#xff0c;并提供相应的代码示例。 1. 手势识别概述 手势识别是一种通过分析人体的手部动作和姿势来识别和理解人的意图的技术。基于STM32的…

Jina AI 的 8K 向量模型上线 AWS Marketplace,支持本地部署!

在当前多模态 AI 和大模型技术风头正劲的背景下&#xff0c;Jina AI 始终领跑于创新前沿&#xff0c;技术领先。2023 年 10 月 30 日&#xff0c;Jina AI 隆重推出 jina-embeddings-v2&#xff0c;这是全球首款支持 8192 输入长度的开源向量大模型&#xff0c;其性能媲美 OpenA…