ProcessDetailViewModel.cs 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521
  1. using Aitex.Core.RT.Log;
  2. using Aitex.Core.UI.ControlDataContext;
  3. using Aitex.Core.Util;
  4. using Caliburn.Micro;
  5. using Caliburn.Micro.Core;
  6. using MECF.Framework.Common.CommonData;
  7. using MECF.Framework.Common.ControlDataContext;
  8. using MECF.Framework.Common.DataCenter;
  9. using MECF.Framework.Common.Utilities;
  10. using MECF.Framework.UI.Client.CenterViews.Configs.SystemConfig;
  11. using MECF.Framework.UI.Client.CenterViews.DataLogs.ProcessHistory;
  12. using MECF.Framework.UI.Client.CenterViews.Dialogs;
  13. using MECF.Framework.UI.Client.ClientBase;
  14. using OpenSEMI.ClientBase;
  15. using SciChart.Charting.Visuals;
  16. using SciChart.Charting.Visuals.Annotations;
  17. using SciChart.Charting.Visuals.Axes;
  18. using SciChart.Charting.Visuals.RenderableSeries;
  19. using SciChart.Data.Model;
  20. using System;
  21. using System.Collections.Concurrent;
  22. using System.Collections.Generic;
  23. using System.Collections.ObjectModel;
  24. using System.Data;
  25. using System.Diagnostics;
  26. using System.Drawing;
  27. using System.Linq;
  28. using System.Threading;
  29. using System.Threading.Tasks;
  30. using System.Windows;
  31. using Action = System.Action;
  32. using Media = System.Windows.Media;
  33. using System.Windows.Controls;
  34. using SciChart.Charting.Model.ChartData;
  35. using MECF.Framework.UI.Client.Converter;
  36. using MECF.Framework.UI.Client.CenterViews.Operations.RealTime;
  37. namespace MECF.Framework.UI.Client.CenterViews.DataLogs.ProcessHistory
  38. {
  39. public class StepInfo
  40. {
  41. public DateTime StartTime { get; set; }
  42. public DateTime StepEndTime { get; set; }
  43. public DateTime EndTime { get; set; }
  44. public string StepNo { get; set; }
  45. public string StepName { get; set; }
  46. public double StepTime { get; set; }
  47. public bool IsChecked { get; set; } = true;
  48. public string SubRecipeStepNumber { get; set; }
  49. public string SubRecipeStepName { get; set; }
  50. public string SubRecipeStepTime { get; set; }
  51. public string SubRecipeLoopInfo { get; set; }
  52. public string TempCorrection { get; set; }
  53. public string TempPid { get; set; }
  54. }
  55. public class ProcessDetailViewModel<T> : ModuleUiViewModelBase where T : IComparable
  56. {
  57. public class TimeChartDataLine : ChartDataLine<T>
  58. {
  59. public string Module { get; set; }
  60. public DateTime StartTime { get; set; }
  61. public DateTime EndTime { get; set; }
  62. public TimeChartDataLine(string dataName, string module, DateTime startTime, DateTime endTime) : base(dataName)
  63. {
  64. StartTime = startTime;
  65. EndTime = endTime;
  66. Module = module;
  67. }
  68. }
  69. public class QueryIndexer
  70. {
  71. public TimeChartDataLine DataLine { get; set; }
  72. public List<string> DataList { get; set; }
  73. public DateTime TimeToken { get; set; }
  74. }
  75. public bool IsPermission { get => this.Permission == 3; }
  76. private byte _directionByte = 0x03;
  77. private ProcessDetailView view;
  78. /// <summary>
  79. /// 正在导出数据事件。
  80. /// </summary>
  81. private event EventHandler Exporting;
  82. private CancellationTokenSource _cancellationTokenSource;
  83. #region Property
  84. private const int MAX_PARAMETERS = 20;
  85. private Queue<Color> colorQueue = new Queue<Color>(new Color[]{Color.Red,Color.Orange,Color.Yellow,Color.Green,Color.Blue,Color.Pink,Color.Purple,Color.Aqua,Color.Bisque,Color.Brown,Color.BurlyWood,Color.CadetBlue,
  86. Color.CornflowerBlue,Color.DarkBlue,Color.DarkCyan,Color.DarkGray,Color.DarkGreen,Color.DarkKhaki,Color.DarkMagenta,Color.DarkOliveGreen, Color.DarkOrange,
  87. Color.DarkSeaGreen,Color.DarkSlateBlue,Color.DarkSlateGray,Color.DarkViolet,Color.DeepPink,Color.DeepSkyBlue,Color.DimGray, Color.DodgerBlue,Color.ForestGreen, Color.Gold,
  88. Color.Gray,Color.GreenYellow,Color.HotPink,Color.Indigo,Color.Khaki,Color.LightBlue,Color.LightCoral,Color.LightGreen, Color.LightPink,Color.LightSalmon,Color.LightSkyBlue,
  89. Color.LightSlateGray,Color.LightSteelBlue,Color.LimeGreen,Color.MediumOrchid,Color.MediumPurple,Color.MediumSeaGreen,Color.MediumSlateBlue,Color.MediumSpringGreen,
  90. Color.MediumTurquoise,Color.Moccasin,Color.NavajoWhite,Color.Olive,Color.OliveDrab,Color.OrangeRed,Color.Orchid,Color.PaleGoldenrod,Color.PaleGreen,
  91. Color.PeachPuff,Color.Peru,Color.Plum,Color.PowderBlue,Color.RosyBrown,Color.RoyalBlue,Color.SaddleBrown,Color.Salmon,Color.SeaGreen, Color.Sienna,
  92. Color.SkyBlue,Color.SlateBlue,Color.SlateGray,Color.SpringGreen,Color.Teal,Color.Aquamarine,Color.Tomato,Color.Turquoise,Color.Violet,Color.Wheat, Color.YellowGreen});
  93. private ObservableCollection<ParameterNode> _ParameterNodes;
  94. public ObservableCollection<ParameterNode> ParameterNodes
  95. {
  96. get { return _ParameterNodes; }
  97. set { _ParameterNodes = value; NotifyOfPropertyChange("ParameterNodes"); }
  98. }
  99. public List<ParameterNode> DoubleParameterNodes { get; set; } = new List<ParameterNode>();
  100. public ObservableCollection<IRenderableSeries> SelectedData { get; set; }
  101. public ObservableCollection<IRenderableSeries> SynSelectedData { get; set; }
  102. public List<ProcessHistoryLot> RecipeDatas { get; set; }
  103. private static object _lockSelection = new object();
  104. private AutoRange _autoRange;
  105. public AutoRange ChartAutoRange
  106. {
  107. get { return _autoRange; }
  108. set
  109. {
  110. _autoRange = value;
  111. NotifyOfPropertyChange(nameof(ChartAutoRange));
  112. }
  113. }
  114. private IRange _timeRange;
  115. public IRange VisibleRangeTime
  116. {
  117. get { return _timeRange; }
  118. set
  119. {
  120. _timeRange = value;
  121. NotifyOfPropertyChange(nameof(VisibleRangeTime));
  122. }
  123. }
  124. private IRange _VisibleRangeValue;
  125. public IRange VisibleRangeValue
  126. {
  127. get { return _VisibleRangeValue; }
  128. set { _VisibleRangeValue = value; NotifyOfPropertyChange(nameof(VisibleRangeValue)); }
  129. }
  130. private PeriodicJob _thread;
  131. private ConcurrentBag<QueryIndexer> _lstTokenTimeData = new ConcurrentBag<QueryIndexer>();
  132. private Dictionary<string, string> _processDetailDisplayDic = new Dictionary<string, string>();
  133. private string _resolution;
  134. private AnnotationCollection _annotations;
  135. public AnnotationCollection Annotations
  136. {
  137. get => _annotations;
  138. set
  139. {
  140. _annotations = value;
  141. InvokePropertyChanged(nameof(Annotations));
  142. }
  143. }
  144. //StartTime,EndTime,StepNo,StepName
  145. private List<StepInfo> _stepInfo = new List<StepInfo>();
  146. public List<StepInfo> StepInfo
  147. {
  148. get { return _stepInfo; }
  149. set { _stepInfo = value; this.NotifyOfPropertyChange(nameof(StepInfo)); }
  150. }
  151. public bool IsStepVisiable => RecipeDatas.Count == 1;
  152. public DateTime StepStartTime { get; set; }
  153. public DateTime StepEndTime { get; set; }
  154. private bool _isAdding;
  155. private string _stepName;
  156. public string StepNameDisPlay
  157. {
  158. get { return _stepName; }
  159. set
  160. {
  161. if (_stepName != value)
  162. {
  163. _stepName = value;
  164. NotifyOfPropertyChange(nameof(StepNameDisPlay));
  165. }
  166. }
  167. }
  168. private string _recipeNameDisPlay;
  169. public string RecipeNameDisPlay
  170. {
  171. get { return _recipeNameDisPlay; }
  172. set
  173. {
  174. if (_recipeNameDisPlay != value)
  175. {
  176. _recipeNameDisPlay = value;
  177. NotifyOfPropertyChange(nameof(RecipeNameDisPlay));
  178. }
  179. }
  180. }
  181. private DateTime _pointTime;
  182. public DateTime PointTime
  183. {
  184. get { return _pointTime; }
  185. set
  186. {
  187. if (_pointTime != value)
  188. {
  189. _pointTime = value;
  190. NotifyOfPropertyChange(nameof(PointTime));
  191. }
  192. }
  193. }
  194. private double _lastPointX;
  195. private string _direction = "XYDirection";
  196. public string Direction
  197. {
  198. get { return _direction; }
  199. set
  200. {
  201. if (value != _direction)
  202. {
  203. _direction = value;
  204. if (_direction == "XDirection") _directionByte = 1;
  205. else if (_direction == "YDirection") _directionByte = 2;
  206. else if (_direction == "XYDirection") _directionByte = 3;
  207. NotifyOfPropertyChange(nameof(Direction));
  208. }
  209. }
  210. }
  211. //public Tuple<DateTime,double> _timePairs;
  212. private MultiLineXAxisLabelProvider _mulitiLineLabel;
  213. public MultiLineXAxisLabelProvider MultiLineLabel
  214. {
  215. get { return _mulitiLineLabel; }
  216. set
  217. {
  218. if (_mulitiLineLabel != value)
  219. {
  220. _mulitiLineLabel = value;
  221. NotifyOfPropertyChange(nameof(MultiLineLabel));
  222. }
  223. }
  224. }
  225. private double _xScale = 1;
  226. public double XScale
  227. {
  228. get { return _xScale; }
  229. set
  230. {
  231. if (_xScale != value)
  232. {
  233. _xScale = value;
  234. NotifyOfPropertyChange(nameof(XScale));
  235. }
  236. }
  237. }
  238. private double _yScale = 0.1;
  239. public double YScale
  240. {
  241. get { return _yScale; }
  242. set
  243. {
  244. if (value != _yScale)
  245. {
  246. _yScale = value;
  247. NotifyOfPropertyChange(nameof(YScale));
  248. }
  249. }
  250. }
  251. #endregion
  252. private RealtimeProvider _realtimeProvider;
  253. #region Function
  254. public ProcessDetailViewModel(List<ProcessHistoryLot> recipes)
  255. {
  256. _realtimeProvider = new RealtimeProvider();
  257. DisplayName = "Process Detail";
  258. RecipeDatas = recipes;
  259. ParameterNodes = _realtimeProvider.GetParameters(out var dict);
  260. DoubleParameterNodes = _realtimeProvider.GetParameters(out dict).ToList();
  261. for (int j = 0; j < ParameterNodes.Count; j++)
  262. {
  263. ParameterNodes[j].IsVisibilityParentNode = Visibility.Hidden;
  264. DoubleParameterNodes[j].IsVisibilityParentNode = Visibility.Hidden;
  265. }
  266. _processDetailDisplayDic = dict;
  267. if (recipes == null || recipes.Count == 0)
  268. {
  269. return;
  270. }
  271. SelectedData = new ObservableCollection<IRenderableSeries>();
  272. SynSelectedData = new ObservableCollection<IRenderableSeries>();
  273. VisibleRangeValue = new DoubleRange(0, 10);
  274. // Annotations = new AnnotationCollection();
  275. _thread = new PeriodicJob(200, MonitorData, "ProcessDetail", true);
  276. try
  277. {
  278. RecipeDatas.ToList().ForEach(recipe =>
  279. {
  280. QueryStep(recipe.StartTime, recipe.EndTime);
  281. });
  282. if (StepInfo != null && StepInfo.Count > 0)
  283. {
  284. StepStartTime = StepInfo.FirstOrDefault().StartTime;
  285. StepEndTime = StepInfo.LastOrDefault().EndTime;
  286. }
  287. MultiLineLabel = new MultiLineXAxisLabelProvider(StepStartTime);
  288. }
  289. catch (Exception ex)
  290. {
  291. LOG.Info(ex.StackTrace + ":" + ex.Message);
  292. }
  293. }
  294. protected override void OnViewLoaded(object view)
  295. {
  296. base.OnViewLoaded(view);
  297. this.view = (ProcessDetailView)view;
  298. }
  299. protected override void OnActivate()
  300. {
  301. _resolution = "f1";
  302. if (QueryDataClient.Instance.Service.GetConfig($"System.DataHistoryResolution") != null)
  303. _resolution = $"f{QueryDataClient.Instance.Service.GetConfig($"System.DataHistoryResolution")}";
  304. base.OnActivate();
  305. }
  306. public void QueryStep(DateTime starTime, DateTime endTime)//, string recipeName去掉查询recipeName名称,有嵌套调用
  307. {
  308. starTime = starTime.AddMinutes(-1);
  309. endTime = endTime.AddMinutes(1);
  310. string sql = $"SELECT * FROM \"process_data\" where (\"process_begin_time\" >= '{starTime:yyyy/MM/dd HH:mm:ss.fff}' and \"process_end_time\" <= '{endTime:yyyy/MM/dd HH:mm:ss.fff}') order by \"process_begin_time\" DESC;";
  311. DataTable dbData = QueryDataClient.Instance.Service.QueryData(sql);
  312. if (dbData != null && dbData.Rows.Count > 0)
  313. {
  314. List<ProcessDataLot> ProcessDataLotList = new List<ProcessDataLot>();
  315. for (int i = 0; i < dbData.Rows.Count; i++)
  316. {
  317. ProcessDataLot item = new ProcessDataLot();
  318. item.GUID = dbData.Rows[i]["guid"].ToString();
  319. item.RecipeName = dbData.Rows[i]["recipe_name"].ToString().Trim('\\');
  320. item.ProcessStatus = dbData.Rows[i]["process_status"].ToString();
  321. item.WaferDataGUID = dbData.Rows[i]["wafer_data_guid"].ToString();
  322. item.ProcessIn = dbData.Rows[i]["process_in"].ToString();
  323. if (!dbData.Rows[i]["process_begin_time"].Equals(DBNull.Value))
  324. {
  325. item.ProcessBeginTime = (DateTime)dbData.Rows[i]["process_begin_time"];
  326. }
  327. if (!dbData.Rows[i]["process_end_time"].Equals(DBNull.Value))
  328. {
  329. item.ProcessEndTime = (DateTime)dbData.Rows[i]["process_end_time"];
  330. }
  331. ProcessDataLotList.Add(item);
  332. }
  333. //Annotations.Add(VerLine(Media.Brushes.Blue, ProcessDataLotList[0].ProcessBeginTime, Media.Brushes.Blue, $"{ProcessDataLotList[0].RecipeName}"));
  334. //Annotations.Add(VerLine(Media.Brushes.Blue, ProcessDataLotList[0].ProcessEndTime, Media.Brushes.Blue, $"Recipe End"));
  335. string sql2 = $"SELECT * FROM \"recipe_step_data\" where";
  336. sql2 += $" \"recipe_step_data\".\"process_data_guid\" = '{ProcessDataLotList[0].GUID.ToString()}'";
  337. sql2 += " order by \"step_begin_time\" ASC;";
  338. using (var table = QueryDataClient.Instance.Service.QueryData(sql2))
  339. {
  340. if (!(table == null || table.Rows.Count == 0))
  341. {
  342. for (int i = 0; i < table.Rows.Count; i++)
  343. {
  344. var item = table.Rows[i];
  345. DateTime StartTime = DateTime.MinValue;
  346. DateTime EndTime = DateTime.MinValue;
  347. double stepTime = 0;
  348. if (!item["step_begin_time"].Equals(DBNull.Value))
  349. StartTime = (DateTime)item["step_begin_time"];
  350. if (!item["step_end_time"].Equals(DBNull.Value))
  351. EndTime = (DateTime)item["step_end_time"];
  352. if (!item["step_time"].Equals(DBNull.Value))
  353. {
  354. stepTime = (float)item["step_time"];
  355. }
  356. string stepNo = item["step_number"].ToString();
  357. string stepName = item["step_name"].ToString();
  358. if (StartTime > DateTime.MinValue && EndTime > DateTime.MinValue)
  359. {
  360. if (EndTime < StartTime.AddSeconds(stepTime))
  361. {
  362. EndTime = StartTime.AddSeconds(stepTime);
  363. }
  364. else
  365. {
  366. if (_stepInfo.Any())//临时处理表中recipe_step_data step_end_time数据不能真实反映步次结束时间的问题
  367. {
  368. int lastIndex = _stepInfo.Count - 1;
  369. if (_stepInfo[lastIndex].EndTime > StartTime) _stepInfo[lastIndex].EndTime = StartTime;
  370. }
  371. _stepInfo.Add(new StepInfo() { StartTime = StartTime, EndTime = EndTime, StepName = stepName, StepTime = stepTime, StepNo = stepNo });
  372. }
  373. }
  374. }
  375. }
  376. }
  377. }
  378. }
  379. public static VerticalLineAnnotation VerLine(Media.Brush stroke, DateTime x, Media.Brush color, string text)
  380. {
  381. var label = new AnnotationLabel()
  382. {
  383. LabelPlacement = LabelPlacement.TopRight,
  384. FontSize = 12,
  385. RotationAngle = 0,
  386. Foreground = color,
  387. Text = text
  388. };
  389. var line = new VerticalLineAnnotation()
  390. {
  391. Stroke = stroke,
  392. StrokeThickness = 1,
  393. X1 = x,
  394. IsEditable = false,
  395. VerticalAlignment = VerticalAlignment.Stretch,
  396. AnnotationLabels = new ObservableCollection<AnnotationLabel>() { label },
  397. };
  398. return line;
  399. }
  400. protected bool MonitorData()
  401. {
  402. try
  403. {
  404. if (_isAdding)
  405. return true;
  406. bool allUpdated = true;
  407. lock (_lockSelection)
  408. {
  409. foreach (var item in _lstTokenTimeData)
  410. {
  411. DateTime timeFrom = item.TimeToken;
  412. if (timeFrom >= item.DataLine.EndTime)
  413. continue;
  414. allUpdated = false;
  415. ChartAutoRange = AutoRange.Always;
  416. DateTime timeTo = timeFrom.AddMinutes(60);
  417. if (timeTo.DayOfYear > timeFrom.DayOfYear)
  418. timeTo = new DateTime(timeFrom.Year, timeFrom.Month, timeFrom.Day).AddDays(1);
  419. if (timeTo > item.DataLine.EndTime)
  420. timeTo = item.DataLine.EndTime;
  421. item.TimeToken = timeTo;
  422. GetData(item.DataList, timeFrom, timeTo, item.DataLine.Module, item.DataLine.DataSource);
  423. #region Update VisualMin、VisualMax、DataStatisticsInfo
  424. Application.Current.Dispatcher.BeginInvoke(new Action(() =>
  425. {
  426. double min = ((DoubleRange)VisibleRangeValue).Min;
  427. double max = ((DoubleRange)VisibleRangeValue).Max;
  428. int PointCount = 0;
  429. foreach (var selectedData in SelectedData)
  430. {
  431. var seriesItem = selectedData as ChartDataLine<T>;
  432. if (seriesItem == null)
  433. continue;
  434. double sumValue = 0;
  435. double minValue = 100000;
  436. double maxValue = 0;
  437. double averageValue = 0;
  438. double stdevValue = 0;
  439. double sigma3Value = 0;
  440. var pointValueList = seriesItem.Points.Select(x => x.Item2).ToList();
  441. for (int i = 0; i < pointValueList.Count; i++)
  442. {
  443. sumValue += pointValueList[i];
  444. if (pointValueList[i] < minValue)
  445. minValue = pointValueList[i];
  446. if (pointValueList[i] > maxValue)
  447. maxValue = pointValueList[i];
  448. }
  449. averageValue = pointValueList.Count == 0 ? 0 : sumValue / pointValueList.Count;
  450. for (int i = 0; i < pointValueList.Count; i++)
  451. {
  452. stdevValue += Math.Pow(pointValueList[i] - averageValue, 2);
  453. }
  454. stdevValue = pointValueList.Count == 0 ? 0 : stdevValue / pointValueList.Count;
  455. sigma3Value = Math.Sqrt(stdevValue) * 3;
  456. (seriesItem.Tag as ParameterNode).AverageValue = averageValue.ToString("F2");
  457. (seriesItem.Tag as ParameterNode).MinValue = minValue.ToString("F2");
  458. (seriesItem.Tag as ParameterNode).MaxValue = maxValue.ToString("F2");
  459. (seriesItem.Tag as ParameterNode).Sigma3Value = sigma3Value.ToString("F2");
  460. min = minValue;
  461. if (maxValue != max)
  462. max = maxValue * 1.1;
  463. PointCount = pointValueList.Count;
  464. }
  465. VisibleRangeValue = new DoubleRange(min, max);
  466. }));
  467. #endregion
  468. }
  469. }
  470. if (allUpdated)
  471. {
  472. lock (_lockSelection)
  473. {
  474. while (_lstTokenTimeData.Count > 0)
  475. {
  476. _lstTokenTimeData.TryTake(out _);
  477. }
  478. ChartAutoRange = AutoRange.Never;
  479. }
  480. }
  481. }
  482. catch (Exception ex)
  483. {
  484. LOG.Error(ex.Message);
  485. }
  486. return true;
  487. }
  488. private void GetData(List<string> keys, DateTime from, DateTime to, string module, string dataSource)
  489. {
  490. string sql = "select time AS InternalTimeStamp";
  491. foreach (var dataKey in keys)
  492. {
  493. var dataId = _processDetailDisplayDic.ContainsKey(dataKey) ? _processDetailDisplayDic[dataKey] : dataKey;
  494. sql += "," + string.Format("\"{0}\"", dataId);
  495. }
  496. sql += string.Format(" from \"{0}\" where time > {1} and time <= {2} order by time asc",
  497. from.ToString("yyyyMMdd") + "." + module, from.Ticks, to.Ticks);
  498. DataTable dataTable = QueryDataClient.Instance.Service.QueryData(sql);
  499. Dictionary<string, List<HistoryDataItem>> historyData = new Dictionary<string, List<HistoryDataItem>>();
  500. if (dataTable == null || dataTable.Rows.Count == 0)
  501. return;
  502. DateTime dt = new DateTime();
  503. Dictionary<int, string> colName = new Dictionary<int, string>();
  504. for (int colNo = 0; colNo < dataTable.Columns.Count; colNo++)
  505. {
  506. colName.Add(colNo, dataTable.Columns[colNo].ColumnName);
  507. historyData[dataTable.Columns[colNo].ColumnName] = new List<HistoryDataItem>();
  508. }
  509. for (int rowNo = 0; rowNo < dataTable.Rows.Count; rowNo++)
  510. {
  511. var row = dataTable.Rows[rowNo];
  512. for (int i = 0; i < dataTable.Columns.Count; i++)
  513. {
  514. HistoryDataItem data = new HistoryDataItem();
  515. if (i == 0)
  516. {
  517. dt = new DateTime((long)row[i]);
  518. continue;
  519. }
  520. else
  521. {
  522. string dataId = colName[i];
  523. if (row[i] is DBNull || row[i] == null)
  524. {
  525. data.dateTime = dt;
  526. data.dbName = colName[i];
  527. data.value = 0;
  528. }
  529. else if (row[i] is bool)
  530. {
  531. data.dateTime = dt;
  532. data.dbName = colName[i];
  533. data.value = (bool)row[i] ? 1 : 0;
  534. }
  535. else
  536. {
  537. data.dateTime = dt;
  538. data.dbName = colName[i];
  539. var value = float.Parse(row[i].ToString()).ToString(_resolution);
  540. data.value = float.Parse(value);
  541. }
  542. }
  543. historyData[data.dbName].Add(data);
  544. }
  545. }
  546. Application.Current.Dispatcher.BeginInvoke(new Action(() =>
  547. {
  548. try
  549. {
  550. FillDataToChart(SelectedData, dataSource, historyData);
  551. FillDataToChart(SynSelectedData, dataSource, historyData);
  552. RefresCharView();
  553. }
  554. catch (Exception ex)
  555. {
  556. LOG.Write(ex);
  557. }
  558. }));
  559. }
  560. void FillDataToChart(ObservableCollection<IRenderableSeries> series, string dataSource, Dictionary<string, List<HistoryDataItem>> historyData)
  561. {
  562. var items = series.Where(x => (x as ChartDataLine<T>).DataSource == dataSource);
  563. if (items == null) return;
  564. foreach (var item in items)
  565. {
  566. var seriesItem = item as ChartDataLine<T>;
  567. if (seriesItem == null)
  568. continue;
  569. foreach (var data in historyData)
  570. {
  571. var dataKey = _processDetailDisplayDic.ContainsKey(seriesItem.DataName) ? _processDetailDisplayDic[seriesItem.DataName] : seriesItem.DataName;
  572. if (data.Key != dataKey)
  573. continue;
  574. seriesItem.Capacity += data.Value.Count;
  575. //DateTime beginTime = StepStartTime;
  576. for (int i = 0; i < data.Value.Count; i++)
  577. {
  578. var historyDataItem = data.Value[i];
  579. if (typeof(T) == typeof(double))
  580. {
  581. //xData = Math.Round((historyDataItem.dateTime - beginTime).TotalMilliseconds / 1000, 0, MidpointRounding.AwayFromZero);
  582. seriesItem.Append((T)Convert.ChangeType((historyDataItem.dateTime - StepStartTime).TotalMilliseconds / 1000d, typeof(T)), historyDataItem.value);
  583. }
  584. else
  585. seriesItem.Append((T)Convert.ChangeType(historyDataItem.dateTime, typeof(T)), historyDataItem.value);
  586. }
  587. }
  588. }
  589. }
  590. /// <summary>
  591. /// 获取时间列表
  592. /// </summary>
  593. /// <param name="from"></param>
  594. /// <param name="to"></param>
  595. /// <param name="module"></param>
  596. /// <param name="dataSource"></param>
  597. private void GetData(DateTime from, DateTime to, string module = "PM1")
  598. {
  599. string sql = "select time AS InternalTimeStamp,\"PM1.RecipeTotalElapseTime\"";
  600. sql += string.Format(" from \"{0}\" where time > {1} and time <= {2} order by time limt 1",
  601. from.ToString("yyyyMMdd") + "." + module, from.Ticks, to.Ticks);
  602. DataTable dataTable = QueryDataClient.Instance.Service.QueryData(sql);
  603. Dictionary<string, List<HistoryDataItem>> historyData = new Dictionary<string, List<HistoryDataItem>>();
  604. if (dataTable == null || dataTable.Rows.Count == 0)
  605. {
  606. return;
  607. }
  608. foreach (DataRow row in dataTable.Rows)
  609. {
  610. DateTime dt = new DateTime();
  611. dt = new DateTime((long)row[0]);
  612. var elapseTime = Convert.ToDouble(row[1]);
  613. }
  614. }
  615. private void SelectedDataChanged()
  616. {
  617. foreach (var item in SelectedData)
  618. {
  619. if (item.Stroke.Equals(System.Windows.Media.Color.FromArgb(255, 0, 0, 255)))
  620. {
  621. Color drawingColor = colorQueue.Peek();
  622. item.Stroke = System.Windows.Media.Color.FromRgb(drawingColor.R, drawingColor.G, drawingColor.B);
  623. colorQueue.Enqueue(colorQueue.Dequeue());
  624. }
  625. }
  626. }
  627. public void TxtMouseLeftButtonDown(ParameterNode node, ObservableCollection<IRenderableSeries> series)
  628. {
  629. node.Selected = !node.Selected;
  630. ParameterCheck(node, series);
  631. }
  632. public void ParameterCheck(ParameterNode node, ObservableCollection<IRenderableSeries> series)
  633. {
  634. bool result = RefreshTreeStatusToChild(node, series);
  635. if (!result)
  636. {
  637. node.Selected = !node.Selected;
  638. DialogBox.ShowWarning($"The max number of parameters is {MAX_PARAMETERS}.");
  639. }
  640. else
  641. RefreshTreeStatusToParent(node);
  642. }
  643. /// <summary>
  644. /// Refresh tree node status from current to children, and add data to SelectedData
  645. /// </summary>
  646. private bool RefreshTreeStatusToChild(ParameterNode node, ObservableCollection<IRenderableSeries> SelectedData)
  647. {
  648. if (node?.ChildNodes.Count > 0)
  649. {
  650. for (int i = 0; i < node.ChildNodes.Count; i++)
  651. {
  652. ParameterNode n = node.ChildNodes[i];
  653. n.Selected = node.Selected;
  654. if (!RefreshTreeStatusToChild(n, SelectedData))
  655. {
  656. n.Selected = !n.Selected;
  657. return false;
  658. }
  659. }
  660. }
  661. else //leaf node
  662. {
  663. bool lockTaken = false;
  664. try
  665. {
  666. var item = SelectedData?.FirstOrDefault(x => (x as ChartDataLine<T>).DataName == node.Name);
  667. bool isExist = item != null;
  668. if (isExist && !node.Selected)//删除
  669. {
  670. SelectedData.Remove(item);
  671. }
  672. else
  673. {
  674. if (!isExist && node.Selected)
  675. {
  676. if (SelectedData.Count >= MAX_PARAMETERS)
  677. {
  678. return false;
  679. }
  680. Monitor.TryEnter(_lockSelection, 1000, ref lockTaken);
  681. if (lockTaken)
  682. {
  683. var dataId = _processDetailDisplayDic.ContainsKey(node.Name) ? _processDetailDisplayDic[node.Name] : node.Name;
  684. var module = dataId.Split('.').ToList()[0];
  685. _isAdding = true;
  686. foreach (var recipe in RecipeDatas)
  687. {
  688. TimeChartDataLine line;
  689. if (IsStepVisiable)
  690. line = new TimeChartDataLine(node.Name.Replace("Tube", "PM1"), module, StepStartTime, StepEndTime);
  691. else
  692. line = new TimeChartDataLine(node.Name.Replace("Tube", "PM1"), module, recipe.StartTime, recipe.EndTime);
  693. line.DataSource = $"{recipe.BatchID}.{recipe.RecipeName}";
  694. line.Tag = node;
  695. if (isExist)
  696. {
  697. line.Stroke = item.Stroke;
  698. line.IsVisible = item.IsVisible;
  699. line.ClearData();
  700. SelectedData.Remove(item);
  701. }
  702. else
  703. SelectedData.Add(line);
  704. AddToMonitor(line);
  705. }
  706. _isAdding = false;
  707. if (!isExist)
  708. SelectedDataChanged();
  709. }
  710. }
  711. }
  712. }
  713. finally
  714. {
  715. if (lockTaken)
  716. {
  717. Monitor.Exit(_lockSelection);
  718. }
  719. }
  720. }
  721. return true;
  722. }
  723. private void AddToMonitor(TimeChartDataLine line)
  724. {
  725. QueryIndexer indexer = new QueryIndexer()
  726. {
  727. DataLine = line,
  728. DataList = new List<string>() { line.DataName },
  729. TimeToken = line.StartTime,
  730. };
  731. _lstTokenTimeData.Add(indexer);
  732. }
  733. /// <summary>
  734. /// Refresh tree node status from current to parent
  735. /// </summary>
  736. /// <param name="node"></param>
  737. /// <returns></returns>
  738. private void RefreshTreeStatusToParent(ParameterNode node)
  739. {
  740. if (node.ParentNode != null)
  741. {
  742. if (node.Selected)
  743. {
  744. bool flag = true;
  745. for (int i = 0; i < node.ParentNode.ChildNodes.Count; i++)
  746. {
  747. if (!node.ParentNode.ChildNodes[i].Selected)
  748. {
  749. flag = false; //as least one child is unselected
  750. break;
  751. }
  752. }
  753. if (flag)
  754. node.ParentNode.Selected = true;
  755. }
  756. else
  757. {
  758. node.ParentNode.Selected = false;
  759. }
  760. RefreshTreeStatusToParent(node.ParentNode);
  761. }
  762. }
  763. #region Parameter Grid Control
  764. public void DeleteAll()
  765. {
  766. //uncheck all tree nodes
  767. foreach (ChartDataLine<T> cp in SelectedData)
  768. {
  769. (cp.Tag as ParameterNode).Selected = false;
  770. RefreshTreeStatusToParent(cp.Tag as ParameterNode);
  771. }
  772. SelectedData.Clear();
  773. }
  774. private void SetParameterNode(ObservableCollection<ParameterNode> nodes, bool isChecked)
  775. {
  776. foreach (ParameterNode n in nodes)
  777. {
  778. n.Selected = isChecked;
  779. SetParameterNode(n.ChildNodes, isChecked);
  780. }
  781. }
  782. public void Delete(ChartDataLine<T> cp)
  783. {
  784. if (cp != null)
  785. {
  786. if (SelectedData.Contains(cp))
  787. {
  788. //uncheck tree node
  789. (cp.Tag as ParameterNode).Selected = false;
  790. RefreshTreeStatusToParent(cp.Tag as ParameterNode);
  791. SelectedData.Remove(cp);
  792. }
  793. }
  794. }
  795. public async void ExportAll()
  796. {
  797. try
  798. {
  799. if (SelectedData.Count == 0)
  800. {
  801. MessageBox.Show($"Please select the data you want to export.", "Export", MessageBoxButton.OK,
  802. MessageBoxImage.Warning);
  803. return;
  804. }
  805. Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
  806. dlg.DefaultExt = ".xlsx"; // Default file extension
  807. dlg.Filter = "Excel数据表格文件(*.xlsx)|*.xlsx"; // Filter files by extension
  808. dlg.FileName = $"{DisplayName}_{string.Join(",", RecipeDatas.Select(x => x.RecipeName.Replace('\\', '.')).ToArray())}_{DateTime.Now:yyyyMMdd_HHmmss}";
  809. Nullable<bool> result = dlg.ShowDialog();// Show open file dialog box
  810. if (result == true) // Process open file dialog box results
  811. {
  812. Exporting?.Invoke(this, System.EventArgs.Empty);
  813. _cancellationTokenSource = new CancellationTokenSource();
  814. var sw = new Stopwatch();
  815. sw.Restart();
  816. System.Data.DataSet ds = new System.Data.DataSet();
  817. ds.Tables.Add(new System.Data.DataTable($"{DisplayName}_{DateTime.Now:yyyyMMdd_HHmmss}"));
  818. ds.Tables[0].Columns.Add("Recipe Info");
  819. ds.Tables[0].Columns[0].DataType = typeof(string);
  820. ds.Tables[0].Columns.Add("Date");
  821. ds.Tables[0].Columns[1].DataType = typeof(string);
  822. ds.Tables[0].Columns.Add("Time");
  823. ds.Tables[0].Columns[2].DataType = typeof(string);
  824. ds.Tables[0].Columns.Add("Step ID");
  825. ds.Tables[0].Columns[3].DataType = typeof(string);
  826. ds.Tables[0].Columns.Add("Step Name");
  827. ds.Tables[0].Columns[4].DataType = typeof(string);
  828. Dictionary<T, double[]> timeValue = new Dictionary<T, double[]>();
  829. await Task.Run(() =>
  830. {
  831. for (int i = 0; i < SelectedData.Count; i++)
  832. {
  833. List<Tuple<T, double>> data = (SelectedData[i] as ChartDataLine<T>).Points;
  834. foreach (var tuple in data)
  835. {
  836. if (!timeValue.ContainsKey(tuple.Item1))
  837. timeValue[tuple.Item1] = new double[SelectedData.Count];
  838. timeValue[tuple.Item1][i] = tuple.Item2;
  839. }
  840. ds.Tables[0].Columns.Add((SelectedData[i] as ChartDataLine<T>).DataName);
  841. ds.Tables[0].Columns[i + 5].DataType = typeof(double);
  842. }
  843. var recipeInfoRow = ds.Tables[0].NewRow();
  844. recipeInfoRow[0] = $"Recipe:{string.Join(",", RecipeDatas.Select(x => x.RecipeName).ToArray())}";
  845. ds.Tables[0].Rows.Add(recipeInfoRow);
  846. recipeInfoRow = ds.Tables[0].NewRow();
  847. recipeInfoRow[0] = $"Start Time";
  848. recipeInfoRow[1] = string.Join(",", RecipeDatas.Select(x => x.StartTime).ToArray());
  849. recipeInfoRow[2] = string.Join(",", RecipeDatas.Select(x => x.StartTime).ToArray());
  850. ds.Tables[0].Rows.Add(recipeInfoRow);
  851. recipeInfoRow = ds.Tables[0].NewRow();
  852. recipeInfoRow[0] = $"End Time";
  853. recipeInfoRow[1] = string.Join(",", RecipeDatas.Select(x => x.EndTime).ToArray());
  854. recipeInfoRow[2] = string.Join(",", RecipeDatas.Select(x => x.EndTime).ToArray());
  855. ds.Tables[0].Rows.Add(recipeInfoRow);
  856. QueryDataClientFromTable(ds);
  857. }, _cancellationTokenSource.Token).ContinueWith(t =>
  858. {
  859. if (t.IsCanceled || t.IsFaulted)
  860. return;
  861. });
  862. if (_cancellationTokenSource?.Token.IsCancellationRequested == true)
  863. return;
  864. if (!ExcelHelper.ExportToExcel(dlg.FileName, ds, out string reason))
  865. {
  866. MessageBox.Show($"Export failed, {reason}", "Export", MessageBoxButton.OK, MessageBoxImage.Warning);
  867. return;
  868. }
  869. MessageBox.Show($"Export succeed, file save as {dlg.FileName}", "Export", MessageBoxButton.OK, MessageBoxImage.Information);
  870. }
  871. }
  872. catch (Exception ex)
  873. {
  874. LOG.Write(ex);
  875. MessageBox.Show("Write failed," + ex.Message, "export failed", MessageBoxButton.OK, MessageBoxImage.Warning);
  876. }
  877. }
  878. public void DGSelectionChanged(object sender, EventArgs e)
  879. {
  880. var temp = (DataGrid)sender;
  881. var tempSelected = (IRenderableSeries)temp.SelectedItem;
  882. tempSelected.IsVisible = !tempSelected.IsVisible;
  883. }
  884. private void QueryDataClientFromTable(DataSet ds)
  885. {
  886. DateTime startTime = StepStartTime;
  887. DateTime endTime = StepEndTime;
  888. if (StepStartTime.Date == StepEndTime.Date)
  889. {
  890. SaveDataToTable(ds, startTime, endTime);
  891. }
  892. else
  893. {
  894. endTime = new DateTime(startTime.Year, startTime.Month, startTime.Day, 23, 59, 59);
  895. while (endTime < StepEndTime)
  896. {
  897. SaveDataToTable(ds, startTime, endTime);
  898. startTime = new DateTime(startTime.Year, startTime.Month, startTime.Day, 0, 0, 0).AddDays(1);
  899. endTime = new DateTime(startTime.Year, startTime.Month, startTime.Day, 23, 59, 59);
  900. }
  901. SaveDataToTable(ds, startTime, StepEndTime);
  902. }
  903. }
  904. private void SaveDataToTable(DataSet ds, DateTime startTime, DateTime endTime)
  905. {
  906. string stepID = "", stepName = "";
  907. string pmsql = "select time AS InternalTimeStamp";
  908. var pmColNames = _realtimeProvider.GetDBCol(startTime.ToString("yyyyMMdd") + "." + "PM1");
  909. List<string> keys = SelectedData.Select(x => (x as ChartDataLine<T>).DataName).ToList();
  910. DataTable pmDataTable = null;
  911. if (keys != null && keys.Count > 0)
  912. {
  913. List<string> pmList = new List<string>();
  914. foreach (var dataKey in keys)
  915. {
  916. var dataId = _processDetailDisplayDic.ContainsKey(dataKey) ? _processDetailDisplayDic[dataKey] : dataKey;
  917. var module = dataId.Split('.').ToList()[0];
  918. if (module.ToLower() == "pm1")
  919. {
  920. if (!pmColNames.Contains(dataId))
  921. {
  922. continue;
  923. }
  924. pmList.Add(dataId);
  925. pmsql += "," + string.Format("\"{0}\"", dataId);
  926. }
  927. }
  928. if (pmList.Count > 0)
  929. {
  930. pmsql += string.Format(" from \"{0}\" where time > {1} and time <= {2} order by time asc",
  931. startTime.ToString("yyyyMMdd") + "." + "PM1", startTime.Ticks, endTime.Ticks);
  932. pmDataTable = QueryDataClient.Instance.Service.QueryData(pmsql);
  933. if (pmDataTable == null)
  934. {
  935. MessageBox.Show($"Export failed, sql:{pmsql}", "Export", MessageBoxButton.OK, MessageBoxImage.Warning);
  936. return;
  937. }
  938. }
  939. }
  940. string systemsql = "select time AS InternalTimeStamp";
  941. var systemColNames = _realtimeProvider.GetDBCol(startTime.ToString("yyyyMMdd") + "." + "System");
  942. DataTable systemDataTable = null;
  943. if (keys != null && keys.Count > 0)
  944. {
  945. List<string> systemList = new List<string>();
  946. foreach (var dataKey in keys)
  947. {
  948. var dataId = _processDetailDisplayDic.ContainsKey(dataKey) ? _processDetailDisplayDic[dataKey] : dataKey;
  949. var module = dataId.Split('.').ToList()[0];
  950. if (module.ToLower() == "system")
  951. {
  952. if (!systemColNames.Contains(dataId))
  953. {
  954. continue;
  955. }
  956. systemsql += "," + string.Format("\"{0}\"", dataId);
  957. systemList.Add(dataId);
  958. }
  959. }
  960. if (systemList.Count > 0)
  961. {
  962. systemsql += string.Format(" from \"{0}\" where time > {1} and time <= {2} order by time asc",
  963. startTime.ToString("yyyyMMdd") + "." + "System", startTime.Ticks, endTime.Ticks);
  964. systemDataTable = QueryDataClient.Instance.Service.QueryData(systemsql);
  965. if (systemDataTable == null)
  966. {
  967. MessageBox.Show($"Export failed, sql:{systemsql}", "Export", MessageBoxButton.OK, MessageBoxImage.Warning);
  968. return;
  969. }
  970. }
  971. }
  972. int maxRow = 0;
  973. if ((pmDataTable == null || pmDataTable.Rows.Count == 0))
  974. {
  975. if (systemDataTable != null)
  976. {
  977. maxRow = systemDataTable.Rows.Count;
  978. }
  979. }
  980. else if ((systemDataTable == null || systemDataTable.Rows.Count == 0))
  981. {
  982. if (pmDataTable != null)
  983. {
  984. maxRow = pmDataTable.Rows.Count;
  985. }
  986. }
  987. else
  988. {
  989. maxRow = pmDataTable.Rows.Count > systemDataTable.Rows.Count ? systemDataTable.Rows.Count : pmDataTable.Rows.Count;
  990. }
  991. for (int i = 0; i < maxRow; i++)
  992. {
  993. var pmRow = pmDataTable != null ? pmDataTable.Rows[i] : null;
  994. var systemRow = systemDataTable != null ? systemDataTable.Rows[i] : null;
  995. //float timeIndex = 0;
  996. //float.TryParse(item.Key.ToString(), out timeIndex);
  997. //DateTime dateTimeKey = startTime.AddMilliseconds(timeIndex * 1000); ;// DateTime.Parse(item.Key.ToString());
  998. DateTime dateTimeKey = new DateTime(pmRow != null ? (long)pmRow[0] : (long)systemRow[0]);
  999. var tempStepInfo = _stepInfo.FirstOrDefault(x => x.StartTime < dateTimeKey && x.EndTime > dateTimeKey);
  1000. if (tempStepInfo != null)// && dateTimeKey > _stepInfo[iIndex].StartTime
  1001. {
  1002. stepID = tempStepInfo.StepNo;
  1003. stepName = tempStepInfo.StepName;
  1004. }
  1005. var row = ds.Tables[0].NewRow();
  1006. row[1] = dateTimeKey.ToString("yyyy/MM/dd");
  1007. row[2] = dateTimeKey.ToString("HH:mm:ss:fff");
  1008. row[3] = stepID;
  1009. row[4] = stepName;
  1010. for (int j = 5; j < ds.Tables[0].Columns.Count; j++)
  1011. {
  1012. string colName = ds.Tables[0].Columns[j].ColumnName;
  1013. DataRow dataRow = null;
  1014. var dataId = _processDetailDisplayDic.ContainsKey(colName) ? _processDetailDisplayDic[colName] : colName;
  1015. var module = dataId.Split('.').ToList()[0];
  1016. int index = 0;
  1017. if (module == "PM1")
  1018. {
  1019. dataRow = pmRow;
  1020. foreach (var item in pmDataTable.Columns)
  1021. {
  1022. if (((DataColumn)item).ColumnName == dataId)
  1023. {
  1024. break;
  1025. }
  1026. index++;
  1027. }
  1028. }
  1029. else if (module == "System")
  1030. {
  1031. dataRow = systemRow;
  1032. foreach (var item in systemDataTable.Columns)
  1033. {
  1034. if (((DataColumn)item).ColumnName == dataId)
  1035. {
  1036. break;
  1037. }
  1038. index++;
  1039. }
  1040. }
  1041. if (dataRow[index] is DBNull || dataRow[index] == null)
  1042. {
  1043. row[j] = dataRow[index];
  1044. }
  1045. else if (dataRow[index] is bool)
  1046. {
  1047. row[j] = (bool)dataRow[index] ? 1 : 0;
  1048. }
  1049. else
  1050. {
  1051. var value = float.Parse(dataRow[index].ToString()).ToString(_resolution);
  1052. row[j] = float.Parse(value);
  1053. }
  1054. }
  1055. ds.Tables[0].Rows.Add(row);
  1056. }
  1057. }
  1058. public void Export(ChartDataLine<T> cp)
  1059. {
  1060. try
  1061. {
  1062. Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
  1063. dlg.DefaultExt = ".xlsx"; // Default file extension
  1064. dlg.Filter = "Excel数据表格文件(*.xlsx)|*.xlsx"; // Filter files by extension
  1065. dlg.FileName = $"{cp.DataName}_{DateTime.Now:yyyyMMdd_HHmmss}";
  1066. Nullable<bool> result = dlg.ShowDialog();// Show open file dialog box
  1067. if (result == true) // Process open file dialog box results
  1068. {
  1069. System.Data.DataSet ds = new System.Data.DataSet();
  1070. ds.Tables.Add(new System.Data.DataTable(cp.DataName));
  1071. ds.Tables[0].Columns.Add("Time");
  1072. ds.Tables[0].Columns[0].DataType = typeof(DateTime);
  1073. ds.Tables[0].Columns.Add(cp.DataName);
  1074. ds.Tables[0].Columns[1].DataType = typeof(double);
  1075. int i = 0;
  1076. foreach (var item in cp.Points)
  1077. {
  1078. var row = ds.Tables[0].NewRow();
  1079. row[0] = StepStartTime.AddSeconds(Convert.ToDouble(item.Item1));
  1080. row[1] = item.Item2;
  1081. ds.Tables[0].Rows.Add(row);
  1082. i++;
  1083. }
  1084. if (!ExcelHelper.ExportToExcel(dlg.FileName, ds, out string reason))
  1085. {
  1086. MessageBox.Show($"Export failed, {reason}", "Export", MessageBoxButton.OK, MessageBoxImage.Warning);
  1087. return;
  1088. }
  1089. MessageBox.Show($"Export succeed, file save as {dlg.FileName}", "Export", MessageBoxButton.OK, MessageBoxImage.Information);
  1090. }
  1091. }
  1092. catch (Exception ex)
  1093. {
  1094. LOG.Write(ex);
  1095. MessageBox.Show("Write failed," + ex.Message, "export failed", MessageBoxButton.OK, MessageBoxImage.Warning);
  1096. }
  1097. }
  1098. public void SelectColor(ChartDataLine<T> cp)
  1099. {
  1100. if (cp == null)
  1101. return;
  1102. var dlg = new System.Windows.Forms.ColorDialog();
  1103. if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  1104. {
  1105. cp.Stroke = new System.Windows.Media.Color() { A = dlg.Color.A, B = dlg.Color.B, G = dlg.Color.G, R = dlg.Color.R };
  1106. }
  1107. }
  1108. public void CloseCmd()
  1109. {
  1110. ((Window)GetView()).Close();
  1111. }
  1112. #endregion
  1113. #region SciChart Move
  1114. public void RefresCharView()
  1115. {
  1116. this.view.sciChart.ZoomExtents();
  1117. }
  1118. public void ArrowClick(string direction)
  1119. {
  1120. switch (direction)
  1121. {
  1122. case "Up":
  1123. if (VisibleRangeValue is DoubleRange uprange)
  1124. {
  1125. VisibleRangeValue = new DoubleRange(uprange.Min + YScale, uprange.Max + YScale);
  1126. }
  1127. break;
  1128. case "Down":
  1129. if (VisibleRangeValue is DoubleRange downrange)
  1130. {
  1131. VisibleRangeValue = new DoubleRange(downrange.Min - YScale, downrange.Max - YScale);
  1132. }
  1133. break;
  1134. case "Left":
  1135. if (VisibleRangeTime is DoubleRange leftrange)
  1136. {
  1137. VisibleRangeTime = new DoubleRange(leftrange.Min - XScale, leftrange.Max - XScale);
  1138. }
  1139. break;
  1140. case "Right":
  1141. if (VisibleRangeTime is DoubleRange range)
  1142. {
  1143. VisibleRangeTime = new DoubleRange(range.Min + XScale, range.Max + XScale);
  1144. }
  1145. break;
  1146. }
  1147. }
  1148. public void ZoomInClick()//放大
  1149. {
  1150. double scale = 0;
  1151. if ((_directionByte & 0x01) == 1)//x
  1152. {
  1153. //LOG.Info($"A ZoomInClick.X:scale{XScale}-{VisibleRangeTime.Min}: {VisibleRangeTime.Max}");
  1154. if (VisibleRangeTime is DoubleRange range)
  1155. {
  1156. if (range.Max - range.Min <= XScale) return;
  1157. if (range.Max - range.Min > 2 * XScale) scale = XScale;
  1158. else scale = XScale / 2;
  1159. VisibleRangeTime = new DoubleRange(range.Min + scale, range.Max - scale);
  1160. //LOG.Info($"ZoomInClick.X:scale{XScale}-{VisibleRangeTime.Min}: {VisibleRangeTime.Max}");
  1161. }
  1162. }
  1163. if ((_directionByte & 0x02) == 2)//y
  1164. {
  1165. //LOG.Info($"A ZoomInClick.Y:scale{YScale}-{VisibleRangeValue.Min}: {VisibleRangeValue.Max}");
  1166. if (VisibleRangeValue is DoubleRange range)
  1167. {
  1168. if (range.Max - range.Min <= YScale) return;
  1169. if (range.Max - range.Min > 2 * XScale) scale = YScale;
  1170. else scale = YScale / 2;
  1171. VisibleRangeValue = new DoubleRange(range.Min + scale, range.Max - scale);
  1172. //LOG.Info($"ZoomInClick.Y:scale{YScale}-{VisibleRangeValue.Min}: {VisibleRangeValue.Max}");
  1173. }
  1174. }
  1175. }
  1176. public void ZoomOutClick()//缩小
  1177. {
  1178. if ((_directionByte & 0x01) == 1)//x
  1179. {
  1180. //LOG.Info($"A ZoomOutClick.X:scale{XScale}-{VisibleRangeTime.Min}: {VisibleRangeTime.Max}");
  1181. if (VisibleRangeTime is DoubleRange range)
  1182. {
  1183. VisibleRangeTime = new DoubleRange(range.Min - XScale, range.Max + XScale);
  1184. //LOG.Info($"ZoomOutClick.X:scale{XScale}-{VisibleRangeTime.Min}: {VisibleRangeTime.Max}");
  1185. }
  1186. }
  1187. if ((_directionByte & 0x02) == 2)//y
  1188. {
  1189. //LOG.Info($"A ZoomOutClick.Y:scale{YScale}-{VisibleRangeValue.Min}: {VisibleRangeValue.Max}");
  1190. if (VisibleRangeValue is DoubleRange range)
  1191. {
  1192. VisibleRangeValue = new DoubleRange(range.Min - YScale, range.Max + YScale);
  1193. // LOG.Info($"ZoomOutClick.Y:scale{YScale}-{VisibleRangeValue.Min}: {VisibleRangeValue.Max}");
  1194. }
  1195. }
  1196. }
  1197. public void SelectStep()
  1198. {
  1199. ObservableCollection<Option> Items = new ObservableCollection<Option>();
  1200. foreach (var item in StepInfo)
  1201. {
  1202. Items.Add(new Option() { Name = $"{item.StepNo} {item.StepName}", Index = int.Parse(item.StepNo) });
  1203. }
  1204. ItemsSelectDialogViewModel itemsSelectDialogView = new ItemsSelectDialogViewModel();
  1205. itemsSelectDialogView.Items = Items;
  1206. itemsSelectDialogView.ColumnsCount = Items.Count / 10 + 1;
  1207. WindowManager windowManager = IoC.Get<IWindowManager>() as WindowManager;
  1208. if ((bool)(windowManager as WindowManager)?.ShowDialogWithNoWindow(itemsSelectDialogView))
  1209. {
  1210. var startItem = StepInfo.FirstOrDefault(step => step.StepNo == Items.FirstOrDefault(x => x.IsChecked)?.Index.ToString());
  1211. var endItem = StepInfo.FirstOrDefault(step => step.StepNo == Items.LastOrDefault(x => x.IsChecked)?.Index.ToString());
  1212. if (startItem == null)
  1213. {
  1214. DialogBox.ShowError("Please select begin step!");
  1215. return;
  1216. }
  1217. if (endItem == null)
  1218. {
  1219. DialogBox.ShowError("Please select end step!");
  1220. return;
  1221. }
  1222. if (Items.Where(x => x.IsChecked).Count() > 2)
  1223. {
  1224. DialogBox.ShowError("The selected step numbers must be 1 or 2.");
  1225. return;
  1226. }
  1227. StepStartTime = startItem.StartTime;
  1228. StepEndTime = endItem.EndTime;
  1229. List<ParameterNode> allCheckNode = new List<ParameterNode>();
  1230. ParameterNodes.ToList().ForEach(x =>
  1231. {
  1232. allCheckNode.AddRange(GetAllCheckedLeafNode(x));
  1233. });
  1234. allCheckNode.ForEach(x => { ParameterCheck(x, SelectedData); });
  1235. }
  1236. }
  1237. private List<ParameterNode> GetAllCheckedLeafNode(ParameterNode parameterNode)
  1238. {
  1239. List<ParameterNode> retNodes = new List<ParameterNode>();
  1240. if (parameterNode.ChildNodes != null && parameterNode.ChildNodes.Count > 0)
  1241. {
  1242. foreach (var item in parameterNode.ChildNodes)
  1243. {
  1244. retNodes.AddRange(GetAllCheckedLeafNode(item));
  1245. }
  1246. }
  1247. else
  1248. {
  1249. if (parameterNode.Selected)
  1250. retNodes.Add(parameterNode);
  1251. }
  1252. return retNodes;
  1253. }
  1254. #endregion
  1255. #endregion
  1256. public void GetCursorPoint(IEnumerable<SeriesInfo> infos)
  1257. {
  1258. if (infos.Any())
  1259. {
  1260. var seriesinfo = infos.First();
  1261. if (seriesinfo.XValue is double xvalue && _lastPointX != xvalue)
  1262. {
  1263. _lastPointX = xvalue;
  1264. PointTime = StepStartTime.AddSeconds(xvalue);
  1265. if (PointTime == DateTime.MinValue) return;
  1266. var step = _stepInfo.Find(r => r.StartTime <= PointTime && r.EndTime >= PointTime);
  1267. if (step == null)
  1268. {
  1269. LOG.Info($"couldn't find CurrentTime:{PointTime:yyyy/MM/dd HH:mm:ss.FFF} in steps ,display last step:{StepNameDisPlay}");
  1270. }
  1271. else
  1272. {
  1273. StepNameDisPlay = $"{step.StepNo}:{step.StepName}";
  1274. //LOG.Info($"CurrentTime:{PointTime:yyyy/MM/dd HH:mm:ss.FFF} {StepNameDisPlay}");
  1275. }
  1276. var name = (seriesinfo.RenderableSeries as ChartDataLine<T>).DataSource.Split('.', '\\');
  1277. if (name.Length > 0)
  1278. {
  1279. RecipeNameDisPlay = name.Last();
  1280. }
  1281. else RecipeNameDisPlay = string.Empty;
  1282. }
  1283. }
  1284. }
  1285. public void ScaleChange(string direction, double factor)
  1286. {
  1287. double t = 0;
  1288. if (direction == "X")
  1289. {
  1290. t = Math.Floor(_xScale * factor * 10) / 10d;//只保留3位小数
  1291. if (t >= 0.1) XScale = t;
  1292. else DialogBox.ShowWarning("already min value");
  1293. }
  1294. else if (direction == "Y")
  1295. {
  1296. t = Math.Floor(_yScale * factor * 1000) / 1000d;
  1297. if (t >= 0.001) YScale = t;
  1298. else DialogBox.ShowWarning("already min value");
  1299. }
  1300. }
  1301. }
  1302. public class ProcessDataLot : NotifiableItem
  1303. {
  1304. private string _guid;
  1305. public string GUID
  1306. {
  1307. get => _guid;
  1308. set
  1309. {
  1310. _guid = value;
  1311. InvokePropertyChanged(nameof(GUID));
  1312. }
  1313. }
  1314. private DateTime _processBeginTime;
  1315. public DateTime ProcessBeginTime
  1316. {
  1317. get => _processBeginTime;
  1318. set
  1319. {
  1320. _processBeginTime = value;
  1321. InvokePropertyChanged(nameof(ProcessBeginTime));
  1322. }
  1323. }
  1324. private DateTime _processEndTime;
  1325. public DateTime ProcessEndTime
  1326. {
  1327. get => _processEndTime;
  1328. set
  1329. {
  1330. _processEndTime = value;
  1331. InvokePropertyChanged(nameof(ProcessEndTime));
  1332. }
  1333. }
  1334. private string _recipeName;
  1335. public string RecipeName
  1336. {
  1337. get => _recipeName;
  1338. set
  1339. {
  1340. _recipeName = value;
  1341. InvokePropertyChanged(nameof(RecipeName));
  1342. }
  1343. }
  1344. private string _processStatus;
  1345. public string ProcessStatus
  1346. {
  1347. get => _processStatus;
  1348. set
  1349. {
  1350. _processStatus = value;
  1351. InvokePropertyChanged(nameof(ProcessStatus));
  1352. }
  1353. }
  1354. private string _waferDataguid;
  1355. public string WaferDataGUID
  1356. {
  1357. get => _waferDataguid;
  1358. set
  1359. {
  1360. _waferDataguid = value;
  1361. InvokePropertyChanged(nameof(WaferDataGUID));
  1362. }
  1363. }
  1364. private string _processIn;
  1365. public string ProcessIn
  1366. {
  1367. get => _processIn;
  1368. set
  1369. {
  1370. _processIn = value;
  1371. InvokePropertyChanged(nameof(ProcessIn));
  1372. }
  1373. }
  1374. private int _recipeSettingTime;
  1375. public int RecipeSettingTime
  1376. {
  1377. get => _recipeSettingTime;
  1378. set
  1379. {
  1380. _recipeSettingTime = value;
  1381. InvokePropertyChanged(nameof(RecipeSettingTime));
  1382. }
  1383. }
  1384. }
  1385. }