优化mqtt协议代码

This commit is contained in:
fengerli
2025-08-16 13:59:17 +08:00
parent 8e1a37dbea
commit fe5545b642
7 changed files with 1443 additions and 1448 deletions

View File

@ -6,7 +6,7 @@ const config = {
API_PREFIX: '', API_PREFIX: '',
// MQTT 配置 // MQTT 配置
MQTT_HOST: '47.120.79.150', MQTT_HOST: '47.120.79.150',
MQTT_PORT: 8083, MQTT_PORT: 9083,
MQTT_USERNAME: 'admin', MQTT_USERNAME: 'admin',
MQTT_PASSWORD: '#YtvpSfCNG' MQTT_PASSWORD: '#YtvpSfCNG'
}, },
@ -16,7 +16,7 @@ const config = {
API_PREFIX: '', API_PREFIX: '',
// MQTT 配置 // MQTT 配置
MQTT_HOST: '47.120.79.150', MQTT_HOST: '47.120.79.150',
MQTT_PORT: 8083, MQTT_PORT: 9083,
MQTT_USERNAME: 'admin', MQTT_USERNAME: 'admin',
MQTT_PASSWORD: '#YtvpSfCNG' MQTT_PASSWORD: '#YtvpSfCNG'
} }

View File

@ -36,7 +36,8 @@
{ {
"path": "pages/common/send/index", "path": "pages/common/send/index",
"style": { "style": {
"navigationBarTitleText": "发送信息" "navigationBarTitleText": "发送信息",
"enablePullDownRefresh": true
} }
}, },
{ {
@ -66,7 +67,8 @@
{ {
"path": "pages/6170/callPolice/index", "path": "pages/6170/callPolice/index",
"style": { "style": {
"navigationBarTitleText": "报警" "navigationBarTitleText": "报警",
"enablePullDownRefresh": true
} }
}, },

View File

@ -3,9 +3,9 @@
<!-- 设备列表 --> <!-- 设备列表 -->
<view class="allSelect" @click="selectAll"> 全选</view> <view class="allSelect" @click="selectAll"> 全选</view>
<scroll-view class="device-list" scroll-y> <scroll-view class="device-list" scroll-y>
<view class="device-card" v-for="(item, index) in deviceList" :key="index" @click="toggleSelect(index)"> <view class="device-card" v-for="(item, index) in deviceList" :key="index" @click="item.onlineStatus === 1 ? toggleSelect(index) : null">
<!-- 复选框 --> <!-- 复选框 -->
<view class="checkbox" :class="{ checked: item.checked }"> <view class="checkbox" :class="{ checked: item.checked,disabled: item.onlineStatus !== 1 }">
<uni-icons v-if="item.checked" type="checkmarkempty" size="18" color="rgb(0, 0, 0)"></uni-icons> <uni-icons v-if="item.checked" type="checkmarkempty" size="18" color="rgb(0, 0, 0)"></uni-icons>
</view> </view>
<!-- 设备信息 --> <!-- 设备信息 -->
@ -81,45 +81,6 @@
} }
}, },
methods: { methods: {
/**
* 获取设备状态(带自动轮询)
* @param {number} val - 功能模式
* @param {string} batchId - 批次ID
* @param {number} [interval=1000] - 轮询间隔(毫秒)
*/
async getdeviceSTatus(val, batchId, interval = 800) {
let retries = 0;
const checkStatus = async () => {
try {
const data = {
functionMode: val, //批量的传2
batchId: batchId,
typeName: this.sendInfo.typeName,
deviceImei: this.sendInfo.deviceImei
};
const res = await deviceRealTimeStatus(data);
if (res.code !== 200) {
throw new Error(res.msg || '请求失败');
}
switch (res.data.functionAccess) {
case 'OK':
return res; // 成功完成
case 'ACTIVE':
await new Promise(r => setTimeout(r, interval));
return checkStatus(); // 继续轮询
case 'FAILED':
throw new Error('设备操作失败');
case 'TIMEOUT':
throw new Error('设备响应超时');
default:
throw new Error('未知状态');
}
} catch (error) {
throw error;
}
};
return checkStatus();
},
onclosePopup() { onclosePopup() {
this.showPopupFlag = false this.showPopupFlag = false
}, },
@ -142,7 +103,7 @@
this.loading = true; this.loading = true;
let data = { let data = {
pageNum: 1, pageNum: 1,
pageSize: 30, pageSize: 50,
deviceType: deviceType deviceType: deviceType
} }
deviceInfo(data).then((res) => { deviceInfo(data).then((res) => {
@ -201,27 +162,14 @@
title: isAlarming ? '设备报警中...' : '解除报警中...', title: isAlarming ? '设备报警中...' : '解除报警中...',
mask: true mask: true
}); });
// 2. 准备请求数据
const batchId = generateShortId();
const data = { const data = {
deviceIds: deviceIds, deviceIds: deviceIds,
batchId: batchId,
typeName: this.sendInfo.typeName, typeName: this.sendInfo.typeName,
deviceImeiList: deviceImeiList, deviceImeiList: deviceImeiList,
instructValue: this.pendingAlarmAction == 1 ? '1' : '0' instructValue: this.pendingAlarmAction == 1 ? '1' : '0'
}; };
// 3.人员信息
const registerRes = await deviceSendAlarmMessage(data); const registerRes = await deviceSendAlarmMessage(data);
if (registerRes.code !== 200) { if (registerRes.code == 200) {
uni.showToast({
title: registerRes.msg,
icon: 'none'
})
return
}
// 4. 获取设备状态
const statusRes = await this.getdeviceSTatus(2, batchId);
if (statusRes.data.functionAccess === 'OK') {
uni.showToast({ uni.showToast({
title: statusRes.msg, title: statusRes.msg,
icon: 'none' icon: 'none'
@ -231,6 +179,11 @@
setTimeout(() => { setTimeout(() => {
uni.navigateBack() uni.navigateBack()
}, 500) }, 500)
} else {
uni.showToast({
title: registerRes.msg,
icon: 'none'
});
} }
} catch (error) { } catch (error) {
uni.showToast({ uni.showToast({
@ -479,4 +432,14 @@
border: 1px solid rgba(255, 255, 255, 0.87); border: 1px solid rgba(255, 255, 255, 0.87);
background: rgba(18, 18, 18, 1); background: rgba(18, 18, 18, 1);
} }
.checkbox.disabled {
opacity: 0.5;
background-color: rgba(255, 255, 255, 0.1) !important;
border-color: rgba(255, 255, 255, 0.2) !important;
pointer-events: none; /* 阻止点击事件 */
}
/* 可选:离线设备的卡片整体置灰 */
.device-card[data-offline="true"] {
opacity: 0.6;
}
</style> </style>

View File

@ -350,16 +350,9 @@ export default {
* @param {number} val - 功能模式 * @param {number} val - 功能模式
* @param {string} batchId - 批次ID * @param {string} batchId - 批次ID
* @param {number} [interval=800] - 轮询间隔(毫秒) * @param {number} [interval=800] - 轮询间隔(毫秒)
* @param {number} [maxRetries=10] - 最大重试次数
*/ */
async getdeviceSTatus(val, batchId, interval = 800) { async getdeviceSTatus(val, batchId, interval = 800) {
//let retries = 0;
const checkStatus = async () => { const checkStatus = async () => {
// if (retries >= maxRetries) {
// throw new Error('超过最大重试次数');
// }
// retries++;
try { try {
const data = { const data = {
functionMode: val, functionMode: val,
@ -477,6 +470,7 @@ export default {
uni.vibrateShort({ uni.vibrateShort({
type: 'light' type: 'light'
}); });
let data = { let data = {
deviceId: this.computedDeviceId, deviceId: this.computedDeviceId,
instructValue: this.sliderValue + '.00', instructValue: this.sliderValue + '.00',
@ -490,6 +484,13 @@ export default {
} }
}, },
onSliderChangeEnd(e) { onSliderChangeEnd(e) {
if (this.deviceInfo.onlineStatus !== 1) {
uni.showToast({
title: '设备已离线',
icon: 'none'
});
return;
}
let value = e.detail.value; let value = e.detail.value;
if (value < 10) { if (value < 10) {
value = 10; value = 10;
@ -569,11 +570,17 @@ export default {
} }
}, },
// 灯光模式的确认 // 灯光模式的确认
async handleSumbit() { handleSumbit() {
if (this.deviceInfo.onlineStatus !== 1) {
uni.showToast({
title: '设备已离线',
icon: 'none'
});
return;
}
// 防重复提交 // 防重复提交
if (this.isProcessing) return; if (this.isProcessing) return;
let loadingShown = false; let loadingShown = false;
try {
uni.showLoading({ uni.showLoading({
title: '处理中...', title: '处理中...',
mask: true mask: true
@ -589,45 +596,43 @@ export default {
deviceImei: this.itemInfo.deviceImei, deviceImei: this.itemInfo.deviceImei,
typeName: this.itemInfo.typeName, typeName: this.itemInfo.typeName,
}; };
// 第一个请求:设置灯光模式 lightModeSettings(data).then((res) => {
const res = await lightModeSettings(data); if (res.code == 200) {
if (res.code !== 200) {
uni.showToast({ uni.showToast({
title: res.msg, title: res.msg,
icon: 'none' icon: 'none'
}) })
return
}
// 第二个请求:获取设备状态
const statusRes = await this.getdeviceSTatus(1);
if (statusRes.data.functionAccess === 'OK') {
uni.showToast({
icon: 'none',
title: statusRes.msg
});
// 关闭弹窗
this.lightModeA = false;
}
} catch (error) {
uni.showToast({
title: error.message,
icon: 'none'
});
} finally {
uni.hideLoading(); uni.hideLoading();
this.lightModeA = false;
this.isProcessing = false this.isProcessing = false
loadingShown = false
} else {
uni.showToast({
title: res.msg,
icon: 'none'
})
this.isProcessing = false
loadingShown = false
uni.hideLoading();
} }
})
}, },
// 激光模式 // 激光模式
lasermode() { lasermode() {
this.lightModeC = true this.lightModeC = true
}, },
// 激光确认框提交 // 激光确认框提交
async handleBtn() { handleBtn() {
if (this.deviceInfo.onlineStatus !== 1) {
uni.showToast({
title: '设备已离线',
icon: 'none'
});
return;
}
// 防重复提交 // 防重复提交
if (this.isProcessing) return; if (this.isProcessing) return;
let loadingShown = false; let loadingShown = false;
try {
uni.showLoading({ uni.showLoading({
title: '处理中...', title: '处理中...',
mask: true mask: true
@ -641,37 +646,27 @@ export default {
deviceImei: this.itemInfo.deviceImei, deviceImei: this.itemInfo.deviceImei,
typeName: this.itemInfo.typeName, typeName: this.itemInfo.typeName,
}; };
// 第一个请求 laserModeSettings(data).then((res) => {
const res = await laserModeSettings(data); if (res.code == 200) {
if (res.code !== 200) {
uni.showToast({
title: res.msg,
icon: 'none'
})
return
}
// 第二个请求
const statusRes = await this.getdeviceSTatus(1);
if (statusRes.data.functionAccess === 'OK') {
uni.showToast({ uni.showToast({
icon: 'none', icon: 'none',
title: statusRes.msg // 添加默认提示 title: res.msg
}); });
// 更新状态 // 更新状态
this.isLaserOn = !this.isLaserOn; this.isLaserOn = !this.isLaserOn;
this.currentlaserMode = this.isLaserOn ? "开启" : "关闭"; this.currentlaserMode = this.isLaserOn ? "开启" : "关闭";
this.lightModeC = false; this.lightModeC = false;
} this.isProcessing = false
loadingShown = false
} catch (error) { } else {
uni.showToast({ uni.showToast({
title: error.message, title: res.msg,
icon: 'none' icon: 'none'
}); });
} finally { this.isProcessing = false
uni.hideLoading(); loadingShown = false
this.isProcessing = false;
} }
})
}, },
//激光取消 //激光取消
handleDisagree() { handleDisagree() {
@ -721,18 +716,25 @@ export default {
}); });
return; return;
} }
if (this.deviceInfo.onlineStatus !== 1) {
uni.showToast({
title: '设备已离线',
icon: 'none'
});
return;
}
// 显示上传加载状态 // 显示上传加载状态
uni.showLoading({ uni.showLoading({
title: '图片上传中...', title: '图片上传中...',
mask: true mask: true
}); });
loadingShown = true loadingShown = true;
uni.uploadFile({ uni.uploadFile({
url: baseURL + '/app/bjq/device/uploadLogo', url: baseURL + '/app/bjq/device/uploadLogo',
filePath: this.selectedImage, filePath: this.selectedImage,
name: 'file', name: 'file',
formData: { formData: {
deviceId: this.computedDeviceId, deviceId: this.apiType === 'listA' ? this.deviceID : this.itemInfo.deviceId,
deviceImei: this.itemInfo.deviceImei, deviceImei: this.itemInfo.deviceImei,
typeName: this.itemInfo.typeName, typeName: this.itemInfo.typeName,
}, },
@ -740,43 +742,47 @@ export default {
'Authorization': 'Bearer ' + getToken(), 'Authorization': 'Bearer ' + getToken(),
'clientid': clientid(), 'clientid': clientid(),
}, },
complete: (res) => { // 使用 complete 确保 hideLoading 总能被调用 complete: async (res) => {
try { try {
uni.hideLoading(); // 首先关闭“
const responseData = JSON.parse(res.data); const responseData = JSON.parse(res.data);
if (responseData.code === 200) { if (responseData.code === 200) {
// 异步操作链 uni.showLoading({
this.getdeviceSTatus(1) title: '等待设备响应...',
.then(statusRes => { mask: true
});
try {
// 获取设备状态
const statusRes = await this.getdeviceSTatus(1);
if (statusRes.data.functionAccess === 'OK') { if (statusRes.data.functionAccess === 'OK') {
uni.hideLoading();
this.selectedImage = ''; this.selectedImage = '';
this.file = null;
this.popupType = 'logo'; this.popupType = 'logo';
this.showPopupFlag = true; this.showPopupFlag = true;
this.popupMessage = '上传成功'; this.popupMessage = '上传成功';
this.lightModeB = false; this.lightModeB = false;
} }
}) } catch (error) {
.catch(error => { uni.hideLoading();
uni.showToast({ uni.showToast({
title: error.message, title: error.message,
icon: 'none' icon: 'none'
}); });
}) }
.finally(() => {
uni.hideLoading(); // 在所有异步操作完成后关闭loading
});
} else { } else {
uni.hideLoading();
uni.showToast({ uni.showToast({
title: responseData.msg || '上传失败', title: responseData.msg,
icon: 'none' icon: 'none'
}); });
uni.hideLoading();
} }
} catch (e) { } catch (e) {
uni.hideLoading();
uni.showToast({ uni.showToast({
title: '解析响应失败', title: e.message,
icon: 'none' icon: 'none'
}); });
uni.hideLoading();
} }
} }
}); });
@ -795,8 +801,6 @@ export default {
} }
}) })
}, },
// 发送人员信息 // 发送人员信息
async sendPersonnelInfo() { async sendPersonnelInfo() {
if (this.isSending) return; if (this.isSending) return;
@ -830,6 +834,13 @@ export default {
return; return;
} }
} }
if (this.deviceInfo.onlineStatus !== 1) {
uni.showToast({
title: '设备已离线',
icon: 'none'
});
return;
}
this.isSending = true; this.isSending = true;
let loadingShown = false; let loadingShown = false;
try { try {
@ -847,26 +858,20 @@ export default {
deviceId: this.computedDeviceId, deviceId: this.computedDeviceId,
deviceImei: this.itemInfo.deviceImei deviceImei: this.itemInfo.deviceImei
}; };
// 3. 注册人员信息
const registerRes = await registerPersonInfo(data); const registerRes = await registerPersonInfo(data);
if (registerRes.code !== 200) { if (registerRes.code == 200) {
this.popupType = 'person';
this.showPopupFlag = true;
this.popupMessage = '人员信息发送成功';
} else {
uni.showToast({ uni.showToast({
title: registerRes.msg, title: registerRes.msg,
icon: 'none' icon: 'none'
}); });
return;
}
// 4. 获取设备状态
const statusRes = await this.getdeviceSTatus(1);
// 只有当状态为'OK'时才显示成功弹窗
if (statusRes.data.functionAccess === 'OK') {
this.popupType = 'person';
this.showPopupFlag = true;
this.popupMessage = '人员信息发送成功';
} }
} catch (error) { } catch (error) {
uni.showToast({ uni.showToast({
title: error.message, title: error.msg,
icon: 'none' icon: 'none'
}); });
} finally { } finally {
@ -886,6 +891,13 @@ export default {
}, },
// 解除报警逻辑 // 解除报警逻辑
async onPopupConfirmPolice() { async onPopupConfirmPolice() {
if (this.deviceInfo.onlineStatus !== 1) {
uni.showToast({
title: '设备已离线',
icon: 'none'
});
return;
}
try { try {
uni.showLoading({ uni.showLoading({
title: '解除告警中...', title: '解除告警中...',
@ -900,18 +912,9 @@ export default {
deviceImeiList: [this.itemInfo.deviceImei], deviceImeiList: [this.itemInfo.deviceImei],
instructValue: 0, // '解除报警' instructValue: 0, // '解除报警'
}; };
// 3.人员信息 // 3.解除告警状态
const registerRes = await deviceSendAlarmMessage(data); const registerRes = await deviceSendAlarmMessage(data);
if (registerRes.code !== 200) { if (registerRes.code == 200) {
uni.showToast({
title: registerRes.msg,
icon: 'none'
})
return
}
// 4. 获取设备状态 批量的报警解除报警发送信息都传2单次的都传1
const statusRes = await this.getdeviceSTatus(2, batchId);
if (statusRes.data.functionAccess === 'OK') {
uni.showToast({ uni.showToast({
title: statusRes.msg, title: statusRes.msg,
icon: 'none' icon: 'none'
@ -920,6 +923,11 @@ export default {
this.fetchDeviceDetail(this.computedDeviceId, true); this.fetchDeviceDetail(this.computedDeviceId, true);
uni.$emit('deviceStatusUpdate', {}); uni.$emit('deviceStatusUpdate', {});
this.showPopupFlag = false this.showPopupFlag = false
} else {
uni.showToast({
title: registerRes.message,
icon: 'none'
});
} }
} catch (error) { } catch (error) {
uni.showToast({ uni.showToast({
@ -932,6 +940,13 @@ export default {
}, },
// 发送文本消息 // 发送文本消息
async sendTextMessage() { async sendTextMessage() {
if (this.deviceInfo.onlineStatus !== 1) {
uni.showToast({
title: '设备已离线',
icon: 'none'
});
return;
}
// 防重复提交 // 防重复提交
if (this.isSending) return; if (this.isSending) return;
if (!this.messageToSend) { if (!this.messageToSend) {
@ -981,6 +996,7 @@ export default {
icon: 'none' icon: 'none'
}); });
} finally { } finally {
console.log('失败还是成功了');
uni.hideLoading(); uni.hideLoading();
this.isSending = false; this.isSending = false;
} }
@ -1002,25 +1018,9 @@ export default {
this.messageToSend = res.data.sendMsg || ''; this.messageToSend = res.data.sendMsg || '';
this.sliderValue = res.data.lightBrightness || '25' this.sliderValue = res.data.lightBrightness || '25'
let mainLightMode = parseInt(res.data.mainLightMode); let mainLightMode = parseInt(res.data.mainLightMode);
switch (mainLightMode) { // 取主灯光模式初始值
case 0: this.currentMainMode = this.getMainLightModeLabel(mainLightMode)
this.currentMainMode = '关闭'; console.log(this.currentMainMode, 'this.currentMainMode');
break;
case 1:
this.currentMainMode = '强光';
break;
case 2:
this.currentMainMode = '弱光';
break;
case 3:
this.currentMainMode = '爆闪';
break;
case 4:
this.currentMainMode = '泛光';
break;
default:
console.log('未知的灯光模式:', mainLightMode);
}
const laserMode = res.data.LaserLightMode; const laserMode = res.data.LaserLightMode;
this.isLaserOn = laserMode === 1; this.isLaserOn = laserMode === 1;
this.currentlaserMode = this.isLaserOn ? "开启" : "关闭"; this.currentlaserMode = this.isLaserOn ? "开启" : "关闭";
@ -1050,22 +1050,40 @@ export default {
async fetchDeviceDetail(id, isUpdate = false) { async fetchDeviceDetail(id, isUpdate = false) {
try { try {
const res = await deviceDetail(id) const res = await deviceDetail(id)
if(res.code==200){
this.handleDeviceData(res, false, isUpdate) this.handleDeviceData(res, false, isUpdate)
} catch (error) { }else{
uni.showToast({ uni.showToast({
title: '获取详情失败', title: error.msg,
icon: 'none' icon: 'none'
}) })
uni.hideLoading()
}
} catch (error) {
uni.hideLoading()
// uni.showToast({
// title: error.msg,
// icon: 'none'
// })
} }
}, },
// 获取分享设备详情 // 获取分享设备详情
async fetchSharedDeviceDetail(id) { async fetchSharedDeviceDetail(id) {
try { try {
const res = await deviceShareId(id) const res = await deviceShareId(id)
if(res.code==200){
this.handleDeviceData(res, true) this.handleDeviceData(res, true)
}else{
uni.showToast({
title: error.msg,
icon: 'none'
})
}
} catch (error) { } catch (error) {
uni.showToast({ uni.showToast({
title: '获取分享详情失败', title: error.msg,
icon: 'none' icon: 'none'
}) })
} }
@ -1103,6 +1121,17 @@ export default {
console.log('MQTT not connected, cannot query status.'); console.log('MQTT not connected, cannot query status.');
} }
}, },
// 灯光模式共用封装共其他地方使用
getMainLightModeLabel(mode) {
const modeMap = {
0: '关闭',
1: '强光',
2: '弱光',
3: '爆闪',
4: '泛光'
}
return modeMap[mode] || (console.log('未知的灯光模式:', mode), '未知');
}
}, },
onLoad(options) { onLoad(options) {
@ -1127,68 +1156,56 @@ export default {
this.mqttClient.subscribe(statusTopic, (payload) => { this.mqttClient.subscribe(statusTopic, (payload) => {
try { try {
console.log(`收到来自 ${statusTopic} 的消息:`, payload); console.log(`收到来自 ${statusTopic} 的消息:`, payload);
//收到电量上报。
const parsedMessage = typeof payload === 'string' ? JSON.parse( const parsedMessage = typeof payload === 'string' ? JSON.parse(
payload) : payload) :
payload; payload;
const deviceState = parsedMessage.state; // 直接取 state 数组 const deviceState = parsedMessage.state; // 直接取 state 数组
if (deviceState && deviceState[0] === 12) { // 切换主灯光模式,亮度值设备同步
// 根据协议直接更新设备状态,提供即时反馈 if (!deviceState) return;
const mainLightMode = deviceState[1]; // 1设备切换灯光实时返回
switch (mainLightMode) { switch (deviceState[0]) {
case 0:
this.currentMainMode = '关闭';
break;
case 1: case 1:
this.currentMainMode = '强光'; this.currentMainMode = this.getMainLightModeLabel(deviceState[
1]);
this.sliderValue = deviceState[2];
this.deviceInfo.batteryRemainingTime = deviceState[3];
break; break;
case 2: // 12为设备实时上报
this.currentMainMode = '弱光'; case 12:
break; this.currentMainMode = this.getMainLightModeLabel(deviceState[
case 3: 1]);
this.currentMainMode = '爆闪'; this.isLaserOn = deviceState[2] === 1;
break;
case 4:
this.currentMainMode = '泛光';
break;
default:
console.log('未知的灯光模式:', mainLightMode);
}
const laserMode = deviceState[2];
this.isLaserOn = laserMode === 1;
this.currentlaserMode = this.isLaserOn ? "开启" : "关闭"; this.currentlaserMode = this.isLaserOn ? "开启" : "关闭";
if (this.deviceInfo) { if (this.deviceInfo) {
this.deviceInfo.batteryPercentage = deviceState[3]; this.deviceInfo.batteryPercentage = deviceState[3];
this.deviceInfo.chargeState = deviceState[4]; this.deviceInfo.chargeState = deviceState[4];
this.deviceInfo.batteryRemainingTime = deviceState[5]; this.deviceInfo.batteryRemainingTime = deviceState[5];
} }
// 这里的10秒延迟是为了解决一个特定的后端问题
// GPS坐标上报后逆地址解析将坐标转换为地址需要一些时间。
// 如果立即请求设备详情,地址字段可能尚未更新。
// 这是一个临时解决方案,理想情况下应由后端通过消息通知或其他机制来确保数据一致性。
setTimeout(() => { setTimeout(() => {
this.fetchDeviceDetail(data.data.id, true).then(() => { this.fetchDeviceDetail(data.data.id, true).then(
// 在获取到最新信息后,再判断电量 () => {
if (this.deviceInfo.batteryPercentage < 20) { if (this.deviceInfo.batteryPercentage <
20) {
this.popupType = 'bettery'; this.popupType = 'bettery';
this.popupMessage = '请及时充电'; this.popupMessage = '请及时充电';
this.showPopupFlag = true; this.showPopupFlag = true;
} }
}); });
}, 10000); }, 10000);
// 上报电量,在列表里面同步
// ✅ 发送全局事件通知主页面更新
uni.$emit('deviceStatusUpdate', { uni.$emit('deviceStatusUpdate', {
message: parsedMessage, // 消息内容 message: parsedMessage,
timestamp: new Date().getTime() // 时间戳 timestamp: new Date().getTime()
}); });
break;
default:
console.log('未知的 deviceState 类型:', deviceState[0]);
} }
} catch (error) { } catch (error) {
console.log('解析MQTT消息失败:', error, '原始消息:', payload); console.log('解析MQTT消息失败:', error, '原始消息:', payload);
} }
}); });
// 连接成功后,立即查询一次设备状态 // mqtt连接成功后,上报一次设备状态
this.queryDeviceStatus(); this.queryDeviceStatus();
}) })
if (this.apiType === 'listA') { if (this.apiType === 'listA') {
@ -1199,7 +1216,6 @@ export default {
} }
}); });
// 如果需要向调用页面返回数据,可以触发 'ack' 事件
eventChannel.emit('ack', { eventChannel.emit('ack', {
}) })

View File

@ -2,9 +2,9 @@
<view class="container"> <view class="container">
<!-- 设备列表 --> <!-- 设备列表 -->
<scroll-view class="device-list" scroll-y> <scroll-view class="device-list" scroll-y>
<view class="device-card" v-for="(item, index) in deviceList" :key="index" @click="toggleSelect(index)"> <view class="device-card" v-for="(item, index) in deviceList" :key="index" @click="item.onlineStatus === 1 ? toggleSelect(index) : null">
<!-- 复选框 --> <!-- 复选框 -->
<view class="checkbox" :class="{ checked: item.checked }"> <view class="checkbox" :class="{ checked: item.checked,disabled: item.onlineStatus !== 1 }">
<uni-icons v-if="item.checked" type="checkmarkempty" size="18" color="rgb(0, 0, 0)"></uni-icons> <uni-icons v-if="item.checked" type="checkmarkempty" size="18" color="rgb(0, 0, 0)"></uni-icons>
</view> </view>
<!-- 设备信息 --> <!-- 设备信息 -->
@ -71,6 +71,10 @@
} }
}, },
methods: { methods: {
onPullDownRefresh() {
// 执行下拉刷新时的操作,比如重新获取数据
this.getData();
},
/** /**
* 获取设备状态(带自动轮询) * 获取设备状态(带自动轮询)
* @param {number} val - 功能模式 * @param {number} val - 功能模式
@ -419,4 +423,14 @@
border-radius: 50rpx; border-radius: 50rpx;
width: 90%; width: 90%;
} }
.checkbox.disabled {
opacity: 0.5;
background-color: rgba(255, 255, 255, 0.1) !important;
border-color: rgba(255, 255, 255, 0.2) !important;
pointer-events: none; /* 阻止点击事件 */
}
/* 可选:离线设备的卡片整体置灰 */
.device-card[data-offline="true"] {
opacity: 0.6;
}
</style> </style>

View File

@ -6,7 +6,7 @@
<image src="/static/images/common/logo.png" class="logo"></image> <image src="/static/images/common/logo.png" class="logo"></image>
</view> </view>
<view class="user-right"> <view class="user-right">
<view class="user-title">富源晟科技</view> <view class="user-title">武汉研创</view>
<view class="ID">ID:123456</view> <view class="ID">ID:123456</view>
</view> </view>
</view> </view>

View File

@ -1,5 +1,5 @@
import config from '../config/index.js'; import config from '../config/index.js';
const env = 'development'; //production development //开发of线上 改这里就行 const env = 'production'; //production development //开发of线上 改这里就行
const BASE = config[env]; const BASE = config[env];
const request = (options) => { const request = (options) => {
console.log("options"+JSON.stringify(options),BASE.BASE_URL) console.log("options"+JSON.stringify(options),BASE.BASE_URL)
@ -20,7 +20,7 @@ const request = (options) => {
method: options.method || 'GET', method: options.method || 'GET',
data: options.method !== 'GET' ? options.data : {}, data: options.method !== 'GET' ? options.data : {},
header: options.header || {}, header: options.header || {},
timeout: 10000, timeout: 30000,
success: (res) => { success: (res) => {
resolve(res.data); resolve(res.data);
}, },