RecipeFileManager.cs 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192
  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. //if (needValidation)
  283. //{
  284. // List<string> reason;
  285. // if (!ValidateRecipe(chamberId, recipeName, rcp, out reason))
  286. // {
  287. // rcp = string.Empty;
  288. // LOG.Write("校验recipe file 出错, " + string.Join(",", reason.ToArray()));
  289. // }
  290. //}
  291. }
  292. catch (Exception ex)
  293. {
  294. LOG.WriteExeption($"load recipe file failed, {recipeName}", ex);
  295. rcp = string.Empty;
  296. }
  297. return rcp;
  298. }
  299. /// <summary>
  300. /// Get recipe list
  301. /// </summary>
  302. /// <param name="chamId"></param>
  303. /// <param name="includingUsedRecipe"></param>
  304. /// <returns></returns>
  305. public IEnumerable<string> GetRecipes(string chamberId, bool includingUsedRecipe)
  306. {
  307. return _rcpContext.GetRecipes(chamberId, includingUsedRecipe);
  308. }
  309. /// <summary>
  310. /// Get recipe list in xml format
  311. /// </summary>
  312. /// <param name="chamId"></param>
  313. /// <param name="includingUsedRecipe"></param>
  314. /// <returns></returns>
  315. public string GetXmlRecipeList(string chamberId, bool includingUsedRecipe)
  316. {
  317. XmlDocument doc = new XmlDocument();
  318. var baseFolderPath = getRecipeDirPath(chamberId);
  319. DirectoryInfo curFolderInfo = new DirectoryInfo(baseFolderPath);
  320. doc.AppendChild(GenerateRecipeList(chamberId, curFolderInfo, doc, includingUsedRecipe));
  321. return doc.OuterXml;
  322. }
  323. public void SaveRecipeHistory(string chamberId, string recipeName, string recipeContent, bool needSaveAs = true)
  324. {
  325. try
  326. {
  327. if (!string.IsNullOrEmpty(recipeName) && needSaveAs)
  328. {
  329. string newRecipeName = string.Format("HistoryRecipe\\{0}\\{1}", DateTime.Now.ToString("yyyyMM"), recipeName);
  330. SaveRecipe(chamberId, newRecipeName, recipeContent, true, false);
  331. //LOG.Write(string.Format("{0}通知TM保存工艺程序{1}", chamberId, recipeName));
  332. }
  333. }
  334. catch (Exception ex)
  335. {
  336. LOG.WriteExeption(string.Format("保存{0}工艺程序{1}发生错误", chamberId, recipeName), ex);
  337. }
  338. }
  339. /// <summary>
  340. /// generate recipe list information in current directory
  341. /// </summary>
  342. /// <param name="chamId"></param>
  343. /// <param name="currentDir"></param>
  344. /// <param name="doc"></param>
  345. /// <returns></returns>
  346. XmlElement GenerateRecipeList(string chamberId, DirectoryInfo currentDir, XmlDocument doc, bool includingUsedRecipe)
  347. {
  348. int trimLength = getRecipeDirPath(chamberId).Length;
  349. XmlElement folderEle = doc.CreateElement("Folder");
  350. folderEle.SetAttribute("Name", currentDir.FullName.Substring(trimLength));
  351. DirectoryInfo[] dirInfos = currentDir.GetDirectories();
  352. foreach (DirectoryInfo dirInfo in dirInfos)
  353. {
  354. if (!includingUsedRecipe && dirInfo.Name == "HistoryRecipe")
  355. continue;
  356. folderEle.AppendChild(GenerateRecipeList(chamberId, dirInfo, doc, includingUsedRecipe));
  357. }
  358. FileInfo[] fileInfos = currentDir.GetFiles("*.rcp");
  359. foreach (FileInfo fileInfo in fileInfos)
  360. {
  361. XmlElement fileNd = doc.CreateElement("File");
  362. string fileStr = fileInfo.FullName.Substring(trimLength).TrimStart(new char[] { '\\' }); ;
  363. fileStr = fileStr.Substring(0, fileStr.LastIndexOf("."));
  364. fileNd.SetAttribute("Name", fileStr);
  365. folderEle.AppendChild(fileNd);
  366. }
  367. return folderEle;
  368. }
  369. /// <summary>
  370. /// Delete a recipe by recipe name
  371. /// </summary>
  372. /// <param name="chamId"></param>
  373. /// <param name="recipeName"></param>
  374. /// <returns></returns>
  375. public bool DeleteRecipe(string chamberId, string recipeName)
  376. {
  377. try
  378. {
  379. var path = GenerateRecipeFilePath(chamberId, recipeName);
  380. if (!_rcpContext.EnableEdit(path))
  381. return false;
  382. File.Delete(path);
  383. InfoDialog(string.Format(Resources.RecipeFileManager_DeleteRecipe_RecipeFile0DeleteSucceeded, recipeName));
  384. }
  385. catch (Exception ex)
  386. {
  387. LOG.WriteExeption("删除recipe file 出错", ex);
  388. WarningDialog(string.Format(Resources.RecipeFileManager_DeleteRecipe_RecipeFile0DeleteFailed, recipeName));
  389. return false;
  390. }
  391. return true;
  392. }
  393. /// <summary>
  394. /// Rename recipe
  395. /// </summary>
  396. /// <param name="chamId"></param>
  397. /// <param name="oldName"></param>
  398. /// <param name="newName"></param>
  399. /// <returns></returns>
  400. public bool RenameRecipe(string chamId, string oldName, string newName)
  401. {
  402. try
  403. {
  404. var path = GenerateRecipeFilePath(chamId, newName);
  405. if (!_rcpContext.EnableEdit(path))
  406. return false;
  407. if (File.Exists(path))
  408. {
  409. WarningDialog(string.Format(Resources.RecipeFileManager_RenameRecipe_RecipeFile0FileExisted, oldName));
  410. return false;
  411. }
  412. else
  413. {
  414. File.Move(GenerateRecipeFilePath(chamId, oldName), GenerateRecipeFilePath(chamId, newName));
  415. InfoDialog(string.Format(Resources.RecipeFileManager_RenameRecipe_RecipeFile0Renamed, oldName, newName));
  416. }
  417. }
  418. catch (Exception ex)
  419. {
  420. LOG.WriteExeption("重命名recipe file 出错", ex);
  421. WarningDialog(string.Format(Resources.RecipeFileManager_RenameRecipe_RecipeFile0RenameFailed, oldName, newName));
  422. return false;
  423. }
  424. return true;
  425. }
  426. //private void EventInfo(string message)
  427. //{
  428. // _rcpContext.PostInfoEvent(message);
  429. //}
  430. //private void EventWarning(string message)
  431. //{
  432. // _rcpContext.PostWarningEvent(message);
  433. //}
  434. //private void EventAlarm(string message)
  435. //{
  436. // _rcpContext.PostAlarmEvent(message);
  437. //}
  438. private void InfoDialog(string message)
  439. {
  440. _rcpContext.PostInfoDialogMessage(message);
  441. }
  442. private void WarningDialog(string message)
  443. {
  444. _rcpContext.PostWarningDialogMessage(message);
  445. }
  446. //private void AlarmDialog(string message)
  447. //{
  448. // _rcpContext.PostAlarmDialogMessage(message);
  449. //}
  450. private void EventDialog(string message, List<string> reason)
  451. {
  452. string msg = message;
  453. foreach (var r in reason)
  454. {
  455. msg += "\r\n" + r;
  456. }
  457. _rcpContext.PostDialogEvent(msg);
  458. }
  459. /// <summary>
  460. /// get recipe's file path
  461. /// </summary>
  462. /// <param name="recipeName"></param>
  463. /// <returns></returns>
  464. private string GenerateRecipeFilePath(string chamId, string recipeName)
  465. {
  466. return getRecipeDirPath(chamId) + recipeName + ".rcp";
  467. }
  468. private string GenerateSequenceFilePath(string chamId, string recipeName)
  469. {
  470. return getRecipeDirPath(chamId) + recipeName + ".seq";
  471. }
  472. /// <summary>
  473. /// get recipe's dir path
  474. /// </summary>
  475. /// <param name="recipeName"></param>
  476. /// <returns></returns>
  477. private string getRecipeDirPath(string chamId)
  478. {
  479. var dir = string.Format("{0}{1}\\", PathManager.GetRecipeDir(), chamId);
  480. DirectoryInfo di = new DirectoryInfo(dir);
  481. if (!di.Exists) di.Create();
  482. return dir;
  483. }
  484. /// <summary>
  485. /// delete a recipe folder
  486. /// </summary>
  487. /// <param name="chamId"></param>
  488. /// <param name="folderName"></param>
  489. /// <returns></returns>
  490. public bool DeleteFolder(string chamId, string folderName)
  491. {
  492. try
  493. {
  494. Directory.Delete(getRecipeDirPath(chamId) + folderName, true);
  495. InfoDialog(string.Format(Resources.RecipeFileManager_DeleteFolder_RecipeFolder0DeleteSucceeded, folderName));
  496. }
  497. catch (Exception ex)
  498. {
  499. LOG.WriteExeption("删除recipe folder 出错", ex);
  500. WarningDialog(string.Format("recipe folder {0} delete failed", folderName));
  501. return false;
  502. }
  503. return true;
  504. }
  505. /// <summary>
  506. /// save as recipe content
  507. /// </summary>
  508. /// <param name="chamId"></param>
  509. /// <param name="recipeName"></param>
  510. /// <param name="recipeContent"></param>
  511. /// <returns></returns>
  512. public bool SaveAsRecipe(string chamId, string recipeName, string recipeContent)
  513. {
  514. var path = GenerateRecipeFilePath(chamId, recipeName);
  515. //if (File.Exists(path))
  516. //{
  517. // WarningDialog(string.Format(Resources.RecipeFileManager_SaveAsRecipe_RecipeFile0savefailed, recipeName));
  518. // return false;
  519. //}
  520. return SaveRecipe(chamId, recipeName, recipeContent, true, true);
  521. }
  522. public bool SaveAsRecipe2(string chamId,string type, string recipeName, string recipeContent)
  523. {
  524. var path = GenerateRecipeFilePath(chamId, recipeName);
  525. //if (File.Exists(path))
  526. //{
  527. // WarningDialog(string.Format(Resources.RecipeFileManager_SaveAsRecipe_RecipeFile0savefailed, recipeName));
  528. // return false;
  529. //}
  530. return SaveRecipe2(chamId,type, recipeName, recipeContent, true, true);
  531. }
  532. /// <summary>
  533. /// save recipe content
  534. /// </summary>
  535. /// <param name="chamId"></param>
  536. /// <param name="recipeName"></param>
  537. /// <param name="recipeContent"></param>
  538. /// <returns></returns>
  539. public bool SaveRecipe(string chamId, string recipeName, string recipeContent, bool clearBarcode, bool notifyUI)
  540. {
  541. bool ret = true;
  542. try
  543. {
  544. var path = GenerateRecipeFilePath(chamId, recipeName);
  545. if (!_rcpContext.EnableEdit(path))
  546. return false;
  547. FileInfo fi = new FileInfo(path);
  548. if (!fi.Directory.Exists)
  549. fi.Directory.Create();
  550. File.WriteAllText(path, RecipeUnity.ConvertJsonString(recipeContent), Encoding.UTF8);
  551. }
  552. catch (Exception ex)
  553. {
  554. LOG.WriteExeption("保存recipe file 出错", ex);
  555. if (notifyUI)
  556. {
  557. WarningDialog(string.Format(Resources.RecipeFileManager_SaveRecipe_RecipeFile0SaveFailed, recipeName));
  558. }
  559. ret = false;
  560. }
  561. return ret;
  562. }
  563. /// <summary>
  564. /// save recipe content
  565. /// </summary>
  566. /// <param name="chamId"></param>
  567. /// <param name="recipeName"></param>
  568. /// <param name="recipeContent"></param>
  569. /// <returns></returns>
  570. public bool SaveRecipe2(string chamId,string type, string recipeName, string recipeContent, bool clearBarcode, bool notifyUI)
  571. {
  572. bool ret = true;
  573. try
  574. {
  575. var path = GenerateRecipeFilePath(chamId, recipeName);
  576. if (!_rcpContext.EnableEdit(path))
  577. return false;
  578. FileInfo fi = new FileInfo(path);
  579. if (!fi.Directory.Exists)
  580. fi.Directory.Create();
  581. File.WriteAllText(path, RecipeUnity.ConvertJsonString(recipeContent), Encoding.UTF8);
  582. }
  583. catch (Exception ex)
  584. {
  585. LOG.WriteExeption("保存recipe file 出错", ex);
  586. if (notifyUI)
  587. {
  588. WarningDialog(string.Format(Resources.RecipeFileManager_SaveRecipe_RecipeFile0SaveFailed, recipeName));
  589. }
  590. ret = false;
  591. }
  592. return ret;
  593. }
  594. /// <summary>
  595. /// move recipe file
  596. /// </summary>
  597. /// <param name="chamId"></param>
  598. /// <param name="recipeName"></param>
  599. /// <returns></returns>
  600. public bool MoveRecipeFile(string chamId, string recipeName, string tragetFolderName, bool clearBarcode, bool notifyUI)
  601. {
  602. bool ret = true;
  603. try
  604. {
  605. var path = getRecipeDirPath(chamId);
  606. string fullFileName = path + recipeName + ".rcp";
  607. string tragetFullFilePath = path + tragetFolderName;
  608. File.Move(fullFileName, tragetFullFilePath + "\\" + recipeName.Split('\\')[recipeName.Split('\\').Length - 1] + ".rcp");
  609. if (notifyUI)
  610. {
  611. InfoDialog(string.Format(Resources.RecipeFileManager_MoveRecipe_RecipeFile0MoveCompleted, recipeName));
  612. }
  613. else
  614. {
  615. LOG.Write(eEvent.EV_SEQUENCE, ModuleName.System, string.Format(Resources.RecipeFileManager_MoveRecipe_RecipeFile0MoveCompleted, recipeName));
  616. }
  617. }
  618. catch (Exception ex)
  619. {
  620. LOG.WriteExeption("移动 recipe file 出错", ex);
  621. if (notifyUI)
  622. {
  623. WarningDialog(string.Format(Resources.RecipeFileManager_MoveRecipe_RecipeFile0MoveFailed, recipeName));
  624. }
  625. ret = false;
  626. }
  627. return ret;
  628. }
  629. /// <summary>
  630. /// create a new recipe folder
  631. /// </summary>
  632. /// <param name="chamId"></param>
  633. /// <param name="folderName"></param>
  634. /// <returns></returns>
  635. public bool CreateFolder(string chamId, string folderName)
  636. {
  637. try
  638. {
  639. Directory.CreateDirectory(getRecipeDirPath(chamId) + folderName);
  640. InfoDialog(string.Format(Resources.RecipeFileManager_CreateFolder_RecipeFolder0Created, folderName));
  641. }
  642. catch (Exception ex)
  643. {
  644. LOG.WriteExeption("创建recipe folder 出错", ex);
  645. WarningDialog(string.Format(Resources.RecipeFileManager_CreateFolder_RecipeFolder0CreateFailed, folderName));
  646. return false;
  647. }
  648. return true;
  649. }
  650. /// <summary>
  651. /// Rename recipe folder name
  652. /// </summary>
  653. /// <param name="chamId"></param>
  654. /// <param name="oldName"></param>
  655. /// <param name="newName"></param>
  656. /// <returns></returns>
  657. public bool RenameFolder(string chamId, string oldName, string newName)
  658. {
  659. try
  660. {
  661. string oldPath = getRecipeDirPath(chamId) + oldName;
  662. string newPath = getRecipeDirPath(chamId) + newName;
  663. Directory.Move(oldPath, newPath);
  664. InfoDialog(string.Format(Resources.RecipeFileManager_RenameFolder_RecipeFolder0renamed, oldName, newName));
  665. }
  666. catch (Exception ex)
  667. {
  668. LOG.WriteExeption("重命名recipe folder 出错", ex);
  669. WarningDialog(string.Format(Resources.RecipeFileManager_RenameFolder_RecipeFolder0RenameFailed, oldName, newName));
  670. return false;
  671. }
  672. return true;
  673. }
  674. private string GetRecipeBody(string chamberId, string nodePath)
  675. {
  676. if (_rcpContext == null)
  677. return string.Empty;
  678. string schema = _rcpContext.GetRecipeDefiniton(chamberId);
  679. XmlDocument dom = new XmlDocument();
  680. dom.LoadXml(schema);
  681. XmlNode node = dom.SelectSingleNode(nodePath);
  682. return node.OuterXml;
  683. }
  684. /// <summary>
  685. /// get reactor's recipe format define file
  686. /// </summary>
  687. /// <param name="chamId"></param>
  688. /// <returns></returns>
  689. public string GetRecipeFormatXml(string chamberId)
  690. {
  691. return GetRecipeBody(chamberId, "/Aitex/TableRecipeFormat");
  692. }
  693. /// <summary>
  694. /// get reactor's template recipe file
  695. /// </summary>
  696. /// <param name="chamId"></param>
  697. /// <returns></returns>
  698. public string GetRecipeTemplate(string chamberId)
  699. {
  700. if (_rcpContext != null)
  701. return _rcpContext.GetRecipeTemplate(chamberId);
  702. return GetRecipeBody(chamberId, "/Aitex/TableRecipeData");
  703. }
  704. /// <summary>
  705. /// get reactor's template recipe file
  706. /// </summary>
  707. /// <param name="chamId"></param>
  708. /// <returns></returns>
  709. public string GetRecipeSchema(string chamberId)
  710. {
  711. if (_rcpContext == null)
  712. return string.Empty;
  713. string schema = _rcpContext.GetRecipeDefiniton(chamberId);
  714. XmlDocument dom = new XmlDocument();
  715. dom.LoadXml(schema);
  716. XmlNode node = dom.SelectSingleNode("/Aitex/TableRecipeSchema");
  717. return node.InnerXml;
  718. }
  719. public string GetRecipeByBarcode(string chamberId, string barcode)
  720. {
  721. try
  722. {
  723. string recipePath = PathManager.GetRecipeDir() + chamberId + "\\";
  724. var di = new DirectoryInfo(recipePath);
  725. var fis = di.GetFiles("*.rcp", SearchOption.AllDirectories);
  726. XmlDocument xml = new XmlDocument();
  727. foreach (var fi in fis)
  728. {
  729. string str = fi.FullName.Substring(recipePath.Length);
  730. if (!str.Contains("HistoryRecipe\\"))
  731. {
  732. xml.Load(fi.FullName);
  733. if (xml.SelectSingleNode(string.Format("/TableRecipeData[@Barcode='{0}']", barcode)) != null)
  734. {
  735. return str.Substring(0, str.LastIndexOf('.'));
  736. }
  737. }
  738. }
  739. return string.Empty;
  740. }
  741. catch (Exception ex)
  742. {
  743. LOG.WriteExeption(ex);
  744. return string.Empty;
  745. }
  746. }
  747. #region Sequence
  748. private string GetSequenceConfig(string nodePath)
  749. {
  750. if (_seqContext == null)
  751. return string.Empty;
  752. string schema = _seqContext.GetConfigXml();
  753. XmlDocument dom = new XmlDocument();
  754. dom.LoadXml(schema);
  755. XmlNode node = dom.SelectSingleNode(nodePath);
  756. return node.OuterXml;
  757. }
  758. public string GetSequence(string sequenceName, bool needValidation)
  759. {
  760. string seq = string.Empty;
  761. try
  762. {
  763. using (StreamReader fs = new StreamReader(GenerateSequenceFilePath(SequenceFolder, sequenceName)))
  764. {
  765. seq = fs.ReadToEnd();
  766. fs.Close();
  767. }
  768. if (needValidation && !_seqContext.Validation(seq))
  769. {
  770. LOG.Write(eEvent.WARN_SEQUENCE, ModuleName.System, $"Read {sequenceName} failed, validation failed");
  771. seq = string.Empty;
  772. }
  773. }
  774. catch (Exception ex)
  775. {
  776. LOG.WriteExeption(ex);
  777. seq = string.Empty;
  778. }
  779. return seq;
  780. }
  781. private void TryAppendNode(XmlElement preOrNextNode, XmlElement curPM,XmlDocument dom, bool isLeft)
  782. {
  783. if (preOrNextNode != null && preOrNextNode.GetAttribute("Position") != "LL" && preOrNextNode.GetAttribute("Position") != "PM")
  784. {
  785. XmlElement newNode = dom.CreateElement("Step");
  786. newNode.SetAttribute("Position", "LL");
  787. newNode.SetAttribute("LLSelection", "LLA,LLB");
  788. if (isLeft)
  789. curPM.ParentNode.InsertBefore(newNode, curPM);
  790. else
  791. curPM.ParentNode.InsertAfter(newNode, curPM);
  792. }
  793. }
  794. public string GetSequenceAndTryAppendLL(string sequenceName, bool needValidation)
  795. {
  796. string seq = string.Empty;
  797. try
  798. {
  799. seq = GetSequence(sequenceName, needValidation);
  800. if(!string.IsNullOrWhiteSpace(seq))
  801. {
  802. XmlDocument dom = new XmlDocument();
  803. dom.LoadXml(seq);
  804. XmlNodeList lstStepNode = dom.SelectNodes("Aitex/TableSequenceData/Step");
  805. if (lstStepNode != null)
  806. {
  807. List<XmlElement> pmList = new List<XmlElement>();
  808. foreach (XmlElement nodeStep in lstStepNode)
  809. {
  810. var positionValue = nodeStep.GetAttribute("Position");
  811. if (positionValue == "PM")
  812. {
  813. pmList.Add(nodeStep);
  814. }
  815. }
  816. foreach (XmlElement pmNode in pmList)
  817. {
  818. TryAppendNode((XmlElement)pmNode.PreviousSibling, pmNode, dom, true);
  819. TryAppendNode((XmlElement)pmNode.NextSibling, pmNode, dom, false);
  820. }
  821. using (var ms = new MemoryStream())
  822. using (var writer = new XmlTextWriter(ms, null))
  823. {
  824. writer.Formatting = Formatting.Indented;
  825. dom.Save(writer);
  826. return Encoding.UTF8.GetString(ms.ToArray());
  827. }
  828. }
  829. }
  830. }
  831. catch(Exception ex)
  832. {
  833. LOG.WriteExeption(ex);
  834. seq = string.Empty;
  835. }
  836. return seq;
  837. }
  838. public List<string> GetSequenceNameList()
  839. {
  840. var result = new List<string>();
  841. try
  842. {
  843. string recipePath = PathManager.GetRecipeDir() + SequenceFolder + "\\";
  844. var di = new DirectoryInfo(recipePath);
  845. var fis = di.GetFiles("*.seq", SearchOption.AllDirectories);
  846. foreach (var fi in fis)
  847. {
  848. string str = fi.FullName.Substring(recipePath.Length);
  849. str = str.Substring(0, str.LastIndexOf('.'));
  850. result.Add(str);
  851. }
  852. }
  853. catch (Exception ex)
  854. {
  855. LOG.WriteExeption(ex);
  856. }
  857. return result;
  858. }
  859. public bool DeleteSequence(string sequenceName)
  860. {
  861. try
  862. {
  863. var path = GenerateSequenceFilePath(SequenceFolder, sequenceName);
  864. if (!_seqContext.EnableEdit(path))
  865. return false;
  866. File.Delete(path);
  867. LOG.Write(eEvent.EV_SEQUENCE, ModuleName.System, $"sequence {sequenceName} deleted");
  868. }
  869. catch (Exception ex)
  870. {
  871. LOG.WriteExeption(ex);
  872. return false;
  873. }
  874. return true;
  875. }
  876. public bool SaveSequence(string sequenceName, string sequenceContent, bool notifyUI)
  877. {
  878. bool ret = true;
  879. try
  880. {
  881. var path = GenerateSequenceFilePath(SequenceFolder, sequenceName);
  882. if (!_seqContext.EnableEdit(path))
  883. return false;
  884. FileInfo fi = new FileInfo(path);
  885. if (!fi.Directory.Exists)
  886. {
  887. fi.Directory.Create();
  888. }
  889. XmlDocument xml = new XmlDocument();
  890. xml.LoadXml(sequenceContent);
  891. XmlTextWriter writer = new XmlTextWriter(path, null);
  892. writer.Formatting = Formatting.Indented;
  893. xml.Save(writer);
  894. writer.Close();
  895. if (notifyUI)
  896. {
  897. EV.PostPopDialogMessage(EventLevel.Information, "Save Complete", $"Sequence {sequenceName} saved ");
  898. }
  899. else
  900. {
  901. LOG.Write(eEvent.EV_SEQUENCE, ModuleName.System, $"Sequence {sequenceName} saved ");
  902. }
  903. }
  904. catch (Exception ex)
  905. {
  906. LOG.WriteExeption(ex);
  907. if (notifyUI)
  908. {
  909. EV.PostPopDialogMessage(EventLevel.Alarm, "Save Error", $"save sequence {sequenceName} failed, " + ex.Message);
  910. }
  911. ret = false;
  912. }
  913. return ret;
  914. }
  915. public bool SaveAsSequence(string sequenceName, string sequenceContent)
  916. {
  917. var path = GenerateSequenceFilePath(SequenceFolder, sequenceName);
  918. if (File.Exists(path))
  919. {
  920. LOG.Write(eEvent.WARN_SEQUENCE, ModuleName.System, $"save sequence {sequenceName} failed, already exist");
  921. return false;
  922. }
  923. return SaveSequence(sequenceName, sequenceContent, false);
  924. }
  925. public bool RenameSequence(string oldName, string newName)
  926. {
  927. try
  928. {
  929. var path = GenerateSequenceFilePath(SequenceFolder, oldName);
  930. if (!_seqContext.EnableEdit(path))
  931. return false;
  932. if (File.Exists(GenerateSequenceFilePath(SequenceFolder, newName)))
  933. {
  934. LOG.Write(eEvent.WARN_SEQUENCE, ModuleName.System, $"{newName} already exist, rename failed");
  935. return false;
  936. }
  937. else
  938. {
  939. File.Move(path, GenerateSequenceFilePath(SequenceFolder, newName));
  940. LOG.Write(eEvent.EV_SEQUENCE, ModuleName.System, $"sequence {oldName} renamed to {newName}");
  941. }
  942. }
  943. catch (Exception ex)
  944. {
  945. LOG.WriteExeption(ex);
  946. return false;
  947. }
  948. return true;
  949. }
  950. public string GetSequenceFormatXml()
  951. {
  952. return GetSequenceConfig("/Aitex/TableSequenceFormat");
  953. }
  954. internal bool DeleteSequenceFolder(string folderName)
  955. {
  956. try
  957. {
  958. Directory.Delete(PathManager.GetRecipeDir() + SequenceFolder + "\\" + folderName, true);
  959. LOG.Write(eEvent.EV_SEQUENCE,ModuleName.System, "Folder " + folderName + "deleted");
  960. }
  961. catch (Exception ex)
  962. {
  963. //LOG.Write(ex, "delete sequence folder exception");
  964. LOG.Write(eEvent.WARN_SEQUENCE, ModuleName.System, $"can not delete folder {folderName}, {ex.Message}");
  965. return false;
  966. }
  967. return true;
  968. }
  969. internal bool CreateSequenceFolder(string folderName)
  970. {
  971. try
  972. {
  973. Directory.CreateDirectory(PathManager.GetRecipeDir() + SequenceFolder + "\\" + folderName);
  974. LOG.Write(eEvent.EV_SEQUENCE, ModuleName.System, "Folder " + folderName + "created");
  975. }
  976. catch (Exception ex)
  977. {
  978. //LOG.Write(ex, "sequence folder create exception");
  979. LOG.Write(eEvent.WARN_SEQUENCE, ModuleName.System, $"can not create folder {folderName}, {ex.Message}");
  980. return false;
  981. }
  982. return true;
  983. }
  984. internal bool RenameSequenceFolder(string oldName, string newName)
  985. {
  986. try
  987. {
  988. string oldPath = PathManager.GetRecipeDir() + SequenceFolder + "\\" + oldName;
  989. string newPath = PathManager.GetRecipeDir() + SequenceFolder + "\\" + newName;
  990. Directory.Move(oldPath, newPath);
  991. LOG.Write(eEvent.EV_SEQUENCE, ModuleName.System, $"rename folder from {oldName} to {newName}");
  992. }
  993. catch (Exception ex)
  994. {
  995. //LOG.Write(ex, "rename sequence folder failed");
  996. LOG.Write(eEvent.WARN_SEQUENCE, ModuleName.System, $"can not rename folder {oldName}, {ex.Message}");
  997. return false;
  998. }
  999. return true;
  1000. }
  1001. public string GetXmlSequenceList(string chamberId)
  1002. {
  1003. XmlDocument doc = new XmlDocument();
  1004. DirectoryInfo curFolderInfo = new DirectoryInfo(PathManager.GetRecipeDir() + SequenceFolder + "\\");
  1005. doc.AppendChild(GenerateSequenceList(chamberId, curFolderInfo, doc));
  1006. return doc.OuterXml;
  1007. }
  1008. XmlElement GenerateSequenceList(string chamberId, DirectoryInfo currentDir, XmlDocument doc)
  1009. {
  1010. int trimLength = (PathManager.GetRecipeDir() + SequenceFolder + "\\").Length;
  1011. XmlElement folderEle = doc.CreateElement("Folder");
  1012. folderEle.SetAttribute("Name", currentDir.FullName.Substring(trimLength));
  1013. DirectoryInfo[] dirInfos = currentDir.GetDirectories();
  1014. foreach (DirectoryInfo dirInfo in dirInfos)
  1015. {
  1016. folderEle.AppendChild(GenerateSequenceList(chamberId, dirInfo, doc));
  1017. }
  1018. FileInfo[] fileInfos = currentDir.GetFiles("*.seq");
  1019. foreach (FileInfo fileInfo in fileInfos)
  1020. {
  1021. XmlElement fileNd = doc.CreateElement("File");
  1022. string fileStr = fileInfo.FullName.Substring(trimLength).TrimStart(new char[] { '\\' }); ;
  1023. fileStr = fileStr.Substring(0, fileStr.LastIndexOf("."));
  1024. fileNd.SetAttribute("Name", fileStr);
  1025. folderEle.AppendChild(fileNd);
  1026. }
  1027. return folderEle;
  1028. }
  1029. #endregion
  1030. }
  1031. }