ProcessExportAllViewModel.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  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.CenterViews.Operations.RealTime;
  14. using MECF.Framework.UI.Client.ClientBase;
  15. using OpenSEMI.ClientBase;
  16. using SciChart.Charting.Visuals;
  17. using SciChart.Charting.Visuals.Annotations;
  18. using SciChart.Charting.Visuals.Axes;
  19. using SciChart.Charting.Visuals.RenderableSeries;
  20. using SciChart.Data.Model;
  21. using System;
  22. using System.Collections.Concurrent;
  23. using System.Collections.Generic;
  24. using System.Collections.ObjectModel;
  25. using System.Data;
  26. using System.Diagnostics;
  27. using System.Drawing;
  28. using System.Linq;
  29. using System.Text;
  30. using System.Threading;
  31. using System.Threading.Tasks;
  32. using System.Windows;
  33. using static MECF.Framework.Common.FAServices.DataVariables;
  34. using Action = System.Action;
  35. using Media = System.Windows.Media;
  36. namespace MECF.Framework.UI.Client.CenterViews.DataLogs.ProcessHistory
  37. {
  38. class ProcessExportAllViewModel<T> : ModuleUiViewModelBase where T : IComparable
  39. {
  40. private ProcessExportAllView view;
  41. private CancellationTokenSource _cancellationTokenSource;
  42. private event EventHandler Exporting;
  43. private const int MAX_PARAMETERS = 1000;
  44. public List<ProcessHistoryLot> RecipeDatas { get; set; }
  45. private ObservableCollection<ParameterNode> _ParameterNodes;
  46. public ObservableCollection<ParameterNode> ParameterNodes
  47. {
  48. get { return _ParameterNodes; }
  49. set { _ParameterNodes = value; NotifyOfPropertyChange("ParameterNodes"); }
  50. }
  51. private Dictionary<string, string> _processDetailDisplayDic = new Dictionary<string, string>();
  52. private Dictionary<string, Dictionary<string, string>> _processProcessDetailAttributeDict = new Dictionary<string, Dictionary<string, string>>();
  53. // public ObservableCollection<IRenderableSeries> SelectedData { get; set; }
  54. public ObservableCollection<ParameterNode> GetParameters()
  55. {
  56. ObservableCollection<ParameterNode> rootNode = new ObservableCollection<ParameterNode>();
  57. try
  58. {
  59. Dictionary<string, string> displayDic = QueryDataClient.Instance.Service.GetData("System.ProcessDetailDisplay") as Dictionary<string, string>;
  60. if (displayDic == null)
  61. return rootNode;
  62. List<string> dataList = new List<string>();
  63. foreach (var key in displayDic.Keys)
  64. {
  65. string[] item = key.Split('.');
  66. if (item != null)
  67. {
  68. if (item.Length == 2)
  69. {
  70. _processDetailDisplayDic.Add($"{item[1]}", displayDic[key]);
  71. dataList.Add($"{item[0]}.{item[1]}");
  72. }
  73. else if (item.Length == 3)
  74. {
  75. _processDetailDisplayDic.Add($"{item[1]} {item[2]}", displayDic[key]);
  76. dataList.Add($"{item[0]}.{item[1]}.{item[2]}");
  77. }
  78. }
  79. Dictionary<string, ParameterNode> indexer = new Dictionary<string, ParameterNode>();
  80. foreach (string dataName in dataList)
  81. {
  82. string[] nodeName = dataName.Split('.');
  83. ParameterNode parentNode = null;
  84. string pathName = "";
  85. for (int i = 0; i < nodeName.Length; i++)
  86. {
  87. pathName = (i == 0 || i == 1) ? nodeName[i] : (pathName + " " + nodeName[i]);
  88. if (!indexer.ContainsKey(pathName))
  89. {
  90. indexer[pathName] = new ParameterNode() { Name = pathName, ChildNodes = new ObservableCollection<ParameterNode>(), ParentNode = parentNode };
  91. if (parentNode == null)
  92. {
  93. rootNode.Add(indexer[pathName]);
  94. }
  95. else
  96. {
  97. parentNode.ChildNodes.Add(indexer[pathName]);
  98. }
  99. }
  100. parentNode = indexer[pathName];
  101. }
  102. }
  103. SortParameterNode(rootNode, "Heater", 0);
  104. SortParameterNode(rootNode, "MFC", 1);
  105. SortParameterNode(rootNode, "Pressure", 2);
  106. SortParameterNode(rootNode, "Boat", 3);
  107. SortParameterNode(rootNode, "HeaterBand", 4);
  108. SortParameterNode(rootNode, "Valve", 5);
  109. }
  110. }
  111. catch (Exception ex)
  112. {
  113. LOG.Write(ex);
  114. }
  115. return rootNode;
  116. }
  117. void SortParameterNode(ObservableCollection<ParameterNode> rootNode, string Name, int Index)
  118. {
  119. if (rootNode[Index].Name != Name)
  120. {
  121. for (int i = 0; i < rootNode.Count; i++)
  122. {
  123. rootNode[i].Selected = true;
  124. if (rootNode[i].Name == Name)
  125. {
  126. ParameterNode node = rootNode[i];
  127. rootNode.RemoveAt(i);
  128. rootNode.Insert(Index, node);
  129. }
  130. }
  131. }
  132. }
  133. private IRange _timeRange;
  134. public IRange VisibleRangeTime
  135. {
  136. get { return _timeRange; }
  137. set
  138. {
  139. _timeRange = value;
  140. NotifyOfPropertyChange(nameof(VisibleRangeTime));
  141. }
  142. }
  143. private IRange _VisibleRangeValue;
  144. public IRange VisibleRangeValue
  145. {
  146. get { return _VisibleRangeValue; }
  147. set { _VisibleRangeValue = value; NotifyOfPropertyChange(nameof(VisibleRangeValue)); }
  148. }
  149. private AnnotationCollection _annotations;
  150. public AnnotationCollection Annotations
  151. {
  152. get => _annotations;
  153. set
  154. {
  155. _annotations = value;
  156. InvokePropertyChanged(nameof(Annotations));
  157. }
  158. }
  159. //private PeriodicJob _thread;
  160. private List<StepInfo> _stepInfo = new List<StepInfo>();
  161. public List<StepInfo> StepInfo
  162. {
  163. get { return _stepInfo; }
  164. set { _stepInfo = value; this.NotifyOfPropertyChange(nameof(StepInfo)); }
  165. }
  166. private bool _isBusy = false;
  167. private string _busyIndicatorMessage;
  168. /// <summary>
  169. /// 设置或返回忙信息。
  170. /// </summary>
  171. public string BusyIndicatorContent
  172. {
  173. get => _busyIndicatorMessage;
  174. set
  175. {
  176. _busyIndicatorMessage = value;
  177. NotifyOfPropertyChange(nameof(BusyIndicatorContent));
  178. }
  179. }
  180. /// <summary>
  181. /// 设置或返回视图是否正忙。
  182. /// </summary>
  183. public bool IsBusy
  184. {
  185. get => _isBusy;
  186. set
  187. {
  188. _isBusy = value;
  189. NotifyOfPropertyChange(nameof(IsBusy));
  190. }
  191. }
  192. private RealtimeProvider _realtimeProvider;
  193. public ProcessExportAllViewModel(List<ProcessHistoryLot> recipes)
  194. {
  195. DisplayName = "Process Export";
  196. RecipeDatas = recipes;
  197. _realtimeProvider = new RealtimeProvider();
  198. ParameterNodes = _realtimeProvider.GetParameters(out var dict, true);
  199. _processDetailDisplayDic = dict;
  200. _processProcessDetailAttributeDict = _realtimeProvider.GetProcessProcessDetailAttributeDict();
  201. if (recipes == null || recipes.Count == 0)
  202. {
  203. return;
  204. }
  205. //SelectedData = new ObservableCollection<IRenderableSeries>();
  206. var now = DateTime.Now;
  207. VisibleRangeTime = new DateRange(DateTime.Now.AddMinutes(60), DateTime.Now.AddMinutes(-60));
  208. VisibleRangeValue = new DoubleRange(0, 10);
  209. Annotations = new AnnotationCollection();
  210. // _thread = new PeriodicJob(200, MonitorData, "ProcessExport", true);
  211. RecipeDatas.ToList().ForEach(recipe =>
  212. {
  213. QueryStep(recipe.StartTime, recipe.EndTime);
  214. });
  215. if (StepInfo != null && StepInfo.Count > 0)
  216. {
  217. StepStartTime = StepInfo.FirstOrDefault().StartTime;
  218. StepEndTime = StepInfo.LastOrDefault().EndTime;
  219. }
  220. else
  221. {
  222. if (recipes.Count > 0)
  223. {
  224. StepStartTime = recipes[0].StartTime;
  225. StepEndTime = recipes[0].EndTime;
  226. }
  227. }
  228. }
  229. public bool IsStepVisiable => RecipeDatas.Count == 1;
  230. public DateTime StepStartTime { get; set; }
  231. public DateTime StepEndTime { get; set; }
  232. private bool _isAdding;
  233. private static object _lockSelection = new object();
  234. private ConcurrentBag<QueryIndexer> _lstTokenTimeData = new ConcurrentBag<QueryIndexer>();
  235. public class QueryIndexer
  236. {
  237. public TimeChartDataLine DataLine { get; set; }
  238. public List<string> DataList { get; set; }
  239. public DateTime TimeToken { get; set; }
  240. }
  241. public class TimeChartDataLine : ChartDataLine<T>
  242. {
  243. public string Module { get; set; }
  244. public DateTime StartTime { get; set; }
  245. public DateTime EndTime { get; set; }
  246. public TimeChartDataLine(string dataName, string module, DateTime startTime, DateTime endTime) : base(dataName)
  247. {
  248. StartTime = startTime;
  249. EndTime = endTime;
  250. Module = module;
  251. }
  252. }
  253. private string _resolution;
  254. private AutoRange _autoRange;
  255. public AutoRange ChartAutoRange
  256. {
  257. get { return _autoRange; }
  258. set
  259. {
  260. _autoRange = value;
  261. NotifyOfPropertyChange(nameof(ChartAutoRange));
  262. }
  263. }
  264. public void QueryStep(DateTime starTime, DateTime endTime)//, string recipeName去掉查询recipeName名称,有嵌套调用
  265. {
  266. starTime = starTime.AddMinutes(-1);
  267. endTime = endTime.AddMinutes(1);
  268. 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;";
  269. DataTable dbData = QueryDataClient.Instance.Service.QueryData(sql);
  270. if (dbData != null && dbData.Rows.Count > 0)
  271. {
  272. List<ProcessDataLot> ProcessDataLotList = new List<ProcessDataLot>();
  273. for (int i = 0; i < dbData.Rows.Count; i++)
  274. {
  275. ProcessDataLot item = new ProcessDataLot();
  276. item.GUID = dbData.Rows[i]["guid"].ToString();
  277. item.RecipeName = dbData.Rows[i]["recipe_name"].ToString();
  278. item.ProcessStatus = dbData.Rows[i]["process_status"].ToString();
  279. item.WaferDataGUID = dbData.Rows[i]["wafer_data_guid"].ToString();
  280. item.ProcessIn = dbData.Rows[i]["process_in"].ToString();
  281. if (!dbData.Rows[i]["process_begin_time"].Equals(DBNull.Value))
  282. {
  283. item.ProcessBeginTime = (DateTime)dbData.Rows[i]["process_begin_time"];
  284. }
  285. if (!dbData.Rows[i]["process_end_time"].Equals(DBNull.Value))
  286. {
  287. item.ProcessEndTime = (DateTime)dbData.Rows[i]["process_end_time"];
  288. }
  289. ProcessDataLotList.Add(item);
  290. }
  291. // Annotations.Add(VerLine(Media.Brushes.Blue, ProcessDataLotList[0].ProcessBeginTime, Media.Brushes.Blue, $"{ProcessDataLotList[0].RecipeName}"));
  292. //Annotations.Add(VerLine(Media.Brushes.Blue, ProcessDataLotList[0].ProcessEndTime, Media.Brushes.Blue, $"Recipe End"));
  293. string sql2 = $"SELECT * FROM \"recipe_step_data\" where";
  294. sql2 += $" \"recipe_step_data\".\"process_data_guid\" = '{ProcessDataLotList[0].GUID.ToString()}'";
  295. sql2 += " order by \"step_begin_time\" ASC;";
  296. using (var table = QueryDataClient.Instance.Service.QueryData(sql2))
  297. {
  298. if (!(table == null || table.Rows.Count == 0))
  299. {
  300. for (int i = 0; i < table.Rows.Count; i++)
  301. {
  302. var item = table.Rows[i];
  303. string startStepTime = "";
  304. string endStepTime = "";
  305. double stepTime = 0;
  306. string subRecipeStepNumber = "";
  307. string subRecipeStepTime = "";
  308. string subRecipeStepName = "";
  309. string subRecipeLoopInfo = "";
  310. string tempCorrection = "";
  311. string tempPid = "";
  312. if (!item["step_begin_time"].Equals(DBNull.Value))
  313. startStepTime = ((DateTime)item["step_begin_time"]).ToString("yyyy/MM/dd HH:mm:ss.fff");
  314. if (!item["step_end_time"].Equals(DBNull.Value))
  315. {
  316. endStepTime = ((DateTime)item["step_end_time"]).ToString("yyyy/MM/dd HH:mm:ss.fff");
  317. }
  318. if (!item["step_time"].Equals(DBNull.Value))
  319. {
  320. stepTime = (float)item["step_time"];
  321. }
  322. if (!item["sub_recipe_step_time"].Equals(DBNull.Value))
  323. {
  324. subRecipeStepTime = item["sub_recipe_step_time"].ToString();
  325. }
  326. if (!item["sub_recipe_step_number"].Equals(DBNull.Value))
  327. {
  328. subRecipeStepNumber = item["sub_recipe_step_number"].ToString();
  329. }
  330. if (!item["sub_recipe_step_name"].Equals(DBNull.Value))
  331. {
  332. subRecipeStepName = item["sub_recipe_step_name"].ToString();
  333. }
  334. if (!item["sub_recipe_loop_info"].Equals(DBNull.Value))
  335. {
  336. subRecipeLoopInfo = item["sub_recipe_loop_info"].ToString();
  337. }
  338. if (!item["temp_correction"].Equals(DBNull.Value))
  339. {
  340. tempCorrection = item["temp_correction"].ToString().Replace(",", ":");
  341. }
  342. if (!item["temp_pid"].Equals(DBNull.Value))
  343. {
  344. tempPid = item["temp_pid"].ToString().Replace(",", ":");
  345. }
  346. string stepNo = item["step_number"].ToString();
  347. string stepName = item["step_name"].ToString();
  348. if (DateTime.TryParse(startStepTime, out DateTime StartTime) && DateTime.TryParse(endStepTime, out DateTime EndTime))
  349. {
  350. //Annotations.Add(VerLine(Media.Brushes.AliceBlue, StartTime, Media.Brushes.Blue, $"{stepNo}"));
  351. var time = StartTime.AddSeconds(stepTime);
  352. if (EndTime < time && time < ProcessDataLotList[0].ProcessEndTime)//解决process过程abort,数据导出问题:数据点时间范围大于recipe结束时间。
  353. {
  354. EndTime = StartTime.AddSeconds(stepTime);
  355. }
  356. _stepInfo.Add(new StepInfo()
  357. {
  358. StartTime = StartTime,
  359. EndTime = EndTime,
  360. StepName = stepName,
  361. StepTime = stepTime,
  362. StepNo = stepNo,
  363. StepEndTime = StartTime.AddSeconds(stepTime),
  364. SubRecipeStepNumber = subRecipeStepNumber,
  365. SubRecipeStepTime = subRecipeStepTime,
  366. SubRecipeStepName = subRecipeStepName,
  367. SubRecipeLoopInfo = subRecipeLoopInfo,
  368. TempCorrection = tempCorrection,
  369. TempPid = tempPid,
  370. });
  371. }
  372. }
  373. }
  374. }
  375. }
  376. }
  377. protected override void OnViewLoaded(object view)
  378. {
  379. base.OnViewLoaded(view);
  380. useMaxRow = (int)QueryDataClient.Instance.Service.GetConfig("System.SetUp.ExportMaxRow");
  381. this.view = (ProcessExportAllView)view;
  382. }
  383. List<string> nodeOrigin = new List<string>();
  384. void GetNode(ParameterNode pNode, bool Selected)
  385. {
  386. foreach (var item in pNode.ChildNodes)
  387. {
  388. if (item.ChildNodes.Count > 0)
  389. {
  390. GetNode(item, Selected);
  391. }
  392. else
  393. {
  394. //if(item.Selected == true)
  395. {
  396. nodeOrigin.Add(item.Name);
  397. }
  398. }
  399. }
  400. }
  401. public static int DivideAndRoundUp(int dividend, int divisor)
  402. {
  403. int result = dividend / divisor;
  404. int remainder = dividend % divisor;
  405. if (remainder > 0)
  406. {
  407. result++;
  408. }
  409. return result;
  410. }
  411. private int useMaxRow = 25000;
  412. string csv = ",";
  413. public async void ExportAll()
  414. {
  415. try
  416. {
  417. nodeOrigin.Clear();
  418. if (StepStartTime.Year == 1 || StepEndTime.Year == 1)
  419. {
  420. MessageBox.Show("No data is available in the selected period!", "Export", MessageBoxButton.OK, MessageBoxImage.Warning);
  421. return;
  422. }
  423. foreach (var node in ParameterNodes)
  424. {
  425. if (node.Selected == true)
  426. {
  427. GetNode(node, node.Selected);
  428. }
  429. }
  430. if (nodeOrigin.Count == 0)
  431. {
  432. MessageBox.Show($"Please select the data you want to export.", "Export", MessageBoxButton.OK,
  433. MessageBoxImage.Warning);
  434. return;
  435. }
  436. Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
  437. dlg.DefaultExt = ".csv"; // Default file extension
  438. dlg.Filter = "Excel数据表格文件(*.csv)|*.csv"; // Filter files by extension
  439. dlg.FileName = $"{DisplayName}_{string.Join(",", RecipeDatas.Select(x => x.RecipeName).ToArray())}_{DateTime.Now:yyyyMMdd_HHmmss}";
  440. Nullable<bool> result = dlg.ShowDialog();// Show open file dialog box
  441. if (result == true) // Process open file dialog box results
  442. {
  443. BusyIndicatorContent = "Exporting start ...";
  444. IsBusy = true;
  445. Exporting?.Invoke(this, System.EventArgs.Empty);
  446. _cancellationTokenSource = new CancellationTokenSource();
  447. //System.Data.DataSet ds = new System.Data.DataSet();
  448. //var sw = new Stopwatch();
  449. //sw.Restart();
  450. //BusyIndicatorContent = "Create table header start ...";
  451. //ds.Tables.Add(new System.Data.DataTable($"{DisplayName}_{DateTime.Now:yyyyMMdd_HHmmss}"));
  452. //ds.Tables[0].Columns.Add("Recipe Info");
  453. //ds.Tables[0].Columns[0].DataType = typeof(string);
  454. //ds.Tables[0].Columns.Add("Date");
  455. //ds.Tables[0].Columns[1].DataType = typeof(string);
  456. //ds.Tables[0].Columns.Add("Time");
  457. //ds.Tables[0].Columns[2].DataType = typeof(string);
  458. //ds.Tables[0].Columns.Add("Step ID");
  459. //ds.Tables[0].Columns[3].DataType = typeof(string);
  460. //ds.Tables[0].Columns.Add("Step Name");
  461. //ds.Tables[0].Columns[4].DataType = typeof(string);
  462. StringBuilder stringBuilder = new StringBuilder();
  463. stringBuilder.AppendLine($"Recipe Info{csv}Date{csv}Time{csv}Step ID{csv}Step Name");
  464. Dictionary<T, double[]> timeValue = new Dictionary<T, double[]>();
  465. await Task.Run(() =>
  466. {
  467. for (int i = 0; i < nodeOrigin.Count; i++)
  468. {
  469. //List<Tuple<T, double>> data = (nodeOrigin[i] as ChartDataLine<T>).Points;
  470. //foreach (var tuple in data)
  471. //{
  472. // if (!timeValue.ContainsKey(tuple.Item1))
  473. // timeValue[tuple.Item1] = new double[nodeOrigin.Count];
  474. // timeValue[tuple.Item1][i] = tuple.Item2;
  475. //}
  476. // ds.Tables[0].Columns.Add(nodeOrigin[i]);
  477. // ds.Tables[0].Columns[i + 5].DataType = typeof(double);
  478. }
  479. stringBuilder.AppendLine($"Recipe:{string.Join(",", RecipeDatas.Select(x => x.RecipeName).ToArray())}");
  480. stringBuilder.AppendLine($"Start Time{csv}{string.Join(",", RecipeDatas.Select(x => x.StartTime).ToArray())}{csv}{string.Join(",", RecipeDatas.Select(x => x.StartTime).ToArray())}");
  481. stringBuilder.AppendLine($"End Time{csv}{string.Join(",", RecipeDatas.Select(x => x.EndTime).ToArray())}{csv}{string.Join(",", RecipeDatas.Select(x => x.EndTime).ToArray())}");
  482. FileHelper.Instance.SaveText(dlg.FileName, stringBuilder.ToString());
  483. //var recipeInfoRow = ds.Tables[0].NewRow();
  484. //recipeInfoRow[0] = $"Recipe:{string.Join(",", RecipeDatas.Select(x => x.RecipeName).ToArray())}";
  485. //ds.Tables[0].Rows.Add(recipeInfoRow);
  486. //recipeInfoRow = ds.Tables[0].NewRow();
  487. //recipeInfoRow[0] = $"Start Time";
  488. //recipeInfoRow[1] = string.Join(",", RecipeDatas.Select(x => x.StartTime).ToArray());
  489. //recipeInfoRow[2] = string.Join(",", RecipeDatas.Select(x => x.StartTime).ToArray());
  490. //ds.Tables[0].Rows.Add(recipeInfoRow);
  491. //recipeInfoRow = ds.Tables[0].NewRow();
  492. //recipeInfoRow[0] = $"End Time";
  493. //recipeInfoRow[1] = string.Join(",", RecipeDatas.Select(x => x.EndTime).ToArray());
  494. //recipeInfoRow[2] = string.Join(",", RecipeDatas.Select(x => x.EndTime).ToArray());
  495. //ds.Tables[0].Rows.Add(recipeInfoRow);
  496. //var rowCaption = ds.Tables[0].NewRow();
  497. //for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
  498. //{
  499. // rowCaption[i] = ds.Tables[0].Columns[i].Caption;
  500. //}
  501. //ds.Tables[0].Rows.Add(rowCaption);
  502. //for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
  503. //{
  504. // ds.Tables[0].Columns[i].Caption = null;
  505. //}
  506. DateTime startTime = startTime = StepStartTime;
  507. QueryDataClientFromTable(dlg.FileName);
  508. }, _cancellationTokenSource.Token).ContinueWith(t =>
  509. {
  510. if (t.IsCanceled || t.IsFaulted)
  511. {
  512. IsBusy = false;
  513. return;
  514. }
  515. });
  516. if (_cancellationTokenSource?.Token.IsCancellationRequested == true)
  517. {
  518. IsBusy = false;
  519. return;
  520. }
  521. BusyIndicatorContent = "Data is written to Excel file ...";
  522. IsBusy = false;
  523. MessageBox.Show($"Export succeed, file save as {dlg.FileName}", "Export", MessageBoxButton.OK, MessageBoxImage.Information);
  524. Window window = Window.GetWindow(this.view);
  525. window.Close();
  526. }
  527. }
  528. catch (Exception ex)
  529. {
  530. LOG.Write(ex);
  531. MessageBox.Show("Write failed," + ex.Message, "export failed", MessageBoxButton.OK, MessageBoxImage.Warning);
  532. IsBusy = false;
  533. }
  534. }
  535. private void QueryDataClientFromTable(string fileName)
  536. {
  537. DateTime startTime = StepStartTime;
  538. DateTime endTime = StepEndTime;
  539. List<string> keys = new List<string>(nodeOrigin);
  540. List<string> pmList = new List<string>();
  541. List<string> systemList = new List<string>();
  542. if (keys != null && keys.Count > 0)
  543. {
  544. foreach (var dataKey in keys)
  545. {
  546. var dataId = _processDetailDisplayDic.ContainsKey(dataKey) ? _processDetailDisplayDic[dataKey] : dataKey;
  547. var module = dataId.Split('.').ToList()[0];
  548. if (module.ToLower() == "pm1")
  549. {
  550. pmList.Add(dataId);
  551. }
  552. else if (module.ToLower() == "system")
  553. {
  554. systemList.Add(dataId);
  555. // systemList.Add(string.Format("\"{0}\"", dataId));
  556. }
  557. }
  558. }
  559. if (StepStartTime.Date == StepEndTime.Date)
  560. {
  561. SaveDataToTable(fileName, pmList, systemList, startTime, endTime);
  562. }
  563. else
  564. {
  565. endTime = new DateTime(startTime.Year, startTime.Month, startTime.Day, 23, 59, 59);
  566. while (endTime < StepEndTime)
  567. {
  568. SaveDataToTable(fileName, pmList, systemList, startTime, endTime);
  569. startTime = new DateTime(startTime.Year, startTime.Month, startTime.Day, 0, 0, 0).AddDays(1);
  570. endTime = new DateTime(startTime.Year, startTime.Month, startTime.Day, 23, 59, 59);
  571. }
  572. SaveDataToTable(fileName, pmList, systemList, startTime, StepEndTime);
  573. }
  574. }
  575. private bool firstHeader = false;
  576. private Dictionary<string, string> GetReverseDict()
  577. {
  578. Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
  579. foreach (var kvp in _processDetailDisplayDic)
  580. {
  581. if (!keyValuePairs.ContainsKey(kvp.Value))
  582. keyValuePairs[kvp.Value] = kvp.Key.Trim().Contains(" ") ? kvp.Key.Trim().Substring(kvp.Key.Trim().LastIndexOf(" ") + 1) : kvp.Key;
  583. }
  584. return keyValuePairs;
  585. }
  586. private void SaveDataToTable(string fileName, List<string> pmList, List<string> systemList, DateTime startTime, DateTime endTime)
  587. {
  588. string stepID = "", stepName = "", subRecipeLoopInfo = "", subRecipeStepName = "", subRecipeStepNumber = "", tempCorrection = "", tempPid = "";
  589. DataTable pmDataTable = null;
  590. Dictionary<string, string> reverseDict = GetReverseDict();
  591. var columnsql = $"select column_name from information_schema.columns where table_name = '{startTime.ToString("yyyyMMdd")}.PM1'";
  592. var columnTable = QueryDataClient.Instance.Service.QueryData(columnsql);
  593. List<string> col = columnTable.Rows.Cast<DataRow>().Select(x => x.ItemArray[0].ToString()).ToList();
  594. pmList = pmList.Where(x => col.Any(y => y == x)).ToList();
  595. string pmsql = $"select time AS InternalTimeStamp, {string.Join(",", pmList.Select(x => string.Format("\"{0}\"", x)))}";
  596. DataTable systemDataTable = null;
  597. pmsql += string.Format(" from \"{0}\" where time > {1} and time <= {2} order by time asc",
  598. startTime.ToString("yyyyMMdd") + "." + "PM1", startTime.Ticks, endTime.Ticks);
  599. BusyIndicatorContent = "Example Query PM data ...";
  600. pmDataTable = QueryDataClient.Instance.Service.QueryData(pmsql);
  601. if (pmDataTable != null)
  602. {
  603. foreach (DataRow item in pmDataTable.Rows)
  604. {
  605. if (item.Table.Columns.Contains("PM1.APC.ModeFeedback"))
  606. {
  607. if (item.Table.Columns.Contains("PM1.APC.PressureSetPoint"))
  608. {
  609. if (item.Field<float>("PM1.APC.ModeFeedback") != 7 && item.Field<float>("PM1.APC.ModeFeedback") != 8)
  610. {
  611. item["PM1.APC.PressureSetPoint"] = 0;
  612. }
  613. }
  614. if (item.Table.Columns.Contains("PM1.APC.PositionSetPoint"))
  615. {
  616. if (item.Field<float>("PM1.APC.ModeFeedback") != 2)
  617. {
  618. item["PM1.APC.PositionSetPoint"] = 0;
  619. }
  620. }
  621. if (item.Table.Columns.Contains("PM1.APC.SlowRateSetPoint"))
  622. {
  623. if (item.Field<float>("PM1.APC.ModeFeedback") != 12)
  624. {
  625. item["PM1.APC.SlowRateSetPoint"] = 0;
  626. }
  627. }
  628. }
  629. }
  630. }
  631. var sysColumnsql = $"select column_name from information_schema.columns where table_name = '{startTime.ToString("yyyyMMdd")}.System'";
  632. var sysColumnTable = QueryDataClient.Instance.Service.QueryData(sysColumnsql);
  633. List<string> systemCol = sysColumnTable.Rows.Cast<DataRow>().Select(x => x.ItemArray[0].ToString()).ToList();
  634. systemList = systemList.Where(x => systemCol.Any(y => y == x)).ToList();
  635. string systemsql = $"select time AS InternalTimeStamp, {string.Join(",", systemList.Select(x => string.Format("\"{0}\"", x)))}";
  636. systemsql += string.Format(" from \"{0}\" where time > {1} and time <= {2} order by time asc",
  637. startTime.ToString("yyyyMMdd") + "." + "System", startTime.Ticks, endTime.Ticks);
  638. BusyIndicatorContent = "Example Query System data ...";
  639. systemDataTable = QueryDataClient.Instance.Service.QueryData(systemsql);
  640. int maxRow = 0;
  641. if ((pmDataTable == null || pmDataTable.Rows.Count == 0))
  642. {
  643. if (systemDataTable != null)
  644. {
  645. maxRow = systemDataTable.Rows.Count;
  646. }
  647. }
  648. else if ((systemDataTable == null || systemDataTable.Rows.Count == 0))
  649. {
  650. if (pmDataTable != null)
  651. {
  652. maxRow = pmDataTable.Rows.Count;
  653. }
  654. }
  655. else
  656. {
  657. maxRow = pmDataTable.Rows.Count > systemDataTable.Rows.Count ? systemDataTable.Rows.Count : pmDataTable.Rows.Count;
  658. }
  659. var subColNames = new List<DataColumn>() {
  660. new DataColumn("SubRecipeStepName"),
  661. new DataColumn("SubRecipeStepNumber"),
  662. new DataColumn("SubRecipeLoopInfo"),
  663. new DataColumn("TempCorrection"),
  664. new DataColumn("TempPid"),
  665. };
  666. BusyIndicatorContent = "Data is saved to excel Table ...";
  667. StringBuilder stringBuilder = new StringBuilder();
  668. if (!firstHeader)
  669. {
  670. firstHeader = true;
  671. var systemColNames = systemDataTable?.Columns.Cast<DataColumn>().Where(x => x.ColumnName != "internaltimestamp").Select(x =>
  672. {
  673. if (_processProcessDetailAttributeDict.ContainsKey(x.ColumnName))
  674. {
  675. var colAttributeName = "ColName";
  676. if (!_processProcessDetailAttributeDict[x.ColumnName].ContainsKey(colAttributeName))
  677. {
  678. colAttributeName = "DisplayName";
  679. }
  680. return string.IsNullOrEmpty(_processProcessDetailAttributeDict[x.ColumnName][colAttributeName]) ? x.ColumnName : _processProcessDetailAttributeDict[x.ColumnName][colAttributeName];
  681. }
  682. return x.ColumnName;
  683. });
  684. var pmColNames = pmDataTable?.Columns.Cast<DataColumn>().Where(x => x.ColumnName != "internaltimestamp").Select(x =>
  685. {
  686. if (_processProcessDetailAttributeDict.ContainsKey(x.ColumnName))
  687. {
  688. var colAttributeName = "ColName";
  689. if (!_processProcessDetailAttributeDict[x.ColumnName].ContainsKey(colAttributeName))
  690. {
  691. colAttributeName = "DisplayName";
  692. }
  693. return string.IsNullOrEmpty(_processProcessDetailAttributeDict[x.ColumnName][colAttributeName]) ? x.ColumnName : _processProcessDetailAttributeDict[x.ColumnName][colAttributeName];
  694. }
  695. return x.ColumnName;
  696. });
  697. stringBuilder.AppendLine($"{csv}{csv}{csv}{csv}{csv}{string.Join($"{csv}", subColNames.Cast<DataColumn>())} {csv}{string.Join($"{csv}", systemColNames ?? new string[0])} {csv}{string.Join($"{csv}", pmColNames ?? new string[0])}");
  698. }
  699. for (int i = 0; i < maxRow; i++)
  700. {
  701. BusyIndicatorContent = $"Total data {maxRow} current {i + 1} ...";
  702. var pmRow = pmDataTable != null && pmDataTable.Rows.Count > 0 ? pmDataTable.Rows[i] : null;
  703. var systemRow = systemDataTable != null && systemDataTable.Rows.Count > 0 ? systemDataTable.Rows[i] : null;
  704. //float timeIndex = 0;
  705. //float.TryParse(item.Key.ToString(), out timeIndex);
  706. //DateTime dateTimeKey = startTime.AddMilliseconds(timeIndex * 1000); ;// DateTime.Parse(item.Key.ToString());
  707. DateTime dateTimeKey = new DateTime(systemRow != null ? (long)systemRow[0] : (long)pmRow[0]);
  708. var tempStepInfo = _stepInfo.OrderByDescending(x => x.StartTime).Where(x => x.StartTime <= dateTimeKey).FirstOrDefault();
  709. if (tempStepInfo != null)// && dateTimeKey > _stepInfo[iIndex].StartTime && x.StepEndTime >= dateTimeKey
  710. {
  711. stepID = tempStepInfo.StepNo;
  712. stepName = tempStepInfo.StepName;
  713. subRecipeStepName = tempStepInfo.SubRecipeStepName;
  714. subRecipeStepNumber = tempStepInfo.SubRecipeStepNumber;
  715. subRecipeLoopInfo = !string.IsNullOrEmpty(tempStepInfo.SubRecipeLoopInfo) ? tempStepInfo.SubRecipeLoopInfo.Replace("/", "|") : tempStepInfo.SubRecipeLoopInfo;
  716. tempCorrection = !string.IsNullOrEmpty(tempStepInfo.TempCorrection) ? tempStepInfo.TempCorrection : "";
  717. tempPid = !string.IsNullOrEmpty(tempStepInfo.TempPid) ? tempStepInfo.TempPid : "";
  718. }
  719. if (pmRow == null && systemRow != null)
  720. {
  721. stringBuilder.AppendLine($"{csv}{dateTimeKey.ToString("yyyy/MM/dd")}{csv}{dateTimeKey.ToString("HH:mm:ss:fff")}{csv}{stepID}{csv}{stepName}{csv}{subRecipeStepName}{csv}{subRecipeStepNumber}{csv}{subRecipeLoopInfo}{csv}{tempCorrection}{csv}{tempPid}{csv}{string.Join($"{csv}", systemRow.ItemArray.ToList().GetRange(1, systemRow.ItemArray.Count() - 1).Select(x => x.ToString()))}{csv}{string.Join($"{csv}", Enumerable.Repeat("", pmDataTable?.Columns.Count ?? 0).ToArray())}");
  722. }
  723. else if (pmRow != null && systemRow == null)
  724. {
  725. stringBuilder.AppendLine($"{csv}{dateTimeKey.ToString("yyyy/MM/dd")}{csv}{dateTimeKey.ToString("HH:mm:ss:fff")}{csv}{stepID}{csv}{stepName}{csv}{subRecipeStepName}{csv}{subRecipeStepNumber}{csv}{subRecipeLoopInfo}{csv}{tempCorrection}{csv}{tempPid}{csv}{string.Join($"{csv}", Enumerable.Repeat("", systemDataTable?.Columns?.Count ?? 0).ToArray())}{csv}{string.Join($"{csv}", pmRow.ItemArray.ToList().GetRange(1, pmRow.ItemArray.Count() - 1).Select(x => x.ToString()))}");
  726. }
  727. else if (systemDataTable != null)
  728. {
  729. stringBuilder.AppendLine($"{csv}{dateTimeKey.ToString("yyyy/MM/dd")}{csv}{dateTimeKey.ToString("HH:mm:ss:fff")}{csv}{stepID}{csv}{stepName}{csv}{subRecipeStepName}{csv}{subRecipeStepNumber}{csv}{subRecipeLoopInfo}{csv}{tempCorrection}{csv}{tempPid}{csv}{string.Join($"{csv}", systemDataTable.Rows[i].ItemArray.ToList().GetRange(1, systemDataTable.Rows[i].ItemArray.Count() - 1).Select(x => x.ToString()))}{csv}{string.Join($"{csv}", pmDataTable.Rows[i].ItemArray.ToList().GetRange(1, pmDataTable.Rows[i].ItemArray.Count() - 1).Select(x => x.ToString()))}");
  730. }
  731. if (i == maxRow - 1)
  732. {
  733. var str = stringBuilder.ToString();
  734. str = str.TrimEnd((new char[] { '\r', '\n' }));
  735. FileHelper.Instance.SaveNewLineDataToTxt(fileName, str, true);
  736. stringBuilder.Clear();
  737. }
  738. }
  739. }
  740. static string CheckAndReplace(string input)
  741. {
  742. if (input.StartsWith("PM1"))
  743. {
  744. return input.Substring(4);
  745. }
  746. if (input.StartsWith("System"))
  747. {
  748. return input.Substring(7);
  749. }
  750. return input;
  751. }
  752. /// <summary>
  753. /// 取消查询。
  754. /// </summary>
  755. public void CancelQuery()
  756. {
  757. Task.Run(() =>
  758. {
  759. if (_cancellationTokenSource?.Token.CanBeCanceled == true)
  760. {
  761. _cancellationTokenSource.Cancel();
  762. }
  763. Thread.Sleep(100);
  764. //_progQueryUpdate.Report(new ProgressUpdatingEventArgs(100, 100, ""));
  765. //_progChartSuspendUpdating.Report(false);
  766. });
  767. }
  768. }
  769. }