deviceDetail.vue 5.38 KB
<template>
	<view class="device-detail-page">
		<!-- 公共组件-每个页面必须引入 -->
		<public-module></public-module>
		<u-sticky bgColor="#fff">
			<u-tabs
				:list="list"
				:current="currentTab"
				@click="handleTabClick"
				:activeStyle="{
					fontWeight: 'bold',
					color: '#333'
				}"
				:inactiveStyle="{
					color: '#999'
				}"
			/>
		</u-sticky>
		<view style="margin-top:30rpx;">
			<basicInfo v-show="currentTab == 0" :deviceDetail="deviceDetail" />
			<realTimeData v-show="currentTab === 1" :recordList="recordList" />
			<historyData
				v-if="currentTab === 2"
				:keys="keys"
				:yesterday="yesterday"
				:today="today"
				:timeDiff="timeDiff"
				:historyData="historyData"
				:entityId="entityId"
				:start="startTs"
				:end="endTs"
				@update="handleUpdate"
			/>
			<alarmHistory v-show="currentTab === 3" :deviceId="deviceId" />
			<commondRecord v-if="currentTab === 4" :tbDeviceId="entityId" />
		</view>
	</view>
</template>

<script>
import fTabbar from '@/components/module/f-tabbar/f-tabbar';
import basicInfo from './tabDetail/basicInfo.vue';
import realTimeData from './tabDetail/realtimeData.vue';
import alarmHistory from './tabDetail/alarmHistory.vue';
import historyData from './tabDetail/historyData.vue';
import commondRecord from './tabDetail/CommandRecord.vue';
import { getDeviceKeys, getHistoryData } from './api/index.js';
import { formatToDate } from '@/plugins/utils.js';
export default {
	components: {
		fTabbar,
		basicInfo,
		realTimeData,
		alarmHistory,
		historyData,
		commondRecord
	},
	data() {
		return {
			list: [{ name: '基础信息' }, { name: '实时数据' }, { name: '历史数据' }, { name: '告警记录' }, { name: '命令记录' }],
			currentTab: 0,
			deviceId: '',
			deviceDetail: {},
			keys: [],
			yesterday: '',
			today: '',
			timeDiff: '',
			historyData: [],
			entityId: '',
			startTs: '',
			endTs: '',
			recordList: []
		};
	},
	onUnload(){
		// 页面关闭时,销毁webSocket连接,否则第二次会存在连接不到的情况
		uni.closeSocket();
	},
	async onLoad(options) {
		const { id, alarmStatus, lastOnlineTime, tbDeviceId } = options;
		this.deviceId = id;
		const res = await uni.$u.http.get(`/yt/device/${id}`);
		this.deviceDetail = { ...res, alarmStatus, lastOnlineTime };
		// 连接webSockte
		const socketTask = uni.connectSocket({
			url: 'wss://dev.thingskit.com/api/ws/plugins/telemetry?token=' + uni.getStorageSync('userInfo').isToken, //仅为示例,并非真实接口地址。
			complete: () => {}
		});
		uni.onSocketOpen(header => {
			socketTask.send({
				data: JSON.stringify({
					attrSubCmds: [],
					tsSubCmds: [
						{
							entityType: 'DEVICE',
							entityId: tbDeviceId,
							scope: 'LATEST_TELEMETRY',
							cmdId: 1
						}
					],
					historyCmds: [],
					entityDataCmds: [],
					entityDataUnsubscribeCmds: [],
					alarmDataCmds: [],
					alarmDataUnsubscribeCmds: [],
					entityCountCmds: [],
					entityCountUnsubscribeCmds: []
				}),
				success() {}
			});
		});
		socketTask.onMessage(msg => {
			const { data } = JSON.parse(msg.data);
			const newArray = [];
			for (const key in data) {
				const [time, value] = data[key].flat(1);
				let obj = { key, time, value };
				if (this.recordList.length === 0) {
					this.recordList.unshift(obj);
				} else {
					newArray.push(obj);
				}
			}
			newArray.forEach(item => {
				let flag = false;
				this.recordList.forEach(item1 => {
					if (item1.key === item.key) {
						item1.value = item.value;
						item1.time = item.time;
						flag = true;
					}
				});
				if (!flag) {
					this.recordList.unshift(item);
				}
			});
			this.recordList = this.recordList.map(item => {
				return {
					...item,
					time: formatToDate(item.time, 'YYYY-MM-DD HH:mm:ss')
				};
			});
		});

		const keys = await getDeviceKeys(tbDeviceId);
		this.keys = [keys];
		const date = new Date();
		const year = date.getFullYear(); //获取完整的年份(4位)
		const month = date.getMonth() + 1; //获取当前月份(0-11,0代表1月)
		const day = date.getDate(); //获取当前日(1-31)
		const yesterday = `${year}-${month}-${day - 1}`;
		const today = `${year}-${month}-${day}`;
		this.yesterday = yesterday;
		this.today = today;
		this.startTs = formatToDate(yesterday, 'x');
		this.endTs = formatToDate(today, 'x');
		this.entityId = tbDeviceId;
		console.log(this.entityId)
		const data = await getHistoryData({
			entityId: tbDeviceId,
			startTs: formatToDate(yesterday, 'x'),
			endTs: formatToDate(today, 'x'),
			keys: keys[0],
			interval: 1800000
		});
		this.timeDiff = '30分钟';
		if (!Object.keys(data).length) return;

		this.historyData = data[keys[0]]
			.map(item => {
				return {
					value: item.value,
					ts: formatToDate(item.ts, 'YYYY-MM-DD HH:mm:ss')
				};
			})
			.reverse();
	},
	methods: {
		handleTabClick({ index }) {
			this.currentTab = index;
		},
		handleUpdate(data) {
			if (!Array.isArray(data)) {
				this.historyData = [];
				return;
			}
			this.historyData = data
				.map(item => {
					return {
						value: item.value,
						ts: formatToDate(item.ts, 'YYYY-MM-DD HH:mm:ss')
					};
				})
				.reverse();
		}
	}
};
</script>

<style lang="scss" scoped>
.device-detail-page {
	height: 100vh;
	background-color: #f8f9fa;
}
</style>