SystemConfigManager.cs 20 KB

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