const app = getApp(); Page({ data: { getDeviceSetting: false, initText: "", devicesList: [], searchDevicesList: true, }, onLoad(options) { this.checkBluetoothPermissionAndInit(); }, onShow() { if (this.data.getDeviceSetting) { this.getDeviceSettingList(); } else { this.checkBluetoothPermissionAndInit(); } }, checkBluetoothPermissionAndInit() { this.setData({ initText: "正在检查蓝牙权限..." }); wx.getSetting({ success: (res) => { if (res.authSetting['scope.bluetooth']) { this.openBluetoothAdapter(); } else { wx.authorize({ scope: 'scope.bluetooth', success: () => { this.openBluetoothAdapter(); }, fail: (err) => { this.setData({ initText: "蓝牙权限被拒绝。" }); wx.showModal({ title: '提示', content: '您拒绝了蓝牙权限,将无法连接蓝牙秤。是否前往设置开启?', confirmText: '去开启', cancelText: '不开启', success: (modalRes) => { if (modalRes.confirm) { wx.openSetting({ success: (settingRes) => { console.log('openSetting success', settingRes); }, fail: (settingErr) => { wx.navigateBack({ delta: 1 }); } }); } else { wx.navigateBack({ delta: 1 }); } } }); } }); } }, fail: (err) => { this.setData({ initText: "获取权限设置失败。" }); wx.showToast({ title: '获取权限设置失败', icon: 'none' }); wx.navigateBack({ delta: 1 }); } }); }, openBluetoothAdapter() { this.setData({ initText: "正在初始化蓝牙..." }); wx.openBluetoothAdapter({ success: () => { this.setData({ initText: "蓝牙初始化成功" }); this.getDeviceSettingList(); }, fail: (err) => { this.setData({ initText: "蓝牙初始化失败。" }); if (err.errCode === 10001) { wx.showModal({ title: "提示", content: "请确保手机蓝牙已开启。", showCancel: false, success: () => { wx.navigateBack({ delta: 1 }); } }); } else if (err.errMsg && err.errMsg.includes('permission denied')) { wx.showModal({ title: '提示', content: '蓝牙权限仍被拒绝,无法使用蓝牙功能。', showCancel: false, success: () => { wx.navigateBack({ delta: 1 }); } }); } else { wx.showToast({ title: `蓝牙适配器打开失败: ${err.errMsg || err.errCode}`, icon: 'none', success: () => { wx.navigateBack({ delta: 1 }); } }); } }, }); }, getDeviceSettingList() { // app.globalData.ppScale.plugin.Blue.visibleLog(true); this.setData({ initText: "设备搜索中..." }); app.globalData.ppScale.device.list = []; let seviceList = app.globalData.ppScale.device.setting; app.globalData.ppScale.plugin.Blue.setDeviceSetting(seviceList); let deviceNames = seviceList.map(item => item.deviceName); app.globalData.ppScale.plugin.Blue.start(deviceNames, false); app.globalData.ppScale.plugin.bus.subscribe("devicesList", (res) => { console.log("searchDevice ===> devicesList", res); this.setData({ devicesList: res }); this.selectDevice(); }); }, selectDevice() { if(this.data.devicesList && this.data.devicesList.length && this.data.searchDevicesList) { this.setData({ searchDevicesList: false }); setTimeout(() => { app.globalData.ppScale.plugin.Blue.stopBluetoothDevicesDiscovery(); app.globalData.ppScale.device.list = this.data.devicesList; wx.redirectTo({ url: "/pages/configureDevice/configureDevice" }) }, 1000); } } })