RecipeFileManager.cs 43 KB

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