SystemConfigManager.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  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. if(item == null)
  282. {
  283. return null;
  284. }
  285. switch (item.Type)
  286. {
  287. case "Bool": return item.BoolValue;
  288. case "Integer": return item.IntValue;
  289. case "Double": return item.DoubleValue;
  290. case "String": return item.StringValue;
  291. }
  292. return null;
  293. }
  294. public T GetValue<T>(string name) where T : struct
  295. {
  296. try
  297. {
  298. if (typeof(T) == typeof(bool))
  299. return (T)(object)_items[name].BoolValue;
  300. if (typeof(T) == typeof(int))
  301. return (T)(object)_items[name].IntValue;
  302. if (typeof(T) == typeof(double))
  303. return (T)(object)_items[name].DoubleValue;
  304. }
  305. catch (KeyNotFoundException)
  306. {
  307. MessageBox.Show($"Can not find system config item {name}");
  308. return default(T);
  309. }
  310. catch (Exception)
  311. {
  312. MessageBox.Show($"Can not get valid system config item value {name}");
  313. return default(T);
  314. }
  315. Debug.Assert(false, "unsupported type");
  316. return default(T);
  317. }
  318. public string GetStringValue(string name)
  319. {
  320. if (!_items.ContainsKey(name))
  321. return null;
  322. return _items[name].StringValue;
  323. }
  324. public List<SCConfigItem> GetItemList()
  325. {
  326. return _items.Values.ToList();
  327. }
  328. public void SetItemValueFromString(string name, string value)
  329. {
  330. if (InitializeItemValue(_items[name], value))
  331. {
  332. GenerateDataFile();
  333. }
  334. }
  335. private bool InitializeItemValue(SCConfigItem item, string value)
  336. {
  337. bool changed = false;
  338. switch (item.Type)
  339. {
  340. case "Bool":
  341. bool boolValue;
  342. if (bool.TryParse(value, out boolValue) && boolValue != item.BoolValue)
  343. {
  344. item.BoolValue = boolValue;
  345. changed = true;
  346. }
  347. break;
  348. case "Integer":
  349. int intValue;
  350. if (int.TryParse(value, out intValue) && intValue != item.IntValue)
  351. {
  352. int.TryParse(item.Min, out int min);
  353. int.TryParse(item.Max, out int max);
  354. if (intValue <min || intValue > max)
  355. {
  356. LOG.Write(eEvent.WARN_SYSTEM_CONFIG, ModuleName.System, $"SC {item.PathName} value {intValue} out of setting range ({item.Min}, {item.Max})");
  357. break;
  358. }
  359. item.IntValue = intValue;
  360. changed = true;
  361. }
  362. break;
  363. case "Double":
  364. double doubleValue;
  365. if (double.TryParse(value, out doubleValue) && Math.Abs(doubleValue - item.DoubleValue) > 0.0001)
  366. {
  367. double.TryParse(item.Min, out double min);
  368. double.TryParse(item.Max, out double max);
  369. if (doubleValue < min || doubleValue > max)
  370. {
  371. LOG.Write(eEvent.WARN_SYSTEM_CONFIG, ModuleName.System, $"SC {item.PathName} value {doubleValue} out of setting range ({item.Min}, {item.Max})");
  372. break;
  373. }
  374. item.DoubleValue = doubleValue;
  375. changed = true;
  376. }
  377. break;
  378. case "String":
  379. if (value != item.StringValue)
  380. {
  381. item.StringValue = value;
  382. changed = true;
  383. }
  384. break;
  385. }
  386. return changed;
  387. }
  388. public void SetItemValue(string name, object value)
  389. {
  390. Debug.Assert(_items.ContainsKey(name), "can not find sc name, " + name);
  391. if (!_items.ContainsKey(name))
  392. {
  393. return;
  394. }
  395. bool changed = false;
  396. switch (_items[name].Type)
  397. {
  398. case "Bool":
  399. bool boolValue = (bool)value;
  400. if (boolValue != _items[name].BoolValue)
  401. {
  402. _items[name].BoolValue = boolValue;
  403. changed = true;
  404. }
  405. break;
  406. case "Integer":
  407. int intValue = (int)value;
  408. if (intValue != _items[name].IntValue)
  409. {
  410. _items[name].IntValue = intValue;
  411. changed = true;
  412. }
  413. break;
  414. case "Double":
  415. double doubleValue = (double)value;
  416. if (Math.Abs(doubleValue - _items[name].DoubleValue) > 0.0001)
  417. {
  418. _items[name].DoubleValue = doubleValue;
  419. changed = true;
  420. }
  421. break;
  422. case "String":
  423. string stringValue = (string)value;
  424. if (stringValue != _items[name].StringValue)
  425. {
  426. _items[name].StringValue = stringValue;
  427. changed = true;
  428. }
  429. break;
  430. }
  431. if (changed)
  432. {
  433. GenerateDataFile();
  434. }
  435. }
  436. public void SetItemValueStringFormat(string name, string value)
  437. {
  438. Debug.Assert(_items.ContainsKey(name), "can not find sc name, " + name);
  439. if (!_items.ContainsKey(name))
  440. {
  441. return;
  442. }
  443. bool changed = false;
  444. switch (_items[name].Type)
  445. {
  446. case "Bool":
  447. bool boolValue = Convert.ToBoolean(value);
  448. if (boolValue != _items[name].BoolValue)
  449. {
  450. _items[name].BoolValue = boolValue;
  451. changed = true;
  452. }
  453. break;
  454. case "Integer":
  455. int intValue = Convert.ToInt32(value);
  456. if (intValue != _items[name].IntValue)
  457. {
  458. _items[name].IntValue = intValue;
  459. changed = true;
  460. }
  461. break;
  462. case "Double":
  463. double doubleValue = Convert.ToDouble(value);
  464. if (Math.Abs(doubleValue - _items[name].DoubleValue) > 0.0001)
  465. {
  466. _items[name].DoubleValue = doubleValue;
  467. changed = true;
  468. }
  469. break;
  470. case "String":
  471. string stringValue = (string)value;
  472. if (stringValue != _items[name].StringValue)
  473. {
  474. _items[name].StringValue = stringValue;
  475. changed = true;
  476. }
  477. break;
  478. }
  479. if (changed)
  480. {
  481. GenerateDataFile();
  482. }
  483. }
  484. public void SetItemValue(string name, bool value)
  485. {
  486. Debug.Assert(_items.ContainsKey(name), "can not find sc name, " + name);
  487. Debug.Assert(_items[name].Type=="Bool", "sc type not bool, defined as" + _items[name].Type);
  488. if (value != _items[name].BoolValue)
  489. {
  490. _items[name].BoolValue = value;
  491. GenerateDataFile();
  492. }
  493. }
  494. public void SetItemValue(string name, int value)
  495. {
  496. Debug.Assert(_items.ContainsKey(name), "can not find sc name, " + name);
  497. Debug.Assert(_items[name].Type == "Integer", "sc type not bool, defined as" + _items[name].Type);
  498. if (value != _items[name].IntValue)
  499. {
  500. _items[name].IntValue = value;
  501. GenerateDataFile();
  502. }
  503. }
  504. public void SetItemValue(string name, double value)
  505. {
  506. Debug.Assert(_items.ContainsKey(name), "can not find sc name, " + name);
  507. Debug.Assert(_items[name].Type == "Double", "sc type not bool, defined as" + _items[name].Type);
  508. if (Math.Abs(value - _items[name].DoubleValue) > 0.0001)
  509. {
  510. _items[name].DoubleValue = value;
  511. GenerateDataFile();
  512. }
  513. }
  514. public void SetItemValue(string name, string value)
  515. {
  516. Debug.Assert(_items.ContainsKey(name), "can not find sc name, " + name);
  517. if (value != _items[name].StringValue)
  518. {
  519. _items[name].StringValue = value;
  520. GenerateDataFile();
  521. }
  522. }
  523. }
  524. }