uniapp微信小程序蓝牙连接与设备数据对接

蓝牙连接并通信方法封装大致步骤。

  1. 初始化蓝牙并搜索;
  2. 获取并启用service服务;
  3. 数据读取和监听设备返回数据
需要使用uniapp官方提供api:
// 关闭蓝牙
uni.closeBluetoothAdapter({})
// 打开蓝牙
uni.openBluetoothAdapter({})
// 搜索附近的蓝牙
uni.startBluetoothDevicesDiscovery({})
// 停止搜索
uni.stopBluetoothDevicesDiscovery({})
// 连接低功耗BLE蓝牙
uni.createBLEConnection({})
// 获取蓝牙设备所有服务(service)
uni.getBLEDeviceServices({})
// 获取蓝牙特征值
uni.getBLEDeviceCharacteristics({})
// 启用低功耗蓝牙设备特征值变化时的 notify 功能,订阅特征值
uni.notifyBLECharacteristicValueChange({})
// 监听低功耗蓝牙设备的特征值变化事件
uni.onBLECharacteristicValueChange({})
// 读取低功耗蓝牙设备的特征值的二进制数据值
uni.readBLECharacteristicValue({})

1、开启蓝牙适配器初始化蓝牙模块,获取手机蓝牙是否打开

const getBluetoothState = () => {return new Promise((resolve, reject) => {uni.openBluetoothAdapter({mode: 'central', // 主机模式success: (r) => {console.log("蓝牙初始化成功");// 获取蓝牙的匹配状态uni.getBluetoothAdapterState({success: function(row) {console.log('蓝牙状态:', row.available);if (row.available) {// 蓝牙连接成功,开启蓝牙设备搜索resolve();} else {// 请开启蓝牙uni.showToast({title: "请开启蓝牙",icon: 'none',duration: 2000});reject();}},fail: function(err) {// 请开启蓝牙uni.showToast({title: "请开启蓝牙",icon: 'none',duration: 2000});reject();}})},fail: () => {// 请开启蓝牙uni.showToast({title: "请开启蓝牙",icon: 'none',duration: 2000});reject();}});});
}

2、开启蓝牙设备搜索

const discoveryBluetooth = () => {return new Promise((resolve) => {uni.startBluetoothDevicesDiscovery({success(res) {uni.showLoading({title: "正在搜索设备",icon:"none",duration: 2000});console.log('搜索蓝牙外围设备完成', res)setTimeout(() => {// 监听寻找到的蓝牙设备resolve();}, 2000);}});});
}

3、获取搜索到的设备信息

const getBluetoothDevices = () => {return new Promise((resolve, reject) => {uni.getBluetoothDevices({success(res) {// 过滤掉name为空或者未知设备的设备let devices = res.devices.filter(function(obj) {return obj.name !== "" && obj.name !== "未知设备"});devices && devices.forEach(item => {// 获取指定连接deviceIdif(item.name && item.name.substring(0, 5) === 'aaaa-'){// aaaa-*********蓝牙设备型号,根据需求选择设备型号// item.deviceId;}});},fail: function() {console.log('搜索蓝牙设备失败');reject();},complete: function() {console.log("蓝牙搜索完成");resolve();}});});
}

4、关闭蓝牙搜索

const stopDiscoveryBluetooth = () => {uni.stopBluetoothDevicesDiscovery({success(r) {console.log("停止搜索蓝牙设备", r);}});
};

5、连接蓝牙

const connectBluetooth = () => {return new Promise((resolve, reject) => {uni.createBLEConnection({deviceId: deviceId, // 设备idsuccess() {// 蓝牙连接成功后关闭蓝牙搜索并获取服务idstopDiscoveryBluetooth();resolve();// 获取服务idgetServiceId();},fail() {console.log("蓝牙连接失败");reject();}});});
};

6、获取服务id

const getServiceId = () => {uni.getBLEDeviceServices({deviceId: deviceId,success(res) {console.log("获取服务Id", res)// serviceId固定,获取蓝牙设备某个服务中的所有特征值【读写属性】let model = res.services[0];serviceId = model.uuid;// 调用蓝牙监听和写入功能getCharacteId();},fail(err){console.log('获取服务失败', err);}})
};

7、获取蓝牙低功耗设备某个服务中所有特征

const getCharacteId = () => {uni.getBLEDeviceCharacteristics({deviceId: deviceId, // 蓝牙设备idserviceId: serviceId, // 蓝牙服务UUIDsuccess(res) {console.log('数据监听', res);res.characteristics.forEach(item => {// 003if (item.properties.notify === true) {// 监听notify = item.uuid;}// 002if (item.properties.write === true) {// 写入let writeId = item.uuid;}});},fail(err) {console.log("数据监听失败", err)}})
};

8、监听设备返回数据,启用低功耗蓝牙设备特征值变化时的notify功能

const startNotice = () => {uni.notifyBLECharacteristicValueChange({characteristicId: notify,deviceId: deviceId,serviceId: serviceId,state: true,success(res) {// 监听低功耗蓝牙设备的特征值变化uni.onBLECharacteristicValueChange(result => {console.log("监听低功耗蓝牙设备的特征值变化", result);if (result.value) {console.log('设备返回数据', result.value)}})}});
};

9、向蓝牙设备发送数据

const writeData = (buffer) => {return new Promise((resolve, reject) => {uni.writeBLECharacteristicValue({characteristicId: uni.getStorageSync("writeId"),deviceId: deviceId,serviceId: serviceId,value: buffer,success(res) {console.log("writeBLECharacteristicValue success", res);resolve();},fail(err) {console.log("报错了", err);reject();}});});
};
封装完整方法:
import { TextDecoder } from 'text-encoding-utf-8';
let bluetoothOpen = false; // 手机蓝牙是否打开
let bluetoothConnect = false; // 设备和蓝牙是否连接
let isHaveDevice = false; // 是否查找到设备
let deviceId = null; // 设备id
let serviceId = null; // 服务id
let notify = null; // 监听uuid
let writeId = null; // 写入uuid
/*** 获取手机蓝牙是否打开*/
const getBluetoothState = () => {// 主机模式return new Promise((resolve, reject) => {uni.openBluetoothAdapter({mode: 'central',success: (r) => {console.log("蓝牙初始化成功");// 获取蓝牙的匹配状态uni.getBluetoothAdapterState({success: function(row) {console.log('蓝牙状态:', row.available);if (row.available) {bluetoothOpen = true;resolve();} else {// 请开启蓝牙bluetoothOpen = false;bluetoothConnect = false;reject();}},fail: function(err) {// 请开启蓝牙bluetoothOpen = false;bluetoothConnect = false;reject();}})},fail: () => {// 请开启蓝牙bluetoothOpen = false;bluetoothConnect = false;reject();}});});
};
/*** 开始搜索蓝牙设备*/
const discoveryBluetooth = () => {return new Promise((resolve) => {uni.startBluetoothDevicesDiscovery({success(res) {console.log('搜索蓝牙外围设备完成', res)setTimeout(() => {resolve();}, 2000);}});})
};
// 关闭蓝牙搜索
const stopDiscoveryBluetooth = () => {uni.stopBluetoothDevicesDiscovery({success(r) {console.log("停止搜索蓝牙设备", r);}});
};
/*** 获取搜索到的设备信息*/
const getBluetoothDevices = () => {return new Promise((resolve, reject) => {uni.getBluetoothDevices({success(res) {bluetoothConnect = false;// 过滤掉name为空或者未知设备的设备let devices = res.devices.filter(function(obj) {return obj.name !== "" && obj.name !== "未知设备"});devices && devices.forEach(item => {if(item.name && item.name.substring(0, 5) === 'aaaa-'){deviceId = item.deviceId;}});},fail: function() {console.log('搜索蓝牙设备失败');bluetoothConnect = false;reject();},complete: function() {console.log("蓝牙搜索完成");// 是否具有当前设备if (deviceId) {isHaveDevice = true;} else {isHaveDevice = false;}resolve(isHaveDevice);}});});
}
/*** 连接蓝牙* deviceId 蓝牙设备id*/
const connectBluetooth = () => {return new Promise((resolve, reject) => {uni.createBLEConnection({deviceId: deviceId, // 设备idsuccess() {bluetoothConnect = true;// 蓝牙连接成功后关闭蓝牙搜索stopDiscoveryBluetooth();resolve();// 获取服务idgetServiceId();},fail() {bluetoothConnect = false;console.log("蓝牙连接失败");reject();}});});
};
// 获取服务id
const getServiceId = () => {uni.getBLEDeviceServices({deviceId: deviceId,success(res) {console.log("获取服务Id", res)let model = res.services[0];serviceId = model.uuid;// 调用蓝牙监听和写入功能getCharacteId();}})
};
// 获取蓝牙低功耗设备某个服务中所有特征
const getCharacteId = () => {uni.getBLEDeviceCharacteristics({deviceId: deviceId, // 蓝牙设备idserviceId: serviceId, // 蓝牙服务UUIDsuccess(res) {console.log('数据监听', res);res.characteristics.forEach(item => {// 003if (item.properties.notify === true) {// 监听notify = item.uuid;startNotice();}// 002if (item.properties.write === true) {// 写入let writeId = item.uuid;uni.setStorageSync("writeId", item.uuid);}});},fail(err) {console.log("数据监听失败", err)}})
};
// 启用低功耗蓝牙设备特征值变化时的notify功能
const startNotice = () => {uni.notifyBLECharacteristicValueChange({characteristicId: notify,deviceId: deviceId,serviceId: serviceId,state: true,success(res) {// 监听低功耗蓝牙设备的特征值变化uni.onBLECharacteristicValueChange(result => {console.log("监听低功耗蓝牙设备的特征值变化", result);if (result.value) {let decoder = new TextDecoder('utf-8');let data = decoder.decode(result.value);console.log('帽子返回数据', data)}})}});
};
// 蓝牙发送数据
const writeData = (buffer) => {return new Promise((resolve, reject) => {uni.writeBLECharacteristicValue({characteristicId: uni.getStorageSync("writeId"),deviceId: deviceId,serviceId: serviceId,value: buffer,success(res) {console.log("writeBLECharacteristicValue success", res);resolve();},fail(err) {console.log("报错了", err);reject();}});});
};
export default {getBluetoothState,discoveryBluetooth,stopDiscoveryBluetooth,getBluetoothDevices,connectBluetooth,getServiceId,getCharacteId,startNotice,writeData
};
使用案例:
<template><view class="device_container"></view>
</template><script>import bluetooth from '../bluetooth.js';export default {data() {return {bluetoothStatus: false, // 蓝牙连接状态}},methods: {// 获取蓝牙和设备是否已连接initBluetooth() {let _this = this;// 初始化蓝牙bluetooth.getBluetoothState().then(() => {// 搜索外围蓝牙设备bluetooth.discoveryBluetooth().then(() => {this.discoveryLoading = true;// 获取蓝牙设备bluetooth.getBluetoothDevices().then((isHaveDevice) => {if (isHaveDevice) {// 搜索到指定设备,连接蓝牙bluetooth.connectBluetooth().then(() => {_this.bluetoothStatus = true;}, () => {_this.bluetoothStatus = false;});} else {// 未搜到设备_this.bluetoothStatus = false;}}, () => {// 蓝牙搜索失败_this.bluetoothStatus = false;});});}, () => {// 未开启蓝牙_this.bluetoothStatus = false;});},// 向设备发送数据writeBlueData() {let obj = {cmd: 3,freq: 430125,speakable: 1};let objStr = JSON.stringify(obj);let buffer = new ArrayBuffer(objStr.length); // 每个字符占用2个字节let bufView = new Uint8Array(buffer);for (let i = 0; i < objStr.length; i++) {bufView[i] = objStr.charCodeAt(i);}bluetooth.writeData(buffer);}},onShow() {// 获取蓝牙和设备连接状态this.initBluetooth();},}
</script><style lang="scss">page {height: 100%;}
</style>

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

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

相关文章

服务器or虚拟机安装SSH和虚拟机or服务器设置远程服务权限

第一步 服务器/虚拟机安装SSH工具,这是外部SSH终端连接服务器/虚拟机的第一步! sudo apt update && sudo apt upgrade#更新apt sudo apt install openssh-server#安装SSH工具 service ssh status#查看SSh运行状态 sudo systemctl enable --now ssh#运行SSH工具第二步…

Pytorch-学习记录-1-Tensor

1. 张量 (Tensor): 数学中指的是多维数组&#xff1b; torch.Tensor data: 被封装的 Tensor dtype: 张量的数据类型 shape: 张量的形状 device: 张量所在的设备&#xff0c;GPU/CPU requires_grad: 指示是否需要计算梯度 grad: data 的梯度 grad_fn: 创建 Tensor 的 Functio…

Google Cloud dataflow streaming job简介

简单介绍 首先 gcp 的dataflow 是1个ETL 组件, 它是基于Apache beam的 Apache beam 是1个较新的开源ETL 框架。 对于我们常用的ETL tool Spring batch 有下面的区别 spring batch 更偏向batch &#xff08;后台处理&#xff09;的ETL&#xff0c; 而apache beam 同时支持bat…

[python 刷题] 3 Longest Substring Without Repeating Characters

[python 刷题] 3 Longest Substring Without Repeating Characters 题目&#xff1a; Given a string s, find the length of the longest substring without repeating characters. 这到提要求找的是最长的&#xff0c;没有重复符号的子字符串 解题思路是用双指针哈希表&…

mysql MVCC(多版本并发控制)理解

最近看MVCC相关资料&#xff0c;这边做一个记录总结&#xff0c;方便后续理解。 目录 一、MVCC相关概念 二、MVCC实现原理 1.隐藏字段 2.undo log 3.Read View 4.MVCC的整体处理流程 5. RC&#xff0c;RR级级别下的innoDB快照读有什么不同 6.总结 一、MVCC相关概念 1…

华为云云耀云服务器L实例评测|部署私有网盘 Nextcloud

华为云云耀云服务器L实例评测&#xff5c;部署私有网盘 Nextcloud 一、云耀云服务器L实例介绍1.1 云服务器介绍1.2 产品规格1.3 应用场景 二、云耀云服务器L实例配置2.1 重置密码2.2 服务器连接2.3 安全组配置 三、部署 Nextcloud3.1 Nextcloud 介绍3.2 Docker 环境搭建3.3 Nex…

LeetCode 面试题 08.06. 汉诺塔问题

文章目录 一、题目二、C# 题解 一、题目 在经典汉诺塔问题中&#xff0c;有 3 根柱子及 N 个不同大小的穿孔圆盘&#xff0c;盘子可以滑入任意一根柱子。一开始&#xff0c;所有盘子自上而下按升序依次套在第一根柱子上(即每一个盘子只能放在更大的盘子上面)。移动圆盘时受到以…

服务器的外网IP查阅方式

服务器的外网IP查阅方式 linux服务器查询外网ip地址&#xff0c;可以有以下三种方式查阅 查看服务器的外网IP 1、curl cip.cc IP : 183.1X.2XX.88 地址 : 中国 广东 深圳 运营商 : 电信 数据二 : 广东省深圳市 | 电信 数据三 : 中国广东省深圳市 | 电信 2、curl myip.ipip.n…

mysql面试题23:如果某个表有近千万数据,CRUD比较慢,如何优化?

该文章专注于面试,面试只要回答关键点即可,不需要对框架有非常深入的回答,如果你想应付面试,是足够了,抓住关键点 面试官:如果某个表有近千万数据,CRUD比较慢,如何优化? 当某个表存在近千万数据且CRUD(增删改查)操作比较慢时,可以考虑以下优化策略: 使用索引:索…

数百个下载能够传播 Rootkit 的恶意 NPM 软件包

供应链安全公司 ReversingLabs 警告称&#xff0c;最近观察到的一次恶意活动依靠拼写错误来诱骗用户下载恶意 NPM 软件包&#xff0c;该软件包会通过 rootkit 感染他们的系统。 该恶意软件包名为“node-hide-console-windows”&#xff0c;旨在模仿 NPM 存储库上合法的“node-…

Java中使用正则表达式

正则表达式 正则表达式&#xff08;Regular Expression&#xff09;是一种用于匹配、查找和替换文本的强大工具。它由一系列字符和特殊字符组成&#xff0c;可以用来描述字符串的模式。在编程和文本处理中&#xff0c;正则表达式常被用于验证输入、提取信息、搜索和替换文本等…

使用 Apache Camel 和 Quarkus 的微服务(一)

【squids.cn】 全网zui低价RDS&#xff0c;免费的迁移工具DBMotion、数据库备份工具DBTwin、SQL开发工具等 ​Apache Camel 绝非Java企业技术栈领域的新手。它由James Strachan在2007年创建&#xff0c;旨在实现著名的 "EIP 书"&#xff08;由Gregor Hohpe和Bobby W…

2.5 数字传输系统

笔记&#xff1a; 针对这一节的内容&#xff0c;我为您提供一个笔记的整理方法。将内容按重要性、逻辑关系进行组织&#xff0c;再进行简化。 ## 2.5 数字传输系统 ### 背景介绍&#xff1a; 1. **早期电话网**&#xff1a;市话局到用户采用双绞线电缆&#xff0c;长途干线采…

汇总开源大模型的本地API启动方式

文章目录 CodeGeex2ChatGLM2_6BBaichuan2_13Bsqlcoder开启后测试 CodeGeex2 from fastapi import FastAPI, Request from transformers import AutoTokenizer, AutoModel import uvicorn, json, datetime import torch import argparse try:import chatglm_cppenable_chatglm_…

git stash详解

stash:保存现场 1.建议&#xff08;规范&#xff09; &#xff1a;在功能未没有开发完毕前&#xff0c;不要commit 2.规定&#xff08;必须&#xff09; &#xff1a; 在没有commit之前&#xff0c;不能chekcout切换分支 &#xff08;不在同一个commit阶段&#xff09; 如果还没…

缓存与数据库双写一致性问题解决方案

其实如果使用缓存&#xff0c;就会出现缓存和数据库的不一致问题&#xff0c;关键在于我们可以接受不一致的时间是多少&#xff0c;根据不同的需求采取不同的实现方案。 第一种&#xff1a;先更新数据库后更新缓存 做法简单&#xff0c;但是并发写情况下&#xff0c;会出现数…

Mac安装GYM遇到的一些坑

以下是遇到的一些问题 安装GitHub上说的直接 pip install gym成功了&#xff0c;但是运行实例报错没安装gym[classic_control]&#xff0c;所以就全安装一下[all] 安装GitHub上说的直接 pip install gym成功了&#xff0c;但是运行实例报错没安装gym[classic_control]&#xff…

nodejs+vue快递管理服务系统elementui

电子商务改变了人们的传统经济活动中的交易方式和流通技术&#xff0c; 复杂的物流快递信息需要有效的进行处理&#xff0c;构建一个快递管理服务系统可以确保物流信息的一致性、员工登录&#xff1a;通过用户名和密码登录。这也间接带动了物流快递行业的高速发展。 &#xff0…

运行huggingface Kosmos2报错 nameerror: name ‘kosmos2tokenizer‘ is not defined

尝试运行huggingface上的Kosmos,https://huggingface.co/ydshieh/kosmos-2-patch14-224失败,报错: nameerror: name kosmos2tokenizer is not defined查看报错代码: vi /root/.cache/huggingface/modules/transformers_modules/ydshieh/kosmos-2-patch14-224/48e3edebaeb…

用rabbitMq 怎么处理“延迟消息队列”?

延迟消息队列是一种允许消息在发送后等待一段时间&#xff0c;然后再被消费的机制。这种机制通常用于需要延迟处理的应用场景&#xff0c;如定时任务、消息重试、消息调度等。在 RabbitMQ 中&#xff0c;实现延迟消息队列需要使用一些额外的组件和技术&#xff0c;因为 RabbitM…