<template><view class="dialogWrapp" v-if="showFlag"><view class="content"><view class="title text-center"><text>选择配对设备进行连接</text><uni-icons type="closeempty" class="closeModel" @click="closeBulet(1)" size="16"></uni-icons></view><view class="scrollList"><view v-for="(item, index) in bluetooth"><text>{{ item.name }}</text><button class="cu-btn round bg-blue " v-if="isLink[index] != 2"@click="action(item.deviceId, index)">连接</button><button class="cu-btn round bg-blue " v-if="isLink[index] == 2"@click="action(item.deviceId, index)">已连接</button></view></view></view></view>
</template><script>//蓝牙操作模块import {BluetoothTool} from '@/store/bluetoothUtil.js';import mHelper from '@/utils/helper.js';export default {data() {return {textList: ['连接', '连接中', '已连接', '断开连接', '连接失败', '已断开', '断开连接'],showFlag: false,isSearch: false,bluetooth: [],isLink: [],// 调试数据serverList: [],characteristics: [],readCode: '',readCodeMsg: '',serviceId: '',characteristicId: '',value: '0102',returnMessage: '',macAddress: '',macValue: '', //获取的重量buffer: '',deviceId: '',};},onLoad() {},methods: {init(num) {let data = this.$store.state.BluetoothConnectStateif (num == 1) {console.log(1);this.closeBLEConnection(data.deviceId, -1)}this.getBlueInfo();this.showFlag = true;},//操作action(id, index) {this.stopBluetoothDevicesDiscovery()if (this.isLink[index] != 2) {this.createBLEConnection(id, index);} else if (this.isLink[index] == 2) {this.closeBLEConnection(id, index);}},// 监听蓝牙设备连接状态listenerConnection() {console.log('监听蓝牙设备连接状态');let _this = this;plus.bluetooth.onBLEConnectionStateChange(function(e) {console.log('connection state changed: ' + JSON.stringify(e));_this.deviceId = e.deviceId;_this.createBLEConnection(_this.deviceId);});},// 蓝牙手机初始化getBlueInfo() {const _this = this;plus.bluetooth.openBluetoothAdapter({success(res) {_this.startBluetoothDevicesDiscovery();},fail(err) {console.log('fail', err);uni.showToast({title: '未检测到蓝牙',icon: 'none'});}});},// 搜索周围蓝牙设备startBluetoothDevicesDiscovery() {console.log('开始搜索蓝牙设备');const _this = this;this.isSearch = true;this.bluetooth = [];this.searchNoNameBluetooths = [];plus.bluetooth.startBluetoothDevicesDiscovery({// services:['FE7D','FFF0'],//可选 要获取设备的uuid列表success(res) {// console.log(JSON.stringify(res));plus.bluetooth.onBluetoothDeviceFound(res => {// console.log(JSON.stringify(res));_this.getBluetoothDevices();});},fail(err) {console.log('错误信息', JSON.stringify(err));uni.showToast({title: '蓝牙未初始化',icon: 'none',duration: 2000});}});},// 停止搜索stopBluetoothDevicesDiscovery() {plus.bluetooth.stopBluetoothDevicesDiscovery({success: e => {console.log('停止搜索蓝牙设备:' + e.errMsg);},fail: e => {console.log('停止搜索蓝牙设备失败,错误码:' + e.errCode);}});},// 获取已发现的蓝牙设备getBluetoothDevices() {const _this = this;plus.bluetooth.getBluetoothDevices({success(res) {console.log(' 获取已发现的蓝牙设备', res)// _this.stopBluetoothDevicesDiscovery()_this.bluetooth = res.devices.filter(item => {return item.name;});_this.isLink = [];_this.bluetooth.forEach(e => {_this.isLink.push(0);});}});},// 获取蓝牙适配器状态getBluetoothAdapterState() {plus.bluetooth.getBluetoothAdapterState({success(res) {console.log('获取蓝牙适配器状态', res);}});},// 连接蓝牙createBLEConnection(deviceId, index) {const _this = this;this.deviceId = deviceId;if (this.isLink[index] == 2) {console.log(10012);return;}this.isLink.splice(index, 1, 1);console.log(_this.deviceId, 1122);let flage= trueplus.bluetooth.createBLEConnection({deviceId: _this.deviceId,success: res => {console.log(111);_this.isLink.splice(index, 1, 2);_this.stopBluetoothDevicesDiscovery();_this.getBLEDeviceServices(_this.deviceId);uni.showLoading({title: '连接中...',mask: true});},fail: res => {if (res.message == 'already connect') {_this.isLink[index] = 2;_this.stopBluetoothDevicesDiscovery();_this.getBLEDeviceServices(_this.deviceId);} else {_this.isLink.splice(index, 1, 3);}console.log(222);console.log(JSON.stringify(res));},complete: es => {console.log(es);if (es.code == '10012') {uni.showToast({title: '连接失败,请重试',mask: true});}flage = false}});setTimeout(()=>{if(flage){this.createBLEConnection(deviceId, index)}},3000)},//获取蓝牙设备所有服务(service)。getBLEDeviceServices(deviceId) {const _this = this;console.log(deviceId);setTimeout(() => {plus.bluetooth.getBLEDeviceServices({// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接deviceId: deviceId,success: res => {console.log('获取蓝牙设备所有服务:', JSON.stringify(res.services));_this.serverList = res.services;var findItem = res.services.find(item => {//FE7D FFF0if (item.uuid != '00001800-0000-1000-8000-00805F9B34FB' &&item.uuid != '00001801-0000-1000-8000-00805F9B34FB' &&item.uuid != '0000180A-0000-1000-8000-00805F9B34FB') {return item;}});console.log(JSON.stringify(findItem));_this.serviceId = findItem.uuid;_this.getBLEDeviceCharacteristics(_this.deviceId);},fail: res => {console.log(res);}});}, 1000);},// 获取蓝牙特征值getBLEDeviceCharacteristics(deviceId) {console.log('进入特征');const _this = this;setTimeout(() => {plus.bluetooth.getBLEDeviceCharacteristics({// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接deviceId: deviceId,// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取serviceId: this.serviceId,success: res => {_this.characteristics = res.characteristics;console.log('characteristics', JSON.stringify(_this.characteristics));let findItem = res.characteristics.find(item => {let uuid = item.uuid;console.log(uuid);return item.properties.notify;});_this.characteristicId = findItem.uuid;console.log('当前使用的特征characteristicId:', _this.characteristicId);_this.notifyBLECharacteristicValueChange(_this.deviceId);let bluetoothData = {deviceId: _this.deviceId,serviceId: _this.serviceId,characteristicId: _this.characteristicId};uni.setStorageSync('bluetoothData', bluetoothData);mHelper.toast('连接成功!');_this.closeBulet()},fail: res => {uni.hideLoading();console.log(res);mHelper.toast('连接失败!');}});}, 4000);},// 启用 notify 功能notifyBLECharacteristicValueChange(deviceId) {const _this = this;plus.bluetooth.notifyBLECharacteristicValueChange({state: true, // 启用 notify 功能// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接deviceId: deviceId,// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取serviceId: _this.serviceId,// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取characteristicId: _this.characteristicId,success: res => {_this.$api.msg('连接成功', 'success');},fail: res => {_this.$api.msg('连接失败');}});},ab2hex(buffer) {const hexArr = Array.prototype.map.call(new Uint8Array(buffer), function(bit) {return ('00' + bit.toString(16)).slice(-2);});return hexArr.join('');},//十六进制转字符串,调整高低位hexCharCodeToStr(hexCharCodeStr) {let trimedStr = hexCharCodeStr.trim();let rawStr = trimedStr.substr(0, 2).toLowerCase() === '0x' ? trimedStr.substr(2) : trimedStr;let len = rawStr.length;if (len % 2 !== 0) {alert('Illegal Format ASCII Code!');return '';}let curCharCode;let resultStr = [];for (let i = 0; i < len; i = i + 2) {curCharCode = parseInt(rawStr.substr(i, 2), 16); // ASCII Code ValueresultStr.unshift(String.fromCharCode(curCharCode));}return Math.round(parseFloat(resultStr.join('')) * 100) / 100;},// 监听低功耗蓝牙设备的特征值变化onBLECharacteristicValueChange(deviceId) {const _this = this;plus.bluetooth.onBLECharacteristicValueChange(res => {_this.macAddress = res.deviceId;let val = _this.ab2hex(res.value);let resValue = _this.hexCharCodeToStr(val);_this.macValue = resValue;console.log(resValue + '千克');});},// 读取设备二进制数据readBLECharacteristicValue() {let _this = this;plus.bluetooth.readBLECharacteristicValue({// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接deviceId: _this.deviceId,// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取serviceId: _this.serviceId,// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取characteristicId: _this.characteristicId,success: res => {console.log('readBLECharacteristicValue:', res);this.readCode = res.errCode;this.readCodeMsg = res.errMsg;this.onBLECharacteristicValueChange(this.deviceId);},fail: res => {console.log('readBLECharacteristicValue:', res);this.readCode = res.errCode;this.readCodeMsg = res.errMsg;this.onBLECharacteristicValueChange(this.deviceId);}});},// 写入低功耗蓝牙设备的特征值writeBLECharacteristicValue(value) {const _this = this;console.log('写入低功耗蓝牙设备的特征值');// const data = new Uint8Array(_this.write.qp).buffer;//2let codeLength = value.length / 2;_this.buffer = new ArrayBuffer(codeLength);const dataView = new DataView(_this.buffer);let data = [];//在这里解析将要写入的值for (let i = 0; i < codeLength; i++) {dataView.setUint8(i, '0X' + value.substring(i * 2, i * 2 + 2));data.push(value.substring(2 * i, 2 * i + 2));}plus.bluetooth.writeBLECharacteristicValue({deviceId: _this.deviceId,serviceId: _this.serviceId,characteristicId: _this.characteristicId,value: _this.buffer,success: function(e) {console.log('发送成功', data.join(','));console.log('write characteristics success: ' + JSON.stringify(e));},fail: function(e) {console.log('write characteristics failed: ' + JSON.stringify(e));}});},//断开蓝牙连接closeBLEConnection(deviceId, index) {const _this = this;plus.bluetooth.closeBLEConnection({deviceId: deviceId,success: res => {console.log('断开蓝牙连接');if (index >= 0) {_this.isLink.splice(index, 1, 4);}mHelper.toast('已断开连接!');}});},closeBulet(num) {if(num != 1){let _this = thislet formData = {deviceId: _this.deviceId,serviceId: _this.serviceId,characteristicId: _this.characteristicId,buffer: _this.buffer,}this.$parent.animationly()this.$store.commit('BluetoothConnectState', formData)}this.showFlag = falsethis.stopBluetoothDevicesDiscovery()}}};
</script><style lang="less">page {.dialogWrapp {width: 100%;height: 100%;position: fixed;left: 0;top: 0;z-index: 9;background-color: rgba(0, 0, 0, 0.2);display: flex;justify-content: center;align-items: center;.content {height: auto;padding: 20px;background-color: #fff;.title {font-size: 16px;padding-bottom: 10px;border-bottom: 1px solid #ccc;}.scrollList {margin-top: 5px;view {height: 40px;font-size: 14px;display: flex;justify-content: space-between;align-items: center;}}}}}.ul {margin: 10px;.li {display: flex;justify-content: space-between;background: #ffffff;margin-top: 13upx;align-items: center;font-size: 30upx;border-radius: 20upx;height: 160upx;padding-left: 43upx;.li-left {display: flex;.blueImg {width: 77upx;height: 74upx;margin-right: 40upx;image {width: 100%;height: 100%;}}.eqName {color: #000000;font-size: 30upx;width: 250upx;word-break: break-all;display: flex;align-items: center;}}.status {display: flex;view {margin-right: 48upx;}}}}.search {width: 358upx;height: 70upx;border-radius: 35upx;border: 1px solid #5ca3f9;margin-top: 131upx;color: #5ca3f9;font-size: 24upx;line-height: 70upx;text-align: center;}.foot-btn-g {color: #007fff;margin-top: 80upx;}.ft-color-999999 {color: #999999;}.ft-color-007FFF {color: #007fff;}.closeModel{top: -15px;position: relative;right: -10px;}
</style>

uniapp连接低功耗蓝牙相关推荐

  1. Uni-App使用低功耗蓝牙连接血压仪测量

    1.Uni-APP蓝牙使用流程 在阅读这篇内容之前,建议您详细浏览一遍uni-app官方关于蓝牙和低功耗蓝牙(BLE)使用教程文档 uni-app官方低功耗蓝牙接口,如果您有微信小程序方面的开发经验, ...

  2. uniapp连接低功耗打印机实例,

    ** uniapp连接低功耗打印机实例, **最忌用uniapp开发一个收银机安卓app,拙要功能就是打印,得到需求后一顿操作各种百度但都无济于事,最终通过蓝牙连接低能耗打印机成功,记录一下心得(深知 ...

  3. uniapp微信小程序实现连接低功耗蓝牙打印功能

    微信小程序项目中有使用到蓝牙连接打印,参考官方文档做了一个参考笔记,这样使用的时候就按着步骤查看. uni-app蓝牙连接 蓝牙: 1.初始化蓝牙 uni.openBluetoothAdapter(O ...

  4. mac 更换默认蓝牙适配器_Win7连接低功耗蓝牙(BLE)鼠标

    前段时间出差没带鼠标接收器,不过还好我的罗技M590鼠标支持蓝牙连接,但是win7系统的电脑却死活搜索不到鼠标, 经过一番搜索,终于找到了问题的原因,原来蓝牙鼠标需要蓝牙的低功耗技术,而win7默认是 ...

  5. 【uni-app学习】uni-app低功耗蓝牙采坑记录

    一.低功耗蓝牙的基础知识 1.低功耗蓝牙简介 蓝牙4.0及更高版本被称为蓝牙低功耗,其中蓝牙4.0标准包括传统的蓝牙模块部分和蓝牙低功耗模块部分,这是双模式标准.一般上位机都会有相应的蓝牙API可用, ...

  6. 小程序连接低功耗蓝牙

    小程序连接低功耗蓝牙流程 参考官方api:https://developers.weixin.qq.com/miniprogram/dev/api/device/bluetooth/wx.openBl ...

  7. Qt低功耗蓝牙系列一(什么是低功耗蓝牙开发,低功耗蓝牙的通信机制原理)

    文章目录 前言 Android 蓝牙 BLE 低功耗蓝牙协议栈简介 蓝牙的选用 BLE 低功耗蓝牙模块具体应用场景 蓝牙灯控方案 BLE 蓝牙智能锁方案 蓝牙 MAC 地址扫描打印解决方案 蓝牙 Me ...

  8. Uniapp低功耗蓝牙操作实例

    uniapp低功耗蓝牙在移动端使用较为平常,本文相较于官方文档介绍一下低功耗蓝牙的操作案例,即取即用.低功耗蓝牙虽工作原理与经典蓝牙类似,但是有着独特的架构体系,所以LE独立出来成为一种蓝牙形态.不过 ...

  9. 在uniAPP中使用使用低功耗蓝牙通讯

    在uniAPP中使用使用低功耗蓝牙通讯 1.初始化蓝牙监听器 onLoad(){//蓝牙是否在扫描设备uni.onBluetoothAdapterStateChange((res)=>{cons ...

最新文章

  1. 赠书 | AI 还原宋代皇帝,原来这么帅?!
  2. Activity的生命周期是谁调用的?
  3. 监控服务器项目报备,智慧环保监控预警平台运维项目
  4. linux系统更新字体,更换Linux下字体
  5. Lamp的搭建--centos6.5下安装mysql
  6. MongoDB(6.mongodb的聚合操作以及高级查询3、排序等)
  7. 反思读别人代码的思路
  8. GTK+ 2.4 or later isn't available
  9. php mysql 冒号_php – 使用pdo在搜索变量中使用冒号(:)进行查询
  10. Android Audio Play Out Channel
  11. 米莱迪机器人加物理攻击_王者荣耀:“不死流”白起崛起,秒回8500血完克米莱迪...
  12. [MySQL] InnoDB三大特性之 - 插入缓冲
  13. Eltima SDK 中存在27个漏洞,影响多家云服务提供商
  14. android 关于 textview首行缩进 显示图片、文字问题
  15. 堪萨斯州立大学计算机专业,全美顶尖大学:堪萨斯州立大学
  16. 5G消息富媒体最新形态
  17. python绘制小提琴图_seaborn画小提琴图(violin plot)
  18. 第二讲:双活灾备方案建设方法论
  19. 我的世界手机版开服务器领地系统,我的世界手机版领地指令大全 领地指令怎么用...
  20. 基于Matlab Robotics Toolbox的Dobot机械臂运动规划(3)

热门文章

  1. 0909 编译的开始
  2. xml文件生成与下载
  3. 一、从零认识D-Bus
  4. 全球及中国抹墙机行业发展态势及投资方向分析报告2022-2028年
  5. C#封装-里氏替换原则
  6. 我爱上男友他爸苦不堪言
  7. 2019阿里校招数据研发/算法工程师 hr面
  8. 网页版人脸登录,Web端人脸登录,人脸识别,基于Springboot+vue2.X版本+mysql
  9. 【可视化】复变函数可视化-复变函数导数
  10. 严选3门大厂内训课程!让你年后面试超过身边95%的竞争者!