优化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: '',
// MQTT 配置
MQTT_HOST: '47.120.79.150',
MQTT_PORT: 8083,
MQTT_PORT: 9083,
MQTT_USERNAME: 'admin',
MQTT_PASSWORD: '#YtvpSfCNG'
},
@ -16,7 +16,7 @@ const config = {
API_PREFIX: '',
// MQTT 配置
MQTT_HOST: '47.120.79.150',
MQTT_PORT: 8083,
MQTT_PORT: 9083,
MQTT_USERNAME: 'admin',
MQTT_PASSWORD: '#YtvpSfCNG'
}

View File

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

View File

@ -3,9 +3,9 @@
<!-- 设备列表 -->
<view class="allSelect" @click="selectAll"> 全选</view>
<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>
</view>
<!-- 设备信息 -->
@ -81,45 +81,6 @@
}
},
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() {
this.showPopupFlag = false
},
@ -142,7 +103,7 @@
this.loading = true;
let data = {
pageNum: 1,
pageSize: 30,
pageSize: 50,
deviceType: deviceType
}
deviceInfo(data).then((res) => {
@ -201,27 +162,14 @@
title: isAlarming ? '设备报警中...' : '解除报警中...',
mask: true
});
// 2. 准备请求数据
const batchId = generateShortId();
const data = {
deviceIds: deviceIds,
batchId: batchId,
typeName: this.sendInfo.typeName,
deviceImeiList: deviceImeiList,
instructValue: this.pendingAlarmAction == 1 ? '1' : '0'
};
// 3.人员信息
const registerRes = await deviceSendAlarmMessage(data);
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') {
if (registerRes.code == 200) {
uni.showToast({
title: statusRes.msg,
icon: 'none'
@ -231,6 +179,11 @@
setTimeout(() => {
uni.navigateBack()
}, 500)
} else {
uni.showToast({
title: registerRes.msg,
icon: 'none'
});
}
} catch (error) {
uni.showToast({
@ -479,4 +432,14 @@
border: 1px solid rgba(255, 255, 255, 0.87);
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>

View File

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

View File

@ -2,9 +2,9 @@
<view class="container">
<!-- 设备列表 -->
<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>
</view>
<!-- 设备信息 -->
@ -71,6 +71,10 @@
}
},
methods: {
onPullDownRefresh() {
// 执行下拉刷新时的操作,比如重新获取数据
this.getData();
},
/**
* 获取设备状态(带自动轮询)
* @param {number} val - 功能模式
@ -419,4 +423,14 @@
border-radius: 50rpx;
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>

View File

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

View File

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