SystemConfigManager.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net.Security;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows;
  10. using System.Xml;
  11. using Aitex.Common.Util;
  12. using Aitex.Core.RT.ConfigCenter;
  13. using Aitex.Core.RT.DataCenter;
  14. using Aitex.Core.RT.Event;
  15. using Aitex.Core.RT.Log;
  16. using Aitex.Core.RT.OperationCenter;
  17. using Aitex.Core.RT.SCCore;
  18. using Aitex.Core.Util;
  19. using MECF.Framework.Common.Equipment;
  20. using Venus_Core;
  21. namespace MECF.Framework.Common.SCCore
  22. {
  23. public class SystemConfigManager : Singleton<SystemConfigManager>, ISCManager
  24. {
  25. private Dictionary<string, SCConfigItem> _items = new Dictionary<string, SCConfigItem>();
  26. private object _itemLocker = new object();
  27. private string _scConfigFile ;
  28. private string _scDataFile = PathManager.GetCfgDir() + "_sc.data";
  29. private string _scDataBackupFile = PathManager.GetCfgDir() + "_sc.data.bak";
  30. private string _scDataErrorFile = PathManager.GetCfgDir() + "_sc.data.err.";
  31. public void Initialize(string scConfigPathName,ConfigType configType)
  32. {
  33. if (configType == ConfigType.Other)
  34. {
  35. _scDataFile = PathManager.GetCfgDir() + "_sc.data";
  36. _scDataBackupFile = PathManager.GetCfgDir() + "_sc.data.bak";
  37. _scDataErrorFile = PathManager.GetCfgDir() + "_sc.data.err.";
  38. }
  39. else
  40. {
  41. _scDataFile = PathManager.GetCfgDir() + $"_sc_{configType}.data";
  42. _scDataBackupFile = PathManager.GetCfgDir() + $"_sc.data_{configType}.bak";
  43. //_scDataErrorFile = PathManager.GetCfgDir() + $"_sc.data.err._{configType}";
  44. }
  45. _scConfigFile = scConfigPathName;
  46. BuildItems(_scConfigFile);
  47. BackupAndRecoverDataFile();
  48. CustomData();
  49. GenerateDataFile();
  50. foreach (var item in _items)
  51. {
  52. CONFIG.Subscribe("", item.Key, ()=>item.Value.Value);
  53. }
  54. OP.Subscribe("System.SetConfig", InvokeSetConfig);
  55. SC.Manager = this;
  56. }
  57. private bool InvokeSetConfig(string cmd, object[] parameters)
  58. {
  59. string key = (string) parameters[0];
  60. object old = GetConfigValueAsObject(key);
  61. if ((string)parameters[0] == "PMB.Chiller.ChillerSameWithPMA" && (string)parameters[1] == "true")
  62. {
  63. if (_items["PMA.Chiller.EnableChiller"].Value.ToString() == "False") return true;
  64. }
  65. if (key.Contains("Magnet"))
  66. {
  67. OP.DoOperation("System.SetMagnet", key, parameters[1]);
  68. }
  69. if (InitializeItemValue(_items[(string)parameters[0]], (string)parameters[1]))
  70. {
  71. GenerateDataFile();
  72. LOG.Write(eEvent.EV_SYSTEM_CONFIG, ModuleName.System, string.Format("SC {0} value changed from {1} to {2}", key, old, parameters[1]));
  73. }
  74. if ((string)parameters[0] == "PMA.Chiller.EnableChiller" && (string)parameters[1] == "false")
  75. {
  76. if (_items["PMB.Chiller.ChillerSameWithPMA"].Value.ToString() == "False") return true;
  77. if (InitializeItemValue(_items["PMB.Chiller.ChillerSameWithPMA"], "False"))
  78. {
  79. GenerateDataFile();
  80. LOG.Write(eEvent.EV_SYSTEM_CONFIG, ModuleName.System, string.Format("SC {0} value changed from {1} to {2}", "PMB.Chiller.ChillerSameWithPMA", "true", "false"));
  81. }
  82. }
  83. if ((string)parameters[0] == "PMB.Chiller.EnableChiller" && (string)parameters[1] == "false")
  84. {
  85. if (_items["PMB.Chiller.ChillerSameWithPMA"].Value.ToString() == "False") return true;
  86. if (InitializeItemValue(_items["PMB.Chiller.EnableChiller"], "true"))
  87. {
  88. GenerateDataFile();
  89. LOG.Write(eEvent.EV_SYSTEM_CONFIG, ModuleName.System, string.Format("SC {0} value changed from {1} to {2}", "PMB.Chiller.EnableChiller", "false", "true"));
  90. }
  91. }
  92. if ((string)parameters[0] == "PMB.Chiller.ChillerSameWithPMA" && (string)parameters[1] == "true")
  93. {
  94. if (_items["PMB.Chiller.EnableChiller"].Value.ToString() == "True") return true;
  95. if (InitializeItemValue(_items["PMB.Chiller.EnableChiller"], "true"))
  96. {
  97. GenerateDataFile();
  98. LOG.Write(eEvent.EV_SYSTEM_CONFIG, ModuleName.System, string.Format("SC {0} value changed from {1} to {2}", "PMB.Chiller.EnableChiller", "false", "true"));
  99. }
  100. }
  101. return true;
  102. }
  103. public void Terminate()
  104. {
  105. }
  106. public string GetFileContent()
  107. {
  108. if (!File.Exists(_scConfigFile))
  109. return "";
  110. StringBuilder s = new StringBuilder();
  111. try
  112. {
  113. using (StreamReader sr = new StreamReader(_scConfigFile))
  114. {
  115. while (!sr.EndOfStream)
  116. {
  117. s.Append(sr.ReadLine());
  118. }
  119. }
  120. }
  121. catch (Exception ex)
  122. {
  123. LOG.WriteExeption(ex);
  124. return "";
  125. }
  126. return s.ToString();
  127. }
  128. private void BuildItems(string xmlFile)
  129. {
  130. XmlDocument xml = new XmlDocument();
  131. try
  132. {
  133. var _sc_stream = File.Open(xmlFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
  134. xml.Load(_sc_stream);
  135. _sc_stream.Close();
  136. XmlNodeList nodeConfigs = xml.SelectNodes("root/configs");
  137. foreach (XmlElement nodeConfig in nodeConfigs)
  138. {
  139. BuildPathConfigs(nodeConfig.GetAttribute("name"), nodeConfig as XmlElement);
  140. }
  141. }
  142. catch (Exception ex)
  143. {
  144. LOG.WriteExeption(ex);
  145. }
  146. }
  147. private void BuildPathConfigs(string parentPath, XmlElement configElement)
  148. {
  149. XmlNodeList nodeConfigsList = configElement.SelectNodes("configs");
  150. foreach (XmlElement nodeConfig in nodeConfigsList)
  151. {
  152. if (string.IsNullOrEmpty(parentPath))
  153. {
  154. BuildPathConfigs(nodeConfig.GetAttribute("name"), nodeConfig as XmlElement);
  155. }
  156. else
  157. {
  158. BuildPathConfigs(parentPath + "." + nodeConfig.GetAttribute("name"), nodeConfig as XmlElement);
  159. }
  160. }
  161. XmlNodeList nodeConfigs = configElement.SelectNodes("config");
  162. foreach (XmlElement nodeConfig in nodeConfigs)
  163. {
  164. SCConfigItem item = new SCConfigItem()
  165. {
  166. Default = nodeConfig.GetAttribute("default"),
  167. Name = nodeConfig.GetAttribute("name"),
  168. Description = nodeConfig.GetAttribute("description"),
  169. Max = nodeConfig.GetAttribute("max"),
  170. Min = nodeConfig.GetAttribute("min"),
  171. Parameter = nodeConfig.GetAttribute("paramter"),
  172. Path = parentPath,
  173. Tag = nodeConfig.GetAttribute("tag"),
  174. Type = nodeConfig.GetAttribute("type"),
  175. Unit = nodeConfig.GetAttribute("unit"),
  176. };
  177. InitializeItemValue(item, item.Default);
  178. if (_items.ContainsKey(item.PathName))
  179. {
  180. //LOG.Error("Duplicated SC item, "+ item.PathName);
  181. }
  182. _items[item.PathName] = item;
  183. }
  184. }
  185. private void BackupAndRecoverDataFile()
  186. {
  187. try
  188. {
  189. if (File.Exists(_scDataFile) && IsXmlFileLoadable(_scDataFile))
  190. {
  191. File.Copy(_scDataFile, _scDataBackupFile, true);
  192. }
  193. else if (File.Exists(_scDataBackupFile) && IsXmlFileLoadable(_scDataBackupFile))
  194. {
  195. if (File.Exists(_scDataFile))
  196. {
  197. File.Copy(_scDataFile, _scDataErrorFile + DateTime.Now.ToString("yyyyMMdd_HHmmss"), true);
  198. }
  199. File.Copy(_scDataBackupFile, _scDataFile, true);
  200. }
  201. }
  202. catch (Exception ex)
  203. {
  204. LOG.WriteExeption(ex);
  205. }
  206. }
  207. private void CustomData()
  208. {
  209. Dictionary<string, string> values = new Dictionary<string, string>();
  210. try
  211. {
  212. if (File.Exists(_scDataFile))
  213. {
  214. XmlDocument xmlData = new XmlDocument();
  215. var _sc_stream = File.Open(_scDataFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
  216. xmlData.Load(_sc_stream);
  217. _sc_stream.Close();
  218. XmlNodeList scdatas = xmlData.SelectNodes("root/scdata");
  219. foreach (XmlElement nodedata in scdatas)
  220. {
  221. string name = nodedata.GetAttribute("name");
  222. if (_items.ContainsKey(name))
  223. {
  224. InitializeItemValue(_items[name], nodedata.GetAttribute("value"));
  225. }
  226. }
  227. }
  228. }
  229. catch (Exception ex)
  230. {
  231. LOG.WriteExeption(ex);
  232. }
  233. }
  234. private void GenerateDataFile()
  235. {
  236. try
  237. {
  238. XmlDocument xml = new XmlDocument();
  239. xml.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?><root></root>");
  240. XmlElement nodeRoot = xml.SelectSingleNode("root") as XmlElement;
  241. foreach (var scConfigItem in _items)
  242. {
  243. XmlElement node = xml.CreateElement("scdata");
  244. node.SetAttribute("name", scConfigItem.Key);
  245. node.SetAttribute("value", scConfigItem.Value.Value.ToString());
  246. nodeRoot.AppendChild(node);
  247. }
  248. if (File.Exists(_scDataFile) && IsXmlFileLoadable(_scDataFile))
  249. {
  250. File.Copy(_scDataFile, _scDataBackupFile, true);
  251. //File.Delete(_scDataFile);
  252. }
  253. using (FileStream fsFileStream = new FileStream(_scDataFile,
  254. FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 1024, FileOptions.WriteThrough))
  255. {
  256. fsFileStream.SetLength(0);
  257. XmlWriterSettings settings = new XmlWriterSettings();
  258. settings.Indent = true;
  259. settings.OmitXmlDeclaration = false;
  260. using (XmlWriter xmlWrite = XmlWriter.Create(fsFileStream, settings))
  261. {
  262. xml.Save(xmlWrite);
  263. }
  264. }
  265. }
  266. catch (Exception ex)
  267. {
  268. LOG.WriteExeption(ex);
  269. }
  270. }
  271. private bool IsXmlFileLoadable(string file)
  272. {
  273. try
  274. {
  275. XmlDocument xml = new XmlDocument();
  276. xml.Load(file);
  277. }
  278. catch (Exception ex)
  279. {
  280. LOG.WriteExeption(ex);
  281. return false;
  282. }
  283. return true;
  284. }
  285. public SCConfigItem GetConfigItem(string name)
  286. {
  287. //Debug.Assert(_items.ContainsKey(name), "can not find sc name, "+name);
  288. if (!_items.ContainsKey(name))
  289. {
  290. return null;
  291. }
  292. return _items[name];
  293. }
  294. public bool ContainsItem(string name)
  295. {
  296. return _items.ContainsKey(name);
  297. }
  298. public object GetConfigValueAsObject(string name)
  299. {
  300. SCConfigItem item = GetConfigItem(name);
  301. if(item == null)
  302. {
  303. return null;
  304. }
  305. switch (item.Type)
  306. {
  307. case "Bool": return item.BoolValue;
  308. case "Integer": return item.IntValue;
  309. case "Double": return item.DoubleValue;
  310. case "String": return item.StringValue;
  311. }
  312. return null;
  313. }
  314. public T GetValue<T>(string name) where T : struct
  315. {
  316. try
  317. {
  318. if (typeof(T) == typeof(bool))
  319. return (T)(object)_items[name].BoolValue;
  320. if (typeof(T) == typeof(int))
  321. return (T)(object)_items[name].IntValue;
  322. if (typeof(T) == typeof(double))
  323. return (T)(object)_items[name].DoubleValue;
  324. }
  325. catch (KeyNotFoundException)
  326. {
  327. MessageBox.Show($"Can not find system config item {name}");
  328. return default(T);
  329. }
  330. catch (Exception)
  331. {
  332. MessageBox.Show($"Can not get valid system config item value {name}");
  333. return default(T);
  334. }
  335. Debug.Assert(false, "unsupported type");
  336. return default(T);
  337. }
  338. public string GetStringValue(string name)
  339. {
  340. if (!_items.ContainsKey(name))
  341. return null;
  342. return _items[name].StringValue;
  343. }
  344. public List<SCConfigItem> GetItemList()
  345. {
  346. return _items.Values.ToList();
  347. }
  348. public void SetItemValueFromString(string name, string value)
  349. {
  350. if (InitializeItemValue(_items[name], value))
  351. {
  352. GenerateDataFile();
  353. }
  354. }
  355. private bool InitializeItemValue(SCConfigItem item, string value)
  356. {
  357. bool changed = false;
  358. switch (item.Type)
  359. {
  360. case "Bool":
  361. bool boolValue;
  362. if (bool.TryParse(value, out boolValue) && boolValue != item.BoolValue)
  363. {
  364. item.BoolValue = boolValue;
  365. changed = true;
  366. }
  367. break;
  368. case "Integer":
  369. int intValue;
  370. if (int.TryParse(value, out intValue) && intValue != item.IntValue)
  371. {
  372. int.TryParse(item.Min, out int min);
  373. int.TryParse(item.Max, out int max);
  374. if (intValue <min || intValue > max)
  375. {
  376. LOG.Write(eEvent.WARN_SYSTEM_CONFIG, ModuleName.System, $"SC {item.PathName} value {intValue} out of setting range ({item.Min}, {item.Max})");
  377. break;
  378. }
  379. item.IntValue = intValue;
  380. changed = true;
  381. }
  382. break;
  383. case "Double":
  384. double doubleValue;
  385. if (double.TryParse(value, out doubleValue) && Math.Abs(doubleValue - item.DoubleValue) > 0.0001)
  386. {
  387. double.TryParse(item.Min, out double min);
  388. double.TryParse(item.Max, out double max);
  389. if (doubleValue < min || doubleValue > max)
  390. {
  391. LOG.Write(eEvent.WARN_SYSTEM_CONFIG, ModuleName.System, $"SC {item.PathName} value {doubleValue} out of setting range ({item.Min}, {item.Max})");
  392. break;
  393. }
  394. item.DoubleValue = doubleValue;
  395. changed = true;
  396. }
  397. break;
  398. case "String":
  399. if (value != item.StringValue)
  400. {
  401. item.StringValue = value;
  402. changed = true;
  403. }
  404. break;
  405. }
  406. return changed;
  407. }
  408. public void SetItemValue(string name, object value)
  409. {
  410. Debug.Assert(_items.ContainsKey(name), "can not find sc name, " + name);
  411. if (!_items.ContainsKey(name))
  412. {
  413. return;
  414. }
  415. bool changed = false;
  416. switch (_items[name].Type)
  417. {
  418. case "Bool":
  419. bool boolValue = (bool)value;
  420. if (boolValue != _items[name].BoolValue)
  421. {
  422. _items[name].BoolValue = boolValue;
  423. changed = true;
  424. }
  425. break;
  426. case "Integer":
  427. int intValue = (int)value;
  428. if (intValue != _items[name].IntValue)
  429. {
  430. _items[name].IntValue = intValue;
  431. changed = true;
  432. }
  433. break;
  434. case "Double":
  435. double doubleValue = (double)value;
  436. if (Math.Abs(doubleValue - _items[name].DoubleValue) > 0.0001)
  437. {
  438. _items[name].DoubleValue = doubleValue;
  439. changed = true;
  440. }
  441. break;
  442. case "String":
  443. string stringValue = (string)value;
  444. if (stringValue != _items[name].StringValue)
  445. {
  446. _items[name].StringValue = stringValue;
  447. changed = true;
  448. }
  449. break;
  450. }
  451. if (changed)
  452. {
  453. GenerateDataFile();
  454. }
  455. }
  456. public void SetItemValueStringFormat(string name, string value)
  457. {
  458. Debug.Assert(_items.ContainsKey(name), "can not find sc name, " + name);
  459. if (!_items.ContainsKey(name))
  460. {
  461. return;
  462. }
  463. bool changed = false;
  464. switch (_items[name].Type)
  465. {
  466. case "Bool":
  467. bool boolValue = Convert.ToBoolean(value);
  468. if (boolValue != _items[name].BoolValue)
  469. {
  470. _items[name].BoolValue = boolValue;
  471. changed = true;
  472. }
  473. break;
  474. case "Integer":
  475. int intValue = Convert.ToInt32(value);
  476. if (intValue != _items[name].IntValue)
  477. {
  478. _items[name].IntValue = intValue;
  479. changed = true;
  480. }
  481. break;
  482. case "Double":
  483. double doubleValue = Convert.ToDouble(value);
  484. if (Math.Abs(doubleValue - _items[name].DoubleValue) > 0.0001)
  485. {
  486. _items[name].DoubleValue = doubleValue;
  487. changed = true;
  488. }
  489. break;
  490. case "String":
  491. string stringValue = (string)value;
  492. if (stringValue != _items[name].StringValue)
  493. {
  494. _items[name].StringValue = stringValue;
  495. changed = true;
  496. }
  497. break;
  498. }
  499. if (changed)
  500. {
  501. GenerateDataFile();
  502. }
  503. }
  504. public void SetItemValue(string name, bool value)
  505. {
  506. Debug.Assert(_items.ContainsKey(name), "can not find sc name, " + name);
  507. Debug.Assert(_items[name].Type=="Bool", "sc type not bool, defined as" + _items[name].Type);
  508. if (value != _items[name].BoolValue)
  509. {
  510. _items[name].BoolValue = value;
  511. GenerateDataFile();
  512. }
  513. }
  514. public void SetItemValue(string name, int value)
  515. {
  516. Debug.Assert(_items.ContainsKey(name), "can not find sc name, " + name);
  517. Debug.Assert(_items[name].Type == "Integer", "sc type not bool, defined as" + _items[name].Type);
  518. if (value != _items[name].IntValue)
  519. {
  520. _items[name].IntValue = value;
  521. GenerateDataFile();
  522. }
  523. }
  524. public void SetItemValue(string name, double value)
  525. {
  526. Debug.Assert(_items.ContainsKey(name), "can not find sc name, " + name);
  527. Debug.Assert(_items[name].Type == "Double", "sc type not bool, defined as" + _items[name].Type);
  528. if (Math.Abs(value - _items[name].DoubleValue) > 0.0001)
  529. {
  530. _items[name].DoubleValue = value;
  531. GenerateDataFile();
  532. }
  533. }
  534. public void SetItemValue(string name, string value)
  535. {
  536. Debug.Assert(_items.ContainsKey(name), "can not find sc name, " + name);
  537. if (value != _items[name].StringValue)
  538. {
  539. _items[name].StringValue = value;
  540. GenerateDataFile();
  541. }
  542. }
  543. }
  544. }