BluetoothDemo/bluetooth_demo/pages/index/index.js

329 lines
8.0 KiB
JavaScript
Raw Permalink Normal View History

2023-10-17 15:36:02 +08:00
const util = require("../../utils/util");
const {
inArray,
ab2hex
} = util
Page({
data: {
devices: [],
connected: false,
cmd: '',
name: '',
weight: "",
text: "",
imp: "",
deviceId: null,
},
onLoad: function() {},
// 初始化蓝牙模块
openBluetoothAdapter() {
wx.openBluetoothAdapter({
success: (res) => {
console.log('openBluetoothAdapter success', res)
wx.showToast({
title: '蓝牙连接中',
icon: "none"
})
this.startBluetoothDevicesDiscovery()
},
fail: (res) => {
if (res.errCode === 10001) {
wx.showToast({
title: '请打开蓝牙',
icon: "none"
})
// 监听本机蓝牙状态变化的事件
wx.onBluetoothAdapterStateChange((res) => {
console.log('onBluetoothAdapterStateChange', res)
if (res.available) {
this.startBluetoothDevicesDiscovery()
}
})
}
}
})
},
// 开始搜寻附近的蓝牙外围设备
startBluetoothDevicesDiscovery() {
if (this._discoveryStarted) {
return
}
this._discoveryStarted = true
wx.startBluetoothDevicesDiscovery({
allowDuplicatesKey: true, //是否允许重复上报同一设备
services: [ //要搜索蓝牙设备主 service 的 uuid 列表
"FFE0",
],
success: (res) => {
console.log('startBluetoothDevicesDiscovery success', res)
this.onBluetoothDeviceFound()
},
})
},
// 停止搜寻附近的蓝牙外围设备
stopBluetoothDevicesDiscovery() {
wx.stopBluetoothDevicesDiscovery()
},
// 找到新设备的事件
onBluetoothDeviceFound() {
wx.onBluetoothDeviceFound((res) => {
res.devices.forEach(device => {
if (device.name.indexOf('AiLink_') != -1) {
wx.stopBluetoothDevicesDiscovery() //搜索到名称为“AiLink_”的蓝牙后停止搜寻附近的蓝牙
const foundDevices = this.data.devices
const idx = inArray(foundDevices, 'deviceId', device.deviceId)
const data = {}
let buff = device.advertisData.slice(-6)
device.mac = new Uint8Array(buff) // 保存广播数据中的mac地址这是由于iOS不直接返回mac地址
let tempMac = Array.from(device.mac)
tempMac.reverse()
device.macAddr = ab2hex(tempMac, ':').toUpperCase()
if (idx === -1) {
data[`devices[${foundDevices.length}]`] = device
} else {
data[`devices[${idx}]`] = device
}
console.log("131", data)
this.setData(data)
}
})
})
},
// 连接低功耗蓝牙设备
createBLEConnection(e) {
this._connLoading = true
wx.showLoading({
title: '连接中',
})
setTimeout(() => {
if (this._connLoading) {
this._connLoading = false
wx.hideLoading()
}
}, 6000)
const ds = e.currentTarget.dataset
const index = ds.index
this._device = this.data.devices[index]
const deviceId = ds.deviceId
const name = ds.name
this.mac = ds.mac
wx.createBLEConnection({
deviceId,
success: (res) => {
this.setData({
connected: true,
name,
deviceId,
})
console.log("createBLEConnection:success")
this.onBLEConnectionStateChange()
this.getBLEDeviceServices(deviceId)
},
fail: res => {
this._connLoading = false
wx.hideLoading()
wx.showToast({
title: '连接失败',
icon: 'none'
})
}
})
},
//监听蓝牙连接状态
onBLEConnectionStateChange() {
wx.onBLEConnectionStateChange((res) => {
if (!res.connected) {
setTimeout(() => {
wx.showToast({
title: '连接已断开',
icon: 'none'
})
}, 500)
this.setData({
connected: false,
devices: [],
weight: "",
text: "",
imp: ""
})
}
})
},
// 获取蓝牙设备的 serviceId
getBLEDeviceServices(deviceId) {
wx.getBLEDeviceServices({
deviceId,
success: (res) => {
for (let i = 0; i < res.services.length; i++) {
if (res.services[i].isPrimary && res.services[i].uuid.indexOf('FFE0') > -1) {
wx.showLoading({
title: '获取设备的UUID成功',
})
this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
return
}
}
}
})
},
// 获取蓝牙设备某个服务中所有特征值(characteristic)
/**
* read: true读,write: true写,notify: true广播
*/
getBLEDeviceCharacteristics(deviceId, serviceId) {
this._deviceId = deviceId
this._serviceId = serviceId
this._device.serviceId = serviceId
wx.getBLEDeviceCharacteristics({
deviceId,
serviceId,
success: (res) => {
console.log('getBLEDeviceCharacteristics success', res.characteristics)
wx.showLoading({
title: '获取特征值成功',
})
//FFE1write: true FFE2notify: trueFFE3read: true, write: true, notify: true,
for (let i = 0; i < res.characteristics.length; i++) {
let characteristic = res.characteristics[i];
if (characteristic.uuid.indexOf("FFE2") != -1) {
if (characteristic.properties.notify == true) {
this.notifyBLECharacteristicValue(deviceId, serviceId, characteristic
.uuid)
console.log("ffe2服务的notifyId获取成功")
}
if (characteristic.properties.read == true) {
that.readId = characteristic.uuid
}
if (characteristic.properties.write == true) {
that.writeId = characteristic.uuid
}
break;
}
}
},
fail(res) {
console.error('getBLEDeviceCharacteristics', res)
}
})
},
//解析蓝牙返回数据
notifyBLECharacteristicValue(deviceId, serviceId, notifyId) {
let that = this
wx.notifyBLECharacteristicValueChange({
state: true, // 启用 notify 功能
deviceId: deviceId,
serviceId: serviceId,
characteristicId: notifyId,
success(res) {
wx.onBLECharacteristicValueChange(function(res) {
let value = ab2hex(res.value);
let num = value.substring(18, 19)
let dw = value.substring(19, 20)
let typeInfo = value.substring(10, 12)
console.log("16进制转化:", value);
if (value.length == 26) {
let data = parseInt(value.substring(13, 18), 16)
let dw1 = "kg"
if (dw == "1") {
dw1 = "斤"
console.log("体重单位:斤")
}
if (dw == "4") {
dw1 = "st:lb"
console.log("体重单位st:lb,计算方法1 * data + 5")
}
if (dw == "6") {
dw1 = "lb"
console.log("体重单位lb")
}
if (num == "1") {
data = parseInt(value.substring(13, 18), 16) / 10
console.log("体重小数点后1位")
}
if (num == "2") {
data = parseInt(value.substring(13, 18), 16) / 100
console.log("体重小数点后2位")
}
if (num == "3") {
data = parseInt(value.substring(13, 18), 16) / 1000
console.log("体重小数点后3位")
}
if (typeInfo == "01") {
console.log("实时体重:", data)
that.setData({
weight: "实时体重是:" + data + dw1
})
}
if (typeInfo == "02") {
console.log("稳定体重:", data)
that.setData({
weight: "稳定体重是:" + data + dw1
})
}
}
if (value.length == 30) {
console.log("阻抗值:", value)
if (typeInfo == "03") {
let imp = parseInt(value.substring(17, 22), 16)
that.setData({
imp: "阻抗值:" + imp
})
}
}
if (value.toUpperCase() == "A90026023000589A") {
console.log("测量完成")
that.setData({
text: "测量完成"
})
}
});
},
fail(res) {
console.log("测量失败", res.value);
}
});
},
/**
* 断开蓝牙模块
*/
closeBluetoothAdapter() {
wx.closeBluetoothAdapter()
this._discoveryStarted = false
wx.showToast({
title: '断开蓝牙模块',
icon: 'none'
})
this.setData({
devices: [],
weight: "",
text: "",
imp: ""
})
},
// 断开与低功耗蓝牙设备的连接
closeBLEConnection() {
wx.closeBLEConnection({
deviceId: this._deviceId
})
wx.showToast({
title: '断开蓝牙连接',
icon: 'none'
})
this.setData({
connected: false,
devices: [],
text: "",
weight: "",
imp: ""
})
},
});