1
0
forked from dyf/APP

优化设备控制,提交后,实时获取设备返回状态信息

This commit is contained in:
fengerli
2025-08-14 13:46:57 +08:00
parent d8edb9f31e
commit e56bbfe674
15 changed files with 1104 additions and 383 deletions

View File

@ -19,19 +19,19 @@
<image src="/static/images/common/dl.png" class="dlIMG"></image>
<view>
<view class="battery-v2"
:style="{color: deviceInfo.batteryPercentage < 20 ? '#FF0000' : ''}">
{{deviceInfo.batteryPercentage}}%
:style="{ color: deviceInfo.batteryPercentage < 20 ? '#FF0000' : '' }">
{{ deviceInfo.batteryPercentage }}%
</view>
<view class="battery-v3">电量</view>
</view>
<view v-if="deviceInfo.chargeState==1">
<view v-if="deviceInfo.chargeState == 1">
<image src="/static/images/common/chargeState.png" class="chargeStateIMG"></image>
</view>
</view>
<view class="battery-v1">
<image src="/static/images/common/nz.png" class="dlIMG" mode="aspectFit"></image>
<view>
<view class="battery-v2">{{deviceInfo.batteryRemainingTime || '0'}}分钟</view>
<view class="battery-v2">{{ deviceInfo.batteryRemainingTime || '0' }}分钟</view>
<view class="battery-v3">续航时间</view>
</view>
</view>
@ -44,11 +44,11 @@
<view class="info-card">
<view class="info-row">
<text class="info-label">IMEI号</text>
<text class="info-value status-running">{{deviceInfo.deviceImei}}</text>
<text class="info-value status-running">{{ deviceInfo.deviceImei }}</text>
</view>
<view class="info-row">
<text class="info-label">设备状态</text>
<text class="info-value status-running">{{deviceInfo.onlineStatus===0?'离线':'在线'}}</text>
<text class="info-value status-running">{{ deviceInfo.onlineStatus === 0 ? '离线' : '在线' }}</text>
</view>
<view class="info-row">
<text class="info-label" style="display: flex; align-items: center;">定位信息</text>
@ -60,14 +60,14 @@
<view class="info-value status-running locationGPS">
<uni-icons @click="toggleForm" type="location" size="17"
color="rgba(255, 255, 255, 0.8)" style="vertical-align: bottom;" />
{{deviceInfo.address}}
{{ deviceInfo.address }}
</view>
</view>
</view>
</view>
<view class="callpolice" v-if="deviceInfo.onlineStatus==0">
<view class="callpolice" v-if="deviceInfo.onlineStatus == 0 && deviceInfo.alarmStatus == 1">
<view class="">设备强制报警中</view>
<view>
<uni-icons type="closeempty" size="15" color="rgba(255, 255, 255, 0.9)"
@ -107,7 +107,7 @@
<image src="/static/images/6170/jg.png" class="setIMG" mode="aspectFit"></image>
<view>
<view class="battery-v2">激光模式</view>
<view class="mode-v3">{{currentlaserMode}}</view>
<view class="mode-v3">{{ currentlaserMode }}</view>
</view>
</view>
</view>
@ -133,7 +133,7 @@
</view>
</view>
<view class="form-content" v-if="isFormExpanded">
<button class="send-btn1" @click="sendPersonnelInfo">发送</button>
<button class="send-btn1" @click.stop="sendPersonnelInfo">发送</button>
<view class="form-row">
<text class="form-label">单位</text>
<input class="form-input" placeholder="请输入单位" v-model="personnelInfo.unitName"
@ -160,7 +160,7 @@
<view class="form-section" v-if="hasPermission('5')">
<view class="mode-buttons">
<view class="section-title">发送信息</view>
<button class="send-btn" @click="sendTextMessage">发送</button>
<button class="send-btn" @click.stop="sendTextMessage">发送</button>
</view>
<view class="form-row">
@ -195,9 +195,9 @@
<view class="popup-title"> {{ popupTitle }}</view>
<view class="popup-content">
<view v-for="(item, index) in items" :key="index">
<view class="item" :class="{'selected': item.selected}" @click="onItemClick(index)">
<view class="item" :class="{ 'selected': item.selected }" @click="onItemClick(index)">
<image :src="item.image" class="setIMG"></image>
{{item.text}}
{{ item.text }}
</view>
</view>
</view>
@ -270,27 +270,14 @@
icon="/static/images/6170/svg.png" :confirm-text="popupConfirmText" :show-cancel="false"
@confirm="onPopupConfirmPolice" confirmBtnBg="rgba(224, 52, 52, 1)" confirmBtnColor="#fff" />
</view>
<!-- ===============进度条============== -->
<view
v-if="Progress.show"
@click="closeProgress"
:style="{
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: Progress.maskBgColor,
zIndex: 999
}"
>
<Progress :config="Progress" @click.stop />
</view>
</view>
</template>
<script>
import MqttClient from '@/utils/mqtt.js';
import {
generateShortId
} from '@/utils/function.js';
import {
deviceDetail,
registerPersonInfo,
@ -299,6 +286,7 @@
lightModeSettings, //灯光模式设置
laserModeSettings, //激光模式设置
lightBrightnessSettings, //灯光亮度设置
deviceRealTimeStatus //设备状态
} from '@/api/6170/deviceControl.js'
import {
baseURL,
@ -352,23 +340,9 @@
selectedItemIndex: 0,
popupType: 'person', //弹框类型
isLaserOn: false,
// 进度条
Progress: {
show: false, //是否显示
height: '40rpx',
showMask: true, //是否显示mask
maskBgColor: 'rgba(0, 0, 0, 0.5)', // 半透明黑色遮罩
contentBgColor: 'rgba(18, 18, 18, 0.8)', // 主背景带透明度
showText: true, //是否显示当前进度的文字
txtColor: '#ffffffde', //文字的颜色
curr: 20, //当前进度
total: 100, //总进度
proBgColor: '#2a2a2a', //进度条底色,
proBorder: '', //进度条border
currBgColor: '#bbe600', //当前进度底色
currBorder: '', //当前进度border
borderRadius: '10rpx'
}
isSending: false,
isGettingStatus: false,
isProcessing: false
}
},
computed: {
@ -377,6 +351,50 @@
}
},
methods: {
/**
* 获取设备状态(带自动轮询)
* @param {number} val - 功能模式
* @param {string} batchId - 批次ID
* @param {number} [maxRetries=30] - 最大重试次数约30秒
* @param {number} [interval=1000] - 轮询间隔(毫秒)
*/
async getdeviceSTatus(val, batchId, maxRetries = 30, interval = 2000) {
let retries = 0;
const checkStatus = async () => {
try {
const data = {
functionMode: val,
batchId: batchId,
typeName: this.itemInfo.typeName,
deviceImei: this.itemInfo.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':
if (++retries >= maxRetries) {
throw new Error('操作超时');
}
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();
},
filterChinese(e) {
const value = e.detail.value;
// 允许中文和常见中文标点
@ -391,10 +409,9 @@
this.lightModeA = false;
this.lightModeB = false;
this.lightModeC = false;
this.selectedImage = '';
this.file = null;
},
closeProgress() {
this.Progress.show = false; // 直接关闭进度条
},
// *******定位******
gpsPosition(item) {
// 添加调试日志
@ -471,21 +488,18 @@
value = 10;
}
this.sliderValue = value; // 实时更新UI
const now = Date.now();
// 使用节流防止指令发送过于频繁
if (now - this.lastBrightnessTime > 200) { // 200毫秒节流
this.lastBrightnessTime = now;
// 增加轻微的震动反馈,提升手感
uni.vibrateShort({
type: 'light'
});
let data = {
deviceId: this.deviceID,
instructValue: this.sliderValue + '.00',
deviceImei:this.itemInfo.deviceImei
deviceImei: this.itemInfo.deviceImei,
}
lightBrightnessSettings(data).then((res) => {
if (res.code !== 200) {
@ -500,11 +514,10 @@
value = 10;
}
this.sliderValue = value;
let data = {
deviceId: this.apiType === 'listA' ? this.deviceID : this.itemInfo.deviceId,
instructValue: this.sliderValue + '.00',
deviceImei:this.itemInfo.deviceImei
deviceImei: this.itemInfo.deviceImei,
}
lightBrightnessSettings(data).then((res) => {
if (res.code == 200) {
@ -512,7 +525,7 @@
} else {
uni.showToast({
icon: 'none',
title: res.msg || '亮度调节失败'
title: res.msg
})
}
})
@ -575,61 +588,109 @@
}
},
// 灯光模式的确认
handleSumbit() {
if (this.selectedItemIndex === null) return;
const selectedItem = this.items[this.selectedItemIndex];
console.log(selectedItem, 'selectedItemselectedItem');
// 修正这里的赋值错误,应该保存索引而不是文本
this.selectedItemIndex = this.selectedItemIndex;
let data = {
deviceId: this.apiType === 'listA' ? this.deviceID : this.itemInfo.deviceId,
instructValue: selectedItem.instructValue,
deviceImei:this.itemInfo.deviceImei
}
lightModeSettings(data).then((res) => {
if (res.code == 200) {
async handleSumbit() {
// 防重复提交
if (this.isProcessing) return;
let loadingShown = false;
try {
uni.showLoading({
title: '处理中...',
mask: true
});
loadingShown = true;
this.isProcessing = true
if (this.selectedItemIndex === null) return;
const selectedItem = this.items[this.selectedItemIndex];
// 准备请求数据
let data = {
deviceId: this.apiType === 'listA' ? this.deviceID : this.itemInfo.deviceId,
instructValue: selectedItem.instructValue,
deviceImei: this.itemInfo.deviceImei,
typeName: this.itemInfo.typeName,
};
// 第一个请求:设置灯光模式
const res = await lightModeSettings(data);
if (res.code !== 200) {
uni.showToast({
icon: 'none',
title: res.msg
})
this.lightModeA = false;
} else {
uni.showToast({
icon: 'none',
title: res.msg
title: res.msg,
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();
this.isProcessing = false
}
},
// 激光模式
lasermode() {
this.lightModeC = true
},
// 激光确认框提交
handleBtn() {
const instructValue = this.isLaserOn ? 0 : 1;
let data = {
deviceId: this.apiType === 'listA' ? this.deviceID : this.itemInfo.deviceId,
instructValue: instructValue,
deviceImei:this.itemInfo.deviceImei
}
laserModeSettings(data).then((res) => {
if (res.code == 200) {
async handleBtn() {
// 防重复提交
if (this.isProcessing) return;
let loadingShown = false;
try {
uni.showLoading({
title: '处理中...',
mask: true
});
loadingShown = true;
this.isProcessing = true
const instructValue = this.isLaserOn ? 0 : 1;
let data = {
deviceId: this.apiType === 'listA' ? this.deviceID : this.itemInfo.deviceId,
instructValue: instructValue,
deviceImei: this.itemInfo.deviceImei,
typeName: this.itemInfo.typeName,
};
// 第一个请求
const res = await laserModeSettings(data);
if (res.code !== 200) {
uni.showToast({
icon: 'none',
title: res.msg
})
this.isLaserOn = !this.isLaserOn;
this.currentlaserMode = this.isLaserOn ? "开启" : "关闭"; // 更新显示文本
this.lightModeC = false
} else {
uni.showToast({
icon: 'none',
title: res.msg
title: res.msg,
icon: 'none'
})
return
}
// 第二个请求
const statusRes = await this.getdeviceSTatus(1);
if (statusRes.data.functionAccess === 'OK') {
uni.showToast({
icon: 'none',
title: statusRes.msg // 添加默认提示
});
// 更新状态
this.isLaserOn = !this.isLaserOn;
this.currentlaserMode = this.isLaserOn ? "开启" : "关闭";
this.lightModeC = false;
}
})
} catch (error) {
uni.showToast({
title: error.message,
icon: 'none'
});
} finally {
uni.hideLoading();
this.isProcessing = false;
}
},
//激光取消
handleDisagree() {
@ -660,10 +721,8 @@
}
this.selectedImage = res.tempFilePaths[0];
console.log('选择的图片:', res);
//this.file = res.tempFiles[0].file
},
fail: (err) => {
console.error('选择图片失败:', err);
uni.showToast({
title: '选择图片失败',
icon: 'none'
@ -673,6 +732,7 @@
},
// 上传开机画面确认按键
handleupload() {
let loadingShown = false;
if (!this.selectedImage) {
uni.showToast({
title: '请上传一张图片',
@ -680,34 +740,48 @@
});
return;
}
// 显示进度条
this.Progress = {
...this.Progress,
show: true,
curr: 0,
showText: true
};
// 显示上传加载状态
uni.showLoading({
title: '图片上传中...',
mask: true
});
loadingShown = true
uni.uploadFile({
url: baseURL + '/app/bjq/device/uploadLogo',
filePath: this.selectedImage,
name: 'file',
formData: {
deviceId: this.apiType === 'listA' ? this.deviceID : this.itemInfo.deviceId,
deviceImei:this.itemInfo.deviceImei
deviceImei: this.itemInfo.deviceImei,
typeName: this.itemInfo.typeName,
},
header: {
'Authorization': 'Bearer ' + getToken(),
'clientid': clientid(),
},
complete: (res) => {
console.log(res, 'resss');
complete: async (res) => {
try {
const responseData = JSON.parse(res.data);
if (responseData.code === 200) {
this.selectedImage = '';
this.file = null;
this.lightModeB = false
try {
// 获取设备状态
const statusRes = await this.getdeviceSTatus(1);
if (statusRes.data.functionAccess === 'OK') {
// 两个操作都成功,重置状态并显示成功提示
this.selectedImage = '';
this.file = null;
this.lightModeB = false;
uni.showToast({
title: responseData.msg,
icon: 'success',
});
}
} catch (error) {
uni.showToast({
title: error.message,
icon: 'none'
});
}
} else {
uni.showToast({
title: responseData.msg,
@ -716,10 +790,10 @@
}
} catch (e) {
uni.showToast({
title: '上传失败',
title: error.message,
icon: 'none'
});
this.Progress.show = false; // 上传失败隐藏进度条
} finally {
uni.hideLoading();
}
@ -741,87 +815,86 @@
})
},
// 操作说明
operatingInst() {
let id = this.apiType === 'listA' ? this.deviceID : this.itemInfo.deviceId
uni.navigateTo({
url: `/pages/common/operatingInstruct/index?id=${id}`
})
},
// 产品参数
productparams() {
let id = this.apiType === 'listA' ? this.deviceID : this.itemInfo.deviceId
uni.navigateTo({
url: `/pages/common/productDes/index?id=${id}`
})
},
// 操作视频
operatingVideo() {
let id = this.apiType === 'listA' ? this.deviceID : this.itemInfo.deviceId
uni.navigateTo({
url: `/pages/common/operationVideo/index?id=${id}`
})
},
// 发送人员信息
sendPersonnelInfo() {
if (!this.personnelInfo.unitName) {
uni.showToast({
title: '单位名称不能为空',
icon: 'none'
});
return;
}
if (!this.personnelInfo.name) {
uni.showToast({
title: '姓名不能为空',
icon: 'none'
});
return;
}
if (!this.personnelInfo.position) {
uni.showToast({
title: '职位不能为空',
icon: 'none'
});
return;
}
if (!this.personnelInfo.code) {
uni.showToast({
title: 'ID不能为空',
icon: 'none'
});
return;
}
uni.showLoading({
title: '发送中...',
mask: true
})
let data = {
code: this.personnelInfo.code,
name: this.personnelInfo.name,
position: this.personnelInfo.position,
unitName: this.personnelInfo.unitName,
deviceId: this.apiType === 'listA' ? this.deviceID : this.itemInfo.deviceId,
}
registerPersonInfo(data).then((res) => {
if (res.code == 200) {
uni.hideLoading()
this.popupType = 'person';
this.showPopupFlag = true
this.popupMessage = '人员信息发送成功'
} else {
async sendPersonnelInfo() {
if (this.isSending) return;
const requiredFields = [{
field: 'unitName',
message: '单位名称不能为空'
},
{
field: 'name',
message: '姓名不能为空'
},
{
field: 'position',
message: '职位不能为空'
},
{
field: 'code',
message: 'ID不能为空'
}
];
for (const {
field,
message
}
of requiredFields) {
if (!this.personnelInfo[field]) {
uni.showToast({
title: res.msg,
title: message,
icon: 'none'
});
return;
}
})
}
this.isSending = true;
let loadingShown = false;
try {
uni.showLoading({
title: '发送中...',
mask: true
});
loadingShown = true;
// 2. 准备请求数据
const data = {
code: this.personnelInfo.code,
name: this.personnelInfo.name,
position: this.personnelInfo.position,
unitName: this.personnelInfo.unitName,
deviceId: this.apiType === 'listA' ? this.deviceID : this.itemInfo.deviceId,
deviceImei: this.itemInfo.deviceImei
};
// 3. 注册人员信息
const registerRes = await registerPersonInfo(data);
if (registerRes.code !== 200) {
uni.showToast({
title: registerRes.msg,
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) {
uni.showToast({
title: error.message,
icon: 'none'
});
} finally {
uni.hideLoading();
this.isSending = false;
}
},
onPopupConfirm() {
this.showPopupFlag = false
console.log('用户点击了确定')
},
// 解除报警
onPopupConfirmPolice() {
@ -850,7 +923,9 @@
});
},
// 发送文本消息
sendTextMessage() {
async sendTextMessage() {
// 防重复提交
if (this.isSending) return;
if (!this.messageToSend) {
uni.showToast({
title: '请输入要发送的文字',
@ -858,42 +933,55 @@
});
return;
}
uni.showLoading({
title: '发送中...',
mask: true
})
let data = {
sendMsg: this.messageToSend,
//deviceIds: [this.deviceID],
deviceIds: this.apiType === 'listA' ? [this.deviceID] : [this.itemInfo.deviceId],
}
deviceSendMessage(data).then((res) => {
if (res.code == 200) {
uni.hideLoading()
this.popupType = 'person';
this.showPopupFlag = true
this.popupMessage = '发送信息成功'
} else {
this.isSending = true;
let loadingShown = false;
try {
uni.showLoading({
title: '正在发送...',
mask: true
});
loadingShown = true;
// 2. 准备请求数据
const batchId = generateShortId();
const data = {
sendMsg: this.messageToSend,
deviceIds: this.apiType === 'listA' ? [this.deviceID] : [this.itemInfo.deviceId],
typeName: this.itemInfo.typeName,
batchId: batchId,
deviceImeiList: [this.itemInfo.deviceImei]
};
// 3.人员信息
const registerRes = await deviceSendMessage(data);
if (registerRes.code !== 200) {
uni.showToast({
title: res.msg,
title: registerRes.msg,
icon: 'none'
});
})
return
}
})
// 轮询获取状态重要这里必须await
const statusRes = await this.getdeviceSTatus(2, batchId);
// 只有当状态为'OK'时才显示成功弹窗
if (statusRes.data.functionAccess === 'OK') {
this.popupType = 'person';
this.showPopupFlag = true;
this.popupMessage = '信息发送成功';
}
} catch (error) {
uni.showToast({
title: error.message,
icon: 'none'
});
} finally {
uni.hideLoading();
this.isSending = false;
}
},
// 统一处理返回方法
handleDeviceData(res, isFromShared = false) {
if (res.code == 200) {
// 最后关闭加载状态
this.pageLoading = false
this.$nextTick(() => {
uni.createSelectorQuery().in(this).select('.control-card').boundingClientRect(data => {
if (data) {
this.cardRect = data;
}
}).exec();
})
this.deviceInfo = res.data
this.personnelInfo = {
unitName: res.data.personnelInfo?.unitName || '',
@ -947,12 +1035,27 @@
})
}
},
handleMqttLost() {
this.Progress = {
...this.Progress,
show: false, // 隐藏进度条
};
}
// 操作说明
operatingInst() {
let id = this.apiType === 'listA' ? this.deviceID : this.itemInfo.deviceId
uni.navigateTo({
url: `/pages/common/operatingInstruct/index?id=${id}`
})
},
// 产品参数
productparams() {
let id = this.apiType === 'listA' ? this.deviceID : this.itemInfo.deviceId
uni.navigateTo({
url: `/pages/common/productDes/index?id=${id}`
})
},
// 操作视频
operatingVideo() {
let id = this.apiType === 'listA' ? this.deviceID : this.itemInfo.deviceId
uni.navigateTo({
url: `/pages/common/operationVideo/index?id=${id}`
})
},
},
onLoad(options) {
@ -962,6 +1065,7 @@
title: '加载中...'
})
eventChannel.on('deviceControl', (data) => {
console.log(data, 'data');
this.itemInfo = data.data;
this.deviceID = data.data.id;
this.navTitle = data.data.deviceName;
@ -971,22 +1075,18 @@
// 初始化并连接MQTT
this.mqttClient = new MqttClient();
this.mqttClient.connect(() => {
console.log('MQTT 连接成功,开始订阅主题');
// 订阅来自设备的状态更新
const statusTopic = `A/${this.itemInfo.deviceImei}`;
this.mqttClient.subscribe(statusTopic, (payload) => {
try {
console.log(`收到来自 ${statusTopic} 的消息:`, payload);
//收到电量上报。延迟20s请求接口数据
const parsedMessage = typeof payload === 'string' ? JSON.parse(payload) :
const parsedMessage = typeof payload === 'string' ? JSON.parse(
payload) :
payload;
const deviceState = parsedMessage.state; // 直接取 state 数组
// ✅ 发送全局事件通知主页面更新
uni.$emit('deviceStatusUpdate', {
message: parsedMessage, // 消息内容
timestamp: new Date().getTime() // 时间戳
});
if (deviceState[0] === 12) {
// 这里延迟20s解决,经纬度,逆解析问题
setTimeout(() => {
this.fetchDeviceDetail(data.data.id);
}, 20000);
@ -996,32 +1096,17 @@
this.popupMessage = '请及时充电';
this.showPopupFlag = true;
}
}
// 处理上传照片进度消息
if (deviceState[0] === 3) {
const progress = deviceState[1];
// 更新进度条
this.Progress = {
...this.Progress,
curr: progress * 2,
show: progress < 50 // 进度达到100时自动隐藏
};
// 当进度为100时显示成功弹框
if (progress === 50) {
this.popupType = 'logo';
this.popupMessage = '上传成功';
this.showPopupFlag = true;
this.lightModeB = false; // 关闭上传弹窗
this.selectedImage = ''; // 清空已选图片
}
// ✅ 发送全局事件通知主页面更新
uni.$emit('deviceStatusUpdate', {
message: parsedMessage, // 消息内容
timestamp: new Date().getTime() // 时间戳
});
}
} catch (error) {
console.error('解析MQTT消息失败:', error, '原始消息:', payload);
console.log('解析MQTT消息失败:', error, '原始消息:', payload);
}
});
})
// 设置连接丢失回调
uni.$on('mqttConnectionLost', this.handleMqttLost);
if (this.apiType === 'listA') {
this.fetchDeviceDetail(data.data.id)
} else {
@ -1041,7 +1126,6 @@
if (this.mqttClient) {
this.mqttClient.disconnect();
}
uni.$off('mqttConnectionLost', this.handleMqttLost);
if (this.mqttClient) {
this.mqttClient.disconnect();
}