RecipeFileManager.cs 43 KB

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