RealTimeData.vue
3.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<template>
<BasicTable @register="registerTable" />
</template>
<script lang="ts">
import { defineComponent, reactive } from 'vue';
import { BasicTable, useTable } from '/@/components/Table';
import { realTimeDataColumns } from '../../config/detail.config';
import { useWebSocket } from '@vueuse/core';
import { JWT_TOKEN_KEY } from '/@/enums/cacheEnum';
import { getAuthCache } from '/@/utils/auth';
import { useMessage } from '/@/hooks/web/useMessage';
import type { socketDataType } from '../../types';
export default defineComponent({
name: 'RealTimeData',
components: {
BasicTable,
},
props: {
deviceDetail: {
type: Object,
required: true,
},
},
setup(props) {
const token: string = getAuthCache(JWT_TOKEN_KEY);
const state = reactive({
server: `${import.meta.env.VITE_WEB_SOCKET}${token}`,
sendValue: JSON.stringify({
attrSubCmds: [],
tsSubCmds: [
{
entityType: 'DEVICE',
entityId: props.deviceDetail.tbDeviceId,
scope: 'LATEST_TELEMETRY',
cmdId: 1,
},
],
historyCmds: [],
entityDataCmds: [],
entityDataUnsubscribeCmds: [],
alarmDataCmds: [],
alarmDataUnsubscribeCmds: [],
entityCountCmds: [],
entityCountUnsubscribeCmds: [],
}),
recordList: Array<socketDataType>(),
});
const { createMessage } = useMessage();
const [registerTable] = useTable({
columns: realTimeDataColumns,
showTableSetting: true,
bordered: true,
showIndexColumn: false,
dataSource: state.recordList,
});
const { send, close } = useWebSocket(state.server, {
onConnected() {
send(state.sendValue);
console.log('建立连接了');
},
onMessage(_, e) {
const { data } = JSON.parse(e.data);
console.log('来新消息了', '---data---', data);
const newArray: socketDataType[] = [];
for (const key in data) {
const [time, value] = data[key].flat(1);
let obj = {
key,
time,
value,
};
if (state.recordList.length === 0) {
state.recordList.unshift(obj);
} else {
newArray.push(obj);
}
}
newArray.forEach((item) => {
let flag = false;
state.recordList.forEach((item1) => {
if (item1.key === item.key) {
item1.value = item.value;
item1.time = item.time;
flag = true;
}
});
if (!flag) {
state.recordList.unshift(item);
}
});
},
onDisconnected() {
console.log('断开连接了');
close();
},
onError() {
createMessage.error('webSocket连接超时,请联系管理员');
},
});
return {
registerTable,
};
},
});
</script>