基于uniapp的低功耗蓝牙配对以及指令发送
直接贴代码
- 新建uniapp项目
- 将如下代码直接粘贴到 index.vue 文件夹内
- 该文件包含uniapp 对低功耗蓝牙的所以操作 从配对到连接 到指令生成 进制转换以及指令发送蓝牙设备监听
在这里插入代码片
```<template>
<view class="content">
<view style="display: block;width: 100%; min-height: 40%;background: #000;color: #FFF;">
<text class="title" style=" color: #FFF;">设备id:{{uid}}--------------log:</text>
<view>
<text>{{look}}</text>
</view>
</view>
<view class="liebiao" style="margin-top: 40%;">
<view class="cazuo" v-for="(item,index) in drive">
<text @click="Connectbluetooth(item,index)">插座名称:{{item.name}} 点击连接</text>
</view>
</view>
<button @click="Searchbluetooth">搜索蓝牙</button>
<input type="text" value="" v-if="uid" v-model="serial" placeholder="序号"
style="border: #000 1rpx solid ;margin-top: 30rpx;margin-bottom: 30rpx;" />
<input type="text" value="" v-if="uid" v-model="cmd" placeholder="指令"
style="border: #000 1rpx solid ;margin-top: 30rpx;margin-bottom: 30rpx;" />
<input type="text" value="" v-if="uid" v-model="msg" placeholder="消息体"
style="border: #000 1rpx solid ;margin-top: 30rpx;margin-bottom: 30rpx;" />
<button @click="sendinputcommand" v-if="uid!=''">执行输入框指令</button>
<button @click="sendcommand" v-if="ok && uid==0">获取设备id</button>
<button @click="tiaozhuan">跳转新页面</button>
</view>
</template>
<script>
import {Crc,modelFind } from '@ratriches/crc';
export default {
data() {
return {
title: 'Hello',
filtersServices: null,
drive: [],
drovechild: {},
look: {},
ok: false,
command: '',
uid: '',
cmd: '',
msg: ''
}
},
onLoad() {
},
methods: {
tiaozhuan(){
uni.navigateTo({
url:'/pages/index/main'
})
},
// 输入框指令
sendinputcommand() {
let that = this;
//需要先拼接指令
let msglen = that.msg.toString().length / 2;
msglen = this.dec2hex(msglen, 2);
// xvhaoserial 发送序号 cmd 指令
let value = '68' + that.serial + that.uid + that.cmd + msglen + that.msg+that.CRC_16_CCITT_FALSE('68' + that.serial + that.uid + that.cmd + msglen + that.msg)
console.log('value',value);
value = this.sextoten(value);
// 兼容ios
let writeType = 'write';
if (uni.getSystemInfoSync().platform == 'ios') {
writeType = 'write';
}
console.log('蓝牙发送', value);
uni.writeBLECharacteristicValue({
deviceId: that.drovechild.deviceId,
serviceId: that.drovechild.serviceId,
characteristicId: that.drovechild.write,
value,
writeType,
success: (res) => {
that.look = res;
},
fail: (res) => {
console.log('发送失败', res);
that.look = res;
},
complete: (res) => {
that.show = res;
console.log('发送完成', res);
}
})
},
// 写入指令(发送指令)
sendcommand() {
let that = this;
let value = this.sextoten('680000000000D00063B8');
// 兼容ios
let writeType = 'write';
if (uni.getSystemInfoSync().platform == 'ios') {
writeType = 'write';
}
console.log('蓝牙发送', value);
uni.writeBLECharacteristicValue({
deviceId: that.drovechild.deviceId,
serviceId: that.drovechild.serviceId,
characteristicId: that.drovechild.write,
value,
writeType,
success: (res) => {
that.look = res;
},
fail: (res) => {
console.log('发送失败', res);
that.look = res;
},
complete: (res) => {
that.show = res;
console.log('发送完成', res);
}
})
},
//10进制转16进制 并且 补0
dec2hex(dec, len) { //10进制转16进制补0
var hex = "";
while (dec) {
var last = dec & 15;
hex = String.fromCharCode(((last > 9) ? 55 : 48) + last) + hex;
dec >>= 4;
}
if (len) {
while (hex.length < len) hex = '0' + hex;
}
return hex;
},
// ArrayBuffer转16进度字符串示例
ab2hex(buffer) {
const hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function(bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('')
},
//16进制钻转换发送
sextoten(hex) {
var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function(h) {
return parseInt(h, 16)
}))
return typedArray;
},
// 进行编码校验
CRC_16_CCITT_FALSE(hexString) {
let crc = 0xffff;
const polynomial = 0x8005;
let byte_val, bit, c15;
for (let i = 0; i < hexString.length / 2; i++) {
byte_val = parseInt(hexString.substr(i * 2, 2), 16);
for (let k = 0; k < 8; k++) {
bit = ((byte_val >> (7 - k) & 1) == 1);
c15 = ((crc >> 15 & 1) == 1);
crc <<= 1;
if (c15 ^ bit) {
crc ^= polynomial;
}
}
}
crc &= 0xFFFF;
return ('0000' + crc.toString(16)).slice(-4);
},
// 获取蓝牙特征
getBLEDeviceCharacteristics() {
let that = this;
uni.getBLEDeviceCharacteristics({
deviceId: that.drovechild.deviceId,
serviceId: that.drovechild.serviceId,
success: (res) => {
// 存储蓝牙特征值
// 读取
that.drovechild.write = res.characteristics[0].uuid;
// 写入
that.drovechild.notifyread = res.characteristics[1].uuid;
console.log('获取蓝牙特征成功', that.drovechild);
that.look = that.drovechild;
//开启监听蓝牙特征值变化 人话就是设备向手机发送指令
that.notifyBLECharacteristicValueChange();
},
fail: (res) => {
console.log('获取蓝牙特征失败', res);
}
});
},
notifyBLECharacteristicValueChange() {
let that = this;
uni.notifyBLECharacteristicValueChange({
deviceId: that.drovechild.deviceId,
serviceId: that.drovechild.serviceId,
characteristicId: that.drovechild.notifyread,
state: true,
success: (res) => {
setTimeout(function() {
that.look = res;
}, 2000)
// 启动监听服务
uni.onBLECharacteristicValueChange(function(res) {
if (res.value) {
if (that.ab2hex(res.value).indexOf('c0') != -1) {
that.uid = that.ab2hex(res.value).substring(6, 12);
}
}
setTimeout(function() {
that.ok = true;
that.look = that.ab2hex(res.value);
}, 900)
});
},
fail: (res) => {
console.log('启动蓝牙监听err', res);
}
});
},
Connectbluetooth(device, index) {
let that = this;
console.log('连接插座');
// 连接设备 关闭搜索设备
uni.stopBluetoothDevicesDiscovery();
uni.showLoading({
title: '正在连接,请等待!'
})
uni.createBLEConnection({
deviceId: device.deviceId,
success: (res) => {
console.log('连接成功', res);
uni.hideLoading();
uni.showToast({
icon: 'none',
title: res.errMsg
})
// 获取蓝牙设备的服务 uuid 解决安卓获取不到参数的问题
setTimeout(function() {
uni.getBLEDeviceServices({
deviceId: device.deviceId,
success: (res) => {
console.log('蓝牙设备服务suc', res);
res.services.forEach((item) => {
if (item.uuid.indexOf(
"FFF0") != -1) {
// 存储已经使用的蓝牙设别 uuid
that.drive[index]
.serviceId = item
.uuid;
// 确认使用当前设备
that.drovechild = that
.drive[index];
//进入特征
that
.getBLEDeviceCharacteristics();
}
})
},
fail(res) {
console.log('蓝牙设备服务err', res);
}
});
}, 2000)
},
fail: (res) => {
console.log('连接失败', res);
uni.hideLoading();
uni.showToast({
icon: 'none',
title: res.errMsg
})
}
});
},
Searchbluetooth() {
let that = this;
console.log('正在搜索中');
// 先初始化蓝牙
uni.openBluetoothAdapter({});
// 开始搜索附近设备
uni.startBluetoothDevicesDiscovery({
services: this.filtersServices || [],
allowDuplicatesKey: false,
interval: 0,
powerLevel: 'high',
success: (res) => {
console.log("开始发现设备", res)
},
fail: (err) => {
console.log('err', err);
}
}); -
uni.onBluetoothDeviceFound(function(drive) {
if (drive.devices[0].advertisServiceUUIDs != null) {
// 用来过滤当前是否为插座设备
if (drive.devices[0].advertisServiceUUIDs[0] ==
'0000FFF0-0000-1000-8000-00805F9B34FB') {
that.drive.push(drive.devices[0]);
}
}
});
}
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
height: 200rpx;
width: 200rpx;
margin-top: 200rpx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50rpx;
}
.text-area {
display: flex;
justify-content: center;
}
.title {
font-size: 36rpx;
color: #8f8f94;
}
</style>