ProtocolProxy.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. using MessagePack;
  2. using MessagePack.Resolvers;
  3. using Newtonsoft.Json;
  4. using System.Collections.Concurrent;
  5. using System.Diagnostics;
  6. using System.Linq.Dynamic.Core;
  7. using WCS.Core;
  8. using WCS.Core.BaseExtensions;
  9. using WCS.Core.DataTrans;
  10. using WCS.Core.DbHelper;
  11. using WCS.Core.Redis;
  12. using WCS.Entity;
  13. using WCS.Entity.Protocol;
  14. namespace WCS.Service
  15. {
  16. /// <summary>
  17. /// 代理协议
  18. /// </summary>
  19. public class ProtocolProxy : ProtocolProxyBase
  20. {
  21. public ProtocolProxy(string id, WCS_DATABLOCK db, ushort start, WCS_DEVICEPROTOCOL protocol) : base(id, db, start, protocol)
  22. {
  23. }
  24. private static readonly ConcurrentDictionary<Type, object[]> LastDatas = new();
  25. /// <summary>
  26. /// 获取新的数据
  27. /// </summary>
  28. /// <param name="db"></param>
  29. /// <returns></returns>
  30. protected override WCS_PROTOCOLDATA GetLastData(Db db)
  31. {
  32. if (!LastDatas.ContainsKey(this.ProtocolDataType))
  33. {
  34. LastDatas[this.ProtocolDataType] = db.Default.Queryable<dynamic>().AS($"{this.ProtocolDataType.Name}", "it").Where("ISLAST=0").OrderBy("ID").ToArray();
  35. }
  36. dynamic data = LastDatas[this.ProtocolDataType];
  37. var list = new List<WCS_PROTOCOLDATA>();
  38. foreach (var itemData in data)
  39. {
  40. try
  41. {
  42. if (itemData.DEVICECOD == Protocol.DEVICE.CODE)
  43. list.Add(itemData);
  44. }
  45. catch
  46. {
  47. // ignored
  48. }
  49. }
  50. if (list.Count > 1)
  51. {
  52. for (var i = 0; i < list.Count - 1; i++)
  53. {
  54. var obj = list[i];
  55. db.Default.Insertable((object)obj).ExecuteCommand();
  56. obj.ISLAST = false;
  57. }
  58. }
  59. var res = list.LastOrDefault();
  60. return res;
  61. }
  62. private static int _total;
  63. protected override WCS_PROTOCOLDATA SaveNewData(Db db, WCS_PROTOCOLDATA last, WCS_PROTOCOLDATA newobj, string user)
  64. {
  65. _total++;
  66. if (last != null)
  67. {
  68. var dc = TypeExtension.EntityClassToDictionary((object)last);
  69. db.Default.Insertable(dc).AS($"{last.GetType().Name}").ExecuteCommand();
  70. last.ISLAST = false;
  71. }
  72. newobj.DEVICECOD = Protocol.DEVICE.CODE;
  73. newobj.ISLAST = true;
  74. newobj.UPDATETIME = DateTime.Now;
  75. newobj.UPDATEUSER = user;
  76. newobj.FRAME = LogicHandler.Frame;
  77. var typeName = newobj.GetType().Name;
  78. var dc1 = TypeExtension.EntityClassToDictionary((object)newobj);
  79. db.Default.Insertable(dc1).AS($"{typeName}").ExecuteCommand();
  80. return newobj;
  81. }
  82. static ProtocolProxy()
  83. {
  84. MessagePackSerializer.DefaultOptions = StandardResolver.Options.WithCompression(MessagePackCompression.Lz4Block);
  85. //RedisHelper.CreateContext("127.0.0.1,database=0", "default", true);
  86. RedisHelper.CreateContext("127.0.0.1,database=10", "3D");
  87. RedisHelper.CreateContext("127.0.0.1,database=1", "ConcurrencyControlRedis");
  88. RedisHelper.Default.Serialize = obj =>
  89. {
  90. var bytes = MessagePackSerializer.Serialize(obj);
  91. return bytes;
  92. };
  93. RedisHelper.Default.DeserializeRaw = (bytes, type) =>
  94. {
  95. var obj = MessagePackSerializer.Deserialize(type, bytes);
  96. return obj;
  97. };
  98. }
  99. public override void Publish(string code, WCS_PROTOCOLDATA obj)
  100. {
  101. try
  102. {
  103. var datas = AllDatas;
  104. if (code.StartsWith("SRM"))
  105. {
  106. if (!datas.ContainsKey(code))
  107. datas[code] = new SCData { Code = code };
  108. }
  109. else if (code.StartsWith("RGV"))
  110. {
  111. if (!datas.ContainsKey(code))
  112. datas[code] = new RGVData { Code = code };
  113. }
  114. else if (code == "Robot")
  115. {
  116. if (!datas.ContainsKey(code))
  117. datas[code] = new RobotData { Code = code };
  118. }
  119. else if (code.Length == 4)
  120. {
  121. if (!datas.ContainsKey(code))
  122. datas[code] = new StationData { Code = code };
  123. }
  124. if (!datas.ContainsKey(code)) return;
  125. var data = datas[code];
  126. data.Frame = LogicHandler.Frame;
  127. var p = data.GetType().GetProperties().FirstOrDefault(v => v.PropertyType == obj.GetType());
  128. if (p == null)
  129. {
  130. Console.WriteLine("类型" + data.GetType().Name + "不包含类型为" + obj.GetType().Name + "的属性");
  131. }
  132. else
  133. {
  134. p.SetValue(data, obj);
  135. }
  136. }
  137. catch (Exception ex)
  138. {
  139. Console.WriteLine(ex.Message);
  140. }
  141. }
  142. /// <summary>
  143. /// 所有的设备数据
  144. /// </summary>
  145. public static ConcurrentDictionary<string, DeviceData> AllDatas = new();
  146. public static void Do()
  147. {
  148. Console.ForegroundColor = ConsoleColor.Green;
  149. Console.WriteLine($"更改:{_total}");
  150. Console.ResetColor();
  151. _total = 0;
  152. try
  153. {
  154. var gs = AllDatas.GroupBy(v => v.Value.GetType());
  155. var pack = new DeviceDataPack
  156. {
  157. Frame = LogicHandler.Frame
  158. };
  159. foreach (var g in gs)
  160. {
  161. var value = g.Select(v => v.Value).ToArray();
  162. var etype = g.Key;
  163. var type = typeof(DeviceDataCollection<>).MakeGenericType(etype);
  164. var coll = Activator.CreateInstance(type, LogicHandler.Frame, value);
  165. var p = pack.GetType().GetProperties().First(v => v.PropertyType == type);
  166. p.SetValue(pack, coll);
  167. }
  168. #region 存入Redis
  169. var sw = new Stopwatch();
  170. sw.Start();
  171. RedisHelper.Default.Set(nameof(DeviceDataPack), pack);
  172. RedisHelper.Default.RPush("Packs", pack);
  173. sw.Stop();
  174. Console.ForegroundColor = ConsoleColor.Blue;
  175. Console.WriteLine($"Redis耗时{sw.ElapsedMilliseconds}");
  176. Console.ResetColor();
  177. var len = RedisHelper.Default.LLen("Packs");
  178. if (len > 150000)
  179. {
  180. RedisHelper.Default.LTrim("Packs", 20000, len);
  181. }
  182. #endregion 存入Redis
  183. var converter = new System.Text.UnicodeEncoding();
  184. var plcRawData = new PlcRawData
  185. {
  186. CONTENT = converter.GetBytes(JsonConvert.SerializeObject(pack)),
  187. WAREHOUSE = "1"
  188. };
  189. #region 存入PGSql
  190. var sw1 = new Stopwatch();
  191. sw1.Start();
  192. Core.DbHelper.Db.Do(db =>
  193. {
  194. db.Context("WCSDlog").Insertable(plcRawData).ExecuteCommand();
  195. });
  196. sw1.Stop();
  197. Console.ForegroundColor = ConsoleColor.Blue;
  198. Console.WriteLine($"PGSql耗时{sw1.ElapsedMilliseconds}");
  199. Console.ResetColor();
  200. RedisHelper.Default.RPush("Packs", pack);
  201. #endregion 存入PGSql
  202. #region 存入sqlServe
  203. var sw2 = new Stopwatch();
  204. sw2.Start();
  205. Core.DbHelper.Db.Do(db =>
  206. {
  207. db.Default.Insertable(plcRawData).ExecuteCommand();
  208. });
  209. sw2.Stop();
  210. Console.ForegroundColor = ConsoleColor.Blue;
  211. Console.WriteLine($"sqlServe耗时{sw2.ElapsedMilliseconds}");
  212. Console.ResetColor();
  213. RedisHelper.Default.RPush("Packs", pack);
  214. #endregion 存入sqlServe
  215. foreach (var data in AllDatas)
  216. {
  217. data.Value.Info = "";
  218. if (data.Value is not ProdLineData pld) continue;
  219. pld.TaskList.Clear();
  220. pld.Frame = LogicHandler.Frame;
  221. pld.Code = data.Key;
  222. }
  223. }
  224. catch (Exception)
  225. {
  226. // ignored
  227. }
  228. }
  229. }
  230. public class PackInfo
  231. {
  232. public DateTime Frame { get; set; }
  233. public byte[] Data { get; set; }
  234. }
  235. }