RecipeFileManager.cs 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230
  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(GenerateRecipeFilePath2(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. private string GenerateRecipeFilePath2(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 SaveAsRecipe2(string chamId,string type, string recipeName, string recipeContent)
  562. {
  563. var path = GenerateRecipeFilePath(chamId, recipeName);
  564. //if (File.Exists(path))
  565. //{
  566. // WarningDialog(string.Format(Resources.RecipeFileManager_SaveAsRecipe_RecipeFile0savefailed, recipeName));
  567. // return false;
  568. //}
  569. return SaveRecipe2(chamId,type, recipeName, recipeContent, true, true);
  570. }
  571. /// <summary>
  572. /// save recipe content
  573. /// </summary>
  574. /// <param name="chamId"></param>
  575. /// <param name="recipeName"></param>
  576. /// <param name="recipeContent"></param>
  577. /// <returns></returns>
  578. public bool SaveRecipe(string chamId, string recipeName, string recipeContent, bool clearBarcode, bool notifyUI)
  579. {
  580. bool ret = true;
  581. try
  582. {
  583. var path = GenerateRecipeFilePath(chamId, recipeName);
  584. if (!_rcpContext.EnableEdit(path))
  585. return false;
  586. FileInfo fi = new FileInfo(path);
  587. if (!fi.Directory.Exists)
  588. fi.Directory.Create();
  589. File.WriteAllText(path, RecipeUnity.ConvertJsonString(recipeContent), Encoding.UTF8);
  590. }
  591. catch (Exception ex)
  592. {
  593. LOG.WriteExeption("保存recipe file 出错", ex);
  594. if (notifyUI)
  595. {
  596. WarningDialog(string.Format(Resources.RecipeFileManager_SaveRecipe_RecipeFile0SaveFailed, recipeName));
  597. }
  598. ret = false;
  599. }
  600. return ret;
  601. }
  602. /// <summary>
  603. /// save recipe content
  604. /// </summary>
  605. /// <param name="chamId"></param>
  606. /// <param name="recipeName"></param>
  607. /// <param name="recipeContent"></param>
  608. /// <returns></returns>
  609. public bool SaveRecipe2(string chamId,string type, string recipeName, string recipeContent, bool clearBarcode, bool notifyUI)
  610. {
  611. bool ret = true;
  612. try
  613. {
  614. var path = GenerateRecipeFilePath2(chamId, type, recipeName);
  615. if (!_rcpContext.EnableEdit(path))
  616. return false;
  617. FileInfo fi = new FileInfo(path);
  618. if (!fi.Directory.Exists)
  619. fi.Directory.Create();
  620. File.WriteAllText(path, RecipeUnity.ConvertJsonString(recipeContent), Encoding.UTF8);
  621. }
  622. catch (Exception ex)
  623. {
  624. LOG.WriteExeption("保存recipe file 出错", ex);
  625. if (notifyUI)
  626. {
  627. WarningDialog(string.Format(Resources.RecipeFileManager_SaveRecipe_RecipeFile0SaveFailed, recipeName));
  628. }
  629. ret = false;
  630. }
  631. return ret;
  632. }
  633. /// <summary>
  634. /// move recipe file
  635. /// </summary>
  636. /// <param name="chamId"></param>
  637. /// <param name="recipeName"></param>
  638. /// <returns></returns>
  639. public bool MoveRecipeFile(string chamId, string recipeName, string tragetFolderName, bool clearBarcode, bool notifyUI)
  640. {
  641. bool ret = true;
  642. try
  643. {
  644. var path = getRecipeDirPath(chamId);
  645. string fullFileName = path + recipeName + ".rcp";
  646. string tragetFullFilePath = path + tragetFolderName;
  647. File.Move(fullFileName, tragetFullFilePath + "\\" + recipeName.Split('\\')[recipeName.Split('\\').Length - 1] + ".rcp");
  648. if (notifyUI)
  649. {
  650. InfoDialog(string.Format(Resources.RecipeFileManager_MoveRecipe_RecipeFile0MoveCompleted, recipeName));
  651. }
  652. else
  653. {
  654. LOG.Write(eEvent.EV_SEQUENCE, ModuleName.System, string.Format(Resources.RecipeFileManager_MoveRecipe_RecipeFile0MoveCompleted, recipeName));
  655. }
  656. }
  657. catch (Exception ex)
  658. {
  659. LOG.WriteExeption("移动 recipe file 出错", ex);
  660. if (notifyUI)
  661. {
  662. WarningDialog(string.Format(Resources.RecipeFileManager_MoveRecipe_RecipeFile0MoveFailed, recipeName));
  663. }
  664. ret = false;
  665. }
  666. return ret;
  667. }
  668. /// <summary>
  669. /// create a new recipe folder
  670. /// </summary>
  671. /// <param name="chamId"></param>
  672. /// <param name="folderName"></param>
  673. /// <returns></returns>
  674. public bool CreateFolder(string chamId, string folderName)
  675. {
  676. try
  677. {
  678. Directory.CreateDirectory(getRecipeDirPath(chamId) + folderName);
  679. InfoDialog(string.Format(Resources.RecipeFileManager_CreateFolder_RecipeFolder0Created, folderName));
  680. }
  681. catch (Exception ex)
  682. {
  683. LOG.WriteExeption("创建recipe folder 出错", ex);
  684. WarningDialog(string.Format(Resources.RecipeFileManager_CreateFolder_RecipeFolder0CreateFailed, folderName));
  685. return false;
  686. }
  687. return true;
  688. }
  689. /// <summary>
  690. /// Rename recipe folder name
  691. /// </summary>
  692. /// <param name="chamId"></param>
  693. /// <param name="oldName"></param>
  694. /// <param name="newName"></param>
  695. /// <returns></returns>
  696. public bool RenameFolder(string chamId, string oldName, string newName)
  697. {
  698. try
  699. {
  700. string oldPath = getRecipeDirPath(chamId) + oldName;
  701. string newPath = getRecipeDirPath(chamId) + newName;
  702. Directory.Move(oldPath, newPath);
  703. InfoDialog(string.Format(Resources.RecipeFileManager_RenameFolder_RecipeFolder0renamed, oldName, newName));
  704. }
  705. catch (Exception ex)
  706. {
  707. LOG.WriteExeption("重命名recipe folder 出错", ex);
  708. WarningDialog(string.Format(Resources.RecipeFileManager_RenameFolder_RecipeFolder0RenameFailed, oldName, newName));
  709. return false;
  710. }
  711. return true;
  712. }
  713. private string GetRecipeBody(string chamberId, string nodePath)
  714. {
  715. if (_rcpContext == null)
  716. return string.Empty;
  717. string schema = _rcpContext.GetRecipeDefiniton(chamberId);
  718. XmlDocument dom = new XmlDocument();
  719. dom.LoadXml(schema);
  720. XmlNode node = dom.SelectSingleNode(nodePath);
  721. return node.OuterXml;
  722. }
  723. /// <summary>
  724. /// get reactor's recipe format define file
  725. /// </summary>
  726. /// <param name="chamId"></param>
  727. /// <returns></returns>
  728. public string GetRecipeFormatXml(string chamberId)
  729. {
  730. return GetRecipeBody(chamberId, "/Aitex/TableRecipeFormat");
  731. }
  732. /// <summary>
  733. /// get reactor's template recipe file
  734. /// </summary>
  735. /// <param name="chamId"></param>
  736. /// <returns></returns>
  737. public string GetRecipeTemplate(string chamberId)
  738. {
  739. if (_rcpContext != null)
  740. return _rcpContext.GetRecipeTemplate(chamberId);
  741. return GetRecipeBody(chamberId, "/Aitex/TableRecipeData");
  742. }
  743. /// <summary>
  744. /// get reactor's template recipe file
  745. /// </summary>
  746. /// <param name="chamId"></param>
  747. /// <returns></returns>
  748. public string GetRecipeSchema(string chamberId)
  749. {
  750. if (_rcpContext == null)
  751. return string.Empty;
  752. string schema = _rcpContext.GetRecipeDefiniton(chamberId);
  753. XmlDocument dom = new XmlDocument();
  754. dom.LoadXml(schema);
  755. XmlNode node = dom.SelectSingleNode("/Aitex/TableRecipeSchema");
  756. return node.InnerXml;
  757. }
  758. public string GetRecipeByBarcode(string chamberId, string barcode)
  759. {
  760. try
  761. {
  762. string recipePath = PathManager.GetRecipeDir() + chamberId + "\\";
  763. var di = new DirectoryInfo(recipePath);
  764. var fis = di.GetFiles("*.rcp", SearchOption.AllDirectories);
  765. XmlDocument xml = new XmlDocument();
  766. foreach (var fi in fis)
  767. {
  768. string str = fi.FullName.Substring(recipePath.Length);
  769. if (!str.Contains("HistoryRecipe\\"))
  770. {
  771. xml.Load(fi.FullName);
  772. if (xml.SelectSingleNode(string.Format("/TableRecipeData[@Barcode='{0}']", barcode)) != null)
  773. {
  774. return str.Substring(0, str.LastIndexOf('.'));
  775. }
  776. }
  777. }
  778. return string.Empty;
  779. }
  780. catch (Exception ex)
  781. {
  782. LOG.WriteExeption(ex);
  783. return string.Empty;
  784. }
  785. }
  786. #region Sequence
  787. private string GetSequenceConfig(string nodePath)
  788. {
  789. if (_seqContext == null)
  790. return string.Empty;
  791. string schema = _seqContext.GetConfigXml();
  792. XmlDocument dom = new XmlDocument();
  793. dom.LoadXml(schema);
  794. XmlNode node = dom.SelectSingleNode(nodePath);
  795. return node.OuterXml;
  796. }
  797. public string GetSequence(string sequenceName, bool needValidation)
  798. {
  799. string seq = string.Empty;
  800. try
  801. {
  802. using (StreamReader fs = new StreamReader(GenerateSequenceFilePath(SequenceFolder, sequenceName)))
  803. {
  804. seq = fs.ReadToEnd();
  805. fs.Close();
  806. }
  807. if (needValidation && !_seqContext.Validation(seq))
  808. {
  809. LOG.Write(eEvent.WARN_SEQUENCE, ModuleName.System, $"Read {sequenceName} failed, validation failed");
  810. seq = string.Empty;
  811. }
  812. }
  813. catch (Exception ex)
  814. {
  815. LOG.WriteExeption(ex);
  816. seq = string.Empty;
  817. }
  818. return seq;
  819. }
  820. private void TryAppendNode(XmlElement preOrNextNode, XmlElement curPM,XmlDocument dom, bool isLeft)
  821. {
  822. if (preOrNextNode != null && preOrNextNode.GetAttribute("Position") != "LL" && preOrNextNode.GetAttribute("Position") != "PM")
  823. {
  824. XmlElement newNode = dom.CreateElement("Step");
  825. newNode.SetAttribute("Position", "LL");
  826. newNode.SetAttribute("LLSelection", "LLA,LLB");
  827. if (isLeft)
  828. curPM.ParentNode.InsertBefore(newNode, curPM);
  829. else
  830. curPM.ParentNode.InsertAfter(newNode, curPM);
  831. }
  832. }
  833. public string GetSequenceAndTryAppendLL(string sequenceName, bool needValidation)
  834. {
  835. string seq = string.Empty;
  836. try
  837. {
  838. seq = GetSequence(sequenceName, needValidation);
  839. if(!string.IsNullOrWhiteSpace(seq))
  840. {
  841. XmlDocument dom = new XmlDocument();
  842. dom.LoadXml(seq);
  843. XmlNodeList lstStepNode = dom.SelectNodes("Aitex/TableSequenceData/Step");
  844. if (lstStepNode != null)
  845. {
  846. List<XmlElement> pmList = new List<XmlElement>();
  847. foreach (XmlElement nodeStep in lstStepNode)
  848. {
  849. var positionValue = nodeStep.GetAttribute("Position");
  850. if (positionValue == "PM")
  851. {
  852. pmList.Add(nodeStep);
  853. }
  854. }
  855. foreach (XmlElement pmNode in pmList)
  856. {
  857. TryAppendNode((XmlElement)pmNode.PreviousSibling, pmNode, dom, true);
  858. TryAppendNode((XmlElement)pmNode.NextSibling, pmNode, dom, false);
  859. }
  860. using (var ms = new MemoryStream())
  861. using (var writer = new XmlTextWriter(ms, null))
  862. {
  863. writer.Formatting = Formatting.Indented;
  864. dom.Save(writer);
  865. return Encoding.UTF8.GetString(ms.ToArray());
  866. }
  867. }
  868. }
  869. }
  870. catch(Exception ex)
  871. {
  872. LOG.WriteExeption(ex);
  873. seq = string.Empty;
  874. }
  875. return seq;
  876. }
  877. public List<string> GetSequenceNameList()
  878. {
  879. var result = new List<string>();
  880. try
  881. {
  882. string recipePath = PathManager.GetRecipeDir() + SequenceFolder + "\\";
  883. var di = new DirectoryInfo(recipePath);
  884. var fis = di.GetFiles("*.seq", SearchOption.AllDirectories);
  885. foreach (var fi in fis)
  886. {
  887. string str = fi.FullName.Substring(recipePath.Length);
  888. str = str.Substring(0, str.LastIndexOf('.'));
  889. result.Add(str);
  890. }
  891. }
  892. catch (Exception ex)
  893. {
  894. LOG.WriteExeption(ex);
  895. }
  896. return result;
  897. }
  898. public bool DeleteSequence(string sequenceName)
  899. {
  900. try
  901. {
  902. var path = GenerateSequenceFilePath(SequenceFolder, sequenceName);
  903. if (!_seqContext.EnableEdit(path))
  904. return false;
  905. File.Delete(path);
  906. LOG.Write(eEvent.EV_SEQUENCE, ModuleName.System, $"sequence {sequenceName} deleted");
  907. }
  908. catch (Exception ex)
  909. {
  910. LOG.WriteExeption(ex);
  911. return false;
  912. }
  913. return true;
  914. }
  915. public bool SaveSequence(string sequenceName, string sequenceContent, bool notifyUI)
  916. {
  917. bool ret = true;
  918. try
  919. {
  920. var path = GenerateSequenceFilePath(SequenceFolder, sequenceName);
  921. if (!_seqContext.EnableEdit(path))
  922. return false;
  923. FileInfo fi = new FileInfo(path);
  924. if (!fi.Directory.Exists)
  925. {
  926. fi.Directory.Create();
  927. }
  928. XmlDocument xml = new XmlDocument();
  929. xml.LoadXml(sequenceContent);
  930. XmlTextWriter writer = new XmlTextWriter(path, null);
  931. writer.Formatting = Formatting.Indented;
  932. xml.Save(writer);
  933. writer.Close();
  934. if (notifyUI)
  935. {
  936. EV.PostPopDialogMessage(EventLevel.Information, "Save Complete", $"Sequence {sequenceName} saved ");
  937. }
  938. else
  939. {
  940. LOG.Write(eEvent.EV_SEQUENCE, ModuleName.System, $"Sequence {sequenceName} saved ");
  941. }
  942. }
  943. catch (Exception ex)
  944. {
  945. LOG.WriteExeption(ex);
  946. if (notifyUI)
  947. {
  948. EV.PostPopDialogMessage(EventLevel.Alarm, "Save Error", $"save sequence {sequenceName} failed, " + ex.Message);
  949. }
  950. ret = false;
  951. }
  952. return ret;
  953. }
  954. public bool SaveAsSequence(string sequenceName, string sequenceContent)
  955. {
  956. var path = GenerateSequenceFilePath(SequenceFolder, sequenceName);
  957. if (File.Exists(path))
  958. {
  959. LOG.Write(eEvent.WARN_SEQUENCE, ModuleName.System, $"save sequence {sequenceName} failed, already exist");
  960. return false;
  961. }
  962. return SaveSequence(sequenceName, sequenceContent, false);
  963. }
  964. public bool RenameSequence(string oldName, string newName)
  965. {
  966. try
  967. {
  968. var path = GenerateSequenceFilePath(SequenceFolder, oldName);
  969. if (!_seqContext.EnableEdit(path))
  970. return false;
  971. if (File.Exists(GenerateSequenceFilePath(SequenceFolder, newName)))
  972. {
  973. LOG.Write(eEvent.WARN_SEQUENCE, ModuleName.System, $"{newName} already exist, rename failed");
  974. return false;
  975. }
  976. else
  977. {
  978. File.Move(path, GenerateSequenceFilePath(SequenceFolder, newName));
  979. LOG.Write(eEvent.EV_SEQUENCE, ModuleName.System, $"sequence {oldName} renamed to {newName}");
  980. }
  981. }
  982. catch (Exception ex)
  983. {
  984. LOG.WriteExeption(ex);
  985. return false;
  986. }
  987. return true;
  988. }
  989. public string GetSequenceFormatXml()
  990. {
  991. return GetSequenceConfig("/Aitex/TableSequenceFormat");
  992. }
  993. internal bool DeleteSequenceFolder(string folderName)
  994. {
  995. try
  996. {
  997. Directory.Delete(PathManager.GetRecipeDir() + SequenceFolder + "\\" + folderName, true);
  998. LOG.Write(eEvent.EV_SEQUENCE,ModuleName.System, "Folder " + folderName + "deleted");
  999. }
  1000. catch (Exception ex)
  1001. {
  1002. //LOG.Write(ex, "delete sequence folder exception");
  1003. LOG.Write(eEvent.WARN_SEQUENCE, ModuleName.System, $"can not delete folder {folderName}, {ex.Message}");
  1004. return false;
  1005. }
  1006. return true;
  1007. }
  1008. internal bool CreateSequenceFolder(string folderName)
  1009. {
  1010. try
  1011. {
  1012. Directory.CreateDirectory(PathManager.GetRecipeDir() + SequenceFolder + "\\" + folderName);
  1013. LOG.Write(eEvent.EV_SEQUENCE, ModuleName.System, "Folder " + folderName + "created");
  1014. }
  1015. catch (Exception ex)
  1016. {
  1017. //LOG.Write(ex, "sequence folder create exception");
  1018. LOG.Write(eEvent.WARN_SEQUENCE, ModuleName.System, $"can not create folder {folderName}, {ex.Message}");
  1019. return false;
  1020. }
  1021. return true;
  1022. }
  1023. internal bool RenameSequenceFolder(string oldName, string newName)
  1024. {
  1025. try
  1026. {
  1027. string oldPath = PathManager.GetRecipeDir() + SequenceFolder + "\\" + oldName;
  1028. string newPath = PathManager.GetRecipeDir() + SequenceFolder + "\\" + newName;
  1029. Directory.Move(oldPath, newPath);
  1030. LOG.Write(eEvent.EV_SEQUENCE, ModuleName.System, $"rename folder from {oldName} to {newName}");
  1031. }
  1032. catch (Exception ex)
  1033. {
  1034. //LOG.Write(ex, "rename sequence folder failed");
  1035. LOG.Write(eEvent.WARN_SEQUENCE, ModuleName.System, $"can not rename folder {oldName}, {ex.Message}");
  1036. return false;
  1037. }
  1038. return true;
  1039. }
  1040. public string GetXmlSequenceList(string chamberId)
  1041. {
  1042. XmlDocument doc = new XmlDocument();
  1043. DirectoryInfo curFolderInfo = new DirectoryInfo(PathManager.GetRecipeDir() + SequenceFolder + "\\");
  1044. doc.AppendChild(GenerateSequenceList(chamberId, curFolderInfo, doc));
  1045. return doc.OuterXml;
  1046. }
  1047. XmlElement GenerateSequenceList(string chamberId, DirectoryInfo currentDir, XmlDocument doc)
  1048. {
  1049. int trimLength = (PathManager.GetRecipeDir() + SequenceFolder + "\\").Length;
  1050. XmlElement folderEle = doc.CreateElement("Folder");
  1051. folderEle.SetAttribute("Name", currentDir.FullName.Substring(trimLength));
  1052. DirectoryInfo[] dirInfos = currentDir.GetDirectories();
  1053. foreach (DirectoryInfo dirInfo in dirInfos)
  1054. {
  1055. folderEle.AppendChild(GenerateSequenceList(chamberId, dirInfo, doc));
  1056. }
  1057. FileInfo[] fileInfos = currentDir.GetFiles("*.seq");
  1058. foreach (FileInfo fileInfo in fileInfos)
  1059. {
  1060. XmlElement fileNd = doc.CreateElement("File");
  1061. string fileStr = fileInfo.FullName.Substring(trimLength).TrimStart(new char[] { '\\' }); ;
  1062. fileStr = fileStr.Substring(0, fileStr.LastIndexOf("."));
  1063. fileNd.SetAttribute("Name", fileStr);
  1064. folderEle.AppendChild(fileNd);
  1065. }
  1066. return folderEle;
  1067. }
  1068. #endregion
  1069. }
  1070. }