不同品牌的称,只需要打印下方函数返回值,根据自己需要做处理就可以了。
wx.onBLECharacteristicValueChange(function (res) {
let receiverText = that.buf2string(res.value);
}
第一次连接需要手动配置,然后把所需参数(deviceId)保存到storage中,方便下次自动连接。
App({
globalData: {
serviceId: '',
characteristicId: '',
deviceId: '', // 已连接蓝牙的设备ID
BluetoothState: false, // 蓝牙适配器状态
connectState: false, // 蓝牙连接状态,
weight: 0, // 重量
},
onLaunch: function () {
// 设置初始重量为0
wx.setStorageSync('weight', 0)
},
onShow() {
// 读取本地数据,实现蓝牙自动连接
let deviceId = wx.getStorageSync('deviceId') || []
if(deviceId){
this.globalData.deviceId = deviceId
this.initBlue()
} else {
wx.showToast({
title: '蓝牙未连接',
icon: 'error',
duration: 3000,
})
}
},
// 初始化蓝牙
initBlue(){
var that = this;
wx.openBluetoothAdapter({//调用微信小程序api 打开蓝牙适配器接口
success: function (res) {
console.log('app初始化蓝牙成功')
that.getTheBlueDisConnectWithAccident();//监听蓝牙是否会异常断开
that.globalData.BluetoothState = true
that.monitorTheBlue(); // 监听手机蓝牙的开关
that.startConnect(that.globalData.deviceId) // 连接蓝牙
},
fail: function (err) {//如果手机上的蓝牙没有打开,可以提醒用户
if (err.errCode === 10001) { // 手机蓝牙未开启
that.globalData.BluetoothState = false
wx.showToast({
title: '手机蓝牙未开启',
icon: 'error',
duration: 3000,
})
}
}
})
},
// 监听手机蓝牙的开关
monitorTheBlue:function(){
var that =this;
wx.onBluetoothAdapterStateChange(function(res){
if (res.available){
that.globalData.BluetoothState = true
if(!that.globalData.connectState){
let deviceId = wx.getStorageSync('deviceId') || []
if(deviceId){
that.globalData.deviceId = deviceId
that.initBlue()
}
}
}else{
wx.showToast({
title: '蓝牙已关闭',
icon: 'error',
duration: 3000,
})
}
})
},
// 监听蓝牙设备是否会异常断开
getTheBlueDisConnectWithAccident:function(e){
var that = this;
wx.onBLEConnectionStateChange(function (res) {
if (!res.connected){
that.globalData.connectState = false
wx.showToast({
title: '蓝牙已断开连接',
icon: 'error',
duration: 3000,
})
that.monitorTheBlue()
}
})
},
// 停止搜索附近蓝牙
stopSearchDevs: function () {
wx.stopBluetoothDevicesDiscovery({
success: function (res) { },
})
},
// 开始连接
startConnect(deviceId, isFirst = false){
const that =this
wx.createBLEConnection({
deviceId: deviceId,
timeout: 10000, // 10s连接超时
success: function (res) {
that.globalData.connectState = true
wx.showToast({
title: '蓝牙连接成功',
icon: 'success',
duration: 3000,
success: res=>{
that.getServiceId()
if(isFirst){
wx.navigateTo({
url: `/pages/bluetooth/com/com`,
})
}
}
})
},
})
},
// 获取蓝牙设备服务ID
getServiceId(){
const that = this
wx.getBLEDeviceServices({
deviceId: wx.getStorageSync('deviceId'),
success: function(res) {
const services = res.services.filter((item, i) => {
return !/^000018/.test(item.uuid)
})
that.globalData.serviceId = services[0].uuid
that.getCharacteristicId()
},
fail: function(res) {
wx.showToast({
title: '设备服务获取失败',
icon: 'none'
})
}
})
},
// 获取特征ID
getCharacteristicId(){
const that = this
wx.getBLEDeviceCharacteristics({
deviceId: wx.getStorageSync('deviceId'),
serviceId: that.globalData.serviceId,
success: function(res) {
for (var i = 0; i < res.characteristics.length; i++) {//2个值
var model = res.characteristics[i]
if (model.properties.notify == true) {
that.startNotice(model.uuid)//7.0
}
}
}
})
},
// 接收值处理
buf2string(buffer) {
var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
return arr.map((char, i) => {
return String.fromCharCode(char);
}).join('');
},
// 开启通知,通知特征值变化
startNotice(uuid) {
var that = this;
wx.notifyBLECharacteristicValueChange({
state: true, // 启用 notify 功能
deviceId: wx.getStorageSync('deviceId'),
serviceId: that.globalData.serviceId,
characteristicId: uuid, //第一步 开启监听 notityid
success: function (res) {
// 设备返回的方法
wx.onBLECharacteristicValueChange(function (res) {
let receiverText = that.buf2string(res.value);
receiverText = receiverText.split('').reverse().join('').slice(1)
receiverText = Number(receiverText)
if(that.globalData.weigh == receiverText) {
return;
} else {
// that.globalData.weight = receiverText
wx.setStorageSync('weight', receiverText)
}
})
},
fail: function (res) {
console.log(res);
}
})
},
// 断开连接
endConnect(deviceId) {
if (this.globalData.BluetoothState) {
wx.closeBLEConnection({
deviceId: deviceId,
success: function (res) {},
})
}
},
onHide () {
// Do something when hide.
let deviceId = wx.getStorageSync('deviceId') || []
this.endConnect(deviceId)
this.globalData.connectState = false
wx.closeBluetoothAdapter({
success: res=>{
this.globalData.BluetoothState = false
}
})
},
})
手动连接
const app = getApp()
Page({
// 页面的初始数据
data: {
devs: []
},
// 自定义数据
customData: {
_devs: []
},
// 监听页面加载
onLoad: function () {
// 微信蓝牙模块初始化
const self = this
wx.openBluetoothAdapter({
success: function (res) {
app.globalData.BluetoothState = true
self.startSearchDevs() // 搜索附近蓝牙
},
fail: function (err) {
if (err.errCode === 10001) { // 手机蓝牙未开启
app.globalData.BluetoothState = false
wx.showLoading({
title: '请开启手机蓝牙',
})
} else {
// console.log(err.errMsg)
}
}
})
// 监听蓝牙适配器状态变化
wx.onBluetoothAdapterStateChange(function(res) {
if (res.available) {
app.globalData.BluetoothState = true
wx.openBluetoothAdapter({
success: function(res) {
app.globalData.BluetoothState = true
wx.hideLoading()
},
})
} else {
app.globalData.BluetoothState = false
app.globalData.connectState = false
wx.showLoading({
title: '请开启手机蓝牙',
})
}
})
// 监听BLE蓝牙连接状态变化
wx.onBLEConnectionStateChange(function(res) {
if (res.connected) {
wx.hideLoading()
wx.showToast({
title: '连接成功',
icon: 'success',
success: function(res) {
app.globalData.connectState = true
}
})
} else {
wx.hideLoading()
wx.showToast({
title: '已断开连接',
icon: 'none',
success: function(res) {
app.globalData.connectState = false
}
})
}
})
},
// 监听页面卸载
onUnload: function () {
app.stopSearchDevs()
},
// 监听用户下拉动作
onPullDownRefresh: function () {
if (app.globalData.BluetoothState) {
const self = this
this.customData._devs = []
wx.closeBluetoothAdapter({
success: function (res) {
wx.openBluetoothAdapter({
success: function (res) {
self.startSearchDevs()
}
})
}
})
}
setTimeout(() => {
wx.stopPullDownRefresh()
}, 2000)
},
// 开始搜索附近蓝牙
startSearchDevs: function () {
const self = this
wx.startBluetoothDevicesDiscovery({ // 开启搜索
allowDuplicatesKey: false,
success: function (res) {
wx.onBluetoothDeviceFound(function (devices) {
var isExist = false
if (devices.deviceId) {
for (let item of self.customData._devs) {
if (item.deviceId === devices.deviceId) {
isExist = true
break;
}
}
!isExist && self.customData._devs.push(devices)
self.setData({
devs: self.customData._devs
})
}
else if (devices.devices) {
for (let item of self.customData._devs) {
if (item.deviceId === devices.devices[0].deviceId) {
isExist = true
break;
}
}
!isExist && self.customData._devs.push(devices.devices[0])
self.setData({
devs: self.customData._devs
})
}
else if (devices[0]) {
for (let item of self.customData._devs) {
if (item.deviceId === devices[0].deviceId) {
isExist = true
break;
}
}
!isExist && self.customData._devs.push(devices[0])
self.setData({
devs: self.customData._devs
})
}
})
}
})
},
// 选择设备连接
connect (event) {
app.stopSearchDevs()
if (app.globalData.BluetoothState) {
const deviceId = event.currentTarget.dataset.dev.deviceId
app.globalData.deviceId = deviceId
wx.setStorageSync('deviceId', deviceId)
wx.showLoading({
title: '正在连接...',
})
app.startConnect(deviceId, true)
}
},
})