uniapp连接蓝牙操作(蓝牙设备地锁)

 介绍:

本文采用uni-app框架来创建一个简单的用户界面,用于搜索、连接和发送命令给蓝牙设备。

1.打开蓝牙适配器 

function openBluetooth() {uni.openBluetoothAdapter({success() {uni.offBluetoothDeviceFound();// 监听新设备发现事件uni.onBluetoothDeviceFound((res) => {res.devices.forEach(device => {if (device.name && device.name.startsWith('one-parking')) {const existingDevice = devicesInfo.value.find(d => d.deviceId === device.deviceId);if (!existingDevice) {devicesInfo.value.push(device);}}});});// 开始搜索蓝牙设备uni.startBluetoothDevicesDiscovery({success() {console.log('开始搜索蓝牙设备...');// 设置一个定时器,在一定时间后停止搜索setTimeout(stopDiscovery, 10000);},fail(err) {console.error('开始搜索失败', err);}});},fail() {uni.showToast({title: '请打开蓝牙',icon: 'none'});}});}

2.连接蓝牙

function connectBluetooth( data : any ) {bluetoothInfo.value = data;bluetoothInfo.value.deviceId = data.deviceId;uni.createBLEConnection({deviceId : data.deviceId,success() {// 判断连接的状态和断开重新连接checkSttusOrReconnect(data);// 获取蓝牙的服务ServiceIDuni.getBLEDeviceServices({deviceId : data.deviceId,success(servicesRes : any) {if(servicesRes.services.length > 0) {bluetoothInfo.value.serviceId = servicesRes.services[0].uuid;// 获取蓝牙的特征值characteristicIduni.getBLEDeviceCharacteristics({deviceId : data.deviceId,serviceId : servicesRes.services[0].uuid,success(resCharacter) {if(resCharacter.characteristics.length > 0) {bluetoothInfo.value.characteristics = resCharacter.characteristics;// 接受通知notify();let macAddress = data.name.split('-')[1];let password = calculatePassword(macAddress);let bondCommand = `phbond${password}`;sendMsg(bondCommand);}}})}}});}})}

提示:这里根据蓝牙的设备id连接后,一起获取了服务和特征id,用于方便后面蓝牙进行通信,其中的特征值是一个重点,不同的特征值id会对应不同的操作,不然就会操作不了其他的api,比如uni.notifyBLECharacteristicValueChange(OBJECT)这个就需要notify 或者 indicate 才可以成功调用

3.监听蓝牙的通知

    // 接收蓝牙端发送的通知function notify() {uni.notifyBLECharacteristicValueChange({state: true,// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接deviceId : bluetoothInfo.value.deviceId,serviceId: bluetoothInfo.value.serviceId,characteristicId : bluetoothInfo.value.characteristics.find(item => item.properties.notify).uuid,success() {monitorMsg();},fail(res) {console.log('不支持这个notify' + JSON.stringify(res))}})}function monitorMsg() {uni.onBLECharacteristicValueChange((res : any) => {console.log("发送过来的数据---------", res);let resHex = ab2ascii(res.value)console.log("转换后的简易数据----------",resHex);});}

 提示: 刚刚在上面说到的点就是特征值id有多个,需要有对应的特征权限

 4.发送数据

    // 向蓝牙写数据function sendMsg( msg : string ) {uni.writeBLECharacteristicValue({deviceId : bluetoothInfo.value.deviceId,serviceId: bluetoothInfo.value.serviceId,characteristicId : bluetoothInfo.value.characteristics.find(item => item.properties.write).uuid,value: asciiToArrayBuffer(msg) as any,writeType: 'write',success(res) {console.log('消息发送成功', res)},fail(res) {console.log('消息发送失败', res)}});}

注意:其中写数据需要向设备写的是二进制,所以需要转换一下

    // 二进制转化工具function ab2ascii(buffer : ArrayBuffer) {var str = Array.prototype.map.call(new Uint8Array(buffer),function(bit : any) {return String.fromCharCode(bit);})return str.join('');}function asciiToArrayBuffer(str : string) {if (!str) {return new ArrayBuffer(0);}var buffer = new ArrayBuffer(str.length);var bufView = new Uint8Array(buffer);for (var i = 0, strLen = str.length; i < strLen; i++) {bufView[i] = str.charCodeAt(i);}return buffer;}

5.监听蓝牙的状态并发现断开重连

function checkSttusOrReconnect( data : any ) {uni.onBLEConnectionStateChange(function (state) {if (!state.connected) {console.warn('与设备' + data.name + '的连接已断开');if(breakCount.value < 2) {reconnectionTimer = setTimeout(()=>{connectBluetooth(bluetoothInfo.value);},3000);}breakCount.value += 1;} else {console.log('与设备 ' + data.name + ' 的连接已建立');if(reconnectionTimer) { clearTimeout(reconnectionTimer) }breakCount.value = 0;}});
}

6.完整的demo代码(设备是车辆地锁)

<template><view class="pageBox"><view style="font-size: 22px;text-align: center;margin-top: 32px;">蓝牙测试用例</view><view style="margin: 12px;display: flex;flex-direction: column;"><radio-group style="margin: 12px;gap: 26px;display: flex;flex-wrap: wrap;padding: 6px;"><radio value="phup" @click="cmdText = 'phup'">phup(升)</radio><radio value="phdown" @click="cmdText = 'phdown'">phdown(降)</radio><radio value="phstatus" @click=" cmdText = 'phstatus'">phstatus(状态)</radio></radio-group><button @click="sendControllCmd()" style="background-color: #564DD6;color: #fff;border-radius: 26px;margin: 12px;">发送指令</button></view><view style="margin: 22px;font-size: 18px;font-weight: bold;color: royalblue;">蓝牙设置信息:</view><view v-for="devices in devicesInfo"><view style="justify-content: space-between;border-radius: 8px;display: flex;margin: 12px;margin:12px 22px;background-color: #fff;border: 2px dashed #564DD6;padding: 12px;"><view style="display: flex;flex-direction: column;gap: 6px;"><view>设备名称:{{devices.name}}</view><view>ID: {{devices.deviceId}}</view></view><view><button style="margin: 6px;border-radius: 6px;background-color: #9A2CD7;color: #fff;" size="mini" @click="connectBluetooth(devices)">连接</button></view></view></view></view>
</template><script setup lang="ts">import { onReady } from "@dcloudio/uni-app";import { ref } from "vue";onReady(()=>{openBluetooth();});let devicesInfo = ref([]);let reconnectionTimer : any;let breakCount = ref<number>(0);function openBluetooth() {uni.openBluetoothAdapter({success() {uni.offBluetoothDeviceFound();// 监听新设备发现事件uni.onBluetoothDeviceFound((res) => {res.devices.forEach(device => {if (device.name && device.name.startsWith('one-parking')) {const existingDevice = devicesInfo.value.find(d => d.deviceId === device.deviceId);if (!existingDevice) {devicesInfo.value.push(device);}}});});// 开始搜索蓝牙设备uni.startBluetoothDevicesDiscovery({success() {console.log('开始搜索蓝牙设备...');// 设置一个定时器,在一定时间后停止搜索setTimeout(stopDiscovery, 10000);},fail(err) {console.error('开始搜索失败', err);}});},fail() {uni.showToast({title: '请打开蓝牙',icon: 'none'});}});}function stopDiscovery() {uni.stopBluetoothDevicesDiscovery({success() {console.log('停止蓝牙嗅探成功');},fail(err) {console.error('停止蓝牙嗅探失败', err);}});}// 地锁密码获取: 提取MAC地址的最后6位转换为十进制 , 加上520168 , 取结果的最后六位function calculatePassword(mac : string) {let lastSixHex = mac.slice(-6);let hexToInt = parseInt(lastSixHex, 16);let sum = hexToInt + 520168;let finalPassword = ('000000' + sum).slice(-6);return finalPassword;}let bluetoothInfo = ref({deviceId: '',serviceId: '',characteristics: [],devicesInfo: {} // 连接的蓝牙设备});function connectBluetooth( data : any ) {bluetoothInfo.value = data;bluetoothInfo.value.deviceId = data.deviceId;uni.createBLEConnection({deviceId : data.deviceId,success() {// 判断连接的状态和断开重新连接checkSttusOrReconnect(data);// 获取蓝牙的服务ServiceIDuni.getBLEDeviceServices({deviceId : data.deviceId,success(servicesRes : any) {if(servicesRes.services.length > 0) {bluetoothInfo.value.serviceId = servicesRes.services[0].uuid;// 获取蓝牙的特征值characteristicIduni.getBLEDeviceCharacteristics({deviceId : data.deviceId,serviceId : servicesRes.services[0].uuid,success(resCharacter) {if(resCharacter.characteristics.length > 0) {bluetoothInfo.value.characteristics = resCharacter.characteristics;// 接受通知notify();let macAddress = data.name.split('-')[1];let password = calculatePassword(macAddress);let bondCommand = `phbond${password}`;sendMsg(bondCommand);}}})}}});}})}// 检查设备并重连function checkSttusOrReconnect( data : any ) {uni.onBLEConnectionStateChange(function (state) {if (!state.connected) {console.warn('与设备' + data.name + '的连接已断开');if(breakCount.value < 2) {reconnectionTimer = setTimeout(()=>{connectBluetooth(bluetoothInfo.value);},3000);}breakCount.value += 1;} else {console.log('与设备 ' + data.name + ' 的连接已建立');if(reconnectionTimer) { clearTimeout(reconnectionTimer) }breakCount.value = 0;}});}// 接收蓝牙端发送的通知function notify() {uni.notifyBLECharacteristicValueChange({state: true,// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接deviceId : bluetoothInfo.value.deviceId,serviceId: bluetoothInfo.value.serviceId,characteristicId : bluetoothInfo.value.characteristics.find(item => item.properties.notify).uuid,success() {monitorMsg();},fail(res) {console.log('不支持这个notify' + JSON.stringify(res))}})}function monitorMsg() {uni.onBLECharacteristicValueChange((res : any) => {console.log("发送过来的数据---------", res);let resHex = ab2ascii(res.value)console.log("转换后的简易数据----------",resHex);});}let cmdText = ref('');function sendControllCmd() {console.log('发送的指令:' + cmdText.value);sendMsg(cmdText.value);}// 向蓝牙写数据function sendMsg( msg : string ) {uni.writeBLECharacteristicValue({deviceId : bluetoothInfo.value.deviceId,serviceId: bluetoothInfo.value.serviceId,characteristicId : bluetoothInfo.value.characteristics.find(item => item.properties.write).uuid,value: asciiToArrayBuffer(msg) as any,writeType: 'write',success(res) {console.log('消息发送成功', res)},fail(res) {console.log('消息发送失败', res)}});}// 二进制转化工具function ab2ascii(buffer : ArrayBuffer) {var str = Array.prototype.map.call(new Uint8Array(buffer),function(bit : any) {return String.fromCharCode(bit);})return str.join('');}function asciiToArrayBuffer(str : string) {if (!str) {return new ArrayBuffer(0);}var buffer = new ArrayBuffer(str.length);var bufView = new Uint8Array(buffer);for (var i = 0, strLen = str.length; i < strLen; i++) {bufView[i] = str.charCodeAt(i);}return buffer;}</script> <style scoped lang="scss">.pageBox {height: 100%;width: 100%;position: fixed;}
</style>
ui界面
UI操作界面

操作台连接和蓝牙通知日志

最后官方文档地址:
Uniapp蓝牙连接文档icon-default.png?t=O83Ahttps://uniapp.dcloud.net.cn/api/system/bluetooth.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/bicheng/64485.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

web:pc端企业微信登录-vue版

官方文档&#xff1a;developer.work.weixin.qq.com/document/pa… 不需要调用ww.register&#xff0c;直接调用ww.createWWLoginPanel即可创建企业微信登录面板 - 文档 - 企业微信开发者中心 (qq.com) 引入 //通过 npm 引入 npm install wecom/jssdk import * as ww from we…

登陆harbor发现证书是错误的, 那么如何更新harbor的证书呢

Error response from daemon: Get "https://172.16.21.35/v2/": tls: failed to verify certificate: x509: certificate is valid for 127.0.0.1, ::1, 172.16.21.30, not 172.16.21.35 版本 v2.10.1-b7b88476 不需要从头看, 直接看最下面的成功的证书创建 这里面首…

外观模式的理解和实践

外观模式&#xff08;Facade Pattern&#xff09;是一种常用的软件设计模式&#xff0c;它提供了一个统一的接口&#xff0c;用来访问子系统中的一群接口。该模式定义了一个高层的接口&#xff0c;使得子系统更容易使用。简单来说&#xff0c;外观模式就是通过引入一个外观角色…

excel使用笔记

1.工作表1计算工作表2某列的和 假设我们有两个工作表&#xff0c;分别命名为“Sheet1”和“Sheet2”&#xff0c;我们想要求和这两个工作表中A1到A**单元格的数据&#xff0c;可以在任意一个工作表的单元格中输入以下公式&#xff1a; SUM(Sheet1!A1:A10, Sheet2!A1:A10) SUM…

《应用导航设计:裂变式路由风暴来袭》——HarmonyOS开发项目时的Navigation路由奇妙使用

文章目录 应用导航设计引言概述场景示例基本实现推荐方案路由管理模块的实现页面跳转实现 业务实现中的关键点动态加载路由栈管理 应用导航设计 引言 在大型应用开发中&#xff0c;如何高效地设计应用导航&#xff0c;处理多模块间的路由跳转与解耦&#xff0c;始终是一个关键…

【腾讯云】AI驱动TDSQL-C Serveress 数据库技术实战营-如何是从0到1体验电商可视化分析小助手得统计功能,一句话就能输出目标统计图

欢迎来到《小5讲堂》 这是《腾讯云》系列文章&#xff0c;每篇文章将以博主理解的角度展开讲解。 温馨提示&#xff1a;博主能力有限&#xff0c;理解水平有限&#xff0c;若有不对之处望指正&#xff01; 目录 背景效果图流程图创建数据库基本信息数据库配置设置密码控制台开启…

XSLT 编辑 XML

XSLT 编辑 XML 介绍 XSLT&#xff08;可扩展样式表语言转换&#xff09;是一种用于转换XML文档的语言。它允许开发人员将XML数据转换为其他格式&#xff0c;如HTML、PDF或纯文本。XSLT通过使用XPath查询来定位XML文档中的元素&#xff0c;并对这些元素应用转换规则。在本教程…

thinkphp8自带分页bootstrap

tp8引用的是bootstrap3.4.1这个版本&#xff1b; 前端结构&#xff1a; <ul class"pagination"><li><a href"/index.php?page4"></a></li><li><a href"/index.php?page1">1</a></li>…

win服务器的架设、windows server 2012 R2 系统的下载与安装使用

文章目录 windows server 2012 R2 系统的下载与安装使用1 windows server 2012 的下载2 打开 VMware 虚拟机软件&#xff08;1&#xff09;新建虚拟机&#xff08;2&#xff09;设置虚拟机&#xff08;3&#xff09;打开虚拟机 windows server 2012&#xff08;4&#xff09;进…

如何在谷歌浏览器中开启安全浏览

在数字化时代&#xff0c;网络安全变得愈发重要。作为全球最受欢迎的网络浏览器之一&#xff0c;谷歌浏览器提供了多种功能来保护用户的在线安全。本文将详细介绍如何在谷歌浏览器中开启安全浏览&#xff0c;并额外提供一些有用的页面滚动设置、地址栏快捷搜索和跟踪防护的相关…

djiango DRF的使用

djiango DRF的使用 一 、初始 DRF序列化环境安装环境配置数据模型定义定义DRF序列化模型对象 二 、DRF请求和响应请求对象&#xff08;Request objects&#xff09;响应对象&#xff08;Response objects&#xff09;状态码&#xff08;Status codes&#xff09;包装&#xff0…

如何使用 Python 连接 PostgreSQL 数据库?

在Python开发中&#xff0c;连接PostgreSQL数据库是一个常见的需求。 我们可以使用多种库来实现这一功能&#xff0c;其中最常用的是psycopg2。 下面我将详细介绍如何使用psycopg2来连接PostgreSQL数据库&#xff0c;并提供一些实际开发中的建议和注意事项。 1. 使用 psycop…

计算机网络-HTTP协议

HTTP HTTP是一种不保存状态&#xff0c;即无状态的协议。HTTP协议自身不对请求和响应之间的通信进行保存。为了保存状态因此后面也有一些技术产生比如Cookies技术。 HTTP是通过URI定位网上的资源&#xff0c;理论上将URI可以访问互联网上的任意资源。 如果不是访问特定的资源…

CTFHub 命令注入-综合练习(学习记录)

综合过滤练习 命令分隔符的绕过姿势 ; %0a %0d & 那我们使用%0a试试&#xff0c;发现ls命令被成功执行 /?ip127.0.0.1%0als 发现一个名为flag_is_here的文件夹和index.php的文件&#xff0c;那么我们还是使用cd命令进入到文件夹下 http://challenge-438c1c1fb670566b.sa…

前端 下载文件时如何处理后端返回的 文件流

在前端&#xff0c;处理文件下载通常涉及到接受一个 文件流&#xff08;Blob 或者 ArrayBuffer&#xff09;&#xff0c;然后将它转换成可以下载的链接。以下是实现前端文件下载并接受文件流的一些常见方法。 1. 使用 Blob 和 URL.createObjectURL 创建下载链接 假设后端返回…

HttpSevletRequest Body信息不能被多次读取的问题

在 Java Web 开发中&#xff0c;HTTP 请求体是客户端向服务器发送数据的主要载体&#xff0c;例如表单提交、JSON 数据等。当服务器收到请求后&#xff0c;通常通过 HttpServletRequest 类获取请求体的内容。然而&#xff0c;HTTP 请求体通常只能被读取一次。这是因为请求体使用…

ARM CCA机密计算安全模型之受保护内存

安全之安全(security)博客目录导读 目录 1、一般威胁模型 2、可能的缓解措施 3、CCA 使用外部内存 4、外部内存初始化 5、资产 6、基线内存保护配置文件 7、内存清理 8、额外的内存保护 许多 Realm 和 CCA 资产存储在外部内存中。本博客讨论针对基于内存攻击的缓解措施…

ubuntu升级python版本

Ubuntu升级Python版本 解压缩文件&#xff1a; 下载完成后&#xff0c;解压缩文件&#xff1a; tar -xf Python-3.12.0.tgz编译并安装&#xff1a; 进入解压后的目录&#xff0c;然后配置和安装Python&#xff1a; codecd Python-3.12.0 ./configure --enable-optimizations ma…

从Windows到Linux:跨平台数据库备份与还原

数据库的备份与还原 目录 引言备份 2.1 备份所有数据库2.2 备份单个数据库2.3 备份多个指定数据库 传输备份文件还原 4.1 还原所有数据库4.2 还原单个数据库4.3 还原多个指定数据库 注意事项拓展 1. 引言 在不同的操作系统间进行数据库迁移时&#xff0c;命令行工具是我们的…

准备写一个内网穿透的工具

准备写一个内网穿透的工具&#xff0c;目前只实现了HTTP内网穿透的GET方式&#xff0c;看能不能坚持写下去 git地址&#xff1a; xuejiazhi/PortRelay