SubscriptionViewModelBase.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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(IViewModelControl target)
  168. {
  169. Parallel.ForEach(target.GetType().GetProperties().Where(_hasSubscriptionAttribute),
  170. property =>
  171. {
  172. SubscriptionAttribute subscription = property.GetCustomAttributes(false).First(_isSubscriptionAttribute) as SubscriptionAttribute;
  173. string key = subscription.ModuleKey;
  174. if (!_subscribedKeys.Contains(key))
  175. _subscribedKeys.Add(key);
  176. });
  177. Parallel.ForEach(target.GetType().GetFields().Where(_hasSubscriptionAttribute),
  178. method =>
  179. {
  180. SubscriptionAttribute subscription = method.GetCustomAttributes(false).First(_isSubscriptionAttribute) as SubscriptionAttribute;
  181. string key = subscription.ModuleKey;
  182. if (!_subscribedKeys.Contains(key))
  183. _subscribedKeys.Add(key);
  184. });
  185. // Add sub module subscription
  186. var properties = target.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.GetCustomAttribute<SubscriptionModuleAttribute>() != null);
  187. foreach (var property in properties)
  188. {
  189. var moduleAttr = property.GetCustomAttribute<SubscriptionModuleAttribute>();
  190. var module = moduleAttr.Module;
  191. var type = property.PropertyType;
  192. var ps = type.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.GetCustomAttribute<SubscriptionAttribute>() != null);
  193. foreach (var p in ps)
  194. {
  195. var a = p.GetCustomAttribute<SubscriptionAttribute>();
  196. var key = string.Format("{0}.{1}", module, a.ModuleKey);
  197. if (!_subscribedKeys.Contains(key))
  198. _subscribedKeys.Add(key);
  199. }
  200. }
  201. if (target != this)
  202. {
  203. viewModelControls.Add(target);
  204. }
  205. }
  206. public void UpdateSubscribe(Dictionary<string, object> data, object target, string module = null)
  207. {
  208. Parallel.ForEach(target.GetType().GetProperties().Where(_hasSubscriptionAttribute),
  209. property =>
  210. {
  211. PropertyInfo pi = (PropertyInfo)property;
  212. SubscriptionAttribute subscription = property.GetCustomAttributes(false).First(_isSubscriptionAttribute) as SubscriptionAttribute;
  213. string key = subscription.ModuleKey;
  214. key = module == null ? key : string.Format("{0}.{1}", module, key);
  215. if (_subscribedKeys.Contains(key) && data.ContainsKey(key))
  216. {
  217. try
  218. {
  219. var convertedValue = Convert.ChangeType(data[key], pi.PropertyType);
  220. var originValue = Convert.ChangeType(pi.GetValue(target, null), pi.PropertyType);
  221. if (originValue != convertedValue)
  222. {
  223. if (pi.Name == "PumpLimitSetPoint")
  224. pi.SetValue(target, convertedValue, null);
  225. else
  226. pi.SetValue(target, convertedValue, null);
  227. }
  228. }
  229. catch (Exception ex)
  230. {
  231. LOG.Error("由RT返回的数据更新失败" + key, ex);
  232. }
  233. }
  234. });
  235. Parallel.ForEach(target.GetType().GetFields().Where(_hasSubscriptionAttribute),
  236. property =>
  237. {
  238. FieldInfo pi = (FieldInfo)property;
  239. SubscriptionAttribute subscription = property.GetCustomAttributes(false).First(_isSubscriptionAttribute) as SubscriptionAttribute;
  240. string key = subscription.ModuleKey;
  241. if (_subscribedKeys.Contains(key) && data.ContainsKey(key))
  242. {
  243. try
  244. {
  245. var convertedValue = Convert.ChangeType(data[key], pi.FieldType);
  246. pi.SetValue(target, convertedValue);
  247. }
  248. catch (Exception ex)
  249. {
  250. LOG.Error("由RT返回的数据更新失败" + key, ex);
  251. }
  252. }
  253. });
  254. }
  255. }
  256. }