新增mqtt文件,订阅设备消息

This commit is contained in:
fengerli
2025-09-04 13:35:39 +08:00
parent 4749cdce3c
commit 520d6b2b1a
7 changed files with 393 additions and 522 deletions

View File

@ -125,6 +125,7 @@
</template>
<script setup name="DeviceControl" lang="ts">
const route = useRoute();
import { useMqtt } from '@/utils/mqtt';
import api from '@/api/controlCenter/controlPanel/index'
import { DeviceDetail, LightMode } from '@/api/controlCenter/controlPanel/types';
import { generateShortId, getDeviceStatus } from '@/utils/function';
@ -147,7 +148,15 @@ const fullscreenLoading = ref(false)
const forceAlarmLoading = ref(false) //强制报警
const sendTextLoading = ref(false)
const lightModesLoading = ref(false)
const {
connected,
connect,
subscribe,
onConnect,
onError,
onMessage,
disconnect
} = useMqtt();
// 灯光模式数据(引用导入的图片)
const lightModes = ref<LightMode[]>([
{
@ -244,6 +253,7 @@ const handleModeClick = async (modeId: string) => {
typeName: deviceDetail.value.typeName,
});
if (res.code === 200) {
ElMessage.closeAll();
proxy?.$modal.msgSuccess(res.msg);
setActiveLightMode(modeId);
} else {
@ -300,7 +310,7 @@ const getList = async () => {
targetModeId = matchedMode.id;
}
setActiveLightMode(targetModeId);
const laserStatus = res.data.laserModeStatus ?? 0;
const laserStatus = res.data.laserLightMode;
laserMode.value.active = laserStatus === 1;
laserMode.value.switchStatus = laserStatus === 1;
} catch (error) {
@ -321,6 +331,7 @@ const handleLaserClick = async () => {
instructValue: targetStatus ? 1 : 0
});
if (res.code === 200) {
ElMessage.closeAll();
proxy?.$modal.msgSuccess(res.msg);
laserMode.value.active = targetStatus;
laserMode.value.switchStatus = targetStatus;
@ -496,9 +507,118 @@ const lookMap = (row: any) => {
}
});
}
onMounted(() => {
getList();
const getMainLightModeLabel = (mode: any) => {
const modeMap = {
0: 'close', // 0 → 关闭
1: 'strong', // 1 → 强光
2: 'weak', // 2 → 弱光
3: 'strobe', // 3 → 爆闪
4: 'flood' // 4 → 泛光
}
return modeMap[mode] || (console.log('未知的灯光模式:', mode), '未知');
}
// 处理设备消息
const handleDeviceMessage = (msg: any) => {
try {
// 解析设备消息(假设格式为 { state: [类型, 模式值, 亮度, 续航...] }
const payloadObj = JSON.parse(msg.payload.toString());
const deviceState = payloadObj.state; // 设备状态数组
if (!Array.isArray(deviceState)) {
return;
}
// 用switch处理不同的消息类型deviceState[0]
switch (deviceState[0]) {
case 1:
// 类型1灯光主键
const lightModeId = getMainLightModeLabel(deviceState[1]); // 获取模式ID如'strong'
const brightness = deviceState[2]; // 亮度值
const batteryTime = deviceState[3]; // 续航时间
console.log('灯光模式消息:', { 模式ID: lightModeId, 亮度: brightness, 续航: batteryTime });
// 1. 同步灯光模式状态
if (lightModeId !== 'unknown') {
lightModes.value.forEach(mode => {
const isActive = mode.id === lightModeId;
mode.active = isActive;
mode.switchStatus = isActive;
});
}
// 2.亮度
if (brightness !== undefined) {
deviceDetail.value.lightBrightness = brightness.toString();
}
// 3.续航时间
if (batteryTime !== undefined) {
deviceDetail.value.batteryRemainingTime = batteryTime.toString();
}
break;
case 12:
// 灯光主键
const lightModeIdA = getMainLightModeLabel(deviceState[1]); // 获取模式ID如'strong'
if (lightModeIdA !== 'unknown') {
lightModes.value.forEach(mode => {
const isActive = mode.id === lightModeIdA;
mode.active = isActive;
mode.switchStatus = isActive;
});
}
// 激光
const laserValue = deviceState[2];
// 同步激光模式状态1=开启true0=关闭false
laserMode.value.active = laserValue === 1;
laserMode.value.switchStatus = laserValue === 1;
deviceDetail.value.batteryPercentage = deviceState[3]; //电量
deviceDetail.value.batteryRemainingTime = deviceState[5]; //续航时间
// getList(); // 重新获取设备详情
if (deviceDetail.value.batteryPercentage < 20) {
ElMessage.closeAll();
proxy?.$modal.msgWarning('电量低于20%,请及时充电');
}
break;
default:
// 其他类型消息(不处理,仅打印)
console.log('未处理的消息类型:', deviceState[0]);
break;
}
} catch (e) {
}
};
onMounted(async () => {
await getList(); // 先获取设备信息
// 连接mqtt
onConnect(async () => {
const deviceImei = deviceDetail.value.deviceImei;
if (!deviceImei) {
return;
}
try {
await subscribe(`A/${deviceImei}`, { qos: 1 });
console.log('订阅成功');
} catch (err) {
console.error('订阅失败onConnect内:', err);
}
});
// 2. 注册消息接收回调(核心:处理设备发送的消息)
onMessage((msg) => {
console.log('收到新消息:', {
主题: msg.topic,
内容: msg.payload,
时间: msg.time,
QoS: msg.qos
});
// 在这里处理消息(根据实际业务逻辑)
handleDeviceMessage(msg);
});
onError((err) => {
console.error('MQTT连接失败原因:', err.message); // 关键:打印连接失败的具体原因
});
connect();
});
onUnmounted(() => {
// 只有当连接已建立时,才执行断开操作(避免无效调用)
if (connected.value) {
console.log('页面离开断开MQTT连接');
disconnect(); // 调用断开连接方法
}
});
</script>
@ -800,4 +920,4 @@ onMounted(() => {
}
}
}
</style>
</style>