ProcessDetailViewModel.cs 65 KB

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