RecipeFileManager.cs 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231
  1. using Aitex.Common.Util;
  2. using Aitex.Core.RT.Event;
  3. using Aitex.Core.RT.Log;
  4. using Aitex.Core.Util;
  5. using Aitex.Core.Utilities;
  6. using Aitex.Core.WCF;
  7. using MECF.Framework.Common.Equipment;
  8. using MECF.Framework.Common.Properties;
  9. using MECF.Framework.Common.RecipeCenter;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.IO;
  13. using System.Text;
  14. using System.Text.RegularExpressions;
  15. using System.Xml;
  16. using System.Xml.Schema;
  17. using Venus_Core;
  18. namespace Aitex.Core.RT.RecipeCenter
  19. {
  20. public class RecipeFileManager : Singleton<RecipeFileManager>
  21. {
  22. //sequence文件 统一放在 Recipes/Sequence 文件夹下面
  23. public const string SequenceFolder = "Sequence";
  24. public const string SourceModule = "Recipe";
  25. private bool _recipeIsValid;
  26. private List<string> _validationErrors = new List<string>();
  27. private List<string> _validationWarnings = new List<string>();
  28. IRecipeFileContext _rcpContext;
  29. private ISequenceFileContext _seqContext;
  30. public void Initialize(IRecipeFileContext context)
  31. {
  32. Initialize(context, null, true);
  33. }
  34. public void Initialize(IRecipeFileContext context, bool enableService)
  35. {
  36. Initialize(context, null, enableService);
  37. }
  38. public void Initialize(IRecipeFileContext rcpContext, ISequenceFileContext seqContext, bool enableService)
  39. {
  40. _rcpContext = rcpContext == null ? new DefaultRecipeFileContext() : rcpContext;
  41. _seqContext = seqContext == null ? new DefaultSequenceFileContext() : seqContext;
  42. CultureSupported.UpdateCoreCultureResource(CultureSupported.English);
  43. //if (enableService)
  44. //{
  45. // Singleton<WcfServiceManager>.Instance.Initialize(new Type[]
  46. // {
  47. // typeof(RecipeService)
  48. // });
  49. //}
  50. var dir = string.Format("{0}{1}\\", PathManager.GetRecipeDir(), SequenceFolder);
  51. DirectoryInfo di = new DirectoryInfo(dir);
  52. if (!di.Exists)
  53. {
  54. di.Create();
  55. }
  56. }
  57. private void ValidationEventHandler(object sender, ValidationEventArgs e)
  58. {
  59. switch (e.Severity)
  60. {
  61. case XmlSeverityType.Error:
  62. _validationErrors.Add(e.Message);
  63. _recipeIsValid = false;
  64. break;
  65. case XmlSeverityType.Warning:
  66. _validationWarnings.Add(e.Message);
  67. break;
  68. }
  69. }
  70. /// <summary>
  71. /// XML schema checking
  72. /// </summary>
  73. /// <param name="chamId"></param>
  74. /// <param name="recipeName"></param>
  75. /// <param name="recipeContent"></param>
  76. /// <param name="reason"></param>
  77. /// <returns></returns>
  78. public bool ValidateRecipe(string chamberId, string recipeName, string recipeContent, out List<string> reason)
  79. {
  80. try
  81. {
  82. XmlDocument document = new XmlDocument();
  83. document.LoadXml(recipeContent);
  84. MemoryStream schemaStream = new MemoryStream(ASCIIEncoding.ASCII.GetBytes(GetRecipeSchema(chamberId)));
  85. XmlReader xmlSchemaReader = XmlReader.Create(schemaStream);
  86. XmlSchema schema1 = XmlSchema.Read(xmlSchemaReader, ValidationEventHandler);
  87. document.Schemas.Add(schema1);
  88. document.LoadXml(recipeContent);
  89. ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);
  90. _recipeIsValid = true;
  91. _validationErrors = new List<string>();
  92. _validationWarnings = new List<string>();
  93. // Validates recipe.
  94. document.Validate(eventHandler);
  95. }
  96. catch (Exception ex)
  97. {
  98. LOG.WriteExeption(ex);
  99. _recipeIsValid = false;
  100. }
  101. if (!_recipeIsValid && _validationErrors.Count == 0)
  102. {
  103. _validationErrors.Add(Resources.RecipeFileManager_ValidateRecipe_XMLSchemaValidateFailed);
  104. }
  105. reason = _validationErrors;
  106. return _recipeIsValid;
  107. }
  108. /// <summary>
  109. /// Check recipe content
  110. /// </summary>
  111. /// <param name="chamId"></param>
  112. /// <param name="recipeContent"></param>
  113. /// <param name="reasons"></param>
  114. /// <returns></returns>
  115. public bool CheckRecipe(string chamberId, string recipeContent, out List<string> reasons)
  116. {
  117. reasons = new List<string>();
  118. //add recipe content validation here
  119. try
  120. {
  121. var xmlFormat = new XmlDocument();
  122. xmlFormat.LoadXml(GetRecipeFormatXml(chamberId));
  123. var mfcDic = new Dictionary<string, double>(); //name + scale
  124. var pcDic = new Dictionary<string, double>(); //name + scale
  125. foreach (XmlElement mfc in xmlFormat.SelectNodes("/TableRecipeFormat/Catalog/Group/Step[@DeviceType='MFC']"))
  126. {
  127. mfcDic.Add(mfc.Attributes["ControlName"].Value, Convert.ToDouble(mfc.Attributes["Max"].Value));
  128. }
  129. foreach (XmlElement pc in xmlFormat.SelectNodes("/TableRecipeFormat/Catalog/Group/Step[@DeviceType='PC']"))
  130. {
  131. pcDic.Add(pc.Attributes["ControlName"].Value, Convert.ToDouble(pc.Attributes["Max"].Value));
  132. }
  133. //var spindleMaxSpeed = Convert.ToDouble(xmlFormat.SelectSingleNode("/TableRecipeFormat/Catalog/Group/Step[@ControlName='Spindle.Speed']").Attributes["Max"].Value);
  134. var xmlRecipe = new XmlDocument();
  135. xmlRecipe.LoadXml(recipeContent);
  136. //read in all recipe items
  137. Dictionary<int, Dictionary<string, string>> recipeItems = new Dictionary<int, Dictionary<string, string>>();
  138. var stepElements = xmlRecipe.SelectNodes("/TableRecipeData/Step");
  139. for (int stepNo = 0; stepNo < stepElements.Count; stepNo++)
  140. {
  141. var stepElement = stepElements[stepNo] as XmlElement;
  142. var step = new Dictionary<string, string>();
  143. recipeItems.Add(stepNo, step);
  144. foreach (XmlAttribute att1 in stepElement.Attributes)
  145. {
  146. step.Add(att1.Name, att1.Value);
  147. }
  148. foreach (XmlElement subNd1 in stepElement.ChildNodes)
  149. {
  150. foreach (XmlAttribute att2 in subNd1.Attributes)
  151. {
  152. step.Add(att2.Name, att2.Value);
  153. }
  154. foreach (XmlElement subNd2 in subNd1.ChildNodes)
  155. {
  156. foreach (XmlAttribute att3 in subNd2.Attributes)
  157. {
  158. step.Add(att3.Name, att3.Value);
  159. }
  160. foreach (XmlElement subNd3 in subNd2.ChildNodes)
  161. {
  162. foreach (XmlAttribute att4 in subNd3.Attributes)
  163. {
  164. step.Add(att4.Name, att4.Value);
  165. }
  166. }
  167. }
  168. }
  169. }
  170. #region check loop control
  171. for (int j = 0; j < recipeItems.Count; j++)
  172. {
  173. var loopStr = recipeItems[j]["Loop"];
  174. bool isLoopStart = Regex.IsMatch(loopStr, @"^Loop\x20\d+$");
  175. bool isLoopEnd = Regex.IsMatch(loopStr, @"^Loop End$");
  176. bool isNullOrEmpty = string.IsNullOrWhiteSpace(loopStr);
  177. if (!isLoopEnd && !isLoopStart && !isNullOrEmpty)
  178. {
  179. string reason = string.Format("Value '{0}' not valid", loopStr);
  180. reasons.Add(string.Format("第{0}步,{1}。", j + 1, reason));
  181. }
  182. if (isLoopEnd)
  183. {
  184. string reason = "Loop Start 缺失";
  185. reasons.Add(string.Format("第{0}步,{1}。", j + 1, reason));
  186. }
  187. else if (isLoopStart)
  188. {
  189. for (int k = j + 1; k < recipeItems.Count; k++)
  190. {
  191. var loopStr2 = recipeItems[k]["Loop"];
  192. bool isCurStepLoopStart = Regex.IsMatch(loopStr2, @"^Loop\x20\d+$");
  193. bool isCurStepLoopEnd = Regex.IsMatch(loopStr2, @"^Loop End$");
  194. isNullOrEmpty = string.IsNullOrWhiteSpace(loopStr2);
  195. if (!isCurStepLoopEnd && !isCurStepLoopStart && !isNullOrEmpty)
  196. {
  197. string reason = string.Format("Value '{0}' not valid", loopStr2);
  198. reasons.Add(string.Format("第{0}步,{1}。", k + 1, reason));
  199. }
  200. else if (isCurStepLoopStart)
  201. {
  202. string reason = "前面循环没有结束,不能设置新的Loop Start标志";
  203. reasons.Add(string.Format("第{0}步,{1}。", k + 1, reason));
  204. }
  205. else if (isCurStepLoopEnd)
  206. {
  207. j = k;
  208. break;
  209. }
  210. if (k == recipeItems.Count - 1)
  211. {
  212. j = k;
  213. string reason = "Loop End 缺失";
  214. reasons.Add(string.Format("第{0}步,{1}。", k + 1, reason));
  215. }
  216. }
  217. }
  218. }
  219. #endregion
  220. //check mfc range
  221. for (int stepNo = 0; stepNo < recipeItems.Count; stepNo++)
  222. {
  223. foreach (var mfcName in mfcDic.Keys)
  224. {
  225. if (recipeItems[stepNo].ContainsKey(mfcName))
  226. {
  227. var mfcSetpoint = Convert.ToDouble(recipeItems[stepNo][mfcName]);
  228. if (mfcSetpoint < 0 || mfcSetpoint > mfcDic[mfcName])
  229. {
  230. reasons.Add(string.Format("第{0}步,{1}设定{2},超出 0~{3}sccm范围。", stepNo + 1, mfcName, mfcSetpoint, mfcDic[mfcName]));
  231. }
  232. }
  233. }
  234. //check pc range
  235. foreach (var pcName in pcDic.Keys)
  236. {
  237. if (recipeItems[stepNo].ContainsKey(pcName))
  238. {
  239. var pcSetpoint = Convert.ToDouble(recipeItems[stepNo][pcName]);
  240. if (pcSetpoint < 0 || pcSetpoint > pcDic[pcName])
  241. {
  242. reasons.Add(string.Format("第{0}步,{1}设定{2},超出 0~{3}mbar范围。", stepNo + 1, pcName, pcSetpoint, pcDic[pcName]));
  243. }
  244. }
  245. }
  246. }
  247. #region recipe parameter validation
  248. //reading predefined varaible
  249. var recipePredfine = new Dictionary<string, string>();
  250. foreach (XmlElement nd in xmlFormat.SelectNodes("/TableRecipeFormat/Validation/Predefine/Item"))
  251. {
  252. recipePredfine.Add(nd.Attributes["VarName"].Value, nd.Attributes["Value"].Value);
  253. }
  254. #endregion
  255. }
  256. catch (Exception ex)
  257. {
  258. reasons.Add(Resources.RecipeFileManager_CheckRecipe_RecipeValidationFailed + ex.Message);
  259. LOG.WriteExeption(ex);
  260. return false;
  261. }
  262. return reasons.Count == 0;
  263. }
  264. /// <summary>
  265. /// This method will be invoked by two places:
  266. /// (1) Load a recipe from server to GUI for editing (do not need validation when loading, do validation when saving);
  267. /// (2) Load a recipe from recipe engine to run process(always do a validation before run recipe);
  268. /// </summary>
  269. /// <param name="recipeName"></param>
  270. /// <param name="needValidation">indicate whether a recipe format validation is needed or not</param>
  271. /// <returns></returns>
  272. public string LoadRecipe(string chamberId, string recipeName, bool needValidation)
  273. {
  274. string rcp = string.Empty;
  275. try
  276. {
  277. using (StreamReader fs = new StreamReader(GenerateRecipeFilePath(chamberId, recipeName)))
  278. {
  279. rcp = fs.ReadToEnd();
  280. fs.Close();
  281. }
  282. }
  283. catch (Exception ex)
  284. {
  285. LOG.WriteExeption($"load recipe file failed, {recipeName}", ex);
  286. rcp = string.Empty;
  287. }
  288. return rcp;
  289. }
  290. public string LoadRecipeByPath(string path)
  291. {
  292. string rcp = string.Empty;
  293. try
  294. {
  295. using (StreamReader fs = new StreamReader(path))
  296. {
  297. rcp = fs.ReadToEnd();
  298. fs.Close();
  299. }
  300. }
  301. catch (Exception ex)
  302. {
  303. // LOG.WriteExeption($"load recipe file failed, {recipeName}", ex);
  304. rcp = string.Empty;
  305. }
  306. return rcp;
  307. }
  308. /// <summary>
  309. /// This method will be invoked by two places:
  310. /// (1) Load a recipe from server to GUI for editing (do not need validation when loading, do validation when saving);
  311. /// (2) Load a recipe from recipe engine to run process(always do a validation before run recipe);
  312. /// </summary>
  313. /// <param name="recipeName"></param>
  314. /// <param name="needValidation">indicate whether a recipe format validation is needed or not</param>
  315. /// <returns></returns>
  316. public string LoadRecipe(string chamberId, string recipeName, bool needValidation,string type)
  317. {
  318. string rcp = string.Empty;
  319. try
  320. {
  321. using (StreamReader fs = new StreamReader(GenerateRecipeFilePath(chamberId,type, recipeName)))
  322. {
  323. rcp = fs.ReadToEnd();
  324. fs.Close();
  325. }
  326. }
  327. catch (Exception ex)
  328. {
  329. LOG.WriteExeption($"load recipe file failed, {recipeName}", ex);
  330. rcp = string.Empty;
  331. }
  332. return rcp;
  333. }
  334. /// <summary>
  335. /// Get recipe list
  336. /// </summary>
  337. /// <param name="chamId"></param>
  338. /// <param name="includingUsedRecipe"></param>
  339. /// <returns></returns>
  340. public IEnumerable<string> GetRecipes(string chamberId, bool includingUsedRecipe)
  341. {
  342. return _rcpContext.GetRecipes(chamberId, includingUsedRecipe);
  343. }
  344. /// <summary>
  345. /// Get recipe list in xml format
  346. /// </summary>
  347. /// <param name="chamId"></param>
  348. /// <param name="includingUsedRecipe"></param>
  349. /// <returns></returns>
  350. public string GetXmlRecipeList(string chamberId, bool includingUsedRecipe)
  351. {
  352. XmlDocument doc = new XmlDocument();
  353. var baseFolderPath = getRecipeDirPath(chamberId);
  354. DirectoryInfo curFolderInfo = new DirectoryInfo(baseFolderPath);
  355. doc.AppendChild(GenerateRecipeList(chamberId, curFolderInfo, doc, includingUsedRecipe));
  356. return doc.OuterXml;
  357. }
  358. public void SaveRecipeHistory(string chamberId, string recipeName, string recipeContent, bool needSaveAs = true)
  359. {
  360. try
  361. {
  362. if (!string.IsNullOrEmpty(recipeName) && needSaveAs)
  363. {
  364. string newRecipeName = string.Format("HistoryRecipe\\{0}\\{1}", DateTime.Now.ToString("yyyyMM"), recipeName);
  365. SaveRecipe(chamberId, newRecipeName, recipeContent, true, false);
  366. //LOG.Write(string.Format("{0}通知TM保存工艺程序{1}", chamberId, recipeName));
  367. }
  368. }
  369. catch (Exception ex)
  370. {
  371. LOG.WriteExeption(string.Format("保存{0}工艺程序{1}发生错误", chamberId, recipeName), ex);
  372. }
  373. }
  374. /// <summary>
  375. /// generate recipe list information in current directory
  376. /// </summary>
  377. /// <param name="chamId"></param>
  378. /// <param name="currentDir"></param>
  379. /// <param name="doc"></param>
  380. /// <returns></returns>
  381. XmlElement GenerateRecipeList(string chamberId, DirectoryInfo currentDir, XmlDocument doc, bool includingUsedRecipe)
  382. {
  383. int trimLength = getRecipeDirPath(chamberId).Length;
  384. XmlElement folderEle = doc.CreateElement("Folder");
  385. folderEle.SetAttribute("Name", currentDir.FullName.Substring(trimLength));
  386. DirectoryInfo[] dirInfos = currentDir.GetDirectories();
  387. foreach (DirectoryInfo dirInfo in dirInfos)
  388. {
  389. if (!includingUsedRecipe && dirInfo.Name == "HistoryRecipe")
  390. continue;
  391. folderEle.AppendChild(GenerateRecipeList(chamberId, dirInfo, doc, includingUsedRecipe));
  392. }
  393. FileInfo[] fileInfos = currentDir.GetFiles("*.rcp");
  394. foreach (FileInfo fileInfo in fileInfos)
  395. {
  396. XmlElement fileNd = doc.CreateElement("File");
  397. string fileStr = fileInfo.FullName.Substring(trimLength).TrimStart(new char[] { '\\' }); ;
  398. fileStr = fileStr.Substring(0, fileStr.LastIndexOf("."));
  399. fileNd.SetAttribute("Name", fileStr);
  400. folderEle.AppendChild(fileNd);
  401. }
  402. return folderEle;
  403. }
  404. /// <summary>
  405. /// Delete a recipe by recipe name
  406. /// </summary>
  407. /// <param name="chamId"></param>
  408. /// <param name="recipeName"></param>
  409. /// <returns></returns>
  410. public bool DeleteRecipe(string chamberId, string recipeName)
  411. {
  412. try
  413. {
  414. var path = GenerateRecipeFilePath(chamberId, recipeName);
  415. if (!_rcpContext.EnableEdit(path))
  416. return false;
  417. File.Delete(path);
  418. InfoDialog(string.Format(Resources.RecipeFileManager_DeleteRecipe_RecipeFile0DeleteSucceeded, recipeName));
  419. }
  420. catch (Exception ex)
  421. {
  422. LOG.WriteExeption("删除recipe file 出错", ex);
  423. WarningDialog(string.Format(Resources.RecipeFileManager_DeleteRecipe_RecipeFile0DeleteFailed, recipeName));
  424. return false;
  425. }
  426. return true;
  427. }
  428. /// <summary>
  429. /// Rename recipe
  430. /// </summary>
  431. /// <param name="chamId"></param>
  432. /// <param name="oldName"></param>
  433. /// <param name="newName"></param>
  434. /// <returns></returns>
  435. public bool RenameRecipe(string chamId, string oldName, string newName)
  436. {
  437. try
  438. {
  439. var path = GenerateRecipeFilePath(chamId, newName);
  440. if (!_rcpContext.EnableEdit(path))
  441. return false;
  442. if (File.Exists(path))
  443. {
  444. WarningDialog(string.Format(Resources.RecipeFileManager_RenameRecipe_RecipeFile0FileExisted, oldName));
  445. return false;
  446. }
  447. else
  448. {
  449. File.Move(GenerateRecipeFilePath(chamId, oldName), GenerateRecipeFilePath(chamId, newName));
  450. InfoDialog(string.Format(Resources.RecipeFileManager_RenameRecipe_RecipeFile0Renamed, oldName, newName));
  451. }
  452. }
  453. catch (Exception ex)
  454. {
  455. LOG.WriteExeption("重命名recipe file 出错", ex);
  456. WarningDialog(string.Format(Resources.RecipeFileManager_RenameRecipe_RecipeFile0RenameFailed, oldName, newName));
  457. return false;
  458. }
  459. return true;
  460. }
  461. //private void EventInfo(string message)
  462. //{
  463. // _rcpContext.PostInfoEvent(message);
  464. //}
  465. //private void EventWarning(string message)
  466. //{
  467. // _rcpContext.PostWarningEvent(message);
  468. //}
  469. //private void EventAlarm(string message)
  470. //{
  471. // _rcpContext.PostAlarmEvent(message);
  472. //}
  473. private void InfoDialog(string message)
  474. {
  475. _rcpContext.PostInfoDialogMessage(message);
  476. }
  477. private void WarningDialog(string message)
  478. {
  479. _rcpContext.PostWarningDialogMessage(message);
  480. }
  481. //private void AlarmDialog(string message)
  482. //{
  483. // _rcpContext.PostAlarmDialogMessage(message);
  484. //}
  485. private void EventDialog(string message, List<string> reason)
  486. {
  487. string msg = message;
  488. foreach (var r in reason)
  489. {
  490. msg += "\r\n" + r;
  491. }
  492. _rcpContext.PostDialogEvent(msg);
  493. }
  494. /// <summary>
  495. /// get recipe's file path
  496. /// </summary>
  497. /// <param name="recipeName"></param>
  498. /// <returns></returns>
  499. private string GenerateRecipeFilePath(string chamId, string recipeName)
  500. {
  501. return getRecipeDirPath(chamId) + recipeName + ".rcp";
  502. }
  503. public string GenerateRecipeFilePath(string chamId, string type,string recipeName)
  504. {
  505. return getRecipeDirPath(chamId) +type+"\\"+ recipeName + ".rcp";
  506. }
  507. private string GenerateSequenceFilePath(string chamId, string recipeName)
  508. {
  509. return getRecipeDirPath(chamId) + recipeName + ".seq";
  510. }
  511. /// <summary>
  512. /// get recipe's dir path
  513. /// </summary>
  514. /// <param name="recipeName"></param>
  515. /// <returns></returns>
  516. private string getRecipeDirPath(string chamId)
  517. {
  518. var dir = string.Format("{0}{1}\\", PathManager.GetRecipeDir(), chamId);
  519. DirectoryInfo di = new DirectoryInfo(dir);
  520. if (!di.Exists) di.Create();
  521. return dir;
  522. }
  523. /// <summary>
  524. /// delete a recipe folder
  525. /// </summary>
  526. /// <param name="chamId"></param>
  527. /// <param name="folderName"></param>
  528. /// <returns></returns>
  529. public bool DeleteFolder(string chamId, string folderName)
  530. {
  531. try
  532. {
  533. Directory.Delete(getRecipeDirPath(chamId) + folderName, true);
  534. InfoDialog(string.Format(Resources.RecipeFileManager_DeleteFolder_RecipeFolder0DeleteSucceeded, folderName));
  535. }
  536. catch (Exception ex)
  537. {
  538. LOG.WriteExeption("删除recipe folder 出错", ex);
  539. WarningDialog(string.Format("recipe folder {0} delete failed", folderName));
  540. return false;
  541. }
  542. return true;
  543. }
  544. /// <summary>
  545. /// save as recipe content
  546. /// </summary>
  547. /// <param name="chamId"></param>
  548. /// <param name="recipeName"></param>
  549. /// <param name="recipeContent"></param>
  550. /// <returns></returns>
  551. public bool SaveAsRecipe(string chamId, string recipeName, string recipeContent)
  552. {
  553. var path = GenerateRecipeFilePath(chamId, recipeName);
  554. //if (File.Exists(path))
  555. //{
  556. // WarningDialog(string.Format(Resources.RecipeFileManager_SaveAsRecipe_RecipeFile0savefailed, recipeName));
  557. // return false;
  558. //}
  559. return SaveRecipe(chamId, recipeName, recipeContent, true, true);
  560. }
  561. public bool SaveAsRecipe(string chamId,string type, string recipeName, string recipeContent)
  562. {
  563. var path = GenerateRecipeFilePath(chamId, type, recipeName);
  564. if (File.Exists(path))
  565. {
  566. LOG.Write(eEvent.WARN_SYSTEM_CONFIG, ModuleName.System, $"{recipeName}文件已存在,创建recipe {recipeName}失败");
  567. //WarningDialog(string.Format(Resources.RecipeFileManager_SaveAsRecipe_RecipeFile0savefailed, recipeName));
  568. return false;
  569. }
  570. return SaveRecipe(chamId,type, recipeName, recipeContent, true, true);
  571. }
  572. /// <summary>
  573. /// save recipe content
  574. /// </summary>
  575. /// <param name="chamId"></param>
  576. /// <param name="recipeName"></param>
  577. /// <param name="recipeContent"></param>
  578. /// <returns></returns>
  579. public bool SaveRecipe(string chamId, string recipeName, string recipeContent, bool clearBarcode, bool notifyUI)
  580. {
  581. bool ret = true;
  582. try
  583. {
  584. var path = GenerateRecipeFilePath(chamId, recipeName);
  585. if (!_rcpContext.EnableEdit(path))
  586. return false;
  587. FileInfo fi = new FileInfo(path);
  588. if (!fi.Directory.Exists)
  589. fi.Directory.Create();
  590. File.WriteAllText(path, RecipeUnity.ConvertJsonString(recipeContent), Encoding.UTF8);
  591. }
  592. catch (Exception ex)
  593. {
  594. LOG.WriteExeption("保存recipe file 出错", ex);
  595. if (notifyUI)
  596. {
  597. WarningDialog(string.Format(Resources.RecipeFileManager_SaveRecipe_RecipeFile0SaveFailed, recipeName));
  598. }
  599. ret = false;
  600. }
  601. return ret;
  602. }
  603. /// <summary>
  604. /// save recipe content
  605. /// </summary>
  606. /// <param name="chamId"></param>
  607. /// <param name="recipeName"></param>
  608. /// <param name="recipeContent"></param>
  609. /// <returns></returns>
  610. public bool SaveRecipe(string chamId,string type, string recipeName, string recipeContent, bool clearBarcode, bool notifyUI)
  611. {
  612. bool ret = true;
  613. try
  614. {
  615. var path = GenerateRecipeFilePath(chamId, type, recipeName);
  616. if (!_rcpContext.EnableEdit(path))
  617. return false;
  618. FileInfo fi = new FileInfo(path);
  619. if (!fi.Directory.Exists)
  620. fi.Directory.Create();
  621. File.WriteAllText(path, RecipeUnity.ConvertJsonString(recipeContent), Encoding.UTF8);
  622. }
  623. catch (Exception ex)
  624. {
  625. LOG.WriteExeption("保存recipe file 出错", ex);
  626. if (notifyUI)
  627. {
  628. WarningDialog(string.Format(Resources.RecipeFileManager_SaveRecipe_RecipeFile0SaveFailed, recipeName));
  629. }
  630. ret = false;
  631. }
  632. return ret;
  633. }
  634. /// <summary>
  635. /// move recipe file
  636. /// </summary>
  637. /// <param name="chamId"></param>
  638. /// <param name="recipeName"></param>
  639. /// <returns></returns>
  640. public bool MoveRecipeFile(string chamId, string recipeName, string tragetFolderName, bool clearBarcode, bool notifyUI)
  641. {
  642. bool ret = true;
  643. try
  644. {
  645. var path = getRecipeDirPath(chamId);
  646. string fullFileName = path + recipeName + ".rcp";
  647. string tragetFullFilePath = path + tragetFolderName;
  648. File.Move(fullFileName, tragetFullFilePath + "\\" + recipeName.Split('\\')[recipeName.Split('\\').Length - 1] + ".rcp");
  649. if (notifyUI)
  650. {
  651. InfoDialog(string.Format(Resources.RecipeFileManager_MoveRecipe_RecipeFile0MoveCompleted, recipeName));
  652. }
  653. else
  654. {
  655. LOG.Write(eEvent.EV_SEQUENCE, ModuleName.System, string.Format(Resources.RecipeFileManager_MoveRecipe_RecipeFile0MoveCompleted, recipeName));
  656. }
  657. }
  658. catch (Exception ex)
  659. {
  660. LOG.WriteExeption("移动 recipe file 出错", ex);
  661. if (notifyUI)
  662. {
  663. WarningDialog(string.Format(Resources.RecipeFileManager_MoveRecipe_RecipeFile0MoveFailed, recipeName));
  664. }
  665. ret = false;
  666. }
  667. return ret;
  668. }
  669. /// <summary>
  670. /// create a new recipe folder
  671. /// </summary>
  672. /// <param name="chamId"></param>
  673. /// <param name="folderName"></param>
  674. /// <returns></returns>
  675. public bool CreateFolder(string chamId, string folderName)
  676. {
  677. try
  678. {
  679. Directory.CreateDirectory(getRecipeDirPath(chamId) + folderName);
  680. InfoDialog(string.Format(Resources.RecipeFileManager_CreateFolder_RecipeFolder0Created, folderName));
  681. }
  682. catch (Exception ex)
  683. {
  684. LOG.WriteExeption("创建recipe folder 出错", ex);
  685. WarningDialog(string.Format(Resources.RecipeFileManager_CreateFolder_RecipeFolder0CreateFailed, folderName));
  686. return false;
  687. }
  688. return true;
  689. }
  690. /// <summary>
  691. /// Rename recipe folder name
  692. /// </summary>
  693. /// <param name="chamId"></param>
  694. /// <param name="oldName"></param>
  695. /// <param name="newName"></param>
  696. /// <returns></returns>
  697. public bool RenameFolder(string chamId, string oldName, string newName)
  698. {
  699. try
  700. {
  701. string oldPath = getRecipeDirPath(chamId) + oldName;
  702. string newPath = getRecipeDirPath(chamId) + newName;
  703. Directory.Move(oldPath, newPath);
  704. InfoDialog(string.Format(Resources.RecipeFileManager_RenameFolder_RecipeFolder0renamed, oldName, newName));
  705. }
  706. catch (Exception ex)
  707. {
  708. LOG.WriteExeption("重命名recipe folder 出错", ex);
  709. WarningDialog(string.Format(Resources.RecipeFileManager_RenameFolder_RecipeFolder0RenameFailed, oldName, newName));
  710. return false;
  711. }
  712. return true;
  713. }
  714. private string GetRecipeBody(string chamberId, string nodePath)
  715. {
  716. if (_rcpContext == null)
  717. return string.Empty;
  718. string schema = _rcpContext.GetRecipeDefiniton(chamberId);
  719. XmlDocument dom = new XmlDocument();
  720. dom.LoadXml(schema);
  721. XmlNode node = dom.SelectSingleNode(nodePath);
  722. return node.OuterXml;
  723. }
  724. /// <summary>
  725. /// get reactor's recipe format define file
  726. /// </summary>
  727. /// <param name="chamId"></param>
  728. /// <returns></returns>
  729. public string GetRecipeFormatXml(string chamberId)
  730. {
  731. return GetRecipeBody(chamberId, "/Aitex/TableRecipeFormat");
  732. }
  733. /// <summary>
  734. /// get reactor's template recipe file
  735. /// </summary>
  736. /// <param name="chamId"></param>
  737. /// <returns></returns>
  738. public string GetRecipeTemplate(string chamberId)
  739. {
  740. if (_rcpContext != null)
  741. return _rcpContext.GetRecipeTemplate(chamberId);
  742. return GetRecipeBody(chamberId, "/Aitex/TableRecipeData");
  743. }
  744. /// <summary>
  745. /// get reactor's template recipe file
  746. /// </summary>
  747. /// <param name="chamId"></param>
  748. /// <returns></returns>
  749. public string GetRecipeSchema(string chamberId)
  750. {
  751. if (_rcpContext == null)
  752. return string.Empty;
  753. string schema = _rcpContext.GetRecipeDefiniton(chamberId);
  754. XmlDocument dom = new XmlDocument();
  755. dom.LoadXml(schema);
  756. XmlNode node = dom.SelectSingleNode("/Aitex/TableRecipeSchema");
  757. return node.InnerXml;
  758. }
  759. public string GetRecipeByBarcode(string chamberId, string barcode)
  760. {
  761. try
  762. {
  763. string recipePath = PathManager.GetRecipeDir() + chamberId + "\\";
  764. var di = new DirectoryInfo(recipePath);
  765. var fis = di.GetFiles("*.rcp", SearchOption.AllDirectories);
  766. XmlDocument xml = new XmlDocument();
  767. foreach (var fi in fis)
  768. {
  769. string str = fi.FullName.Substring(recipePath.Length);
  770. if (!str.Contains("HistoryRecipe\\"))
  771. {
  772. xml.Load(fi.FullName);
  773. if (xml.SelectSingleNode(string.Format("/TableRecipeData[@Barcode='{0}']", barcode)) != null)
  774. {
  775. return str.Substring(0, str.LastIndexOf('.'));
  776. }
  777. }
  778. }
  779. return string.Empty;
  780. }
  781. catch (Exception ex)
  782. {
  783. LOG.WriteExeption(ex);
  784. return string.Empty;
  785. }
  786. }
  787. #region Sequence
  788. private string GetSequenceConfig(string nodePath)
  789. {
  790. if (_seqContext == null)
  791. return string.Empty;
  792. string schema = _seqContext.GetConfigXml();
  793. XmlDocument dom = new XmlDocument();
  794. dom.LoadXml(schema);
  795. XmlNode node = dom.SelectSingleNode(nodePath);
  796. return node.OuterXml;
  797. }
  798. public string GetSequence(string sequenceName, bool needValidation)
  799. {
  800. string seq = string.Empty;
  801. try
  802. {
  803. using (StreamReader fs = new StreamReader(GenerateSequenceFilePath(SequenceFolder, sequenceName)))
  804. {
  805. seq = fs.ReadToEnd();
  806. fs.Close();
  807. }
  808. if (needValidation && !_seqContext.Validation(seq))
  809. {
  810. LOG.Write(eEvent.WARN_SEQUENCE, ModuleName.System, $"Read {sequenceName} failed, validation failed");
  811. seq = string.Empty;
  812. }
  813. }
  814. catch (Exception ex)
  815. {
  816. LOG.WriteExeption(ex);
  817. seq = string.Empty;
  818. }
  819. return seq;
  820. }
  821. private void TryAppendNode(XmlElement preOrNextNode, XmlElement curPM,XmlDocument dom, bool isLeft)
  822. {
  823. if (preOrNextNode != null && preOrNextNode.GetAttribute("Position") != "LL" && preOrNextNode.GetAttribute("Position") != "PM")
  824. {
  825. XmlElement newNode = dom.CreateElement("Step");
  826. newNode.SetAttribute("Position", "LL");
  827. newNode.SetAttribute("LLSelection", "LLA,LLB");
  828. if (isLeft)
  829. curPM.ParentNode.InsertBefore(newNode, curPM);
  830. else
  831. curPM.ParentNode.InsertAfter(newNode, curPM);
  832. }
  833. }
  834. public string GetSequenceAndTryAppendLL(string sequenceName, bool needValidation)
  835. {
  836. string seq = string.Empty;
  837. try
  838. {
  839. seq = GetSequence(sequenceName, needValidation);
  840. if(!string.IsNullOrWhiteSpace(seq))
  841. {
  842. XmlDocument dom = new XmlDocument();
  843. dom.LoadXml(seq);
  844. XmlNodeList lstStepNode = dom.SelectNodes("Aitex/TableSequenceData/Step");
  845. if (lstStepNode != null)
  846. {
  847. List<XmlElement> pmList = new List<XmlElement>();
  848. foreach (XmlElement nodeStep in lstStepNode)
  849. {
  850. var positionValue = nodeStep.GetAttribute("Position");
  851. if (positionValue == "PM")
  852. {
  853. pmList.Add(nodeStep);
  854. }
  855. }
  856. foreach (XmlElement pmNode in pmList)
  857. {
  858. TryAppendNode((XmlElement)pmNode.PreviousSibling, pmNode, dom, true);
  859. TryAppendNode((XmlElement)pmNode.NextSibling, pmNode, dom, false);
  860. }
  861. using (var ms = new MemoryStream())
  862. using (var writer = new XmlTextWriter(ms, null))
  863. {
  864. writer.Formatting = Formatting.Indented;
  865. dom.Save(writer);
  866. return Encoding.UTF8.GetString(ms.ToArray());
  867. }
  868. }
  869. }
  870. }
  871. catch(Exception ex)
  872. {
  873. LOG.WriteExeption(ex);
  874. seq = string.Empty;
  875. }
  876. return seq;
  877. }
  878. public List<string> GetSequenceNameList()
  879. {
  880. var result = new List<string>();
  881. try
  882. {
  883. string recipePath = PathManager.GetRecipeDir() + SequenceFolder + "\\";
  884. var di = new DirectoryInfo(recipePath);
  885. var fis = di.GetFiles("*.seq", SearchOption.AllDirectories);
  886. foreach (var fi in fis)
  887. {
  888. string str = fi.FullName.Substring(recipePath.Length);
  889. str = str.Substring(0, str.LastIndexOf('.'));
  890. result.Add(str);
  891. }
  892. }
  893. catch (Exception ex)
  894. {
  895. LOG.WriteExeption(ex);
  896. }
  897. return result;
  898. }
  899. public bool DeleteSequence(string sequenceName)
  900. {
  901. try
  902. {
  903. var path = GenerateSequenceFilePath(SequenceFolder, sequenceName);
  904. if (!_seqContext.EnableEdit(path))
  905. return false;
  906. File.Delete(path);
  907. LOG.Write(eEvent.EV_SEQUENCE, ModuleName.System, $"sequence {sequenceName} deleted");
  908. }
  909. catch (Exception ex)
  910. {
  911. LOG.WriteExeption(ex);
  912. return false;
  913. }
  914. return true;
  915. }
  916. public bool SaveSequence(string sequenceName, string sequenceContent, bool notifyUI)
  917. {
  918. bool ret = true;
  919. try
  920. {
  921. var path = GenerateSequenceFilePath(SequenceFolder, sequenceName);
  922. if (!_seqContext.EnableEdit(path))
  923. return false;
  924. FileInfo fi = new FileInfo(path);
  925. if (!fi.Directory.Exists)
  926. {
  927. fi.Directory.Create();
  928. }
  929. XmlDocument xml = new XmlDocument();
  930. xml.LoadXml(sequenceContent);
  931. XmlTextWriter writer = new XmlTextWriter(path, null);
  932. writer.Formatting = Formatting.Indented;
  933. xml.Save(writer);
  934. writer.Close();
  935. if (notifyUI)
  936. {
  937. EV.PostPopDialogMessage(EventLevel.Information, "Save Complete", $"Sequence {sequenceName} saved ");
  938. }
  939. else
  940. {
  941. LOG.Write(eEvent.EV_SEQUENCE, ModuleName.System, $"Sequence {sequenceName} saved ");
  942. }
  943. }
  944. catch (Exception ex)
  945. {
  946. LOG.WriteExeption(ex);
  947. if (notifyUI)
  948. {
  949. EV.PostPopDialogMessage(EventLevel.Alarm, "Save Error", $"save sequence {sequenceName} failed, " + ex.Message);
  950. }
  951. ret = false;
  952. }
  953. return ret;
  954. }
  955. public bool SaveAsSequence(string sequenceName, string sequenceContent)
  956. {
  957. var path = GenerateSequenceFilePath(SequenceFolder, sequenceName);
  958. if (File.Exists(path))
  959. {
  960. LOG.Write(eEvent.WARN_SEQUENCE, ModuleName.System, $"save sequence {sequenceName} failed, already exist");
  961. return false;
  962. }
  963. return SaveSequence(sequenceName, sequenceContent, false);
  964. }
  965. public bool RenameSequence(string oldName, string newName)
  966. {
  967. try
  968. {
  969. var path = GenerateSequenceFilePath(SequenceFolder, oldName);
  970. if (!_seqContext.EnableEdit(path))
  971. return false;
  972. if (File.Exists(GenerateSequenceFilePath(SequenceFolder, newName)))
  973. {
  974. LOG.Write(eEvent.WARN_SEQUENCE, ModuleName.System, $"{newName} already exist, rename failed");
  975. return false;
  976. }
  977. else
  978. {
  979. File.Move(path, GenerateSequenceFilePath(SequenceFolder, newName));
  980. LOG.Write(eEvent.EV_SEQUENCE, ModuleName.System, $"sequence {oldName} renamed to {newName}");
  981. }
  982. }
  983. catch (Exception ex)
  984. {
  985. LOG.WriteExeption(ex);
  986. return false;
  987. }
  988. return true;
  989. }
  990. public string GetSequenceFormatXml()
  991. {
  992. return GetSequenceConfig("/Aitex/TableSequenceFormat");
  993. }
  994. internal bool DeleteSequenceFolder(string folderName)
  995. {
  996. try
  997. {
  998. Directory.Delete(PathManager.GetRecipeDir() + SequenceFolder + "\\" + folderName, true);
  999. LOG.Write(eEvent.EV_SEQUENCE,ModuleName.System, "Folder " + folderName + "deleted");
  1000. }
  1001. catch (Exception ex)
  1002. {
  1003. //LOG.Write(ex, "delete sequence folder exception");
  1004. LOG.Write(eEvent.WARN_SEQUENCE, ModuleName.System, $"can not delete folder {folderName}, {ex.Message}");
  1005. return false;
  1006. }
  1007. return true;
  1008. }
  1009. internal bool CreateSequenceFolder(string folderName)
  1010. {
  1011. try
  1012. {
  1013. Directory.CreateDirectory(PathManager.GetRecipeDir() + SequenceFolder + "\\" + folderName);
  1014. LOG.Write(eEvent.EV_SEQUENCE, ModuleName.System, "Folder " + folderName + "created");
  1015. }
  1016. catch (Exception ex)
  1017. {
  1018. //LOG.Write(ex, "sequence folder create exception");
  1019. LOG.Write(eEvent.WARN_SEQUENCE, ModuleName.System, $"can not create folder {folderName}, {ex.Message}");
  1020. return false;
  1021. }
  1022. return true;
  1023. }
  1024. internal bool RenameSequenceFolder(string oldName, string newName)
  1025. {
  1026. try
  1027. {
  1028. string oldPath = PathManager.GetRecipeDir() + SequenceFolder + "\\" + oldName;
  1029. string newPath = PathManager.GetRecipeDir() + SequenceFolder + "\\" + newName;
  1030. Directory.Move(oldPath, newPath);
  1031. LOG.Write(eEvent.EV_SEQUENCE, ModuleName.System, $"rename folder from {oldName} to {newName}");
  1032. }
  1033. catch (Exception ex)
  1034. {
  1035. //LOG.Write(ex, "rename sequence folder failed");
  1036. LOG.Write(eEvent.WARN_SEQUENCE, ModuleName.System, $"can not rename folder {oldName}, {ex.Message}");
  1037. return false;
  1038. }
  1039. return true;
  1040. }
  1041. public string GetXmlSequenceList(string chamberId)
  1042. {
  1043. XmlDocument doc = new XmlDocument();
  1044. DirectoryInfo curFolderInfo = new DirectoryInfo(PathManager.GetRecipeDir() + SequenceFolder + "\\");
  1045. doc.AppendChild(GenerateSequenceList(chamberId, curFolderInfo, doc));
  1046. return doc.OuterXml;
  1047. }
  1048. XmlElement GenerateSequenceList(string chamberId, DirectoryInfo currentDir, XmlDocument doc)
  1049. {
  1050. int trimLength = (PathManager.GetRecipeDir() + SequenceFolder + "\\").Length;
  1051. XmlElement folderEle = doc.CreateElement("Folder");
  1052. folderEle.SetAttribute("Name", currentDir.FullName.Substring(trimLength));
  1053. DirectoryInfo[] dirInfos = currentDir.GetDirectories();
  1054. foreach (DirectoryInfo dirInfo in dirInfos)
  1055. {
  1056. folderEle.AppendChild(GenerateSequenceList(chamberId, dirInfo, doc));
  1057. }
  1058. FileInfo[] fileInfos = currentDir.GetFiles("*.seq");
  1059. foreach (FileInfo fileInfo in fileInfos)
  1060. {
  1061. XmlElement fileNd = doc.CreateElement("File");
  1062. string fileStr = fileInfo.FullName.Substring(trimLength).TrimStart(new char[] { '\\' }); ;
  1063. fileStr = fileStr.Substring(0, fileStr.LastIndexOf("."));
  1064. fileNd.SetAttribute("Name", fileStr);
  1065. folderEle.AppendChild(fileNd);
  1066. }
  1067. return folderEle;
  1068. }
  1069. #endregion
  1070. }
  1071. }