using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Wit.SDK.Modular.Sensor.Device; using Wit.SDK.Utils; namespace Wit.SDK.Modular.Sensor.Modular.DataProcessor.Utils { /// /// 记录key值切换器 /// 功能:自动匹配记录的key /// public class RecordKeySwitch { /// /// 记录触发器列表 /// public List recordTriggerList = new List {}; /// /// 字典 string:key值 long:刷新时间 /// private Dictionary keyUpdateTimeDict = new Dictionary(); /// /// 是否启用切换触发器线程 /// public bool BolSwitchRecrodThEnable = false; /// /// 上次更新时间 /// public long LastUpdateTs = 0; /// /// 基础设备 /// public DeviceModel DeviceModel { get; private set; } /// /// 初始化 启动 /// /// public void Open(DeviceModel deviceModel, List keyList) { // 设备 this.DeviceModel = deviceModel; // 记录触发器列表 this.recordTriggerList = keyList; DeviceModel.OnKeyUpdate -= DeviceModel_OnKeyUpdate; DeviceModel.OnKeyUpdate += DeviceModel_OnKeyUpdate; DeviceModel.OnListenKeyUpdate -= DeviceModel_OnListenKeyUpdate; DeviceModel.OnListenKeyUpdate += DeviceModel_OnListenKeyUpdate; // 创建线程 Thread th = new Thread(SwitchKeyTh) { IsBackground = true }; BolSwitchRecrodThEnable = true; th.Start(); } /// /// 切换刷新用的key值 /// private void SwitchKeyTh() { // 数据刷新有问题就启动线程 while (BolSwitchRecrodThEnable) { Thread.Sleep(3000); // 实时时间 var ts = DateTimeUtils.GetTimeStamp(); if (ts - LastUpdateTs > 3000) { SwitchListenerKey(); } } } /// /// 切换监听的key /// private void SwitchListenerKey() { if (recordTriggerList.Count == 0) { return; } // 最后切换的key值 string keyLast = recordTriggerList[0]; double min = 0; for (int i = 0; i < recordTriggerList.Count; i++) { string item = recordTriggerList[i]; if (keyUpdateTimeDict.ContainsKey(item)) { double tsVal = keyUpdateTimeDict[item]; if (tsVal > min) { min = tsVal; keyLast = item; } } } // 切换监听的key值 让数据刷新继续下去 DeviceModel.ListenerKey = keyLast; } /// /// 判断自动更新数据有无问题 /// /// private void DeviceModel_OnListenKeyUpdate(DeviceModel deviceModel) { LastUpdateTs = DateTimeUtils.GetTimeStamp(); } /// /// 记录key值刷新时对应的时间 /// /// /// /// private void DeviceModel_OnKeyUpdate(DeviceModel deviceModel, string key, object value) { // 如果是可切换的key就赋值给字典 if (recordTriggerList.Contains(key)) { // 记录数据更新时间戳 keyUpdateTimeDict[key] = DateTimeUtils.GetTimeStamp(); } } /// /// 关闭所有线程 /// public void Close() { // 关线程 BolSwitchRecrodThEnable = false; if (DeviceModel != null && DeviceModel.IsOpen) { // 取消事件委托 DeviceModel.OnKeyUpdate -= DeviceModel_OnKeyUpdate; DeviceModel.OnListenKeyUpdate -= DeviceModel_OnListenKeyUpdate; } } } }