CommonViewModel.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Aitex.UI.Charting.Model;
  6. using System.Threading;
  7. using Abt.Controls.SciChart;
  8. using System.Windows.Media;
  9. using Aitex.UI.Charting.Command;
  10. using System.Windows.Input;
  11. using System.Collections.ObjectModel;
  12. using System.Windows.Threading;
  13. using System.Windows;
  14. using System.Windows.Controls;
  15. using Abt.Controls.SciChart.Model.DataSeries;
  16. using Abt.Controls.SciChart.Visuals.RenderableSeries;
  17. using System.ComponentModel;
  18. using Aitex.UI.Charting.View;
  19. using DataAnalysisControl.Core;
  20. namespace Aitex.UI.Charting.ViewModel
  21. {
  22. public sealed class CommonViewModel : ChartingBaseViewModel
  23. {
  24. /// <summary>
  25. /// 获取所有数据曲线对象
  26. /// </summary>
  27. public List<MyLineSeries> GetAllDataLineSeries()
  28. {
  29. List<MyLineSeries> lines = new List<MyLineSeries>();
  30. for (int i = 0; i < RenderableSeries.Count; i++)
  31. {
  32. var line = RenderableSeries[i] as MyLineSeries;
  33. if (line != null)
  34. {
  35. lines.Add(line);
  36. }
  37. }
  38. return lines;
  39. }
  40. /// <summary>
  41. /// new object is not allowed
  42. /// </summary>
  43. private CommonViewModel()
  44. {
  45. //主窗口的显示
  46. DataConfigViewVisibility = Visibility.Collapsed;
  47. DataDisplayViewVisibility = Visibility.Visible;
  48. Switch2DataCfgViewCommand = new ChartingCommand((o) => true, (o) =>
  49. {
  50. DataDisplayViewVisibility = Visibility.Collapsed;
  51. DataConfigViewVisibility = Visibility.Visible;
  52. InvokePropertyChanged("DataDisplayViewVisibility");
  53. InvokePropertyChanged("DataConfigViewVisibility");
  54. });
  55. Switch2DataDisplayViewCommand = new ChartingCommand((o) => true, (o) =>
  56. {
  57. DataConfigViewVisibility = Visibility.Collapsed;
  58. DataDisplayViewVisibility = Visibility.Visible;
  59. InvokePropertyChanged("DataDisplayViewVisibility");
  60. InvokePropertyChanged("DataConfigViewVisibility");
  61. });
  62. RenderableSeries = new ObservableCollection<IRenderableSeries>();
  63. DataSources = new Dictionary<string, IDataSource>();
  64. //显示或隐藏数据配置窗口
  65. ToggleDataDisplayPanelCommand = new ChartingCommand((o) => true, (o) =>
  66. {
  67. if (DataConfigViewRow != null)
  68. {
  69. DataConfigViewRow.Height = new GridLength(DataConfigViewRow.Height.Value > 0 ? 0 : 150);
  70. InvokePropertyChanged("IsDataConfigVisiable");
  71. }
  72. });
  73. //Charting控件的某些元素必须STA,UI主线程完成,因此此处需定义个DispatcherTimer来实现某些GUI相关的操作
  74. _dispatcherTimer = new DispatcherTimer();
  75. _dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100);
  76. _dispatcherTimer.Tick += new EventHandler(_dispatcherTimer_Tick);
  77. }
  78. public void Start()
  79. {
  80. if (_isAlive) return;
  81. _isAlive = true;
  82. System.Threading.Tasks.Task.Factory.StartNew(TaskRun);
  83. _dispatcherTimer.Start();
  84. }
  85. public void Stop()
  86. {
  87. _dispatcherTimer.Stop();
  88. _isAlive = false;
  89. }
  90. bool _isAlive = false;
  91. /// <summary>
  92. /// DispatcherTimer中定期处理一些和GUI相关的处理,例如新建、删除LineSeries对象等
  93. /// </summary>
  94. /// <param name="sender"></param>
  95. /// <param name="e"></param>
  96. void _dispatcherTimer_Tick(object sender, EventArgs e)
  97. {
  98. //执行命令队列中的指令
  99. if (_commandQueue.Count > 0)
  100. {
  101. if (!Monitor.TryEnter(_dataLocker))
  102. return;
  103. try
  104. {
  105. IEnumerable<ICommand> commandList = null;
  106. lock (_cmdQLocker)
  107. {
  108. commandList = _commandQueue.ToList();
  109. _commandQueue.Clear();
  110. }
  111. foreach (var command in commandList)
  112. {
  113. command.Execute(this);
  114. }
  115. }
  116. catch (Exception ex)
  117. {
  118. CONTEXT.WriteLog(ex);
  119. }
  120. finally
  121. {
  122. Monitor.Exit(_dataLocker);
  123. }
  124. }
  125. }
  126. DispatcherTimer _dispatcherTimer;
  127. //单实例定义
  128. private readonly static Lazy<CommonViewModel> _instance = new Lazy<CommonViewModel>(() => new CommonViewModel(), true);
  129. /// <summary>
  130. /// 获取当前对象的单实例
  131. /// </summary>
  132. public static CommonViewModel Instance
  133. {
  134. get
  135. {
  136. return _instance.Value;
  137. }
  138. }
  139. #region view switch
  140. public ICommand ToggleDataDisplayPanelCommand { get; set; }
  141. public Visibility DataConfigViewVisibility { get; private set; }
  142. public Visibility DataDisplayViewVisibility { get; private set; }
  143. public ICommand Switch2DataCfgViewCommand { get; set; }
  144. public ICommand Switch2DataDisplayViewCommand { get; set; }
  145. #endregion
  146. #region data source operations
  147. /// <summary>
  148. /// 生长率曲线相关的定义
  149. /// </summary>
  150. public MyLineSeries GrowthRateRenderableSeries { get; set; }
  151. public RowDefinition DataConfigViewRow { get; set; }
  152. public bool IsDataConfigVisiable { get { return DataConfigViewRow != null && DataConfigViewRow.Height.Value > 0; } }
  153. Queue<ICommand> _commandQueue = new Queue<ICommand>();
  154. object _cmdQLocker = new object();
  155. object _dataLocker = new object();
  156. public Dictionary<string, IDataSource> DataSources { get; set; }
  157. public ObservableCollection<IRenderableSeries> RenderableSeries { get; set; }
  158. public DateTime Time1 { get; set; } //时间标尺1
  159. public DateTime Time2 { get; set; } //时间标尺2
  160. IDataSource _currentSelectedDataSource;
  161. public IDataSource CurrentSelectedDataSource
  162. {
  163. get
  164. {
  165. return _currentSelectedDataSource;
  166. }
  167. set
  168. {
  169. if ((value != null) &&(_currentSelectedDataSource == null || _currentSelectedDataSource != value))
  170. {
  171. if (!string.IsNullOrEmpty(value.WaferDisplayIndex) &&
  172. (_currentSelectedDataSource == null ||
  173. !value.WaferDisplayIndex.Equals(_currentSelectedDataSource.WaferDisplayIndex)))
  174. {
  175. WaferDisplayIndex = value.WaferDisplayIndex;
  176. }
  177. else
  178. {
  179. WaferDisplayIndex = GetWaferDisplayIndex(value.BeginTime, value.ChamberName);
  180. }
  181. value.WaferDisplayIndex = WaferDisplayIndex;
  182. }
  183. _currentSelectedDataSource = value;
  184. if (_currentSelectedDataSource != null)
  185. CurrentSelectedDataSourceName = _currentSelectedDataSource.Title;
  186. InvokePropertyChanged("CurrentSelectedDataSource");
  187. InvokePropertyChanged("CurrentSelectedDataSourceName");
  188. }
  189. }
  190. /// <summary>
  191. /// 获取数据曲线对象
  192. /// </summary>
  193. /// <param name="uniqueDataId"></param>
  194. /// <returns></returns>
  195. public MyLineSeries GetDataLineSeries(string uniqueDataId)
  196. {
  197. for (int i = 0; i < RenderableSeries.Count; i++)
  198. {
  199. var line = RenderableSeries[i] as MyLineSeries;
  200. if (line != null && line.UniqueId == uniqueDataId)
  201. {
  202. return RenderableSeries[i] as MyLineSeries;
  203. }
  204. }
  205. return null;
  206. }
  207. public string CurrentSelectedDataSourceName
  208. {
  209. get;
  210. private set;
  211. }
  212. public ObservableCollection<IDataSource> DataSourceList
  213. {
  214. get
  215. {
  216. var ret = new ObservableCollection<IDataSource>();
  217. foreach (var key in DataSources.Keys)
  218. ret.Add(DataSources[key]);
  219. return ret;
  220. }
  221. }
  222. public List<string> DataSourceNameList
  223. {
  224. get
  225. {
  226. return DataSources.Keys.ToList();
  227. }
  228. }
  229. /// <summary>
  230. /// 移除先前绘制的生长率计算曲线
  231. /// </summary>
  232. public void ClearGrowthRateCurve()
  233. {
  234. lock (_cmdQLocker)
  235. {
  236. _commandQueue.Enqueue(new RemoveGrowthCurveCommand());
  237. }
  238. }
  239. /// <summary>
  240. /// 新增DataSource对象
  241. /// </summary>
  242. /// <param name="dataSource"></param>
  243. /// <returns></returns>
  244. public void AddDataSource(IDataSource dataSource)
  245. {
  246. lock (_cmdQLocker)
  247. {
  248. CONTEXT.WriteLog("添加数据源");
  249. _commandQueue.Enqueue(new AddDataSourceCommand(dataSource));
  250. }
  251. }
  252. /// <summary>
  253. /// 移除DataSource对象
  254. /// </summary>
  255. /// <param name="sourceName">移除指定的数据源,如果sourceName为null,则移除所有的数据源</param>
  256. /// <returns></returns>
  257. public void RemoveDataSource(string sourceName)
  258. {
  259. lock (_cmdQLocker)
  260. {
  261. _commandQueue.Enqueue(new RemoveDataSourceCommand(sourceName));
  262. }
  263. }
  264. #endregion
  265. #region data item operations
  266. /// <summary>
  267. /// 添加Data Item对象
  268. /// </summary>
  269. /// <param name="dataSourceName"></param>
  270. /// <param name="seriesName"></param>
  271. /// <param name="displayName"></param>
  272. /// <param name="lineColor"></param>
  273. /// <param name="factor"></param>
  274. /// <param name="offset"></param>
  275. /// <param name="lineWidth"></param>
  276. public void AddDataSeries(string dataSourceName, string seriesName, string displayName, Color lineColor, float factor, float offset, int lineWidth)
  277. {
  278. lock (_cmdQLocker)
  279. {
  280. _commandQueue.Enqueue(new AddDataSeriesCommand(dataSourceName, seriesName, displayName, lineColor, factor, offset, lineWidth));
  281. }
  282. }
  283. /// <summary>
  284. /// 显示所有当前数据
  285. /// </summary>
  286. public void ShowAllSeries()
  287. {
  288. lock (_cmdQLocker)
  289. {
  290. _commandQueue.Enqueue(new ShowAllSeriesCommand());
  291. }
  292. }
  293. /// <summary>
  294. /// 隐藏当前所有数据
  295. /// </summary>
  296. public void HidAllSeries()
  297. {
  298. lock (_cmdQLocker)
  299. {
  300. _commandQueue.Enqueue(new HidAllSeriesCommand());
  301. }
  302. }
  303. /// <summary>
  304. /// 显示预设的数据管理对话框
  305. /// </summary>
  306. public void LoadPresetSetting()
  307. {
  308. lock (_cmdQLocker)
  309. {
  310. _commandQueue.Enqueue(new LoadPresetSettingCommand());
  311. }
  312. }
  313. /// <summary>
  314. /// 数据源时间更新
  315. /// </summary>
  316. /// <param name="dataSourceName"></param>
  317. /// <param name="syncTimePoint"></param>
  318. /// <param name="syncStepName"></param>
  319. public void SyncSourceTime(string dataSourceName, DateTime syncTimePoint, string syncStepName)
  320. {
  321. lock (_cmdQLocker)
  322. {
  323. _commandQueue.Enqueue(new SourceTimeSyncCommand(dataSourceName, syncTimePoint, syncStepName));
  324. }
  325. }
  326. /// <summary>
  327. /// 数据缩放因子+Offset改变命令
  328. /// </summary>
  329. /// <param name="uniqueDataName"></param>
  330. /// <param name="newFactor"></param>
  331. public void ChangeDataDisplayFactor(string uniqueDataName, double newFactor, double newOffset)
  332. {
  333. lock (_cmdQLocker)
  334. {
  335. _commandQueue.Enqueue(new ChangeFactorOffsetCommand(uniqueDataName, newFactor, newOffset));
  336. }
  337. }
  338. /// <summary>
  339. /// 去除DataItem对象
  340. /// </summary>
  341. /// <param name="uniqueDataId"></param>
  342. public void RemoveDataSeries(string uniqueDataId)
  343. {
  344. lock (_cmdQLocker)
  345. {
  346. _commandQueue.Enqueue(new RemoveDataSeriesCommand(uniqueDataId));
  347. }
  348. }
  349. /// <summary>
  350. /// 保存当前所有数据
  351. /// </summary>
  352. public void ExportAllSeries()
  353. {
  354. lock (_cmdQLocker)
  355. {
  356. _commandQueue.Enqueue(new ExportAllSeriesCommand());
  357. }
  358. }
  359. #endregion
  360. private int GetIndex(List<string> Total, int index)
  361. {
  362. int _result = -1;
  363. //string[] _temp = Total.Split(',');
  364. //for (int i = 0; i < _temp.Length; i++)
  365. //{
  366. // if (_temp[i].PadLeft(2,'0').Equals(index.ToString().Trim().PadLeft(2,'0')))
  367. // {
  368. // _result = i+1;
  369. // break;
  370. // }
  371. //}
  372. _result = Total.FindIndex((x) => x == (index.ToString().Trim().PadLeft(2, '0')));
  373. if (_result >= 0) { _result++; }
  374. return _result;
  375. }
  376. #region thread - timely retrieve data
  377. /// <summary>
  378. /// data getting task
  379. /// </summary>
  380. void TaskRun()
  381. {
  382. while (_isAlive)
  383. {
  384. Thread.Sleep(100);
  385. try
  386. {
  387. //为提升效率,将线程从IDataSource对象获取数据的缓慢过程尽量和Chart对象通过UI线程的更新分开进行
  388. //通过Dictionary将数据进行当前线程内的暂时缓存
  389. List<Tuple<string/*data Id*/, DataItem/*data item*/, DateTime/*end time*/>> newDataDic =
  390. new List<Tuple<string, DataItem, DateTime>>();
  391. Dictionary<IDataSource, List<Tuple<IDataSource, string/*dataName*/, string/*dataId*/, DateTime/*beginTime*/, DateTime/*endTime*/>>> rqDataDic =
  392. new Dictionary<IDataSource, List<Tuple<IDataSource, string, string, DateTime, DateTime>>>();
  393. lock (_dataLocker)
  394. {
  395. foreach(MyLineSeries line in RenderableSeries)
  396. {
  397. if (DateTime.Now < line.NextQueryTime || line == null || line.DataSource == null)
  398. continue;
  399. IDataSource dataSource = line.DataSource; //数据源对象
  400. string chamName = dataSource.ChamberName; //Chamber名称
  401. DateTime lastUpdateTime = line.LastUpdateTime; //最后一次获取数据的时间
  402. DateTime dataEndTime = dataSource.EndTime; //数据源的结束时间
  403. if (lastUpdateTime >= dataEndTime)
  404. continue;
  405. DateTime nextDataTime = lastUpdateTime.Date + new TimeSpan(0, 23, 59, 59, 999); //ChartDataDic[dataId].Item4.LastUpdateTime + new TimeSpan(2, 0, 0);
  406. if (nextDataTime > dataEndTime) nextDataTime = dataEndTime;
  407. string dataName = line.SeriesName;
  408. //if(int.TryParse(WaferDisplayIndex.Split(',')[index-1],out index))
  409. if (!rqDataDic.ContainsKey(dataSource))
  410. rqDataDic.Add(dataSource, new List<Tuple<IDataSource, string, string, DateTime, DateTime>>());
  411. rqDataDic[dataSource].Add(new Tuple<IDataSource, string, string, DateTime, DateTime>(dataSource, dataName, line.UniqueId, lastUpdateTime, nextDataTime));
  412. }
  413. }
  414. //优化1:在此作判断,如果多个DataItem的如果在同一个DataSource中而且beginTime,EndTime完全一致,那么合并后进行Select Query可以进行加速
  415. foreach (var ds in rqDataDic.Keys)
  416. {
  417. var tempDic = new Dictionary<string, List<Tuple<IDataSource, string/*dataName*/, string/*dataId*/, DateTime/*beginTime*/, DateTime/*endTime*/>>>();
  418. foreach (var daq in rqDataDic[ds])
  419. {
  420. string id = string.Format("{0}-{1}", daq.Item4.Ticks, daq.Item5.Ticks);
  421. if (!tempDic.ContainsKey(id))
  422. tempDic.Add(id, new List<Tuple<IDataSource,string,string,DateTime,DateTime>>());
  423. tempDic[id].Add(daq);
  424. }
  425. //优化2:如果存在2组不同时间区间的数据请求,那么优化执行时间较早的数据请求,目的为了将多组不同时间段的请求合并为一个SQL语句,提升SQL查询效率
  426. DateTime earliestEndT = DateTime.MaxValue;
  427. foreach (var tickKey in tempDic.Keys)
  428. {
  429. var endT = tempDic[tickKey][0].Item5;
  430. if (endT < earliestEndT)
  431. earliestEndT = endT;
  432. }
  433. List<string>removeQueryList = new List<string>();
  434. foreach (var tickKey in tempDic.Keys)
  435. {
  436. var beginT = tempDic[tickKey][0].Item4;
  437. if (beginT > earliestEndT)
  438. removeQueryList.Add(tickKey);
  439. }
  440. foreach (var tickKey in removeQueryList)
  441. tempDic.Remove(tickKey);
  442. //database query
  443. foreach (var tickKey in tempDic.Keys)
  444. {
  445. List<string> dataNameList = new List<string>();
  446. List<string> dataIdList = new List<string>();
  447. foreach (var da in tempDic[tickKey])
  448. {
  449. dataNameList.Add(da.Item2);
  450. dataIdList.Add(da.Item3);
  451. }
  452. if (tempDic[tickKey].Count > 0)
  453. {
  454. List<DataItem> rtdata;
  455. var singleData = tempDic[tickKey][0];
  456. var dataSource = singleData.Item1;
  457. var beginT = singleData.Item4;
  458. var endT = singleData.Item5;
  459. var isSucc = dataSource.GetData(dataNameList, beginT, endT, out rtdata);
  460. if (isSucc)
  461. {
  462. for (int ss = 0; ss < dataIdList.Count; ss++)
  463. {
  464. newDataDic.Add(new Tuple<string, DataItem, DateTime>(dataIdList[ss], rtdata[ss], endT));
  465. }
  466. }
  467. }
  468. }
  469. }
  470. //对Chart对象的数据集进行集中更新
  471. Application.Current.Dispatcher.Invoke(new Action<List<Tuple<string/*data Id*/, DataItem/*data item*/, DateTime/*end time*/>>>((o) =>
  472. {
  473. if (o.Count > 0)
  474. {
  475. lock (_dataLocker)
  476. {
  477. var nextRetryQueryTime = DateTime.Now + new TimeSpan(0, 0, 0, 2);
  478. foreach (var item in o)
  479. {
  480. var dataId = item.Item1;
  481. var dataName = item.Item2.DataName;
  482. var line = GetDataLineSeries(dataId);
  483. if (line == null)
  484. continue;
  485. if (item.Item2.TimeStamp.Count == 0) //get nothing for this querying
  486. {
  487. if (item.Item3.Date >= DateTime.Now.Date)//possible data is still in generating today, try again 2 seconds later
  488. {
  489. line.NextQueryTime = nextRetryQueryTime;
  490. }
  491. else //data not available for this day, jump to query next day
  492. {
  493. line.NextQueryTime = DateTime.Now;
  494. line.LastUpdateTime = item.Item3.Date + new TimeSpan(1, 0, 0, 0);
  495. }
  496. }
  497. else //get something for this querying
  498. {
  499. //update next query time point
  500. line.NextQueryTime = DateTime.Now;
  501. if (item.Item3.Date >= DateTime.Now.Date) //update the last update time by exactly last data timestamp, for some more data is in generating state
  502. line.LastUpdateTime = item.Item2.TimeStamp[item.Item2.TimeStamp.Count - 1] + new TimeSpan(0, 0, 0, 0, 500);
  503. else
  504. line.LastUpdateTime = item.Item3.Date + new TimeSpan(1, 0, 0, 0);
  505. //write to data buf
  506. line.DataSource.Datas[dataName].RawData.AddRange(item.Item2.RawData);
  507. line.DataSource.Datas[dataName].TimeStamp.AddRange(item.Item2.TimeStamp);
  508. var timeMove = line.DataSource.TimeMove;
  509. var factorScale = (float)line.Factor;
  510. var offset = (float)line.Offset;
  511. var dataSet = line.DataSeries as DataSeries<DateTime, float>;
  512. if (timeMove.Ticks != 0 && (factorScale == 1 && offset == 0))
  513. {
  514. List<DateTime> movedTimeList = new List<DateTime>();
  515. foreach (var time1 in item.Item2.TimeStamp)
  516. {
  517. movedTimeList.Add(time1 + timeMove);
  518. }
  519. dataSet.Append(movedTimeList, item.Item2.RawData);
  520. }
  521. else if (timeMove.Ticks == 0 && (factorScale != 1 || offset != 0))
  522. {
  523. List<float> scaledValue = new List<float>();
  524. foreach (var value1 in item.Item2.RawData)
  525. {
  526. scaledValue.Add(value1 * factorScale + offset);
  527. }
  528. dataSet.Append(item.Item2.TimeStamp, scaledValue);
  529. }
  530. else if (timeMove.Ticks != 0 && (factorScale != 1|| offset != 0))
  531. {
  532. List<DateTime> movedTimeList = new List<DateTime>();
  533. List<float> scaledValue = new List<float>();
  534. foreach (var time1 in item.Item2.TimeStamp)
  535. {
  536. movedTimeList.Add(time1 + timeMove);
  537. }
  538. foreach (var value1 in item.Item2.RawData)
  539. {
  540. scaledValue.Add(value1 * factorScale + offset);
  541. }
  542. dataSet.Append(movedTimeList, scaledValue);
  543. }
  544. else
  545. {
  546. dataSet.Append(item.Item2.TimeStamp, item.Item2.RawData);
  547. }
  548. }
  549. }
  550. }
  551. InvokePropertyChanged("RenderableSeries");
  552. }
  553. }), newDataDic);
  554. }
  555. catch (Exception ex)
  556. {
  557. CONTEXT.WriteLog(ex, "Charting绘图Task运行发生异常");
  558. }
  559. }
  560. }
  561. #endregion
  562. }
  563. }