[AI Generated]: refactor(*): 重构蓝牙生命周期管理,修复最小化后重连与进度跳步问题

- app.js: 提取 registerBusListeners 方法,新增自动重连机制(3次上限)
- configureDevice: bus 订阅迁移至 onShow,deviceConnect 按步骤区分处理逻辑
- configureDevice_2: setUserInfo 兼容 WIFISUCCESS 状态,WXML 覆盖六态
- configureDevice_3: 新增 reInitWifi 方法,最小化后重置 WiFi 列表
- replaceNetwork: 订阅迁移至 onShow,修复 selectComponent 空指针
- replaceNetwork_3: 修复 domain1 配网参数引用错误
- userInfo: 订阅迁移至 onShow,setUserInfo 兼容 WIFISUCCESS
- searchDevice: 移除 onLoad 重复初始化,统一由 onShow 处理
- 所有 BLE 页面统一 onHide/onUnload 清理:resetReconnectCount + setGlobalData(null) + stop()

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
17792275749
2026-03-09 17:34:08 +08:00
co-authored by Claude Opus 4.6
parent 6924a1ff5b
commit 81f9301c64
12 changed files with 487 additions and 192 deletions
+59 -12
View File
@@ -142,42 +142,89 @@ App({
_callbacks: {} // 用于存储所有 globalData 属性的监听回调 _callbacks: {} // 用于存储所有 globalData 属性的监听回调
}, },
_reconnectCount: 0, // 自动重连已尝试次数
_reconnectMax: 3, // 最大自动重连次数
_reconnectTimer: null, // 重连定时器
initPpScale() { initPpScale() {
this.globalData.ppScale.plugin = requirePlugin('ppScale-plugin'); this.globalData.ppScale.plugin = requirePlugin('ppScale-plugin');
},
/**
* 注册全局 bus 事件监听(connectState / syncDeviceTimeSuccess / deviceWillDisconnect
* stop() 会销毁所有订阅,页面在 onShow 中需重新调用此方法
*/
registerBusListeners() {
const plugin = this.globalData.ppScale.plugin;
// 蓝牙连接状态监听 // 蓝牙连接状态监听
this.globalData.ppScale.plugin.bus.subscribe("connectState", (res) => { plugin.bus.subscribe("connectState", (res) => {
console.log("app.js ===> connectState", res); console.log("app.js ===> connectState", res);
this.setGlobalData('ppScale.device.connectState', res); this.setGlobalData('ppScale.device.connectState', res);
// 连接失败则重新连接 // 连接成功,重置重连计数
if (res == this.globalData.ppScale.plugin.BLUE_STATE.CONNECTFAILED) { if (res == plugin.BLUE_STATE.CONNECTSUCCESS) {
this.reconnectDevice() this._reconnectCount = 0;
} }
// 连接失败,自动重连(最多重试3次)
if (res == plugin.BLUE_STATE.CONNECTFAILED) {
this.reconnectDevice();
}
wx.hideLoading(); wx.hideLoading();
}); });
// 同步时间 // 同步时间
this.globalData.ppScale.plugin.bus.subscribe("syncDeviceTimeSuccess", (res) => { plugin.bus.subscribe("syncDeviceTimeSuccess", (res) => {
console.log("app.js ===> syncDeviceTimeSuccess", res); console.log("app.js ===> syncDeviceTimeSuccess", res);
}) });
// 设备自动断开监听 // 设备自动断开监听
this.globalData.ppScale.plugin.bus.subscribe("deviceWillDisconnect", (res) => { plugin.bus.subscribe("deviceWillDisconnect", (res) => {
console.log("app.js ===> deviceWillDisconnect", res); console.log("app.js ===> deviceWillDisconnect", res);
this.setGlobalData('ppScale.device.connectState', plugin.BLUE_STATE.CONNECTFAILED);
this.reconnectDevice(); });
})
}, },
/**
* 自动重连设备,最多重试 _reconnectMax 次,超过后停止,由用户手动重连
* 流程:先断开旧连接,再重新扫描设备,由页面级 devicesList 订阅自动接管连接
*/
reconnectDevice() { reconnectDevice() {
if (this._reconnectCount >= this._reconnectMax) {
console.log("app.js ===> 自动重连已达上限,等待用户手动重试");
return;
}
this._reconnectCount++;
console.log(`app.js ===> 自动重连第 ${this._reconnectCount}/${this._reconnectMax}`);
// 延迟 2 秒后重连,避免连续冲突
if (this._reconnectTimer) {
clearTimeout(this._reconnectTimer);
}
this._reconnectTimer = setTimeout(() => {
this.globalData.ppScale.plugin.Blue.disconnect((disres) => { this.globalData.ppScale.plugin.Blue.disconnect((disres) => {
if (disres.errCode == 0) { if (disres.errCode == 0) {
console.log("app.js ===> 断开成功,开始重新扫描设备");
this.globalData.ppScale.plugin.Blue.startBluetoothDevicesDiscovery(); this.globalData.ppScale.plugin.Blue.startBluetoothDevicesDiscovery();
} else { } else {
this.reconnectDevice(); console.log("app.js ===> 断开失败,errCode:", disres.errCode);
}
});
}, 2000);
},
/**
* 重置重连计数,用于用户手动点击重试时调用
*/
resetReconnectCount() {
this._reconnectCount = 0;
if (this._reconnectTimer) {
clearTimeout(this._reconnectTimer);
this._reconnectTimer = null;
} }
})
}, },
/** /**
@@ -88,8 +88,9 @@ Component({
// 组件的方法 // 组件的方法
methods: { methods: {
// 二次连接设备 // 手动重连设备
connectedDevice() { connectedDevice() {
app.resetReconnectCount();
this.triggerEvent('connectedDeviceEvent', { this.triggerEvent('connectedDeviceEvent', {
device: this.data.device device: this.data.device
}); });
@@ -154,7 +155,7 @@ Component({
// console.log("deviceInfo === codeClearDeviceData", res); // console.log("deviceInfo === codeClearDeviceData", res);
// }) // })
if(this.data.connectState == this.data.BLUE_STATE.CONNECTSUCCESS) { if(this.data.connectState == this.data.BLUE_STATE.CONNECTSUCCESS || this.data.connectState == this.data.BLUE_STATE.WIFISUCCESS) {
if(this.data.userId) { if(this.data.userId) {
app.globalData.ppScale.activeProtocol.dataSyncUserInfo({ app.globalData.ppScale.activeProtocol.dataSyncUserInfo({
userID: this.data.userId, userID: this.data.userId,
@@ -5,14 +5,30 @@
<view>型号:{{device.name}}</view> <view>型号:{{device.name}}</view>
</view> </view>
<view> <view>
<block wx:if="{{device && connectState == BLUE_STATE.CONNECTSUCCESS}}"> <block wx:if="{{connectState == BLUE_STATE.CONNECTSUCCESS || connectState == BLUE_STATE.WIFISUCCESS}}">
<view style="background-color: #2AC79F;"></view> <view style="background-color: #2AC79F;"></view>
<view style="color: #2AC79F;">连接成功</view> <view style="color: #2AC79F;">连接成功</view>
</block> </block>
<block wx:else> <block wx:elif="{{connectState == BLUE_STATE.SCANING}}">
<view style="background-color: #3194FB;"></view>
<view style="color: #3194FB;">正在搜索...</view>
</block>
<block wx:elif="{{connectState == BLUE_STATE.READY}}">
<view style="background-color: #3194FB;"></view>
<view style="color: #3194FB;">蓝牙就绪</view>
</block>
<block wx:elif="{{connectState == BLUE_STATE.UNAVAILABLE}}">
<view style="background-color: #F24439;"></view>
<view style="color: #F24439;">蓝牙不可用</view>
</block>
<block wx:elif="{{connectState == BLUE_STATE.CONNECTFAILED}}">
<view style="background-color: #F24439;"></view> <view style="background-color: #F24439;"></view>
<view bind:tap="connectedDevice" style="color: #F24439;">连接失败,点击重试</view> <view bind:tap="connectedDevice" style="color: #F24439;">连接失败,点击重试</view>
</block> </block>
<block wx:else>
<view style="background-color: #999999;"></view>
<view style="color: #999999;">未连接</view>
</block>
</view> </view>
</view> </view>
<view class="section"> <view class="section">
@@ -37,6 +37,17 @@ Component({
}) })
}, },
// 最小化后重连,重置所有状态并重新获取 WiFi 列表
reInitWifi() {
this.setData({
progress: 0,
wifiList: [],
selectWifi: null,
selectWifiPWD: ""
});
this.initWifi();
},
selectDevice(e) { selectDevice(e) {
this.setData({ this.setData({
progress: 1, progress: 1,
@@ -36,8 +36,8 @@ Component({
if (version === 'domain1') { if (version === 'domain1') {
app.globalData.ppScale.activeProtocol.dataConfigNetWork({ app.globalData.ppScale.activeProtocol.dataConfigNetWork({
domain: app.globalData.ppScale.domain1, domain: app.globalData.ppScale.domain1,
ssid: this.data.selectWifi.ssid, ssid: ssid,
password: this.data.selectWifiPWD password: password
}, (res) => { }, (res) => {
console.log("setNetwork.js dataConfigNetWork 1", res); console.log("setNetwork.js dataConfigNetWork 1", res);
@@ -61,14 +61,14 @@ Component({
netWorkCallBack(res) { netWorkCallBack(res) {
if(res === 23) { if(res === 23) {
app.globalData.ppScale.wifi.ssid = ssid; app.globalData.ppScale.wifi.ssid = this.properties.ssid;
app.globalData.ppScale.wifi.password = password; app.globalData.ppScale.wifi.password = this.properties.password;
let scaleDeviceId = app.globalData.ppScale.device.mac.replace(/:/g, ''); let scaleDeviceId = app.globalData.ppScale.device.mac.replace(/:/g, '');
if(scaleDeviceId) { if(scaleDeviceId) {
let params = { let params = {
equipmentCode: scaleDeviceId, equipmentCode: scaleDeviceId,
wifiName: ssid wifiName: this.properties.ssid
}; };
$.ajax("weighingScale/edit/device", params, "POST").then((res) => { $.ajax("weighingScale/edit/device", params, "POST").then((res) => {
this.triggerEvent('wifiEvent', { this.triggerEvent('wifiEvent', {
+125 -8
View File
@@ -1,4 +1,5 @@
const ppScale = getApp().globalData.ppScale; const app = getApp();
const ppScale = app.globalData.ppScale;
import $ from "../../utils/request"; import $ from "../../utils/request";
Page({ Page({
@@ -13,6 +14,17 @@ Page({
}, },
onLoad() { onLoad() {
// 一次性数据初始化,订阅逻辑在 onShow 中注册
},
onShow() {
console.log("configureDevice onShow");
// 延迟 300ms 确保 stop() 完全释放后再重新注册(参照官方 demo)
setTimeout(() => {
// 重新注册 app 级别的全局 bus 订阅
app.registerBusListeners();
// 页面级 bus 订阅
ppScale.plugin.bus.subscribe("deviceInfo", (res) => { ppScale.plugin.bus.subscribe("deviceInfo", (res) => {
console.log("===》deviceInfo", res); console.log("===》deviceInfo", res);
ppScale.device.mac = res.serialNumber; ppScale.device.mac = res.serialNumber;
@@ -24,6 +36,30 @@ Page({
ppScale.plugin.ScaleAction.startDataProgress(true); ppScale.plugin.ScaleAction.startDataProgress(true);
ppScale.activeProtocol = ppScale.plugin.ScaleAction.getActiveProtocol(); ppScale.activeProtocol = ppScale.plugin.ScaleAction.getActiveProtocol();
let currentStep = this.data.progress.index;
// 步骤 1/2/3:最小化后重连,只需恢复连接状态(跳过绑定检查)
if (currentStep >= 1) {
ppScale.activeProtocol.codeUpdateMTU((res) => {
console.log("===》重连 codeUpdateMTU", res);
ppScale.device.name = this.data.device.name;
ppScale.device.connection = this.data.device;
wx.hideLoading();
// 配网步骤:重新获取 WiFi 列表
if (currentStep === 2) {
const comp = this.selectComponent('#configureDevice3');
if (comp) {
comp.reInitWifi();
}
}
});
return;
}
// 步骤 0:首次连接设备,走完整的绑定检查链路
ppScale.activeProtocol.codeUpdateMTU((res) => { ppScale.activeProtocol.codeUpdateMTU((res) => {
console.log("===》codeUpdateMTU", res); console.log("===》codeUpdateMTU", res);
@@ -59,8 +95,6 @@ Page({
icon: "none", icon: "none",
title: "设备初始化成功,请重新绑定。", title: "设备初始化成功,请重新绑定。",
}) })
// device.list = [];
// device.mac = null;
setTimeout(() => { setTimeout(() => {
wx.navigateBack({ wx.navigateBack({
delta: 1 delta: 1
@@ -76,7 +110,6 @@ Page({
} }
}) })
} else if (res.cancel) { } else if (res.cancel) {
// device.mac = null;
ppScale.plugin.Blue.stop(); ppScale.plugin.Blue.stop();
} }
} }
@@ -87,6 +120,8 @@ Page({
const nameArr = this.data.device.name.split("-"); const nameArr = this.data.device.name.split("-");
ppScale.version = nameArr.length === 5 ? "domain2" : "domain1"; ppScale.version = nameArr.length === 5 ? "domain2" : "domain1";
if (this.data.progressNext) { if (this.data.progressNext) {
// 立即重置,防止最小化后重连时重复推进进度
this.setData({ progressNext: false });
let scaleDeviceId = ppScale.device.mac.replace(/:/g, ''); let scaleDeviceId = ppScale.device.mac.replace(/:/g, '');
let params = { let params = {
sn: scaleDeviceId, sn: scaleDeviceId,
@@ -120,6 +155,22 @@ Page({
}) })
}); });
}); });
// 如果之前已选择过设备,自动扫描并重连
if (this.data.device) {
wx.showLoading({ title: "正在重新连接...", mask: true });
ppScale.plugin.bus.subscribe("devicesList", (res) => {
let fIndex = res.findIndex(item => item.deviceId === this.data.device.deviceId);
if (fIndex >= 0) {
ppScale.plugin.Blue.stopBluetoothDevicesDiscovery();
ppScale.plugin.Blue.createBLEConnection(res[fIndex]);
}
});
}
// 通过完整链路重新初始化蓝牙(权限检查 → 打开适配器 → start)
this.checkBluetoothPermissionAndInit();
}, 300);
}, },
// 选择了某个设备 // 选择了某个设备
@@ -139,7 +190,7 @@ Page({
}, },
connectedDevice(e) { connectedDevice(e) {
ppScale.plugin.Blue.stop(); app.resetReconnectCount();
wx.showLoading({ wx.showLoading({
title: "正在尝试连接...", title: "正在尝试连接...",
mask: true mask: true
@@ -148,7 +199,10 @@ Page({
progressNext: false progressNext: false
}) })
let device = e.detail.device; let device = e.detail.device;
// 先断开旧连接再重新连接
ppScale.plugin.Blue.disconnect((disres) => {
this.connectedDevice_(device); this.connectedDevice_(device);
});
}, },
connectedDevice_(device) { connectedDevice_(device) {
@@ -161,9 +215,6 @@ Page({
}, },
setDeviceUserInfo(e) { setDeviceUserInfo(e) {
this.setData({
progressNext: true
})
let status = e.detail.status; let status = e.detail.status;
if (status) { if (status) {
this.setProgress(); this.setProgress();
@@ -190,7 +241,73 @@ Page({
}) })
}, },
checkBluetoothPermissionAndInit() {
wx.getSetting({
success: (res) => {
if (res.authSetting['scope.bluetooth']) {
this.openBluetoothAdapter();
} else {
wx.authorize({
scope: 'scope.bluetooth',
success: () => {
this.openBluetoothAdapter();
},
fail: () => {
wx.hideLoading();
wx.showModal({
title: '提示',
content: '蓝牙权限被拒绝,无法连接设备。是否前往设置开启?',
confirmText: '去开启',
cancelText: '不开启',
success: (modalRes) => {
if (modalRes.confirm) {
wx.openSetting();
}
}
});
}
});
}
},
fail: () => {
wx.hideLoading();
}
});
},
openBluetoothAdapter() {
wx.openBluetoothAdapter({
success: () => {
// 蓝牙适配器打开成功,设置设备配置后启动扫描
let setting = ppScale.device.setting;
ppScale.plugin.Blue.setDeviceSetting(setting);
let deviceNames = setting.map(item => item.deviceName);
ppScale.plugin.Blue.start(deviceNames, false);
},
fail: (err) => {
wx.hideLoading();
if (err.errCode === 10001) {
wx.showModal({
title: "提示",
content: "请确保手机蓝牙已开启。",
showCancel: false
});
}
}
});
},
onHide() {
console.log("configureDevice onHide");
app.resetReconnectCount();
app.setGlobalData('ppScale.device.connectState', null);
ppScale.plugin.Blue.stop();
},
onUnload() { onUnload() {
console.log("configureDevice onUnload");
app.resetReconnectCount();
app.setGlobalData('ppScale.device.connectState', null);
ppScale.plugin.Blue.stop(); ppScale.plugin.Blue.stop();
} }
}) })
+1 -1
View File
@@ -18,7 +18,7 @@
<configureDevice2 bind:deviceEvent="setDeviceUserInfo" bind:connectedDeviceEvent="connectedDevice"></configureDevice2> <configureDevice2 bind:deviceEvent="setDeviceUserInfo" bind:connectedDeviceEvent="connectedDevice"></configureDevice2>
</block> </block>
<block wx:if="{{progress.index === 2}}"> <block wx:if="{{progress.index === 2}}">
<configureDevice3 bind:deviceEvent="setDeviceConfig"></configureDevice3> <configureDevice3 id="configureDevice3" bind:deviceEvent="setDeviceConfig"></configureDevice3>
</block> </block>
<block wx:if="{{progress.index === 3}}"> <block wx:if="{{progress.index === 3}}">
<configureDevice4 bind:deviceEvent="setConfigSuccessful"></configureDevice4> <configureDevice4 bind:deviceEvent="setConfigSuccessful"></configureDevice4>
+60 -19
View File
@@ -19,20 +19,44 @@ Page({
_connectStateWatcher: null, _connectStateWatcher: null,
onLoad(options) { onLoad(options) {
// 一次性数据初始化
this.checkBluetoothPermissionAndInit(); this.checkBluetoothPermissionAndInit();
console.log(`[replaceNetwork] connectState 获取: ${app.globalData.ppScale.device.connectState}`);
this.setData({
BLUE_STATE: app.globalData.ppScale.plugin.BLUE_STATE,
connectState: app.globalData.ppScale.device.connectState
})
this._connectStateWatcher = (newValue, oldValue) => {
console.log(`[replaceNetwork] connectState 变化: ${oldValue} -> ${newValue}`);
this.setData({
connectState: newValue || ''
});
};
app.watch('ppScale.device.connectState', this._connectStateWatcher);
},
onShow() {
console.log("replaceNetwork onShow");
// 延迟 300ms 确保 stop() 完全释放后再重新注册(参照官方 demo)
setTimeout(() => {
// 重新注册 app 级别的全局 bus 订阅
app.registerBusListeners();
// 页面级 bus 订阅
app.globalData.ppScale.plugin.bus.subscribe("devicesModel", (res) => { app.globalData.ppScale.plugin.bus.subscribe("devicesModel", (res) => {
console.log("searchDevice ===》devicesModel", res); console.log("replaceNetwork ===》devicesModel", res);
app.globalData.ppScale.device.mac = res.deviceMac; app.globalData.ppScale.device.mac = res.deviceMac;
});
app.globalData.ppScale.plugin.bus.subscribe("deviceConnect", (res) => { app.globalData.ppScale.plugin.bus.subscribe("deviceConnect", (res) => {
console.log('connectedDevice ===》deviceConnect', res); console.log('replaceNetwork ===》deviceConnect', res);
app.globalData.ppScale.plugin.ScaleAction.startDataProgress(true); app.globalData.ppScale.plugin.ScaleAction.startDataProgress(true);
app.globalData.ppScale.activeProtocol = app.globalData.ppScale.plugin.ScaleAction.getActiveProtocol(); app.globalData.ppScale.activeProtocol = app.globalData.ppScale.plugin.ScaleAction.getActiveProtocol();
app.globalData.ppScale.activeProtocol.codeUpdateMTU((res) => { app.globalData.ppScale.activeProtocol.codeUpdateMTU((res) => {
console.log("connectedDevice ===》codeUpdateMTU", res); console.log("replaceNetwork ===》codeUpdateMTU", res);
app.globalData.ppScale.device.name = this.data.device.name; app.globalData.ppScale.device.name = this.data.device.name;
app.globalData.ppScale.device.connection = this.data.device; app.globalData.ppScale.device.connection = this.data.device;
@@ -40,23 +64,19 @@ Page({
app.globalData.ppScale.version = nameArr.length === 5 ? "domain2" : "domain1"; app.globalData.ppScale.version = nameArr.length === 5 ? "domain2" : "domain1";
wx.hideLoading(); wx.hideLoading();
this.selectComponent('#replaceNetwork1Component').getWiFiList(); // 仅在 WiFi 列表步骤时获取列表(组件只在 progress === 0 时渲染)
}); if (this.data.progress === 0) {
const comp = this.selectComponent('#replaceNetwork1Component');
if (comp) {
comp.getWiFiList();
}
}
}); });
}); });
console.log(`[Component] connectState 获取: ${app.globalData.ppScale.device.connectState}`); // 通过完整链路重新初始化蓝牙(权限检查 → 打开蓝牙 → 获取设备 → start)
this.setData({ this.checkBluetoothPermissionAndInit();
BLUE_STATE: app.globalData.ppScale.plugin.BLUE_STATE, }, 300);
connectState: app.globalData.ppScale.device.connectState
})
this._connectStateWatcher = (newValue, oldValue) => {
console.log(`[Component] connectState 变化: ${oldValue} -> ${newValue}`);
this.setData({
connectState: newValue || ''
});
};
app.watch('ppScale.device.connectState', this._connectStateWatcher);
}, },
checkBluetoothPermissionAndInit() { checkBluetoothPermissionAndInit() {
@@ -201,11 +221,22 @@ Page({
}) })
}, },
// 点击设备重连 // 手动重连设备
connectedDevice() { connectedDevice() {
app.resetReconnectCount();
let device = this.data.device; let device = this.data.device;
if(device) { if(device) {
ppScale.plugin.Blue.createBLEConnection(device); wx.showLoading({
title: "正在重新连接设备...",
mask: true
});
app.globalData.ppScale.plugin.Blue.disconnect((disres) => {
if (disres.errCode == 0) {
app.globalData.ppScale.plugin.Blue.createBLEConnection(device);
} else {
app.globalData.ppScale.plugin.Blue.createBLEConnection(device);
}
});
} }
}, },
@@ -244,8 +275,18 @@ Page({
} }
}, },
onHide() {
console.log("replaceNetwork onHide");
app.resetReconnectCount();
app.setGlobalData('ppScale.device.connectState', null);
app.globalData.ppScale.plugin.Blue.stop();
},
// 卸载事件监听 // 卸载事件监听
onUnload() { onUnload() {
console.log("replaceNetwork onUnload");
app.resetReconnectCount();
app.setGlobalData('ppScale.device.connectState', null);
app.globalData.ppScale.plugin.Blue.stop(); app.globalData.ppScale.plugin.Blue.stop();
if (this._connectStateWatcher) { if (this._connectStateWatcher) {
app.unwatch('ppScale.device.connectState', this._connectStateWatcher); app.unwatch('ppScale.device.connectState', this._connectStateWatcher);
+18 -2
View File
@@ -5,14 +5,30 @@
<view>型号:{{device.name}}</view> <view>型号:{{device.name}}</view>
</view> </view>
<view> <view>
<block wx:if="{{device && connectState == BLUE_STATE.CONNECTSUCCESS}}"> <block wx:if="{{connectState == BLUE_STATE.CONNECTSUCCESS || connectState == BLUE_STATE.WIFISUCCESS}}">
<view style="background-color: #2AC79F;"></view> <view style="background-color: #2AC79F;"></view>
<view style="color: #2AC79F;">连接成功</view> <view style="color: #2AC79F;">连接成功</view>
</block> </block>
<block wx:else> <block wx:elif="{{connectState == BLUE_STATE.SCANING}}">
<view style="background-color: #3194FB;"></view>
<view style="color: #3194FB;">正在搜索...</view>
</block>
<block wx:elif="{{connectState == BLUE_STATE.READY}}">
<view style="background-color: #3194FB;"></view>
<view style="color: #3194FB;">蓝牙就绪</view>
</block>
<block wx:elif="{{connectState == BLUE_STATE.UNAVAILABLE}}">
<view style="background-color: #F24439;"></view>
<view style="color: #F24439;">蓝牙不可用</view>
</block>
<block wx:elif="{{connectState == BLUE_STATE.CONNECTFAILED}}">
<view style="background-color: #F24439;"></view> <view style="background-color: #F24439;"></view>
<view bind:tap="connectedDevice" style="color: #F24439;">连接失败,点击重试</view> <view bind:tap="connectedDevice" style="color: #F24439;">连接失败,点击重试</view>
</block> </block>
<block wx:else>
<view style="background-color: #999999;"></view>
<view style="color: #999999;">未连接</view>
</block>
</view> </view>
</view> </view>
+1 -1
View File
@@ -9,7 +9,7 @@ Page({
}, },
onLoad(options) { onLoad(options) {
this.checkBluetoothPermissionAndInit(); // 一次性数据初始化(蓝牙初始化在 onShow 中统一处理)
}, },
onShow() { onShow() {
+56 -26
View File
@@ -37,37 +37,16 @@ Page({
_connectStateWatcher: null, _connectStateWatcher: null,
onLoad(options) { onLoad(options) {
// 一次性数据初始化
this.checkBluetoothPermissionAndInit(); this.checkBluetoothPermissionAndInit();
app.globalData.ppScale.plugin.bus.subscribe("devicesModel", (res) => { console.log(`[userInfo] connectState 获取: ${app.globalData.ppScale.device.connectState}`);
console.log("searchDevice ===》devicesModel", res);
app.globalData.ppScale.device.mac = res.deviceMac;
app.globalData.ppScale.plugin.bus.subscribe("deviceConnect", (res) => {
console.log('connectedDevice ===》deviceConnect', res);
app.globalData.ppScale.plugin.ScaleAction.startDataProgress(true);
app.globalData.ppScale.activeProtocol = app.globalData.ppScale.plugin.ScaleAction.getActiveProtocol();
app.globalData.ppScale.activeProtocol.codeUpdateMTU((res) => {
console.log("connectedDevice ===》codeUpdateMTU", res);
app.globalData.ppScale.device.name = this.data.device.name;
app.globalData.ppScale.device.connection = this.data.device;
wx.hideLoading();
});
});
});
console.log(`[Component] connectState 获取: ${app.globalData.ppScale.device.connectState}`);
this.setData({ this.setData({
BLUE_STATE: app.globalData.ppScale.plugin.BLUE_STATE, BLUE_STATE: app.globalData.ppScale.plugin.BLUE_STATE,
connectState: app.globalData.ppScale.device.connectState connectState: app.globalData.ppScale.device.connectState
}) })
this._connectStateWatcher = (newValue, oldValue) => { this._connectStateWatcher = (newValue, oldValue) => {
console.log(`[Component] connectState 变化: ${oldValue} -> ${newValue}`); console.log(`[userInfo] connectState 变化: ${oldValue} -> ${newValue}`);
this.setData({ this.setData({
connectState: newValue || '' connectState: newValue || ''
}); });
@@ -101,6 +80,40 @@ Page({
} }
}, },
onShow() {
console.log("userInfo onShow");
// 延迟 300ms 确保 stop() 完全释放后再重新注册(参照官方 demo)
setTimeout(() => {
// 重新注册 app 级别的全局 bus 订阅
app.registerBusListeners();
// 页面级 bus 订阅
app.globalData.ppScale.plugin.bus.subscribe("devicesModel", (res) => {
console.log("userInfo ===》devicesModel", res);
app.globalData.ppScale.device.mac = res.deviceMac;
});
app.globalData.ppScale.plugin.bus.subscribe("deviceConnect", (res) => {
console.log('userInfo ===》deviceConnect', res);
app.globalData.ppScale.plugin.ScaleAction.startDataProgress(true);
app.globalData.ppScale.activeProtocol = app.globalData.ppScale.plugin.ScaleAction.getActiveProtocol();
app.globalData.ppScale.activeProtocol.codeUpdateMTU((res) => {
console.log("userInfo ===》codeUpdateMTU", res);
app.globalData.ppScale.device.name = this.data.device.name;
app.globalData.ppScale.device.connection = this.data.device;
wx.hideLoading();
});
});
// 通过完整链路重新初始化蓝牙(权限检查 → 打开蓝牙 → 获取设备 → start)
this.checkBluetoothPermissionAndInit();
}, 300);
},
// 姓名输入 // 姓名输入
realnameInput(e) { realnameInput(e) {
let realname = e.detail.value.replace(/\s+/g, ''); let realname = e.detail.value.replace(/\s+/g, '');
@@ -156,7 +169,7 @@ Page({
}, },
setUserInfo() { setUserInfo() {
if(this.data.connectState == this.data.BLUE_STATE.CONNECTSUCCESS) { if(this.data.connectState == this.data.BLUE_STATE.CONNECTSUCCESS || this.data.connectState == this.data.BLUE_STATE.WIFISUCCESS) {
let realname = this.data.realname; let realname = this.data.realname;
let sex = this.data.sex; let sex = this.data.sex;
let birthday = this.data.birthday; let birthday = this.data.birthday;
@@ -414,19 +427,36 @@ Page({
}) })
}, },
// 点击设备重连 // 手动重连设备
connectedDevice() { connectedDevice() {
app.resetReconnectCount();
let device = this.data.device; let device = this.data.device;
if(device) { if(device) {
wx.showLoading({ wx.showLoading({
title: "正在重新连接设备...", title: "正在重新连接设备...",
mask: true mask: true
}); });
app.globalData.ppScale.plugin.Blue.disconnect((disres) => {
if (disres.errCode == 0) {
app.globalData.ppScale.plugin.Blue.createBLEConnection(device); app.globalData.ppScale.plugin.Blue.createBLEConnection(device);
} else {
app.globalData.ppScale.plugin.Blue.createBLEConnection(device);
}
});
} }
}, },
onHide() {
console.log("userInfo onHide");
app.resetReconnectCount();
app.setGlobalData('ppScale.device.connectState', null);
app.globalData.ppScale.plugin.Blue.stop();
},
onUnload() { onUnload() {
console.log("userInfo onUnload");
app.resetReconnectCount();
app.setGlobalData('ppScale.device.connectState', null);
app.globalData.ppScale.plugin.Blue.stop(); app.globalData.ppScale.plugin.Blue.stop();
if (this._connectStateWatcher) { if (this._connectStateWatcher) {
app.unwatch('ppScale.device.connectState', this._connectStateWatcher); app.unwatch('ppScale.device.connectState', this._connectStateWatcher);
+18 -2
View File
@@ -5,14 +5,30 @@
<view>型号:{{device.name}}</view> <view>型号:{{device.name}}</view>
</view> </view>
<view> <view>
<block wx:if="{{device && connectState == BLUE_STATE.CONNECTSUCCESS}}"> <block wx:if="{{connectState == BLUE_STATE.CONNECTSUCCESS || connectState == BLUE_STATE.WIFISUCCESS}}">
<view style="background-color: #2AC79F;"></view> <view style="background-color: #2AC79F;"></view>
<view style="color: #2AC79F;">连接成功</view> <view style="color: #2AC79F;">连接成功</view>
</block> </block>
<block wx:else> <block wx:elif="{{connectState == BLUE_STATE.SCANING}}">
<view style="background-color: #3194FB;"></view>
<view style="color: #3194FB;">正在搜索...</view>
</block>
<block wx:elif="{{connectState == BLUE_STATE.READY}}">
<view style="background-color: #3194FB;"></view>
<view style="color: #3194FB;">蓝牙就绪</view>
</block>
<block wx:elif="{{connectState == BLUE_STATE.UNAVAILABLE}}">
<view style="background-color: #F24439;"></view>
<view style="color: #F24439;">蓝牙不可用</view>
</block>
<block wx:elif="{{connectState == BLUE_STATE.CONNECTFAILED}}">
<view style="background-color: #F24439;"></view> <view style="background-color: #F24439;"></view>
<view bind:tap="connectedDevice" style="color: #F24439;">连接失败,点击重试</view> <view bind:tap="connectedDevice" style="color: #F24439;">连接失败,点击重试</view>
</block> </block>
<block wx:else>
<view style="background-color: #999999;"></view>
<view style="color: #999999;">未连接</view>
</block>
</view> </view>
</view> </view>
<view class="section"> <view class="section">