RecipeFileManager.cs 47 KB

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