function inArray(arr, key, value) {
for (let i = 0; i < arr.length; i++) {
if (arr[i][key] === value) {
return i;
}
}
return -1;
}
function strToUtf8ArrayBuffer(str) {
const utf8Bytes = new Uint8Array(str.length);
for (let i = 0; i < str.length; i++) {
utf8Bytes[i] = str.charCodeAt(i);
}
return utf8Bytes.buffer;
}
function ab2hex(buf) {
return Array.from(new Uint8Array(buf))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
Page({
data: {
devices: [],
connected: false,
chs: [],
isConnected: false,
deviceInfo: null,
},
onLoad: function() {
},
tipsBluetoothWarn() {
console.log('蓝牙相关提示');
},
openBluetoothAdapter() {
wx.openBluetoothAdapter({
success: (res) => {
console.log('openBluetoothAdapter success', res)
this.startBluetoothDevicesDiscovery()
},
fail: (res) => {
if (res.errCode === 10001) {
wx.onBluetoothAdapterStateChange(function (res) {
console.log('onBluetoothAdapterStateChange', res)
if (res.available) {
this.startBluetoothDevicesDiscovery()
}
})
}
}
})
},
getBluetoothAdapterState() {
wx.getBluetoothAdapterState({
success: (res) => {
console.log('getBluetoothAdapterState', res)
if (res.discovering) {
this.onBluetoothDeviceFound()
} else if (res.available) {
this.startBluetoothDevicesDiscovery()
}
}
})
},
startBluetoothDevicesDiscovery() {
if (this._discoveryStarted) {
return
}
this._discoveryStarted = true
wx.startBluetoothDevicesDiscovery({
allowDuplicatesKey: true,
success: (res) => {
console.log('startBluetoothDevicesDiscovery success', res)
this.onBluetoothDeviceFound()
},
})
},
stopBluetoothDevicesDiscovery() {
wx.stopBluetoothDevicesDiscovery()
},
onBluetoothDeviceFound: function(e) {
const devices = e.devices;
for (let i = 0; i < devices.length; i++) {
const device = devices[i];
if (device.name === '目标设备名称') {
this.setData({
deviceInfo: device,
});
break;
}
}
},
btnConnectClick: function() {
if (!this.data.isConnected && this.data.deviceInfo) {
this.connectToDevice(this.data.deviceInfo);
} else if (this.data.isConnected) {
wx.showToast({ title: '已连接', icon: 'none' });
} else {
wx.showToast({ title: '未找到设备', icon: 'none' });
}
},
connectToDevice: function(device) {
wx.createBLEConnection({
deviceId: device.deviceId,
success: function(res) {
console.log('连接蓝牙设备成功');
this.setData({ isConnected: true });
}.bind(this),
fail: function(err) {
console.error('连接蓝牙设备失败', err);
wx.showToast({ title: '连接失败', icon: 'none' });
}
});
},
createBLEConnection(e) {
const ds = e.currentTarget.dataset
const deviceId = ds.deviceId
const name = ds.name
wx.createBLEConnection({
deviceId,
success: (res) => {
this.setData({
connected: true,
name,
deviceId,
})
this.getBLEDeviceServices(deviceId)
}
})
this.stopBluetoothDevicesDiscovery()
},
closeBLEConnection() {
wx.closeBLEConnection({
deviceId: this.data.deviceId
})
this.setData({
connected: false,
chs: [],
canWrite: false,
})
},
getBLEDeviceServices(deviceId) {
wx.getBLEDeviceServices({
deviceId,
success: (res) => {
for (let i = 0; i < res.services.length; i++) {
if (res.services[i].isPrimary) {
this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
return
}
}
}
})
},
getBLEDeviceCharacteristics(deviceId, serviceId) {
wx.getBLEDeviceCharacteristics({
deviceId,
serviceId,
success: (res) => {
console.log('getBLEDeviceCharacteristics success', res.characteristics)
for (let i = 0; i < res.characteristics.length; i++) {
let item = res.characteristics[i]
if (item.properties.read) {
wx.readBLECharacteristicValue({
deviceId,
serviceId,
characteristicId: item.uuid,
})
}
if (item.properties.write) {
this.setData({
canWrite: true
});
this._deviceId = deviceId;
this._serviceId = serviceId;
this._characteristicId = item.uuid;
this.writeBLECharacteristicValue('defaultData');
}
if (!data || typeof data !== 'string') {
console.error('Invalid or missing data provided to writeBLECharacteristicValue');
return;
}
}
},
fail(res) {
console.error('getBLEDeviceCharacteristics', res)
}
})
wx.onBLECharacteristicValueChange((characteristic) => {
const valueStr = ab2str(characteristic.value);
console.log('接收到的蓝牙数据:', valueStr);
const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId);
const data = {};
if (idx === -1) {
data[`chs[${this.data.chs.length}]`] = {
uuid: characteristic.characteristicId,
value: valueStr,
};
} else {
data[`chs[${idx}]`] = {
uuid: characteristic.characteristicId,
value: valueStr,
}
}
this.setData(data)
})
},
writeBLECharacteristicValue(data) {
console.log('写入数据前:', data, ', 类型:', typeof data, ', 长度:', data ? data.length : '未定义');
const buffer = strToUtf8ArrayBuffer(data);
wx.writeBLECharacteristicValue({
deviceId: this._deviceId,
serviceId: this._serviceId,
characteristicId: this._characteristicId,
value: buffer,
})
},
btnClickDown() {
console.log('btnClickDown 被点击');
console.log('当前连接状态:', this.data.connected);
console.log('是否可以写入:', this.data.canWrite);
console.log('尝试写入的数据:', 'x');
this.tipsBluetoothWarn();
if (this.data.connected && this.data.canWrite) {
this.writeBLECharacteristicValue('x');
} else {
console.warn('无法写入数据,可能未连接或不可写');
}
console.log('x');
},
btnClickUp() {
console.log('btnClickUp 被点击');
console.log('当前连接状态:', this.data.connected);
console.log('是否可以写入:', this.data.canWrite);
console.log('尝试写入的数据:', 'w');
this.tipsBluetoothWarn();
if (this.data.connected && this.data.canWrite) {
this.writeBLECharacteristicValue('w');
} else {
console.warn('无法写入数据,可能未连接或不可写');
}
console.log('w');
},
btnClickLeft() {
console.log('btnClickLeft 被点击');
console.log('当前连接状态:', this.data.connected);
console.log('是否可以写入:', this.data.canWrite);
console.log('尝试写入的数据:', 'a');
this.tipsBluetoothWarn();
if (this.data.connected && this.data.canWrite) {
this.writeBLECharacteristicValue('a');
} else {
console.warn('无法写入数据,可能未连接或不可写');
}
console.log('a');
},
btnClickRight() {
console.log('btnClickRight 被点击');
console.log('当前连接状态:', this.data.connected);
console.log('是否可以写入:', this.data.canWrite);
console.log('尝试写入的数据:', 'd');
this.tipsBluetoothWarn();
if (this.data.connected && this.data.canWrite) {
this.writeBLECharacteristicValue('d');
} else {
console.warn('无法写入数据,可能未连接或不可写');
}
console.log('d');
},
btnClickStop() {
console.log('btnClickStop 被点击');
console.log('当前连接状态:', this.data.connected);
console.log('是否可以写入:', this.data.canWrite);
console.log('尝试写入的数据:', 's');
this.tipsBluetoothWarn();
if (this.data.connected && this.data.canWrite) {
this.writeBLECharacteristicValue('s');
} else {
console.warn('无法写入数据,可能未连接或不可写');
}
console.log('s');
}
})
请具体描述问题出现的流程,并提供能复现问题的简单代码片段(https://developers.weixin.qq.com/miniprogram/dev/devtools/minicode.html)。