- 备案时 服务内容无法选择
备案时 服务内容无法选择
08-05 - 无法连接到蓝牙,蓝牙无通讯?
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; } // ArrayBuffer转16进度字符串示例 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; // 示例:假设首次写入默认值 'defaultData' 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, } } // data[`chs[${this.data.chs.length}]`] = { // uuid: characteristic.characteristicId, // value: ab2hex(characteristic.value) // } this.setData(data) }) }, writeBLECharacteristicValue(data) { console.log('写入数据前:', data, ', 类型:', typeof data, ', 长度:', data ? data.length : '未定义'); // 调用strToUtf8ArrayBuffer将字符串转换为ArrayBuffer const buffer = strToUtf8ArrayBuffer(data); wx.writeBLECharacteristicValue({ deviceId: this._deviceId, serviceId: this._serviceId, characteristicId: this._characteristicId, value: buffer, }) }, // 在每个btnClick开头添加以下日志输出 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'); } })
07-17