DeviceDefineManager.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Xml.Linq;
  5. using Aitex.Core.RT.DataCenter;
  6. using Aitex.Core.Util;
  7. namespace Aitex.Core.RT.Device
  8. {
  9. /// <summary>
  10. /// 读取机台对应的config xml文件.
  11. /// </summary>
  12. public class DeviceDefineManager : Singleton<DeviceDefineManager>
  13. {
  14. private readonly Dictionary<string, string> _dictionary = new Dictionary<string, string>();
  15. private XDocument _xml;
  16. private string _xmlConfigPath;
  17. public T? GetValue<T>(string name) where T : struct
  18. {
  19. try
  20. {
  21. if (!_dictionary.ContainsKey(name))
  22. return default(T);
  23. if (typeof(T) == typeof(bool))
  24. return (T)(object)(_dictionary[name].ToLower() == "true");
  25. if (typeof(T) == typeof(int))
  26. return (T)(object)(int.Parse(_dictionary[name]));
  27. if (typeof(T) == typeof(double))
  28. return (T)(object)(double.Parse(_dictionary[name]));
  29. //Debug.Assert(false, "unsupported type");
  30. return default(T);
  31. }
  32. catch
  33. {
  34. return null;
  35. }
  36. }
  37. public string GetValue(string name)
  38. {
  39. _dictionary.TryGetValue(name, out string value);
  40. return value;
  41. }
  42. private void Load()
  43. {
  44. foreach (var xNode in _xml.DescendantNodes())
  45. if (xNode is XElement element)
  46. {
  47. if (element.Name == _xml.Root?.Name)
  48. continue;
  49. _dictionary.Add(element.Name.ToString(), element.Value);
  50. }
  51. }
  52. private void Subscribe()
  53. {
  54. foreach (var define in _dictionary)
  55. {
  56. DATA.Subscribe($"DeviceDefine.{define.Key}",()=>_dictionary[define.Key]);
  57. }
  58. }
  59. public void Initialize(string xmlConfigPath)
  60. {
  61. _xmlConfigPath = xmlConfigPath;
  62. _xml = XDocument.Load(_xmlConfigPath);
  63. Load();
  64. Subscribe();
  65. }
  66. }
  67. }