SubscriptionViewModelBase.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Threading.Tasks;
  7. using System.Windows;
  8. using System.Windows.Data;
  9. using System.Windows.Input;
  10. using Aitex.Core.RT.Log;
  11. using Aitex.Core.Util;
  12. namespace Aitex.Core.UI.MVVM
  13. {
  14. /*
  15. * 要求绑定的格式参考如下方式,命名统一为ElementData,这样才能统一由程序把需要从RT获取的数据项名称自动添加进来
  16. <my1:AnalogControl Command="{Binding Path=DeviceOperationCommand}" DeviceData="{Binding Path=ElementData[ReactorA.mfcNH3PushH2] }" Width="54" />
  17. */
  18. public class SubscriptionViewModelBase : TimerViewModelBase
  19. {
  20. const string BindingPathName = "ElementData";
  21. protected Func<IEnumerable<string>, Dictionary<string, object>> PollDataFunction;
  22. protected Action<string[]> InvokeFunction;
  23. protected Action<string, string> DeviceFunction;
  24. protected Action<object[]> DeviceControlFunction;
  25. protected Dictionary<string, Func<string, bool>> PreCommand = new Dictionary<string, Func<string, bool>>();
  26. ConcurrentBag<string> _subscribedKeys = new ConcurrentBag<string>();
  27. Func<object, bool> _isSubscriptionAttribute;
  28. Func<MemberInfo, bool> _hasSubscriptionAttribute;
  29. public ICommand InvokeCommand { get; set; }
  30. List<DelegateCommand<string>> _lstICommand = new List<DelegateCommand<string>>();
  31. List<IViewModelControl> viewModelControls = new List<IViewModelControl>();
  32. /// <summary>
  33. /// 设备名称,设备操作
  34. /// </summary>
  35. public ICommand DeviceCommand { get; set; }
  36. public ICommand DeviceControlCommand { get; set; }
  37. public SubscriptionViewModelBase(string name)
  38. : base(name)
  39. {
  40. _isSubscriptionAttribute = attribute => attribute is SubscriptionAttribute;
  41. _hasSubscriptionAttribute = mi => mi.GetCustomAttributes(false).Any(_isSubscriptionAttribute);
  42. InvokeCommand = new DelegateCommand<string>(param =>
  43. {
  44. PerformInvokeFunction(param.Split(','));
  45. }, functionName => { return true; });
  46. DeviceCommand = new DelegateCommand<string>(operation =>
  47. {
  48. string[] args = operation.Split(',');
  49. DeviceFunction(args[0], args[1]);
  50. }, functionName => { return true; });
  51. DeviceControlCommand = new DelegateCommand<object>(args =>
  52. {
  53. DeviceControlFunction((object[])args);
  54. }, functionName => { return true; });
  55. TraverseKeys();
  56. }
  57. public virtual bool PerformInvokeFunction(string[] param)
  58. {
  59. return true;
  60. }
  61. public static string UIKey(string param1, string param2)
  62. {
  63. return param1 + "." + param2;
  64. }
  65. public static string UIKey(string param1, string param2, string param3)
  66. {
  67. return param1 + "." + param2 + "." + param3;
  68. }
  69. public static string UIKey(string param1, string param2, string param3, string param4)
  70. {
  71. return param1 + "." + param2 + "." + param3 + "." + param4;
  72. }
  73. protected override void Poll()
  74. {
  75. if (PollDataFunction != null && _subscribedKeys.Count > 0)
  76. {
  77. Dictionary<string, object> result = PollDataFunction(_subscribedKeys);
  78. if (result == null)
  79. {
  80. LOG.Error("获取RT数据失败");
  81. return;
  82. }
  83. if (result.Count != _subscribedKeys.Count)
  84. {
  85. string unknowKeys = string.Empty;
  86. foreach (string key in _subscribedKeys)
  87. {
  88. if (!result.ContainsKey(key))
  89. {
  90. unknowKeys += key + "\r\n";
  91. }
  92. }
  93. //if (unknowKeys.Length > 0)
  94. // LOG.Error("UI did not get data element:" + unknowKeys);
  95. }
  96. InvokeBeforeUpdateProperty(result);
  97. UpdateValue(result);
  98. Application.Current.Dispatcher.Invoke(new Action(() =>
  99. {
  100. InvokePropertyChanged();
  101. foreach (var viewModelControl in viewModelControls)
  102. {
  103. viewModelControl.InvokePropertyChanged();
  104. }
  105. InvokeAfterUpdateProperty(result);
  106. }));
  107. }
  108. }
  109. protected virtual void InvokeBeforeUpdateProperty(Dictionary<string, object> data)
  110. {
  111. }
  112. protected virtual void InvokeAfterUpdateProperty(Dictionary<string, object> data)
  113. {
  114. }
  115. void UpdateValue(Dictionary<string, object> data)
  116. {
  117. if (data == null)
  118. return;
  119. UpdateSubscribe(data, this);
  120. var properties = GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.GetCustomAttribute<SubscriptionModuleAttribute>() != null);
  121. foreach (var property in properties)
  122. {
  123. var moduleAttr = property.GetCustomAttribute<SubscriptionModuleAttribute>();
  124. UpdateSubscribe(data, property.GetValue(this), moduleAttr.Module);
  125. }
  126. foreach (var viewModelControl in viewModelControls)
  127. {
  128. UpdateSubscribe(data, viewModelControl);
  129. }
  130. }
  131. void TraverseKeys()
  132. {
  133. SubscribeKeys(this);
  134. }
  135. void Subscribe(Binding binding, string bindingPathName)
  136. {
  137. if (binding != null)
  138. {
  139. string path = binding.Path.Path;
  140. if (path.Contains(bindingPathName) && path.Contains('[') && path.Contains(']'))
  141. {
  142. try
  143. {
  144. Subscribe(path.Substring(path.IndexOf('[') + 1, path.IndexOf(']') - path.IndexOf('[') - 1));
  145. }
  146. catch (Exception ex)
  147. {
  148. LOG.Write(ex);
  149. }
  150. }
  151. }
  152. }
  153. protected void Subscribe(string key)
  154. {
  155. if (!string.IsNullOrEmpty(key))
  156. {
  157. _subscribedKeys.Add(key);
  158. }
  159. }
  160. protected void Subscribe(string key, object value)
  161. {
  162. if (!string.IsNullOrEmpty(key))
  163. {
  164. _subscribedKeys.Add(key);
  165. }
  166. }
  167. //public void SubscribeKeys(UiViewModelBase target)
  168. //{
  169. // SubscribeKeys(target, "");
  170. //}
  171. //public void SubscribeKeys(UiViewModelBase target, string module)
  172. //{
  173. // Parallel.ForEach(target.GetType().GetProperties().Where(_hasSubscriptionAttribute),
  174. // property =>
  175. // {
  176. // SubscriptionAttribute subscription = property.GetCustomAttributes(false).First(_isSubscriptionAttribute) as SubscriptionAttribute;
  177. // string key = subscription.ModuleKey;
  178. // if (!string.IsNullOrEmpty(module))
  179. // {
  180. // key = $"{module}.{key}";
  181. // subscription.SetModule(module);
  182. // }
  183. // if (!_subscribedKeys.Contains(key))
  184. // _subscribedKeys.Add(key);
  185. // });
  186. // Parallel.ForEach(target.GetType().GetFields().Where(_hasSubscriptionAttribute),
  187. // method =>
  188. // {
  189. // SubscriptionAttribute subscription = method.GetCustomAttributes(false).First(_isSubscriptionAttribute) as SubscriptionAttribute;
  190. // string key = subscription.ModuleKey;
  191. // if (!string.IsNullOrEmpty(module))
  192. // {
  193. // key = $"{module}.{key}";
  194. // subscription.SetModule(module);
  195. // }
  196. // if (!_subscribedKeys.Contains(key))
  197. // _subscribedKeys.Add(key);
  198. // });
  199. //}
  200. public void SubscribeKeys(IViewModelControl target)
  201. {
  202. Parallel.ForEach(target.GetType().GetProperties().Where(_hasSubscriptionAttribute),
  203. property =>
  204. {
  205. SubscriptionAttribute subscription = property.GetCustomAttributes(false).First(_isSubscriptionAttribute) as SubscriptionAttribute;
  206. string key = subscription.ModuleKey;
  207. if (!_subscribedKeys.Contains(key))
  208. _subscribedKeys.Add(key);
  209. });
  210. Parallel.ForEach(target.GetType().GetFields().Where(_hasSubscriptionAttribute),
  211. method =>
  212. {
  213. SubscriptionAttribute subscription = method.GetCustomAttributes(false).First(_isSubscriptionAttribute) as SubscriptionAttribute;
  214. string key = subscription.ModuleKey;
  215. if (!_subscribedKeys.Contains(key))
  216. _subscribedKeys.Add(key);
  217. });
  218. // Add sub module subscription
  219. var properties = target.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.GetCustomAttribute<SubscriptionModuleAttribute>() != null);
  220. foreach (var property in properties)
  221. {
  222. var moduleAttr = property.GetCustomAttribute<SubscriptionModuleAttribute>();
  223. var module = moduleAttr.Module;
  224. var type = property.PropertyType;
  225. var ps = type.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.GetCustomAttribute<SubscriptionAttribute>() != null);
  226. foreach (var p in ps)
  227. {
  228. var a = p.GetCustomAttribute<SubscriptionAttribute>();
  229. var key = string.Format("{0}.{1}", module, a.ModuleKey);
  230. if (!_subscribedKeys.Contains(key))
  231. _subscribedKeys.Add(key);
  232. }
  233. }
  234. if (target != this)
  235. {
  236. viewModelControls.Add(target);
  237. }
  238. }
  239. public void UpdateSubscribe(Dictionary<string, object> data, object target, string module = null)
  240. {
  241. Parallel.ForEach(target.GetType().GetProperties().Where(_hasSubscriptionAttribute),
  242. property =>
  243. {
  244. PropertyInfo pi = (PropertyInfo)property;
  245. SubscriptionAttribute subscription = property.GetCustomAttributes(false).First(_isSubscriptionAttribute) as SubscriptionAttribute;
  246. string key = subscription.ModuleKey;
  247. key = module == null ? key : string.Format("{0}.{1}", module, key);
  248. if (_subscribedKeys.Contains(key) && data.ContainsKey(key))
  249. {
  250. try
  251. {
  252. var convertedValue = Convert.ChangeType(data[key], pi.PropertyType);
  253. var originValue = Convert.ChangeType(pi.GetValue(target, null), pi.PropertyType);
  254. if (originValue != convertedValue)
  255. {
  256. if (pi.Name == "PumpLimitSetPoint")
  257. pi.SetValue(target, convertedValue, null);
  258. else
  259. pi.SetValue(target, convertedValue, null);
  260. }
  261. }
  262. catch (Exception ex)
  263. {
  264. LOG.Error("由RT返回的数据更新失败" + key, ex);
  265. }
  266. }
  267. });
  268. Parallel.ForEach(target.GetType().GetFields().Where(_hasSubscriptionAttribute),
  269. property =>
  270. {
  271. FieldInfo pi = (FieldInfo)property;
  272. SubscriptionAttribute subscription = property.GetCustomAttributes(false).First(_isSubscriptionAttribute) as SubscriptionAttribute;
  273. string key = subscription.ModuleKey;
  274. if (_subscribedKeys.Contains(key) && data.ContainsKey(key))
  275. {
  276. try
  277. {
  278. var convertedValue = Convert.ChangeType(data[key], pi.FieldType);
  279. pi.SetValue(target, convertedValue);
  280. }
  281. catch (Exception ex)
  282. {
  283. LOG.Error("由RT返回的数据更新失败" + key, ex);
  284. }
  285. }
  286. });
  287. }
  288. }
  289. }