From f9341f88ee32461473740b2482e17f302de7f36b Mon Sep 17 00:00:00 2001 From: "3321822538@qq.com" <3321822538@qq.com> Date: Mon, 21 Apr 2025 17:59:16 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B5=87=E8=8A=B1=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- page_user/dingshi.vue | 414 +++++++++++++++++++++++------------------- page_user/lanya.vue | 232 +++++++++++++++-------- pages/index/index.vue | 72 +++++++- 3 files changed, 455 insertions(+), 263 deletions(-) diff --git a/page_user/dingshi.vue b/page_user/dingshi.vue index 05fcb10..816b7be 100644 --- a/page_user/dingshi.vue +++ b/page_user/dingshi.vue @@ -3,6 +3,10 @@ + + + + @@ -33,7 +37,7 @@ {{minute}}分 {{second}}秒 - + 取消 @@ -45,9 +49,9 @@ - + - + @@ -124,7 +128,20 @@ shi:'', fen:'', miao:'', - tian:'' + tian: '', + isLoading: false, // 加载状态 + retryCount: 0, // 重试次数 + maxRetries: 3, // 最大重试次数 + lastOperation: null, // 最后一次操作 + // 添加默认时间设置 + defaultTime: { + hour: '00', + minute: '00' + }, + defaultTimeLength: { + minute: '00', + second: '00' + }, } }, // 分享到好友(会话) @@ -181,35 +198,83 @@ }, methods: { - // 点击开关是否开启 - btnchange(key, index, values) { - this.kgflag = true - this.btnitem(key, index, values) - this.btnqx() - this.deviceindex = index - this.devicehour = values[0] - this.deviceminute = values[1] - this.devicemiao = values[2] - if (this.list.hasOwnProperty(key)) { - const array = this.list[key] - const lastIndex = array.length - 1 - const lastElement = array[lastIndex] - const lastElements = array[lastIndex] - array[lastIndex] = !lastElement - if (lastElements) { - this.deviceflag = 0 - } else { - this.deviceflag = 1 - } - } - let cucun = '11num' + this.deviceindex + '@' + this.devicehour + '@' + this.deviceminute + '@' + this - .devicemiao + '@' + this.deviceflag + '@' - xBlufi.notifySendCustomData({ - customData: cucun - }) + // 显示加载 + showLoading() { + this.isLoading = true; + }, + + // 隐藏加载 + hideLoading() { + this.isLoading = false; setTimeout(() => { - this.kgflag = false - }, 1000) + this.isLoading = false; + }, 500); + }, + + // 重试机制 + async retryOperation() { + if (this.retryCount < this.maxRetries) { + this.retryCount++; + await this.delay(1000); + if (this.lastOperation) { + this.lastOperation(); + } + } else { + this.hideLoading(); + uni.showToast({ + title: '操作失败,请重试', + icon: 'none' + }); + this.retryCount = 0; + } + }, + + // 延时函数 + delay(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); + }, + + // 点击开关是否开启 + async btnchange(key, index, values) { + try { + this.showLoading(); + this.kgflag = true; + this.btnitem(key, index, values); + this.btnqx(); + this.deviceindex = index; + this.devicehour = values[0] || 0; // 添加默认值 + this.deviceminute = values[1] || 0; + this.devicemiao = values[2] || 0; + + if (this.list.hasOwnProperty(key)) { + const array = this.list[key]; + const lastIndex = array.length - 1; + const lastElement = array[lastIndex]; + array[lastIndex] = !lastElement; + this.deviceflag = lastElement ? 0 : 1; + } + + let cucun = '11num' + this.deviceindex + '@' + this.devicehour + '@' + this.deviceminute + '@' + this.devicemiao + '@' + this.deviceflag + '@'; + this.lastOperation = () => { + xBlufi.notifySendCustomData({ + customData: cucun + }); + }; + this.lastOperation(); + + await this.delay(1000); + xBlufi.notifySendCustomData({ + customData: "11get" + }); + + setTimeout(() => { + this.kgflag = false; + this.hideLoading(); + }, 2000); + } catch (error) { + console.error('btnchange error:', error); + this.retryOperation(); + } }, // 点击设置定时时间 @@ -259,65 +324,96 @@ this.second = '--' }, // 确定选择设置定时时间 - btnqd() { - this.timeflag = false - this.hour = '--' - this.minutekq = '--' - this.minute = '--' - this.second = '--' - let cucun = '11num' + this.deviceindex + '@' + this.devicehour + '@' + this.deviceminute + '@' + this.devicemiao + '@' + this.deviceflag + '@' - xBlufi.notifySendCustomData({ - customData: cucun - }) - setTimeout(() => { + async btnqd() { + try { + this.showLoading(); + this.timeflag = false; + this.hour = '--'; + this.minutekq = '--'; + this.minute = '--'; + this.second = '--'; + + let cucun = '11num' + this.deviceindex + '@' + this.devicehour + '@' + this.deviceminute + '@' + this.devicemiao + '@' + this.deviceflag + '@'; + this.lastOperation = () => { + xBlufi.notifySendCustomData({ + customData: cucun + }); + }; + this.lastOperation(); + + await this.delay(1000); xBlufi.notifySendCustomData({ customData: "11get" - }) - }, 1000) - }, - btnbc(){ - if(this.shi >= 24){ - uni.showToast({ - title: '最大值为23时', - icon: 'none', - duration:2000 - }) - }else if(this.fen >= 60){ - uni.showToast({ - title: '最大值为59分钟', - icon: 'none', - duration:2000 - }) - }else{ - this.timeflag = false - let cucun = '11num0' + '@' + this.shi + '@' + this.fen + '@' + this.miao + '@' + this.tian + '@' - xBlufi.notifySendCustomData({ - customData: cucun - }) - uni.showToast({ - title: '保存成功', - icon: 'success', - duration:2000 - }) + }); + setTimeout(() => { + this.hideLoading(); + }, 2000); + } catch (error) { + console.error('btnqd error:', error); + this.retryOperation(); + } + }, + // 保存抽水泵设置 + async btnbc() { + try { + if(this.shi >= 24){ + uni.showToast({ + title: '最大值为23时', + icon: 'none', + duration:2000 + }); + return; + } else if(this.fen >= 60){ + uni.showToast({ + title: '最大值为59分钟', + icon: 'none', + duration:2000 + }); + return; + } + + this.showLoading(); + this.timeflag = false; + let cucun = '11num0' + '@' + this.shi + '@' + this.fen + '@' + this.miao + '@' + this.tian + '@'; + this.lastOperation = () => { xBlufi.notifySendCustomData({ - customData: "11get" - }) - }, 1000) + customData: cucun + }); + }; + this.lastOperation(); + + await this.delay(1000); + xBlufi.notifySendCustomData({ + customData: "11get" + }); + + uni.showToast({ + title: '保存成功', + icon: 'success', + duration: 2000 + }); + + setTimeout(() => { + this.hideLoading(); + }, 2000); + } catch (error) { + console.error('btnbc error:', error); + this.retryOperation(); } }, // 定时浇水时间 confirm(e) { - this.hour = e.hour - this.minutekq = e.minute - this.devicehour = e.hour - this.deviceminute = e.minute + this.hour = e.hour || '00' + this.minutekq = e.minute || '00' + this.devicehour = e.hour || '00' + this.deviceminute = e.minute || '00' }, // 定时浇水时长 confirms(e) { - this.minute = e.minute - this.second = e.second - this.devicemiao = Number(this.minute) * 60 + Number(this.second) + this.minute = e.minute || '00' + this.second = e.second || '00' + this.devicemiao = (Number(this.minute) * 60 + Number(this.second)) || 0 console.log(this.devicemiao) }, @@ -325,117 +421,71 @@ switch (options.type) { case xBlufi.XBLUFI_TYPE.TYPE_STATUS_CONNECTED: if (!options.result) { - + uni.showToast({ + title: '蓝牙连接异常', + icon: 'none' + }); } break; case xBlufi.XBLUFI_TYPE.TYPE_RECIEVE_CUSTON_DATA: - console.log("1收到设备发来的自定义数据结果:", options.data) - const inputString = options.data.slice(0, -1) + ";" - console.log(inputString, '12121212100') - if (this.pre == 'WATER') { - const pairs = inputString.split(';') - const showObject = {} - const pSetObjects = {} - pairs.forEach(pair => { - const [key, value] = pair.split(':') - if (key === 'show') { - showObject.showArray = value.split(',').map(Number) - } else if (key.startsWith('p_set')) { - const numbers = value.split(',').map(Number) - pSetObjects[key] = numbers - } - }) - this.list = pSetObjects //六个浇水时间段 - - const ver_Data = this.list - - function secondsToMinutesAndSeconds(seconds) { - const minutes = Math.floor(seconds / 60) - const remainingSeconds = seconds % 60 - return `${minutes}分${remainingSeconds}秒` - } - // 获取当前时间 - const now = new Date() - // 辅助函数:将时间数组转换为 Date 对象 - function timeArrayToDate(timeArray) { - const [hour, minute, second] = timeArray.slice(0, 3) - const date = new Date() - date.setHours(hour, minute, second, 0) // 毫秒设为0 - return date - } - // 辅助函数:计算两个时间之间的差值(以小时和分钟表示) - function timeDifference(date1, date2) { - const diffMs = Math.abs(date1 - date2) - const diffSeconds = Math.floor(diffMs / 1000) - const diffMinutes = Math.floor(diffSeconds / 60) - const diffHours = Math.floor(diffMinutes / 60) - const remainingMinutes = diffMinutes % 60 - return { - hours: diffHours, - minutes: remainingMinutes - } - } - // 遍历 ver_Data 对象 - let nextTimeDiff = null - let nextTime = null - let prevTimeDiff = null - let prevTime = null - let nextWaterDuration = null // 用于存储下次浇水时长 - for (const key in ver_Data) { - if (ver_Data.hasOwnProperty(key) && ver_Data[key][3] === 1) { - const timeArray = ver_Data[key] - const timeDate = timeArrayToDate(timeArray) - // 计算与当前时间的差值 - const diff = timeDifference(timeDate, now) - // 判断是下一次时间还是上一次时间 - if (timeDate > now) { - if (!nextTime || diff.hours * 60 + diff.minutes < nextTimeDiff.hours * 60 + - nextTimeDiff.minutes) { - nextTimeDiff = diff - nextTime = timeDate - nextWaterDuration = secondsToMinutesAndSeconds(timeArray[2]) // 获取并转换浇水时长 + try { + console.log("收到设备发来的自定义数据结果:", options.data); + const inputString = options.data.slice(0, -1) + ";"; + + if (this.pre == 'WATER') { + const pairs = inputString.split(';'); + const pSetObjects = {}; + + pairs.forEach(pair => { + if (!pair) return; + const [key, value] = pair.split(':'); + if (key && key.startsWith('p_set') && value) { + try { + const numbers = value.split(',').map(num => { + const parsed = parseInt(num); + return isNaN(parsed) ? 0 : parsed; + }); + pSetObjects[key] = numbers; + } catch (e) { + console.error('数据解析错误:', e); } - } else { - if (!prevTime || (now.getTime() - timeDate.getTime()) < (now.getTime() - - prevTime.getTime())) { - prevTimeDiff = timeDifference(now, timeDate) // 注意这里要反过来算 - prevTime = timeDate + } + }); + + if (Object.keys(pSetObjects).length > 0) { + this.list = pSetObjects; + + for (let key in this.list) { + if (this.list.hasOwnProperty(key)) { + let arr = this.list[key]; + arr[arr.length - 1] = arr[arr.length - 1] === 1; } } } - } - // 输出结果 - this.xctime = `${nextTimeDiff.hours}时${nextTimeDiff.minutes}分` - for (let key in this.list) { - if (this.list.hasOwnProperty(key)) { - // 获取当前数组 - let arr = this.list[key] - // 判断数组的最后一个元素,并进行替换 - if (arr[arr.length - 1] === 0) { - arr[arr.length - 1] = false - } else if (arr[arr.length - 1] === 1) { - arr[arr.length - 1] = true - } + } else { + const input = options.data.slice(0, -1) + ";" + // 去除末尾的分号并分割字符串 + const parts = input.replace(";", "").split(":") + // 获取时间部分并分割 + const timeParts = parts[1].split(",") + // 解析为对象 + this.csbobj = { + hour: parseInt(timeParts[0]), // 小时 + minute: parseInt(timeParts[1]), // 分钟 + second: parseInt(timeParts[2]), // 秒 + day: parseInt(timeParts[3]) // 天数 } + console.log(this.csbobj); + this.shi = this.csbobj.hour + this.fen = this.csbobj.minute + this.miao = this.csbobj.second + this.tian = this.csbobj.day } - } else { - const input = options.data.slice(0, -1) + ";" - // 去除末尾的分号并分割字符串 - const parts = input.replace(";", "").split(":") - // 获取时间部分并分割 - const timeParts = parts[1].split(",") - // 解析为对象 - this.csbobj = { - hour: parseInt(timeParts[0]), // 小时 - minute: parseInt(timeParts[1]), // 分钟 - second: parseInt(timeParts[2]), // 秒 - day: parseInt(timeParts[3]) // 天数 - } - console.log(this.csbobj); - this.shi = this.csbobj.hour - this.fen = this.csbobj.minute - this.miao = this.csbobj.second - this.tian = this.csbobj.day + + this.hideLoading(); + } catch (error) { + console.error('数据处理错误:', error); + this.retryOperation(); } break } diff --git a/page_user/lanya.vue b/page_user/lanya.vue index d501620..2f856f3 100644 --- a/page_user/lanya.vue +++ b/page_user/lanya.vue @@ -26,12 +26,12 @@ MAC:{{item.mac == undefined ? item.name.slice(-12) : item.mac}} - - 添加 - - + 已添加 + + 添加 + @@ -56,6 +56,18 @@ + + + + 设备名称 + + + 取消 + 确定 + + + + @@ -77,7 +89,10 @@ userid: '', arr: '', jiaohuaqi: [], - getpre:[] + getpre: [], + showNameDialog: false, + customDeviceName: '', + currentDevice: null, } }, // 分享到好友(会话) @@ -124,19 +139,34 @@ } } }) - } + } }) }, - // 点击添加添加绑定设备 + + // 点击添加按钮 btnadd(e) { - console.log(e, '0101'); - let mac = e.slice(-12) + this.currentDevice = e; + this.customDeviceName = e.modelName || '未知设备'; // 默认使用型号名称 + this.showNameDialog = true; + }, + // 确认添加设备 + confirmAddDevice() { + if (!this.customDeviceName.trim()) { + uni.showToast({ + title: '请输入设备名称', + icon: 'none' + }); + return; + } + + let mac = this.currentDevice.name.slice(-12); let data = { mac: mac, userId: this.userid, - pre: e.slice(0, 5) + pre: this.currentDevice.pre, + deviceName: this.customDeviceName } - console.log(data); + this.$u.post(`/app/bandDevice`, data).then((res) => { if (res.code == 200) { uni.showToast({ @@ -144,6 +174,7 @@ icon: 'success', duration: 3000 }) + this.showNameDialog = false; setTimeout(() => { uni.navigateBack() }, 2000) @@ -156,75 +187,73 @@ } }) }, - getmodel() { - this.$u.get(`/app/getAllModelList`).then(res => { - if (res.code == 200) { - this.getpre = res.data; - } - }); - }, - - getpipei(pre) { - // 添加默认返回值防止undefined - return this.getpre.find(item => item.pre == pre) || { - modelName: '未知型号', - picture: '' - }; - }, - - btnss() { - uni.showLoading({ - title: '搜索中...', - mask: true - }); - - this.jiaohuaqi = []; - this.flag = false; - const that = this; - - xBlufi.listenDeviceMsgEvent(true, that.funListenDeviceMsgEvent); - xBlufi.notifyStartDiscoverBle({ 'isStart': true }); - - setTimeout(() => { - xBlufi.notifyStartDiscoverBle({ 'isStart': false }); - - if (that.devicesList.length > 0) { - const data = { mac: that.arr }; - - this.$u.post(`/app/getExistListByMacs`, data).then(res => { - if (res.code == 200) { - // 创建MAC地址映射表 - const macMap = new Map(res.data.map(item => [item.mac, item])); - - that.devicesList.forEach(val => { - const mac = val.name.slice(-12); - if (macMap.has(mac)) { - that.jiaohuaqi.push(macMap.get(mac)); - console.log(that.jiaohuaqi,'1111'); - } else { - const pre = val.name.slice(0, 5); - const matched = that.getpipei(pre); - that.jiaohuaqi.push({ - name: mac, - modelName: matched.modelName, - modelPicture: matched.picture - }); - console.log(that.jiaohuaqi,'2222'); - } - }); - - uni.hideLoading(); - } else { - uni.hideLoading(); - } - }); - } else { - uni.hideLoading(); - } - - that.flag = true; - }, 3000); - }, + getmodel() { + this.$u.get(`/app/getAllModelList`).then(res => { + if (res.code == 200) { + this.getpre = res.data + } + }) + }, + + getpipei(pre) { + // 添加默认返回值防止undefined + return this.getpre.find(item => item.pre == pre) || { + modelName: '未知型号', + picture: '' + }; + }, + + btnss() { + uni.showLoading({ + title: '搜索中...', + mask: true + }); + this.jiaohuaqi = []; + this.flag = false; + const that = this; + xBlufi.listenDeviceMsgEvent(true, that.funListenDeviceMsgEvent); + xBlufi.notifyStartDiscoverBle({ 'isStart': true }); + setTimeout(() => { + xBlufi.notifyStartDiscoverBle({ 'isStart': false }); + if (that.devicesList.length > 0) { + const data = { mac: that.arr }; + that.$u.post(`/app/getExistListByMacs`, data) + .then(res => { + if (res.code === 200) { + // 创建MAC地址映射表 + const updatedDevicesList = that.devicesList.map(item => { + const matchedData = res.data.find(val => item.name.slice(-12) === val.mac); + return matchedData ? { ...item, ...matchedData } : item; + }); + updatedDevicesList.forEach(val => { + const mac = val.name.slice(-12); + const pre = val.name.slice(0, 5); + const matched = that.getpipei(pre); + const userid = val.userId || null; + that.jiaohuaqi.push({ + name: mac, + modelName: matched.modelName, + modelPicture: matched.picture, + pre: pre, + userId: userid + }); + console.log(that.jiaohuaqi, '2222'); + }); + } + }) + .catch(error => { + console.error('请求失败:', error); + }) + .finally(() => { + uni.hideLoading(); + that.flag = true; + }); + } else { + uni.hideLoading(); + that.flag = true; + } + }, 3000); + }, // 获取附近蓝牙设备列表 funListenDeviceMsgEvent: function(options) { @@ -281,6 +310,12 @@ \ No newline at end of file diff --git a/pages/index/index.vue b/pages/index/index.vue index 466b486..aa399f9 100644 --- a/pages/index/index.vue +++ b/pages/index/index.vue @@ -370,7 +370,8 @@ imgflag:true, ver:'', pre:'', - csbobj:{} + csbobj:{}, + disconnectTimer: null, } }, // 分享到好友(会话) @@ -423,10 +424,12 @@ onHide() { // 页面隐藏时清除定时器 this.clearTimer() + this.clearDisconnectTimer() }, onUnload() { // 页面卸载时清除定时器 this.clearTimer() + this.clearDisconnectTimer() }, methods: { // 点击进行设备录入 @@ -560,6 +563,7 @@ // 雨水感应开启 btnyushui() { + this.handleUserAction() this.one = false this.ones = true if(this.vardataflag != 3){ @@ -583,6 +587,7 @@ }, // 雨水感应关闭 btnyushuis() { + this.handleUserAction() this.one = false this.ones = true if(this.vardataflag != 3){ @@ -606,6 +611,7 @@ }, // 点击儿童锁开启 btnertong() { + this.handleUserAction() this.two = false this.twos = true if(this.vardataflag != 3){ @@ -629,6 +635,7 @@ }, // 点击儿童锁关闭 btnertongs() { + this.handleUserAction() this.two = false this.twos = true if(this.vardataflag != 3){ @@ -664,6 +671,7 @@ // 点击选择浇水时间 confirm(e) { + this.handleUserAction() this.minute = e.minute this.second = e.second this.jstime = Number(e.second) + Number(e.minute * 60) @@ -671,6 +679,7 @@ // 点击跳转到定时页面 btntime() { + this.handleUserAction() if(this.vardataflag != 3){ uni.showToast({ title: '蓝牙未连接', @@ -687,6 +696,7 @@ // 点击取消手动浇水 btnqx() { + this.handleUserAction() this.sdjsflag = false this.sdminutes = '' this.sdseconds = '' @@ -696,6 +706,7 @@ }, // 确定选择时间 btnqd() { + this.handleUserAction() if (this.minute == '--' || this.second == '--') { uni.showToast({ title: '请选择浇水时长', @@ -743,6 +754,7 @@ // 关闭手动浇水 btnkq() { + this.handleUserAction() console.log('关闭') if(this.vardataflag != 3){ uni.showToast({ @@ -770,6 +782,7 @@ }, // 开启手动浇水 btngb() { + this.handleUserAction() console.log('开启') if(this.vardataflag != 3){ uni.showToast({ @@ -873,6 +886,7 @@ case xBlufi.XBLUFI_TYPE.TYPE_STATUS_CONNECTED: if (!options.result) { this.vardataflag = 1 + this.clearDisconnectTimer() } break; case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS: @@ -885,11 +899,13 @@ if (options.result == true){ this.datalist = '1' this.vardataflag = 3 + this.initDisconnectTimer() xBlufi.notifyInitBleEsp32({ deviceId: this.deviceId }) }else{ this.vardataflag = 1 + this.clearDisconnectTimer() } break case xBlufi.XBLUFI_TYPE.TYPE_RECIEVE_CUSTON_DATA: @@ -1085,6 +1101,60 @@ this.xctimesj = nextTime ? nextTime.toTimeString().slice(0, 5) : '无下次浇水时间'; console.log('下次浇水时间', this.xctimesj, '距离下次浇水时间', this.xctime, '上次浇水时间', this.sctimejs); }, + // 初始化断开蓝牙定时器 + initDisconnectTimer() { + this.clearDisconnectTimer() + this.disconnectTimer = setTimeout(() => { + if(this.vardataflag === 3) { + console.log('一分钟无操作,断开蓝牙连接') + this.disconnectBluetooth() + } + }, 60000) // 60秒 = 1分钟 + }, + + // 重置断开蓝牙定时器 + resetDisconnectTimer() { + this.initDisconnectTimer() + }, + + // 清除断开蓝牙定时器 + clearDisconnectTimer() { + if(this.disconnectTimer) { + clearTimeout(this.disconnectTimer) + this.disconnectTimer = null + } + }, + + // 断开蓝牙连接 + disconnectBluetooth() { + if(this.deviceId) { + wx.closeBLEConnection({ + deviceId: this.deviceId, + success: () => { + console.log('蓝牙连接已断开') + this.vardataflag = 1 + this.datalist = '' + uni.showToast({ + title: '蓝牙已断开连接', + icon: 'none', + duration: 2000 + }) + } + }) + xBlufi.notifyConnectBle({ + isStart: false, + deviceId: this.deviceId, + name: this.name + }) + } + }, + + // 监听用户操作的方法 + handleUserAction() { + if(this.vardataflag === 3) { + this.resetDisconnectTimer() + } + }, } }