[AI Generated]: feat(Comp): 重写用户同步逻辑支持主子用户、移除callWithTimeout、新增用户上限10人及主用户删除保护

This commit is contained in:
17792275749
2026-04-13 13:21:59 +08:00
parent 4e2e8fb899
commit 4fc829a81f
9 changed files with 118 additions and 264 deletions
+6 -34
View File
@@ -5,8 +5,8 @@ App({
globalData: { globalData: {
// wx.request 请求的服务地址 // wx.request 请求的服务地址
wxRequestUrl: "https://device.shuziweidao.com/gateway/", // wxRequestUrl: "https://device.shuziweidao.com/gateway/",
// wxRequestUrl: "http://192.168.1.207:8889/", wxRequestUrl: "http://192.168.1.207:8889/",
// 秤的所有信息 // 秤的所有信息
ppScale: { ppScale: {
@@ -14,10 +14,10 @@ App({
plugin: null, plugin: null,
activeProtocol: null, activeProtocol: null,
domain1: "http://device.shuziweidao.com:80/gateway", // 老版本 没有鉴权 // domain1: "http://device.shuziweidao.com:80/gateway", // 老版本 没有鉴权
domain2: "http://device.shuziweidao.com:80/weight", // 新版本 有鉴权 // domain2: "http://device.shuziweidao.com:80/weight", // 新版本 有鉴权
// domain1: "http://192.168.1.207:8889", // 老版本 没有鉴权 domain1: "http://192.168.1.207:8889", // 老版本 没有鉴权
// domain2: "http://192.168.1.207:8889/weight", // 新版本 有鉴权 domain2: "http://192.168.1.207:8889/weight", // 新版本 有鉴权
wifi: { wifi: {
ssid: "", ssid: "",
password: "" password: ""
@@ -332,32 +332,4 @@ App({
} }
} }
}, },
/**
* 给回调式 SDK 调用包裹超时保护,防止设备无响应时 UI 永久卡死
* @param {Function} caller 接收 done 回调的执行函数,形如 (done) => sdk.method(params, done)
* @param {number} timeout 超时毫秒数
* @param {Function} onResult 正常回调,参数与 SDK 原始回调一致
* @param {Function} onTimeout 超时后执行,负责 hideLoading + 提示
*/
callWithTimeout(caller, timeout, onResult, onTimeout) {
let settled = false;
const timer = setTimeout(() => {
if (settled) return;
settled = true;
onTimeout();
}, timeout);
caller((res) => {
if (settled) return;
settled = true;
clearTimeout(timer);
onResult(res);
});
// 返回取消函数,供组件/页面在销毁时调用,静默取消超时
return () => {
if (settled) return;
settled = true;
clearTimeout(timer);
};
},
}) })
+69 -136
View File
@@ -1,9 +1,6 @@
const app = getApp(); const app = getApp();
import $ from "../../utils/request"; import $ from "../../utils/request";
// 超时时间:15 秒
const SDK_TIMEOUT = 15000;
/** /**
* 根据生日计算年龄 * 根据生日计算年龄
* @param {string} birthday 生日字符串,如 "1990-05-20" * @param {string} birthday 生日字符串,如 "1990-05-20"
@@ -56,7 +53,6 @@ Component({
if (this._connectStateWatcher) { if (this._connectStateWatcher) {
app.unwatch('ppScale.device.connectState', this._connectStateWatcher); app.unwatch('ppScale.device.connectState', this._connectStateWatcher);
} }
if (this._sdkCancel) { this._sdkCancel(); this._sdkCancel = null; }
} }
}, },
@@ -101,14 +97,16 @@ Component({
}, },
addUser() { addUser() {
if (this.data.userList.length >= 5) { if (this.data.userList.length >= 10) {
wx.showToast({ wx.showToast({
title: "超过最大用户数", title: "超过最大用户数",
icon: "none" icon: "none"
}); });
return; return;
} }
this.selectComponent("#configureDevice2AddUser").showModal(); // 列表为空时,第一个用户只能是员工(主用户)
const isFirstUser = this.data.userList.length === 0;
this.selectComponent("#configureDevice2AddUser").showModal(isFirstUser);
}, },
getAddUserInfo() { getAddUserInfo() {
@@ -146,6 +144,17 @@ Component({
// 删除用户 // 删除用户
delUserClick(e) { delUserClick(e) {
let id = e.currentTarget.dataset.id; let id = e.currentTarget.dataset.id;
const userList = this.data.userList;
const target = userList.find(u => u.id === id);
// 主用户(userType=1)有子用户时不允许删除
if (target && target.userType === 1) {
const hasSubUser = userList.some(u => u.userType === 0);
if (hasSubUser) {
wx.showToast({ title: "请先删除所有普通用户", icon: "none" });
return;
}
}
wx.showModal({ wx.showModal({
title: "提示", title: "提示",
content: "确定要删除该用户吗?", content: "确定要删除该用户吗?",
@@ -188,99 +197,29 @@ Component({
return; return;
} }
// 获取设备端已有用户,与用户列表做双向同步 // 找出主用户,所有用户下发时 userID 统一使用主用户的 userId
wx.showLoading({ title: "正在同步用户信息...", mask: true }); const mainUser = userList.find(u => u.userType === 1);
this._sdkCancel = app.callWithTimeout( if (!mainUser) {
(done) => app.globalData.ppScale.activeProtocol.dataFetchUserID(done), wx.showToast({ title: "未找到主用户,请先添加员工用户", icon: "none" });
SDK_TIMEOUT, return;
(deviceUserIds) => { }
console.log("设备端已有用户ID列表", deviceUserIds); const mainUserId = mainUser.userId;
// 回调返回非数组视为获取失败 wx.showLoading({ title: "正在同步用户数据...", mask: true });
if (!Array.isArray(deviceUserIds)) {
// 第一步:清除秤上所有用户信息
app.globalData.ppScale.activeProtocol.codeClearDeviceData("01", (clearRes) => {
console.log("codeClearDeviceData res", clearRes);
if (clearRes !== 0x00) {
wx.hideLoading(); wx.hideLoading();
wx.showToast({ title: "获取设备用户列表失败,请重试", icon: "none" }); wx.showToast({ title: "同步用户失败,请重试", icon: "none" });
return; return;
} }
let rawList = deviceUserIds; // 第二步:全量下发本地用户列表
// SDK 返回的是 userID 数组,统一转为对象方便后续操作
let deviceIds = rawList.map(item => ({
userID: String(item),
memberID: ""
}));
// 本地列表的 userId 统一转字符串,与 SDK 侧类型对齐
let localIds = userList.map(user => String(user.userId));
// 秤有、列表没有 → 需要从秤删除
let needDeleteList = deviceIds.filter(d => !localIds.includes(d.userID));
// 秤没有、列表有 → 需要下发到秤
let needSyncList = userList.filter(user => !deviceIds.some(d => d.userID === String(user.userId)));
console.log("需删除", needDeleteList, "需下发", needSyncList);
// 无需操作时直接完成
if (!needDeleteList.length && !needSyncList.length) {
wx.hideLoading();
wx.showToast({ title: "用户信息已同步", icon: "success" });
setTimeout(() => {
this._checkWifiAndNext();
}, 1500);
return;
}
// 第一步:逐个下发新用户到秤
let syncIndex = 0; let syncIndex = 0;
const syncNext = () => { const syncNext = () => {
if (syncIndex >= needSyncList.length) { if (syncIndex >= userList.length) {
// 下发完成,开始删除
if (needDeleteList.length) {
wx.showLoading({ title: "正在删除多余用户...", mask: true });
}
deleteNext();
return;
}
wx.showLoading({ title: "正在下发第" + (syncIndex + 1) + "/" + needSyncList.length + "个用户...", mask: true });
let user = needSyncList[syncIndex];
this._sdkCancel = app.callWithTimeout(
(done) => app.globalData.ppScale.activeProtocol.dataSyncUserInfo({
userID: user.userId,
userName: user.realname,
memberID: "",
age: user.age || '',
gender: user.sex === 2 ? 0 : user.sex,
height: String(user.height || ''),
isAthleteMode: 0,
deviceHeaderIndex: syncIndex,
currentWeight: String(user.weight || ''),
targetWeight: "",
idealWeight: "",
recentData: [],
}, done),
SDK_TIMEOUT,
(res) => {
if (res == 0) {
syncIndex++;
syncNext();
} else {
wx.hideLoading();
console.log("dataSyncUserInfo 失败", res);
wx.showToast({ title: "用户信息下发失败,请重试。", icon: "none" });
}
},
() => {
wx.hideLoading();
wx.showToast({ title: "用户下发超时,请重试", icon: "none" });
}
);
};
// 第二步:逐个删除秤端多余用户
let delIndex = 0;
const deleteNext = () => {
if (delIndex >= needDeleteList.length) {
// 全部完成
wx.hideLoading(); wx.hideLoading();
wx.showToast({ title: "用户信息同步成功", icon: "success" }); wx.showToast({ title: "用户信息同步成功", icon: "success" });
setTimeout(() => { setTimeout(() => {
@@ -288,39 +227,36 @@ Component({
}, 1500); }, 1500);
return; return;
} }
wx.showLoading({ title: "正在删除第" + (delIndex + 1) + "/" + needDeleteList.length + "个多余用户...", mask: true }); const user = userList[syncIndex];
let item = needDeleteList[delIndex]; // 主用户 memberID 为空,子用户 memberID 为子用户自己的 userId
this._sdkCancel = app.callWithTimeout( const memberID = user.userId === mainUserId ? "" : user.userId;
(done) => app.globalData.ppScale.activeProtocol.dataDeleteUser({ wx.showLoading({ title: "正在下发第" + (syncIndex + 1) + "/" + userList.length + "个用户...", mask: true });
userID: item.userID, app.globalData.ppScale.activeProtocol.dataSyncUserInfo({
memberID: "" userID: mainUserId,
}, done), userName: user.realname,
SDK_TIMEOUT, memberID: memberID,
(status) => { age: user.age || '',
if (status == 0) { gender: user.sex === 2 ? 0 : user.sex,
delIndex++; height: user.height || '',
deleteNext(); isAthleteMode: 0,
} else { deviceHeaderIndex: syncIndex,
wx.hideLoading(); currentWeight: user.weight || '',
console.log("dataDeleteUser 失败", status); targetWeight: "",
wx.showToast({ title: "删除设备用户失败,请重试。", icon: "none" }); idealWeight: "",
} recentData: [],
}, }, (res) => {
() => { console.log("dataSyncUserInfo res", res, "user:", user.realname, "userID:", mainUserId, "memberID:", memberID);
if (res == 0) {
syncIndex++;
syncNext();
} else {
wx.hideLoading(); wx.hideLoading();
wx.showToast({ title: "删除用户超时,请重试", icon: "none" }); wx.showToast({ title: "用户信息下发失败,请重试", icon: "none" });
} }
); });
}; };
// 从下发开始执行
syncNext(); syncNext();
}, });
() => {
wx.hideLoading();
wx.showToast({ title: "获取设备用户超时,请重试", icon: "none" });
}
);
}, },
/** /**
@@ -330,20 +266,17 @@ Component({
*/ */
_checkWifiAndNext() { _checkWifiAndNext() {
wx.showLoading({ title: "正在检测配网状态...", mask: true }); wx.showLoading({ title: "正在检测配网状态...", mask: true });
this._sdkCancel = app.callWithTimeout( app.globalData.ppScale.activeProtocol.codeFetchWifiConfig((res) => {
(done) => app.globalData.ppScale.activeProtocol.codeFetchWifiConfig(done), wx.hideLoading();
SDK_TIMEOUT, if (res === undefined || res === null) {
(res) => { // 获取失败,自动重试
wx.hideLoading(); this._checkWifiAndNext();
// 0x01 表示已配网,跳过配网步骤直接进入下一步 return;
const progressIndex = res === 0x01 ? 3 : 2;
this.triggerEvent('deviceEvent', { status: true, progressIndex });
},
() => {
wx.hideLoading();
wx.showToast({ title: "检测配网状态超时,请重试。", icon: "none" });
} }
); // 0x01 表示已配网,跳过配网步骤直接进入下一步
const progressIndex = res === 0x01 ? 3 : 2;
this.triggerEvent('deviceEvent', { status: true, progressIndex });
});
}, },
} }
}); });
@@ -8,6 +8,8 @@ Component({
data: { data: {
animationData: null, animationData: null,
modalStatus: false, modalStatus: false,
// 是否是第一个用户(主用户),true 时只能选员工
isFirstUser: false,
// 用户类型:employee=员工,family=家庭用户 // 用户类型:employee=员工,family=家庭用户
userType: 'employee', userType: 'employee',
// 员工模式 // 员工模式
@@ -38,7 +40,8 @@ Component({
}, },
methods: { methods: {
// 显示对话框 // 显示对话框
showModal() { showModal(isFirstUser = false) {
this.setData({ isFirstUser: !!isFirstUser });
// 先瞬间将弹窗移到屏幕下方(duration:0,不产生过渡) // 先瞬间将弹窗移到屏幕下方(duration:0,不产生过渡)
let initAnim = wx.createAnimation({ duration: 0 }); let initAnim = wx.createAnimation({ duration: 0 });
initAnim.translateY(1200).step(); initAnim.translateY(1200).step();
@@ -66,6 +69,7 @@ Component({
// 关闭弹窗并重置所有数据 // 关闭弹窗并重置所有数据
closeModal() { closeModal() {
this.setData({ this.setData({
isFirstUser: false,
userType: 'employee', userType: 'employee',
workNo: "", workNo: "",
userInfo: null, userInfo: null,
@@ -83,6 +87,8 @@ Component({
// 切换用户类型,同时清空所有已填数据 // 切换用户类型,同时清空所有已填数据
switchUserType(e) { switchUserType(e) {
// 主用户模式下禁止切换
if (this.data.isFirstUser) return;
const type = e.currentTarget.dataset.type; const type = e.currentTarget.dataset.type;
if (type === this.data.userType) return; if (type === this.data.userType) return;
this.setData({ this.setData({
@@ -8,8 +8,8 @@
<view>添加用户</view> <view>添加用户</view>
</view> </view>
<view class="seaction"> <view class="seaction">
<!-- 用户类型切换 --> <!-- 用户类型切换(主用户模式下隐藏) -->
<view class="select"> <view class="select" wx:if="{{!isFirstUser}}">
<view <view
class="{{userType === 'employee' ? 'selectActive' : ''}}" class="{{userType === 'employee' ? 'selectActive' : ''}}"
bindtap="switchUserType" bindtap="switchUserType"
@@ -1,8 +1,5 @@
const app = getApp(); const app = getApp();
// 超时时间:15 秒
const SDK_TIMEOUT = 15000;
Component({ Component({
data: { data: {
progress: 0, progress: 0,
@@ -27,25 +24,21 @@ Component({
methods: { methods: {
initWifi() { initWifi() {
wx.showLoading({ title: "正在获取Wi-Fi列表...", mask: true }); wx.showLoading({ title: "正在获取Wi-Fi列表...", mask: true });
// activeProtocol 由父页面在 deviceConnect 回调中赋值,此处直接使用
const activeProtocol = app.globalData.ppScale.activeProtocol; const activeProtocol = app.globalData.ppScale.activeProtocol;
if (!activeProtocol) { if (!activeProtocol) {
wx.hideLoading(); wx.hideLoading();
wx.showToast({ title: '设备未连接,请重试', icon: 'none' }); wx.showToast({ title: '设备未连接,请重试', icon: 'none' });
return; return;
} }
this._sdkCancel = app.callWithTimeout( activeProtocol.dataFindSurroundDevice((res) => {
(done) => activeProtocol.dataFindSurroundDevice(done), wx.hideLoading();
SDK_TIMEOUT, if (!Array.isArray(res)) {
(res) => { // 获取失败,自动重试
wx.hideLoading(); this.initWifi();
this.setData({ wifiList: Array.isArray(res) ? res : [] }); return;
},
() => {
wx.hideLoading();
wx.showToast({ title: "获取Wi-Fi列表超时,请重试", icon: "none" });
} }
); this.setData({ wifiList: res });
});
}, },
// 最小化后重连,重置所有状态并重新获取 WiFi 列表 // 最小化后重连,重置所有状态并重新获取 WiFi 列表
@@ -26,7 +26,7 @@
<view> <view>
<image src="/images/configureDevice/null.png" /> <image src="/images/configureDevice/null.png" />
</view> </view>
<view>获取WIFI失败</view> <view>暂无WIFI数据,点击重新获取</view>
</view> </view>
</block> </block>
</view> </view>
@@ -4,6 +4,10 @@ Component({
data: {}, data: {},
methods: { methods: {
bindOk() {
wx.switchTab({ url: '/pages/home/home' });
},
// 开始 OTA 升级 // 开始 OTA 升级
startOtaUpgrade() { startOtaUpgrade() {
const activeProtocol = app.globalData.ppScale.activeProtocol; const activeProtocol = app.globalData.ppScale.activeProtocol;
@@ -13,42 +17,10 @@ Component({
return; return;
} }
wx.showLoading({ title: '正在升级固件,请稍候...', mask: true });
// 重置完成标志位,防止回调重复触发
this._otaCompleted = false;
// status: false = 成功,true = 失败 // status: false = 成功,true = 失败
activeProtocol.codeOtaUpdate((status) => { activeProtocol.codeOtaUpdate((status) => {
// 延迟 3 秒,让 Loading 多转一会再收口 console.log(status);
setTimeout(() => {
if (status == 0) {
// status false → 升级成功
this._finish(true);
} else {
// status true → 升级失败
this._finish(false, '固件升级失败');
}
}, 3000);
}); });
},
// 统一收口:成功/失败提示后跳转首页
_finish(success, failMsg) {
if (this._otaCompleted) return;
this._otaCompleted = true;
wx.hideLoading();
if (success) {
wx.showToast({ title: '固件升级成功', icon: 'success', duration: 2000 });
} else {
wx.showToast({ title: failMsg || '固件升级失败', icon: 'none', duration: 2000 });
}
setTimeout(() => {
app.cleanupConnection();
wx.switchTab({ url: '/pages/home/home' });
}, 2000);
} }
} }
}); });
@@ -7,4 +7,6 @@
</view> </view>
<view class="describe">随时随地同步测量数据</view> <view class="describe">随时随地同步测量数据</view>
<view class="btn" bind:tap="bindOk">完成</view>
</view> </view>
+18 -42
View File
@@ -1,9 +1,6 @@
const app = getApp(); const app = getApp();
import $ from "../../utils/request"; import $ from "../../utils/request";
// 超时时间:15 秒
const SDK_TIMEOUT = 15000;
Component({ Component({
properties: { properties: {
ssid: { ssid: {
@@ -26,7 +23,6 @@ Component({
this.setNerwork(); this.setNerwork();
}, },
detached() { detached() {
if (this._sdkCancel) { this._sdkCancel(); this._sdkCancel = null; }
} }
}, },
@@ -37,46 +33,26 @@ Component({
let password = this.properties.password; let password = this.properties.password;
let version = app.globalData.ppScale.version; let version = app.globalData.ppScale.version;
if (version === 'domain1') { if (version === 'domain1') {
this._sdkCancel = app.callWithTimeout( app.globalData.ppScale.activeProtocol.dataConfigNetWork({
(done) => app.globalData.ppScale.activeProtocol.dataConfigNetWork({ domain: app.globalData.ppScale.domain1,
domain: app.globalData.ppScale.domain1, ssid: ssid,
ssid: ssid, password: password
password: password }, (res) => {
}, done), console.log("setNetwork.js dataConfigNetWork 1", res);
SDK_TIMEOUT, this.netWorkCallBack(res);
(res) => { });
console.log("setNetwork.js dataConfigNetWork 1", res);
this.netWorkCallBack(res);
},
() => {
wx.showToast({ title: "配网超时,请重试", icon: "none" });
setTimeout(() => {
this.triggerEvent('wifiEvent', { status: false });
}, 1500);
}
);
} }
if (version === 'domain2') { if (version === 'domain2') {
this._sdkCancel = app.callWithTimeout( app.globalData.ppScale.activeProtocol.dataConfigUserNetWork({
(done) => app.globalData.ppScale.activeProtocol.dataConfigUserNetWork({ domain: app.globalData.ppScale.domain2,
domain: app.globalData.ppScale.domain2, ssid: ssid,
ssid: ssid, password: password,
password: password, userName: "apiUser",
userName: "apiUser", userPassword: "3acebb95eb49577e9c2a2082589b9bd6"
userPassword: "3acebb95eb49577e9c2a2082589b9bd6" }, (res) => {
}, done), console.log("setNetwork.js dataConfigUserNetWork 2", res);
SDK_TIMEOUT, this.netWorkCallBack(res);
(res) => { });
console.log("setNetwork.js dataConfigUserNetWork 2", res);
this.netWorkCallBack(res);
},
() => {
wx.showToast({ title: "配网超时,请重试", icon: "none" });
setTimeout(() => {
this.triggerEvent('wifiEvent', { status: false });
}, 1500);
}
);
} }
}, },