uniapp:蓝牙模块

模拟的是蓝牙设备签到/签出:

  1. 获取指定蓝牙设备
  2. 蓝牙初始搜索次数限制,超过限制就停止搜索
  3. 蓝牙连接失败次数限制,超过限制标识蓝牙连接失败(离开蓝牙范围或其他原因)
  4. 自动重连指定蓝牙
const device = ref<any>(null); // 设备信息
const crpBlueList = ref<any[]>([]); // 扫描到的蓝牙信息列表
const linkStatus = ref(false); // 连接状态
const searchTimes = ref(0); // 搜索次数
const searchLimit = 5; // 搜索次数限制
const linkTimes = ref(0); // 扫描次数
const failTimes = ref(0); // 失败次数
const failLimit = 5; // 失败次数限制
const blueName = 'zo-crp'; // 指定蓝牙设备的名称前缀
let isSignIn = false; // 是否签到
// 签到
const signIn = () => {searchTimes.value = 0;uni.showLoading({title: '蓝牙搜索中...',mask: true});openBluetoothAdapter(() => {startBluetoothDeviceDiscovery();});
};
// 签出
const logout = () => {closeBlueTooth(device.value, () => {isSignIn = false;device.value = null;linkStatus.value = false;searchTimes.value = 0;linkTimes.value = 0;failTimes.value = 0;crpBlueList.value = [];uni.showToast({title: '已签出'});});
};
// 初始化蓝牙
const openBluetoothAdapter = (callback: Function) => {uni.openBluetoothAdapter({//打开蓝牙适配器接口success: (res) => {//已打开callback();},fail: (err) => {uni.hideLoading();uni.showModal({title: '',content: '该操作需要蓝牙支持!请打开蓝牙',showCancel: false,success: (res) => {if (res.confirm) {// #ifdef APPlet main = plus.android.runtimeMainActivity();let Intent = plus.android.importClass('android.content.Intent');let mIntent = new Intent('android.settings.BLUETOOTH_SETTINGS');main.startActivity(mIntent);// #endif} else {navigateBack();}},complete: () => {}});}});
};
// 搜索蓝牙
const startBluetoothDeviceDiscovery = () => {if (searchTimes.value > searchLimit - 1) {uni.showModal({content:'没有找到指定的蓝牙设备,请确认所在位置周边有指定蓝牙设备,且手机已开启位置信息并授权',confirmText: '重试',success: (res) => {if (res.confirm) {signIn();} else {stopBluetoothDevicesDiscovery(() => {uni.closeBluetoothAdapter({complete: () => {navigateBack();}});});}}});return;}searchTimes.value += 1;uni.startBluetoothDevicesDiscovery({success: (res) => {// 发现外围设备onBluetoothDeviceFound();},fail: (err) => {console.log(err, '开始搜索蓝牙设备备错误信息');}});
};
// 发现设备
const onBluetoothDeviceFound = () => {let t: any = setTimeout(() => {clearTimeout(t);t = null;stopBluetoothDevicesDiscovery(() => {// 停止搜索蓝牙uni.getBluetoothDevices({success: (res) => {const blueList = res.devices.filter((item: any) => item.name.toLowerCase().startsWith(blueName)).sort((a: any, b: any) => b.RSSI - a.RSSI);crpBlueList.value = blueList;if (!blueList.length) {startBluetoothDeviceDiscovery();return;}const Device: any = blueList[0];isSignIn = true;// 获取电量const serviceData = Array.prototype.map.call(new Uint8Array(Device.serviceData[Object.keys(Device.serviceData)[0]]), (bit) =>bit.toString(16)).join('');const Electric = parseInt(serviceData.slice(-2), 16);// 获取uuidconst UUID = Array.prototype.map.call(new Uint8Array(Device.advertisData), (bit) => ('00' + bit.toString(16)).slice(-2)).join('').substring(8, 40).toUpperCase();device.value = {name: Device.name,deviceId: Device.deviceId,electric: Electric,RSSI: Device.RSSI,UUID: UUID};linkStatus.value = true;createBLEConnection(Device);}});});}, 2000);
};
// 连接设备
const createBLEConnection = (item: any) => {uni.showLoading({title: '连接中,请稍等',mask: true});linkTimes.value += 1;uni.createBLEConnection({deviceId: item.deviceId,success(res) {linkStatus.value = true;failTimes.value = 0;uni.showToast({title: '蓝牙已连接',mask: true});onBLEConnectionStateChange(item);},fail(res) {linkStatus.value = false;plus.device.vibrate(500);if (failTimes.value < failLimit) {failTimes.value += 1;uni.showToast({title: item.name + '蓝牙连接失败',icon: 'none'});reLink(item);} else {closeBlueTooth(item, () => {uni.showToast({title: item.name + '蓝牙连接失败,取消连接',icon: 'none'});});}}});
};
// 监听蓝牙状态
const onBLEConnectionStateChange = (item: any) => {uni.onBLEConnectionStateChange((res) => {m_Debounce(() => {if (!res.connected && isSignIn) {reLink(item);}}, 500);});
};
// 蓝牙重连
const reLink = (item: any) => {closeBlueTooth(item, () => {let t: any = setTimeout(() => {clearTimeout(t);t = null;openBluetoothAdapter(() => {createBLEConnection(item);});}, 1000);});
};// 关闭连接+关闭蓝牙模块
const closeBlueTooth = (item: any, callback: Function) => {// 关闭连接uni.closeBLEConnection({deviceId: item.deviceId,complete: () => {// 关闭蓝牙模块uni.closeBluetoothAdapter({complete: () => {callback();}});}});
};// 停止搜索
const stopBluetoothDevicesDiscovery = (callback: Function) => {uni.stopBluetoothDevicesDiscovery({complete: (e) => {callback();},fail: (e) => {console.log('停止搜索蓝牙设备失败,错误码:' + e.errCode);}});
};
// 后退
const navigateBack = () => {uni.navigateBack({delta: 1,fail: () => {uni.reLaunch({url: '/pages/home/home'});}});
};

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

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

相关文章

MMSegmentation训练自己的语义分割数据集

全流程&#xff0c;训练语义分割数据集 数据标注json转mask 运行源码MMSegmentation模型选择运行部分 数据标注 # 安装 pip install labelme # 启动labelme labelme然后 ctrl N 开启多边形标注即可&#xff0c;命名类为person 之后会保存到同目录下json文件&#xff1a; js…

go-grpc环境编译搭建

1、安装protoc工具 # 地址 https://github.com/protocolbuffers/protobuf/releases # 下载Win64版本的 https://github.com/protocolbuffers/protobuf/releases/download/v3.19.4/protoc-3.19.4-win64.zip # 设置环境变量2、安装protoc-gen-go插件 > go get -u github.com…

【YOLOV5】YOLOV5添加SPPCSPC

当前YOLOV5版本为7.0 第一步 在models/common.py添加SPPCSPC class SPPCSPC(nn.Module):# CSP https://github.com/WongKinYiu/CrossStagePartialNetworksdef __init__(self, c1, c2, n1, shortcutFalse, g1, e0.5, k(5, 9, 13)):super(SPPCSPC, self).__init__()c_ int(2 *…

java.lang.classnotfoundexception: com.android.tools.lint.client.api.vendor

Unity Android studio打包报错修复 解决方式 java.lang.classnotfoundexception: com.android.tools.lint.client.api.vendor 解决方式 在 launcherTemplate 目录下找到 Android/lintOptions 选项 加上 checkReleaseBuilds false lintOptions { abortOnError false checkRelea…

Spring Bean 生命周期顺序验证

看到一篇写的很好的 Spring Bean 生命周期的博客&#xff1a;一文读懂 Spring Bean 的生命周期&#xff0c;在此写个简单的 Bean 进行验证。 1. 创建Springboot项目 基于 springboot 的2.1.8.RELEASE 创建一个简单项目&#xff0c;只添加 spring-aop 包以引入spring依赖。 &…

Redis下载和安装(Windows系统)

文章目录 创建Redis临时服务1) 启动服务端程序2) 启动客户端程序命令创建Redis服务3) 启动Redis客户端4) 检查是否连接成功 为便于大多数读者学习本套教程&#xff0c;教程中采用 Windows 系统对 Redis 数据库进行讲解。虽然 Redis 官方网站没有提供 Windows 版的安装包&#x…

进程间通信

一、进程间通信&#xff08;interprocess communication&#xff0c;简称 IPC&#xff09;指两个进程之间的通信。 系统中每个进程都有自己的地址空间&#xff0c;并且相互独立、隔离&#xff0c;每个进程都处于自己的地址空间中。 二、通信机制 Linux 内核提供了多种 IPC 机制…

无涯教程-Android - List View函数

Android ListView 是垂直滚动列表中显示的视图&#xff0c;使用 Adapter 从列表(如数组或数据库)中获取内容的列表项会自动插入列表中。 适配器(Adapter)实际上是UI组件和将数据填充到UI组件中的数据源之间的桥梁&#xff0c;适配器保存数据并将数据发送到适配器视图&#xff0…

WordPress(3)会员插件安装

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 前言一、服务器中上传插件二、使用步骤1.启动插件前言 提示:会员插件的安装不能在网站后台插件中心中直接安装原因我还没有排查 原因:会导致网站停止运行 一、服务器中上传插件 二、使用步骤 …

ubuntu 上安装flutter dart android studio

因为国内网站不能使用 使用一下&#xff1a; vi ~/.bashrc 最后添加 export FLUTTER_STORAGE_BASE_URLhttps://mirrors.cloud.tencent.com/flutter export PUB_HOSTED_URLhttps://mirrors.tuna.tsinghua.edu.cn/dart-pub export PATH$PATH:/usr/local/go/bin export GOPROXY…

Python钢筋混凝土结构计算.pdf-混凝土强度设计值

计算原理&#xff1a; 需要注意的是&#xff0c;根据不同的规范和设计要求&#xff0c;上述公式可能会有所差异。因此&#xff0c;在进行混凝土强度设计值的计算时&#xff0c;请参考相应的规范和设计手册&#xff0c;以确保计算结果的准确性和合规性。 代码实现&#xff1a; …

vue点击按钮重新加载页面(vue第一次加载页面点击按钮出现页面刷新问题之后一切正常)

问题描述 所开发的vue项目每次跑起来之后就会出现点击按钮后重新加载整个页面的问题&#xff0c;但是只会在第一次点击的时候出现&#xff0c;后面就不会在出现加载整个页面的情况。 原因 在form表单中使用button按钮导致form表单进行了页面刷新。button默认的“type‘submi…

NTT总结

https://www.luogu.com.cn/problem/P3803 公式&#xff1a; ω n 1 ≡ g p − 1 n ( m o d p ) \large\omega_n^1\equiv g^{\frac {p-1}n}\pmod p ωn1​≡gnp−1​(modp) 然后所有单位根运算都可以转成原根了&#xff01;&#xff08;前提 p p p 为质数&#xff09; p p p …

el-select 使用

案例&#xff1a; /* * label : 界面上展示的是哪个字段,我这里需要展示名称 * value : 绑定的字段&#xff0c;一般是id */<el-selectv-model"Form.BillNumber"placeholder"请选择"change"changeValue($event)"><el-optionv-for"…

MySQL数据库开发规范

一、基础规范 表存储引擎必须使用InnoDB 表字符集默认使用utf8&#xff0c;必要时候使用utf8mb4 解读&#xff1a; &#xff08;1&#xff09;通用&#xff0c;无乱码风险&#xff0c;汉字3字节&#xff0c;英文1字节 &#xff08;2&#xff09;utf8mb4是utf8的超集&#xff…

ThePASS研究院|以Safe为例,解码DAO国库管理

本研究文章由ThePASS团队呈现。ThePASS是一家开创性的DAO聚合器和搜索引擎&#xff0c;在为DAO提供洞察力和分析方面发挥着关键作用。 Intro 随着去中心化自治组织&#xff08;DAOs&#xff09;的发展&#xff0c;它们被赋予了越来越多的角色和期望。在这种巨幅增长的背景下&…

ToBeWritten之VSOC安全运营

也许每个人出生的时候都以为这世界都是为他一个人而存在的&#xff0c;当他发现自己错的时候&#xff0c;他便开始长大 少走了弯路&#xff0c;也就错过了风景&#xff0c;无论如何&#xff0c;感谢经历 转移发布平台通知&#xff1a;将不再在CSDN博客发布新文章&#xff0c;敬…

论文阅读_医疗知识图谱_GraphCare

英文名称: GraphCare: Enhancing Healthcare Predictions with Open-World Personalized Knowledge Graphs 中文名称: GraphCare&#xff1a;通过开放世界的个性化知识图增强医疗保健预测 文章: http://arxiv.org/abs/2305.12788 代码: https://github.com/pat-jj/GraphCare 作…

Mac版JFormDesigner IDEA插件安装(非商业用途)

前言 仅供个人开发者使用&#xff0c;勿用作商业用途。 仅供个人开发者使用&#xff0c;勿用作商业用途。 仅供个人开发者使用&#xff0c;勿用作商业用途。 感觉做了这些年开发&#xff0c;怎么感觉市场越搞越回去了。桌面应用又成主流了&#xff1f; 甲方让做桌面客户端&am…

搭建个人备忘录中心服务memos、轻量级笔记服务

目录 一、源码 二、官网 三、搭建 四、使用 一、源码 GitHub - usememos/memos: A privacy-first, lightweight note-taking service. Easily capture and share your great thoughts. 二、官网 memos - Easily capture and share your great thoughts 三、搭建 docke…