ProtocolProxyBase.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. using DBHelper;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.ComponentModel.DataAnnotations;
  5. using System.Diagnostics.Contracts;
  6. using System.Globalization;
  7. using System.Linq;
  8. using System.Linq.Expressions;
  9. using System.Reflection;
  10. using System.Runtime.InteropServices;
  11. using System.Runtime.Serialization;
  12. using System.Text;
  13. using System.Threading;
  14. using System.Xml.Serialization;
  15. using WCS.Entity;
  16. namespace WCS.Core
  17. {
  18. /// <summary>
  19. /// IL动态生成的类型所继承的基类
  20. /// </summary>
  21. public abstract class ProtocolProxyBase : IProtocolProxy
  22. {
  23. protected Type ProtocolType, ProtocolDataType;
  24. public static Func<WCS_PROTOCOLDATA, string,WCS_PROTOCOLDATA> DataChanged;
  25. Dictionary<string, PlcItem> Items = new Dictionary<string, PlcItem>();
  26. //public ushort Start;
  27. //public string Name;
  28. public string Id { get; set; }
  29. public WCS_DEVICEPROTOCOL PROTOCOL { get; private set; }
  30. /// <summary>
  31. /// 起始便宜量,按字节算
  32. /// </summary>
  33. ushort Start;
  34. /// <summary>
  35. /// 长度,按字节算
  36. /// </summary>
  37. ushort Length;
  38. public WCS_DATABLOCK Db;
  39. static Dictionary<Type, object> LockObjs = new Dictionary<Type, object>();
  40. public ProtocolProxyBase(string id, WCS_DATABLOCK db, ushort start, WCS_DEVICEPROTOCOL deviceItem)
  41. {
  42. var type = this.GetType();
  43. if (!LockObjs.ContainsKey(type))
  44. LockObjs[type] = new object();
  45. this.Db = db;
  46. db.Ex().DataChanged += PLCData_DataChanged;
  47. this.Start = start;
  48. var bitStart = start * 8;//偏移量,按位算
  49. this.Id = id;
  50. this.PROTOCOL = deviceItem;
  51. //this.Start = start;
  52. //PlcDB db = new PlcDB(null, 50, 100);
  53. var lst = this.GetType().GetInterfaces().ToList();
  54. var ps = lst.SelectMany(v => v.GetProperties()).ToArray();
  55. foreach (var p in ps)
  56. {
  57. if (p.GetIndexParameters().Length > 0)
  58. continue;
  59. if (typeof(ProtocolProxyBase).GetProperty(p.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) != null)
  60. {
  61. continue;
  62. }
  63. #region 计算偏移量
  64. var modeNum = 0;
  65. var t = p.PropertyType;
  66. if (t.IsEnum)
  67. t = t.GetEnumUnderlyingType();
  68. if (t == typeof(bool))//bit类型,db块中无须补齐16位
  69. {
  70. modeNum = 1;
  71. }
  72. else if (t.IsPrimitive && Marshal.SizeOf(t) == 1)//byte char 等单字节类型,db块中无须补齐16位
  73. {
  74. modeNum = 8;
  75. }
  76. else//其他类型,db块中必须补齐16位
  77. {
  78. modeNum = 16;
  79. }
  80. var mod = bitStart % modeNum;
  81. if (mod > 0)
  82. {
  83. bitStart += modeNum - mod;
  84. }
  85. #endregion
  86. byte arrlen = 0;
  87. byte strLen = 0;
  88. if (t.IsArray)
  89. {
  90. var attr = p.GetCustomAttributes(typeof(MaxLengthAttribute), true).FirstOrDefault() as MaxLengthAttribute;
  91. if (attr != null)
  92. arrlen = (byte)attr.Length;
  93. }
  94. else if (p.PropertyType == typeof(string))
  95. {
  96. var attr = p.GetCustomAttributes(typeof(StringLengthAttribute), true).FirstOrDefault() as StringLengthAttribute;
  97. strLen = (byte)attr.MaximumLength;
  98. }
  99. var m = typeof(DataBlock).GetMethod("Regist");
  100. m = m.MakeGenericMethod(p.PropertyType);
  101. var item = m.Invoke(db.Ex(), new object[] { this.Id, p.Name, bitStart, arrlen, strLen }) as PlcItem;
  102. Items.Add(p.Name, item);
  103. bitStart += item.DataSizeOfBits;
  104. Length += item.DataSize;
  105. }
  106. ProtocolType= this.PROTOCOL.DB.GetProtocolType();
  107. ProtocolDataType = ProtocolType.Assembly.GetTypes().Where(v => v.IsClass).Where(v => v.GetInterface(ProtocolType.Name) != null && v != this.GetType()).First();
  108. }
  109. byte[] Data = null;
  110. static object locobj = new object();
  111. void InvokeUpdate(string user,DB db)
  112. {
  113. SaveChangs(user,db);
  114. }
  115. WCS_PROTOCOLDATA last = null;
  116. public DateTime UpdateTime;
  117. protected virtual void SaveChangs(string user,DB db)
  118. {
  119. var obj = Copy(this,ProtocolDataType) as WCS_PROTOCOLDATA;
  120. obj.WCSVERSION = this.WCSVersion;
  121. if (last == null)
  122. {
  123. Publish(this.PROTOCOL.DEVICE.CODE, obj);
  124. last = GetLastData(db);
  125. }
  126. if (last != null)
  127. {
  128. if (Equals(obj, last, ProtocolType))
  129. return;
  130. }
  131. this.UpdateTime = DateTime.Now;
  132. Publish(this.PROTOCOL.DEVICE.CODE,obj);
  133. last = SaveNewData(db,last,obj,user);
  134. }
  135. public virtual void Publish(string code,WCS_PROTOCOLDATA obj)
  136. {
  137. }
  138. protected abstract WCS_PROTOCOLDATA GetLastData(DB db);
  139. protected abstract WCS_PROTOCOLDATA SaveNewData(DB db, WCS_PROTOCOLDATA last, WCS_PROTOCOLDATA newobj,string user);
  140. private void PLCData_DataChanged(DB db,byte[] data)
  141. {
  142. var temp = data.Skip(Start).Take(Length).ToArray();
  143. try
  144. {
  145. if (Data != null && Data.SequenceEqual(temp))
  146. return;
  147. var d1 = DateTime.Now;
  148. InvokeUpdate("PLC",db);
  149. var d = (DateTime.Now - d1).TotalMilliseconds;
  150. //Console.WriteLine("DB " + d);
  151. }
  152. finally { Data = temp; }
  153. }
  154. object Copy(object obj, Type type)
  155. {
  156. var res = Activator.CreateInstance(type);
  157. foreach (var p in type.GetProperties())
  158. {
  159. var p2 = obj.GetType().GetProperty(p.Name);
  160. if (p2 != null && p2.PropertyType == p.PropertyType)
  161. {
  162. p.SetValue(res, p2.GetValue(obj));
  163. }
  164. }
  165. return res;
  166. }
  167. bool Equals(object a, object b, Type type)
  168. {
  169. foreach (var p in type.GetProperties())
  170. {
  171. var v1 = p.GetValue(a);
  172. var v2 = p.GetValue(b);
  173. var attr = p.GetCustomAttribute<IgnoreChangingAttribute>();
  174. if (attr != null)
  175. {
  176. if (attr.IgnoreValueRange == 0)
  177. continue;
  178. else
  179. {
  180. try
  181. {
  182. var d = Math.Abs((decimal.Parse(v1.ToString())) - (decimal.Parse(v2.ToString())));
  183. if (d < attr.IgnoreValueRange)
  184. continue;
  185. }
  186. catch
  187. {
  188. Console.WriteLine("IgnoreValueRange属性只能用于数字类型");
  189. }
  190. }
  191. }
  192. if (p.PropertyType == typeof(string))
  193. {
  194. v1 = v1 == null ? "" : v1.ToString();
  195. v2 = v2 == null ? "" : v2.ToString();
  196. }
  197. if (p.PropertyType.IsArray)
  198. {
  199. var m = typeof(Enumerable).GetMethods().Where(v => v.Name == nameof(Enumerable.SequenceEqual)).First(v => v.GetParameters().Length == 2);
  200. m = m.MakeGenericMethod(p.PropertyType.GetElementType());
  201. var res = (bool)m.Invoke(null, new object[] { v1, v2 });
  202. if (!res)
  203. return false;
  204. }
  205. else
  206. {
  207. if (!v1.Equals(v2))
  208. return false;
  209. }
  210. }
  211. return true;
  212. }
  213. #region IGenerator
  214. /// <summary>
  215. /// 索引器Get
  216. /// </summary>
  217. /// <typeparam name="T"></typeparam>
  218. /// <param name="args"></param>
  219. /// <returns></returns>
  220. protected T GetItem<T>(params object[] args)
  221. {
  222. Console.WriteLine("GetItem:" + string.Join(",", args.Select(v => v.ToString())));
  223. return default(T);
  224. }
  225. /// <summary>
  226. /// 索引器Set
  227. /// </summary>
  228. /// <param name="args"></param>
  229. /// <returns></returns>
  230. protected void SetItem(params object[] args)
  231. {
  232. Console.WriteLine("SetItem:" + ":" + string.Join(",", args.Select(v => v.ToString())));
  233. }
  234. /// <summary>
  235. /// 版本号,WCS每修改一次数据,版本号变化一次
  236. /// </summary>
  237. public int WCSVersion { get;private set; }
  238. public void Set<T>(string propertyName, T value)
  239. {
  240. var str = PROTOCOL.DEVICE.CODE + "." + ProtocolType.Name + "." + propertyName;
  241. try
  242. {
  243. str += " = " + (value == null ? "null" : value.ToString());
  244. var item = Items[propertyName] as PlcItem<T>;
  245. item.Value = value;
  246. DB.Do(db => {
  247. InvokeUpdate("WCS",db);
  248. });
  249. Data = null;
  250. WCSVersion++;
  251. str += " 写入成功";
  252. }
  253. catch
  254. {
  255. str += " 写入失败";
  256. throw;
  257. }
  258. finally
  259. {
  260. Ltc.Log(str);
  261. }
  262. }
  263. public void Update(string prop, object value, string user)
  264. {
  265. var item = Items[prop];
  266. item.Value = value;
  267. DB.Do(db =>
  268. {
  269. InvokeUpdate(user, db);
  270. });
  271. Data = null;
  272. if (user == "PLC")
  273. return;
  274. WCSVersion++;
  275. }
  276. public T Get<T>(string propertyName)
  277. {
  278. var str = PROTOCOL.DEVICE.CODE + "." + ProtocolType.Name + "." + propertyName;
  279. try
  280. {
  281. var item = Items[propertyName] as PlcItem<T>;
  282. var res = item.Value;
  283. str += " : " + (res == null ? "null" : res.ToString());
  284. return res;
  285. }
  286. catch
  287. {
  288. str += " 读取失败";
  289. throw;
  290. }
  291. finally
  292. {
  293. //Ltc.Log(str);
  294. }
  295. }
  296. public T CallReturn<T>(string methodName, params object[] args)
  297. {
  298. Console.WriteLine(methodName + ":" + string.Join(",", args.Select(v => v.ToString())));
  299. return (T)(object)1.321f;
  300. }
  301. public void CallVoid(string methodName, params object[] args)
  302. {
  303. Console.WriteLine(methodName + ":" + string.Join(",", args.Select(v => v.ToString())));
  304. }
  305. public void AddEvent(string eventName, Delegate delgate)
  306. {
  307. Console.WriteLine("Add:" + eventName);
  308. }
  309. public void RemoveEvent(string eventName, Delegate delgate)
  310. {
  311. Console.WriteLine("Remove:" + eventName);
  312. }
  313. #endregion
  314. public override string ToString()
  315. {
  316. var str = "";
  317. foreach (var p in this.GetType().GetProperties())
  318. {
  319. str += p.Name + ":" + p.GetValue(this, null).ToString() + ",";
  320. }
  321. str = str.Substring(0, str.Length - 1);
  322. return str;
  323. }
  324. }
  325. }