BluetoothDemo/pages/FB03/index.js

320 lines
11 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const util = require("../../utils/util");
const {
inArray,
ab2hex
} = util
const plugin = requirePlugin("sdkPlugin").AiLink;
Page({
data: {
devices: [],
connected: false,
name: '',
weight: "",
text: "",
uuid1: "",
uuid2: "",
uuid3: "",
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,
interval: 1000, //上报设备的间隔
services: [
"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
}
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: "",
})
}
})
},
// 获取蓝牙设备的 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) {
let that = this
this._deviceId = deviceId
this._serviceId = serviceId
this._device.serviceId = serviceId
wx.getBLEDeviceCharacteristics({
deviceId,
serviceId,
success: (res) => {
console.log("特征值:", res)
for (let i = 0; i < res.characteristics.length; i++) {
let item = res.characteristics[i];
if (item.uuid.indexOf('0000FFE1') != -1) {
that.data.uuid1 = item.uuid //主服务 UUID
} else if (item.uuid.indexOf('0000FE2') != -1) {
that.data.uuid2 = item.uuid //写入设置
} else if (item.uuid.indexOf('0000FFE3') != -1) {
that.data.uuid3 = item.uuid //监听数据
}
}
wx.notifyBLECharacteristicValueChange({
deviceId,
serviceId,
characteristicId: that.data.uuid2,
state: true,
})
wx.notifyBLECharacteristicValueChange({
deviceId,
serviceId,
characteristicId: that.data.uuid3,
state: true,
})
plugin.initPlugin(res.characteristics, this._device)
wx.onBLECharacteristicValueChange((characteristic) => {
let bleData = plugin.parseBleData(characteristic.value)
let dw1 = "kg"
if (bleData.status == 0) {
console.log("握手成功")
} else if (bleData.status == 1) {
let payload = ab2hex(bleData.data, '')
let typeInfo = payload.substring(0, 2)
let unit = payload.substring(6, 8) // 单位
let num = payload.substring(8, 9) //正负数
let dot = payload.substring(9, 10) //小数点
let data = parseInt(payload.substring(2, 6), 16)
if (unit == "01") {
dw1 = "斤"
}
if (unit == "04") {
dw1 = "lb"
}
if (unit == "05") {
dw1 = "g"
}
if (unit == "06") {
dw1 = 'lb'
}
//
if (num == "0") {
that.setData({
text: "重量为正数"
})
}
if (num == "1") {
that.setData({
text: "重量为负数"
})
}
//
if (dot == "1") {
data = data / 10
}
if (dot == "2") {
data = data / 100
}
if (dot == "3") {
data = data / 1000
}
if (typeInfo == "01") {
that.setData({
weight: "稳定体重是" + data + dw1
})
}
if (typeInfo == "02") {
that.setData({
weight: "实时体重是:" + data + dw1
})
}
}
})
},
fail(res) {
console.error('getBLEDeviceCharacteristics', res)
}
})
},
handleIsNum() {
let that = this
let str = [0x83, 0x01]
plugin.sendDataOfA7(str)
},
// 归零
handleIsLing() {
let str = [0x83, 0x00]
console.log("归零指令", str)
plugin.sendDataOfA7(str)
},
/**
* 断开蓝牙模块
*/
closeBluetoothAdapter() {
wx.closeBluetoothAdapter()
this._discoveryStarted = false
wx.showToast({
title: '断开蓝牙模块',
icon: 'none'
})
this.setData({
devices: [],
weight: "",
text: "",
})
},
// 断开与低功耗蓝牙设备的连接
closeBLEConnection() {
wx.closeBLEConnection({
deviceId: this._deviceId
})
wx.showToast({
title: '断开蓝牙连接',
icon: 'none'
})
this.setData({
connected: false,
devices: [],
text: "",
weight: "",
})
},
});