SystemConfigManager.cs 21 KB

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