refactor: 重构MQTT多连接架构并对齐dataBoard接口

- MQTT 从单连接改为按 type 隔离的多连接管理,新增 disconnectMqtt
- dataBoard 对齐新接口:字段重命名、POST请求、广告数据合并到同一接口
- LED 价格改为动态绑定,MQTT回调适配多连接模式
- 新增 dataBoard 独立 MQTT 环境变量配置

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
2026-08-07 18:00:30 +08:00
co-authored by Claude Opus 4.7
parent ca5b21bd9a
commit 1ef8e823ed
7 changed files with 153 additions and 145 deletions
+9 -3
View File
@@ -12,6 +12,12 @@ VUE_APP_ST_MQTT_PORT = 61614
VUE_APP_CT_MQTT_URL = vip.shuziweidao.com
VUE_APP_CT_MQTT_PORT = 61614
VUE_APP_LED_MQTT_URL = wss.dm.yixiong-tech.com
VUE_APP_LED_MQTT_PORT = 8443
VUE_APP_LED_MQTT_USERNAME = test
VUE_APP_LED_MQTT_PASSWORD = Yx123456
VUE_APP_LED_MQTT_PORT = 80
VUE_APP_LED_MQTT_USERNAME = admin
VUE_APP_LED_MQTT_PASSWORD = 7dzkZU1GOnYgNP0Y
# dataBoard 排行大屏 mqtt 通信地址
VUE_APP_DB_MQTT_URL = wss.dm.yixiong-tech.com
VUE_APP_DB_MQTT_PORT = 80
VUE_APP_DB_MQTT_USERNAME = admin
VUE_APP_DB_MQTT_PASSWORD = 7dzkZU1GOnYgNP0Y
+9 -3
View File
@@ -11,6 +11,12 @@ VUE_APP_ST_MQTT_PORT = 61614
VUE_APP_CT_MQTT_URL = vip.shuziweidao.com
VUE_APP_CT_MQTT_PORT = 61614
VUE_APP_LED_MQTT_URL = wss.dm.yixiong-tech.com
VUE_APP_LED_MQTT_PORT = 8443
VUE_APP_LED_MQTT_USERNAME = test
VUE_APP_LED_MQTT_PASSWORD = Yx123456
VUE_APP_LED_MQTT_PORT = 80
VUE_APP_LED_MQTT_USERNAME = admin
VUE_APP_LED_MQTT_PASSWORD = 7dzkZU1GOnYgNP0Y
# dataBoard 排行大屏 mqtt 通信地址
VUE_APP_DB_MQTT_URL = wss.dm.yixiong-tech.com
VUE_APP_DB_MQTT_PORT = 80
VUE_APP_DB_MQTT_USERNAME = admin
VUE_APP_DB_MQTT_PASSWORD = 7dzkZU1GOnYgNP0Y
+50 -22
View File
@@ -1,54 +1,82 @@
import mqtt from "mqtt";
import {getServeUrl} from "@/utils/serveUrl";
let mqttClient = null;
const clients = {};
export const initMqtt = (clientId, topic, type, {username='sw_mqtt', password='150326sw@', head='ws'}) => {
return new Promise((resolve, reject) => {
// 同 type 已有连接则先断开
if (clients[type]) {
clients[type].client.end(true);
delete clients[type];
}
const url = {
head: head, // 必须是 ws 或 wss mqtt:// 或 mqtts:// 必须让后端开放websocket服务)
host: getServeUrl(type + 'MqttUrl'), // 服务地址
port: getServeUrl(type + 'MqttPORT'), // 服务端口
tailPath: "mqtt", // 服务路径
head: head,
host: getServeUrl(type + 'MqttUrl'),
port: getServeUrl(type + 'MqttPORT'),
tailPath: "mqtt",
};
const options = {
clientId: clientId,
username: username,
password: password,
// keepalive: 60,
clean: true,
cleanSession: true,
reconnectPeriod: 5000, // 断线后重连间隔 (ms)
connectTimeout: 30 * 1000, // 连接超时时间
reconnectPeriod: 5000,
connectTimeout: 30 * 1000,
};
// 创建MQTT连接
mqttClient = mqtt.connect(`${url.head}://${url.host}:${url.port}/${url.tailPath}`, options);
// 事件处理
mqttClient.on("connect", () => {
console.info("连接成功_clientId" + clientId);
const client = mqtt.connect(`${url.head}://${url.host}:${url.port}/${url.tailPath}`, options);
const entry = { client, callback: null };
clients[type] = entry;
mqttClient.subscribe(topic, (err) => {
client.on("connect", () => {
console.info("MQTT 连接成功_clientId" + clientId);
client.subscribe(topic, (err) => {
if (err) {
reject("订阅失败_clientId" + clientId);
} else {
if (entry.callback) {
client.on('message', (topic, message) => {
entry.callback({ topic, message: JSON.parse(message.toString()) });
});
}
resolve("订阅成功_clientId" + clientId);
}
});
});
mqttClient.on("error", (error) => {
client.on("error", (error) => {
reject("连接失败_clientId" + clientId);
});
})
});
};
export const callBackMqttMessage = (callback) => {
if(mqttClient) {
mqttClient.on('message', (topic, message) => {
callback({ topic, message: JSON.parse(message.toString()) });
export const callBackMqttMessage = (type, callback) => {
const entry = clients[type];
if (entry) {
entry.callback = callback;
if (entry.client) {
entry.client.on('message', (topic, message) => {
callback({ topic, message: JSON.parse(message.toString()) });
});
}
}
};
export const disconnectMqtt = (type) => {
if (type) {
if (clients[type]) {
clients[type].client.end(true);
delete clients[type];
}
} else {
Object.keys(clients).forEach(k => {
clients[k].client.end(true);
delete clients[k];
});
}
}
};
+6
View File
@@ -25,6 +25,12 @@ const getServeUrl = function(type) {
case 'ledMqttPORT':
serveUrl = process.env.VUE_APP_LED_MQTT_PORT;
break;
case 'dbMqttUrl':
serveUrl = process.env.VUE_APP_DB_MQTT_URL;
break;
case 'dbMqttPORT':
serveUrl = process.env.VUE_APP_DB_MQTT_PORT;
break;
}
return serveUrl;
};
+69 -109
View File
@@ -46,7 +46,7 @@
<div>人均营养分</div>
</div>
</div>
<div class="total-right">{{dinnerType}} {{mealTimeStart && mealTimeEnd ? `(${mealTimeStart} ~ ${mealTimeEnd})` : ''}}</div>
<div class="total-right">{{mealType}} {{mealTimeStart && mealTimeEnd ? `(${mealTimeStart} ~ ${mealTimeEnd})` : ''}}</div>
</div>
<div class="table-top">
<div>
@@ -59,8 +59,8 @@
<!-- <div class="scroll-content animal-css" :style="animationCss">-->
<div class="scroll-content" :style="animationCss" :class="[orderListData.length > 0 ? 'animal-css' : '']">
<div v-for="(item,index) in orderListData" :key="`top-list-data-${index}`">
<img style="border-radius: 8px" :src="item.faceUrl || require('@/assets/images/bigScreen/user.png')" alt="" />
{{preName(item.name)}} {{item.userScore}} {{item?.sort}}
<img style="border-radius: 8px" :src="item.avatarUrl || require('@/assets/images/bigScreen/user.png')" alt="" />
{{preName(item.userName)}} {{item.score}} {{item?.rank}}
</div>
</div>
</div>
@@ -95,12 +95,12 @@
{{index+1}}
</div>
</template>
<img style="border-radius: 8px" class="title-img" :src="item.faceUrl || require('@/assets/images/bigScreen/user.png')" alt="" />
<img style="border-radius: 8px" class="title-img" :src="item.avatarUrl || require('@/assets/images/bigScreen/user.png')" alt="" />
</div>
<div>
<div class="table-info-one">{{preName(item.name)}}</div>
<div class="table-info-two" style="color: #FFB99C">{{ item.userScore}}</div>
<div class="table-info-three">{{preDate(item.orderDate)}}</div>
<div class="table-info-one">{{preName(item.userName)}}</div>
<div class="table-info-two" style="color: #FFB99C">{{ item.score}}</div>
<div class="table-info-three">{{preDate(item.pickupTime)}}</div>
</div>
</div>
</transition-group>
@@ -141,14 +141,14 @@
<div class="swiper-slide" v-for="(item, index) in swiperList" :key="`slide-${index}`">
<!-- 图片轮播 -->
<img
v-if="item.type === '1'"
v-if="item.type === 'image'"
:src="item.url"
class="swiper-content"
alt="轮播图片"
/>
<!-- 视频轮播 -->
<video
v-else-if="item.type === '2'"
v-else-if="item.type === 'video'"
class="swiper-content"
:ref="`videRef${index}`"
:src="item.url"
@@ -189,7 +189,7 @@
import 'swiper/css/swiper.css';
import {httpRequest} from "@/XMLHttpRequest";
import countTo from "vue-count-to";
import {callBackMqttMessage, initMqtt} from "@/utils/mqtt";
import {callBackMqttMessage, disconnectMqtt, initMqtt} from "@/utils/mqtt";
export default {
name: 'DataBoard',
@@ -198,10 +198,10 @@
},
data() {
return {
url: "https://api.dm.yixiong-tech.com:8443/",
url: "https://dev.yixiong-tech.com:8081/nutrition/",
nowTimeInterval: null,
nowTime: dayjs(),
dinnerType: '',
mealType: '',
mealTimeStart: '',
mealTimeEnd: '',
dataInitOverview: {
@@ -219,14 +219,7 @@
// 餐品热度数据:包含名称和热度值
valList: [],
// 轮播数据:支持图片和视频
swiperList: [
// { type: '1', src: require('@/assets/images/bigScreen/1.png'), duration: 3000 },
// { type: '2', src: require('@/assets/images/bigScreen/demo.mp4'), duration: 0 },
// { type: '1', src: require('@/assets/images/bigScreen/1.png'), duration: 3000 },
// { type: '2', src: require('@/assets/images/bigScreen/demo.mp4'), duration: 0 }
],
// 当前轮播索引
currentSwiperIndex: 0,
swiperList: [],
// 轮播定时器
swiperTimer: null,
// 是否正在播放视频
@@ -236,8 +229,9 @@
}
},
created() {
this.initMttqF()
this.initMttqFile()
this.initMqttConnect();
this.initTime();
this.initData('');
},
computed: {
animationCss() {
@@ -251,56 +245,45 @@
}
},
mounted() {
callBackMqttMessage((data) => {
console.log('loadData=============='+data.topic+'==='+dayjs().format('YYYY-MM-DD HH:mm:ss'), data)
if (data.topic === 'yx/device/rankingScreen/needUpdate') {
// if (data.message?.type === 'rankingFileUpdate') {
// this.initSwiperData()
// } else {
if(data.message?.userId) this.initData(data.message?.userId);
// }
} else {
this.initSwiperData()
}
})
this.initTime();
this.initData('');
this.initSwiperData();
// this.$nextTick(() => {
// this.initSwiper();
// this.startSwiperAutoPlay();
// });
// this.startRandomVal();
},
beforeDestroy() {
if (this.nowTimeInterval) {
clearInterval(this.nowTimeInterval);
}
if (this.pollTimer) {
clearInterval(this.pollTimer);
}
if (this.swiperTimer) {
clearTimeout(this.swiperTimer);
}
if (this.swiperInstance) {
this.swiperInstance.destroy();
}
disconnectMqtt('db');
},
methods: {
initMttqF() {
initMqtt('deviceId-' + Math.random().toString(16).substring(2, 8),'yx/device/rankingScreen/needUpdate','led', {username: process.env.VUE_APP_LED_MQTT_USERNAME, password: process.env.VUE_APP_LED_MQTT_PASSWORD, head: 'wss'})
.then((res) => {
console.log(res)
initMqttConnect() {
const clientId = 'db-' + Math.random().toString(16).substring(2, 8);
console.log(clientId);
initMqtt(clientId, 'yx/device/rankingScreen/needUpdate', 'db', {
head: 'ws',
username: process.env.VUE_APP_DB_MQTT_USERNAME,
password: process.env.VUE_APP_DB_MQTT_PASSWORD
})
.then(() => {
callBackMqttMessage('db', (data) => {
console.log('[MQTT] 收到消息:', data.topic, dayjs().format('YYYY-MM-DD HH:mm:ss'), data.message);
if (data.topic === 'yx/device/rankingScreen/needUpdate') {
const msg = data.message;
if (msg.type === 'RANKING_UPDATE') {
this.initData('');
}
}
});
})
.catch((err) => {
console.log(err)
})
},
initMttqFile() {
initMqtt('deviceId-' + Math.random().toString(16).substring(2, 8),'yx/device/rankingFile/needUpdate','led', {username: process.env.VUE_APP_LED_MQTT_USERNAME, password: process.env.VUE_APP_LED_MQTT_PASSWORD, head: 'wss'})
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
})
console.error('[MQTT] 连接失败:', err);
});
},
preName(name) {
if (!name) return;
@@ -317,36 +300,27 @@
if (!d) return;
return dayjs(d).format('HH:mm:ss');
},
initSwiperData() {
let _this = this;
httpRequest("GET", this.url + 'terminal/neglect/large-screen/ranking/file', {}, {"authorization": "57ee87183f2a4fa59683ec9ef41c8f5d"})
.then(function (res) {
console.log(res)
if (res.code === '00000') {
_this.swiperList = res.data || [];
if (_this.swiperInstance) {
_this.swiperInstance.destroy(true, true);
_this.swiperInstance = null;
}
if (_this.swiperTimer) {
clearTimeout(_this.swiperTimer);
}
_this.$nextTick(() => {
_this.initSwiper();
_this.startSwiperAutoPlay();
});
}
})
.catch((err) => {
console.log(err)
})
reinitSwiper() {
if (this.swiperInstance) {
this.swiperInstance.destroy(true, true);
this.swiperInstance = null;
}
if (this.swiperTimer) {
clearTimeout(this.swiperTimer);
}
if (this.swiperList.length > 1) {
this.$nextTick(() => {
this.initSwiper();
this.startSwiperAutoPlay();
});
}
},
initData(userId) {
let _this = this;
this.orderListData = [];
httpRequest("GET", this.url + 'terminal/neglect/large-screen/ranking' , {userId}, {"authorization": "57ee87183f2a4fa59683ec9ef41c8f5d"}).then(function (res) {
httpRequest("POST", this.url + 'neglect/large-screen/ranking' , {userId}, {"authorization": "57ee87183f2a4fa59683ec9ef41c8f5d"}).then(function (res) {
if (res?.code === '00000') {
_this.dinnerType = res.data.dinnerType;
_this.mealType = res.data.mealType;
_this.dataOverview = res.data.dataOverview || {
userCount: 0,
perCalorie: 0,
@@ -354,14 +328,18 @@
};
_this.mealTimeStart = res.data.mealTimeStart;
_this.mealTimeEnd = res.data.mealTimeEnd;
_this.listData = res.data.userScoreInfos || [];
_this.orderListData = res.data.userOrderInfos || [];
const maxWeight = res.data.foodSortInfos && res.data.foodSortInfos.length > 0 ? res.data.foodSortInfos[0].foodWeight || 0 : 0;
_this.valList = (res.data.foodSortInfos || []).map((item) => {
_this.listData = res.data.userRankings || [];
_this.orderListData = res.data.tickerItems || [];
const maxWeight = res.data.foodRankings && res.data.foodRankings.length > 0 ? res.data.foodRankings[0].foodWeight || 0 : 0;
_this.valList = (res.data.foodRankings || []).map((item) => {
item['weightPoint'] = maxWeight === 0 ? 0 : parseFloat(((item?.foodWeight || 0) / maxWeight * 100).toFixed(2));
return item;
});
} else {
// 广告数据从同一接口获取
if (res.data.adImages && res.data.adImages.length > 0) {
_this.swiperList = res.data.adImages;
_this.reinitSwiper();
}
}
}).catch(function(err) {
console.log(err)
@@ -377,20 +355,6 @@
this.nowTime = dayjs();
}, 1000);
},
// 生成随机热度值并排序
randomVal() {
this.valList.forEach(item => {
item.value = (Math.floor(Math.random() * 10) + 1) * 10;
});
// 按热度值降序排列
this.valList.sort((a, b) => b.value - a.value);
},
// 启动随机更新
startRandomVal() {
setInterval(() => {
this.randomVal();
}, 1500);
},
// 根据热度值返回对应的进度条样式类
getProgressClass(val) {
if (val < 30) {
@@ -422,9 +386,7 @@
// Swiper 滑动事件处理
onSwiperSlideChange() {
if (!this.swiperInstance || this.swiperList.length <= 1) return;
// 获取当前索引
const realIndex = this.swiperInstance.activeIndex;
this.currentSwiperIndex = realIndex;
// 清除之前的定时器
if (this.swiperTimer) {
@@ -433,7 +395,7 @@
const currentIndex = realIndex === 0 ? 0 : realIndex > this.swiperList.length ? 0 : realIndex - 1;
// 获取当前幻灯片数据
const currentItem = this.swiperList[currentIndex];
if (this.swiperList[currentIndex !== 0 ? currentIndex - 1 : this.swiperList.length - 1].type === '2') {
if (this.swiperList[currentIndex !== 0 ? currentIndex - 1 : this.swiperList.length - 1].type === 'video') {
const refD = this.$refs[`videRef${currentIndex !== 0 ? currentIndex - 1 : this.swiperList.length - 1}`];
if (refD && refD.length > 0 && refD[0]) {
refD[0].currentTime = 0;
@@ -445,24 +407,22 @@
refD1[0].pause();
}
}
if (currentItem.type === '1') {
if (currentItem.type === 'image') {
// 图片:按设定时长自动切换
this.swiperTimer = setTimeout(() => {
this.swiperInstance.slideNext();
}, 3000);
} else if (currentItem.type === '2') {
} else if (currentItem.type === 'video') {
// 视频:等待播放完毕后切换
this.isPlayingVideo = true;
}
},
onSlideChangeTransitionEnd () {
if (!this.swiperInstance) return
// 获取当前索引
const realIndex = this.swiperInstance.activeIndex;
this.currentSwiperIndex = realIndex;
const currentIndex = realIndex === 0 ? 0 : realIndex > this.swiperList.length ? 0 : realIndex - 1;
const currentItem = this.swiperList[currentIndex];
if (currentItem.type === '2') {
if (currentItem.type === 'video') {
const refD = this.$refs[`videRef${currentIndex}`]
if (refD && refD.length > 0) {
refD[0].muted = false;
+1 -1
View File
@@ -19,7 +19,7 @@
<div></div>
</div>
<div>
<div>16.8<span></span></div>
<div>{{ deviceData.price }}<span></span></div>
<div>{{ parseInt(deviceData.calorie) }}<span>kcal</span></div>
</div>
<div></div>
+9 -7
View File
@@ -30,7 +30,7 @@ export default {
},
data() {
return {
url: "http://192.168.10.101:24801/nutrition/",
url: "https://dev.yixiong-tech.com:8081/nutrition/",
screenWidth: 1920,
deviceDataList: [{
deviceCode: '1',
@@ -81,9 +81,6 @@ export default {
}
},
mounted() {
callBackMqttMessage((data) => {
this.getInfoByDevice(data?.message || {});
})
},
created() {
this.initData();
@@ -117,6 +114,7 @@ export default {
}).then(function (res) {
if (res?.code === '00000') {
_this.deviceDataList = res?.data?.foodList.map((item, index) => {
item.calorie = item.calorie ? item.calorie : 0;
if (!item.deviceCode) {
item.deviceCode = index.toString();
}
@@ -129,12 +127,16 @@ export default {
})
},
initMQ() {
initMqtt('deviceId-' + Math.random().toString(16).substring(2, 8), 'yx/device/foodRecord/needUpdate', 'led', {
const clientId = 'deviceId-' + Math.random().toString(16).substring(2, 8);
initMqtt(clientId, 'yx/device/foodRecord/needUpdate', 'led', {
username: process.env.VUE_APP_LED_MQTT_USERNAME,
password: process.env.VUE_APP_LED_MQTT_PASSWORD,
head: 'wss'
head: 'ws'
}).then((res) => {
console.log(res)
console.log(res);
callBackMqttMessage('led', (data) => {
this.getInfoByDevice(data?.message || {});
});
}).catch((err) => {
console.log(err)
})