GenericDeviceProcessor.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. using Edge.Core.Parser;
  2. using Edge.Core.Parser.BinaryParser.MessageEntity;
  3. using Edge.Core.Processor.Communicator;
  4. using Edge.Core.Processor.Dispatcher.Attributes;
  5. using Microsoft.Extensions.DependencyInjection;
  6. using Microsoft.Extensions.Logging;
  7. using Microsoft.Extensions.Logging.Abstractions;
  8. using System;
  9. using System.Collections.Concurrent;
  10. using System.Collections.Generic;
  11. using System.Diagnostics;
  12. using System.Linq;
  13. using System.Text;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace Edge.Core.Processor
  17. {
  18. [MetaPartsDescriptor(
  19. "lang-zh-cn:通用型设备处理器lang-en-us:GenericDeviceProcessor",
  20. "lang-zh-cn:通用型设备处理器lang-en-us:Generic processor for comm with devices")]
  21. public class GenericDeviceProcessor<TRaw, TMessage> : IDeviceProcessor<TRaw, TMessage> where TMessage : MessageBase
  22. {
  23. #region performance related
  24. //private static NLog.Logger perfLogger = NLog.LogManager.LoadConfiguration("nlog.config").GetLogger("Performance");
  25. private static ILogger perfLogger = NullLogger.Instance;
  26. private Stopwatch perfWatch_From_CommOnDataReceived_To_HandlerProcessed;
  27. private Stopwatch perfWatch_From_CommOnDataReceived_To_CommOnDataWriting;
  28. private ConcurrentQueue<string> perfPeriodLogStrings;
  29. private System.Timers.Timer perfPeriodToLogFileTimer;
  30. #endregion
  31. private object syncObject = new object();
  32. public string MetaConfigName { get; set; }
  33. public IContext<TRaw, TMessage> Context { get; protected set; }
  34. public IList<IInterceptor<TRaw, TMessage>> Interceptors { get; }
  35. public ICommunicator<TRaw, TMessage> Communicator { get; }
  36. public GenericDeviceProcessor(IDeviceHandler<TRaw, TMessage> handler, ICommunicator<TRaw, TMessage> communicator, IServiceProvider services)
  37. {
  38. if (services != null)
  39. {
  40. var loggerFactory = services.GetRequiredService<ILoggerFactory>();
  41. perfLogger = loggerFactory.CreateLogger("Performance");
  42. }
  43. if (perfLogger.IsEnabled(LogLevel.Trace))
  44. {
  45. this.perfWatch_From_CommOnDataReceived_To_HandlerProcessed = new Stopwatch();
  46. this.perfWatch_From_CommOnDataReceived_To_HandlerProcessed.Stop();
  47. this.perfWatch_From_CommOnDataReceived_To_CommOnDataWriting = new Stopwatch();
  48. this.perfWatch_From_CommOnDataReceived_To_CommOnDataWriting.Stop();
  49. this.perfPeriodLogStrings = new ConcurrentQueue<string>();
  50. this.perfPeriodToLogFileTimer = new System.Timers.Timer(30 * 1000);// flush to log every 30 seconds
  51. this.perfPeriodToLogFileTimer.Elapsed += (a, b) =>
  52. {
  53. try
  54. {
  55. this.perfPeriodToLogFileTimer.Stop();
  56. if (!perfLogger.IsEnabled(LogLevel.Trace))
  57. {
  58. this.perfWatch_From_CommOnDataReceived_To_HandlerProcessed?.Stop();
  59. this.perfWatch_From_CommOnDataReceived_To_CommOnDataWriting?.Stop();
  60. return;
  61. }
  62. }
  63. catch { }
  64. finally { }
  65. try
  66. {
  67. StringBuilder sb = null;
  68. string s = null;
  69. while (this.perfPeriodLogStrings.TryDequeue(out s))
  70. {
  71. if (sb == null) sb = new StringBuilder();
  72. sb.Append(s + Environment.NewLine);
  73. }
  74. if (sb != null && sb.Length > 0)
  75. perfLogger.LogTrace(sb.ToString());
  76. }
  77. finally
  78. {
  79. this.perfPeriodToLogFileTimer.Start();
  80. }
  81. };
  82. this.perfPeriodToLogFileTimer.Start();
  83. }
  84. this.Communicator = communicator;
  85. var incoming = new HistoryKeepIncoming<TMessage>(10);
  86. this.Context = new Context<TRaw, TMessage>(this, handler, communicator, incoming, new Outgoing<TRaw, TMessage>(incoming, services));
  87. this.Context.Outgoing.OnWriting += (s, a) =>
  88. {
  89. if (a.ExtraControlParameter != null)
  90. this.Communicator.Write(a.Message, a.ExtraControlParameter);
  91. else
  92. this.Communicator.Write(a.Message);
  93. };
  94. this.Communicator.OnConnected += (communicator, a) =>
  95. {
  96. if(communicator is IClinet)
  97. {
  98. IClinet clinet = (IClinet)communicator;
  99. handler.SetTcpClient(clinet?.GetTcpClient());
  100. handler.SendQRCodeAsync();
  101. }
  102. };
  103. this.Communicator.OnDataReceived += (s, a) =>
  104. {
  105. lock (this.syncObject)
  106. {
  107. if (perfLogger.IsEnabled(LogLevel.Trace))
  108. {
  109. this.perfWatch_From_CommOnDataReceived_To_HandlerProcessed?.Restart();
  110. this.perfWatch_From_CommOnDataReceived_To_CommOnDataWriting?.Restart();
  111. }
  112. this.Context.Incoming.DisablePropagate = false;
  113. this.Context.Incoming.Message = a.Message;
  114. if (!this.Context.Incoming.DisablePropagate)
  115. handler.Process(this.Context);
  116. if (perfLogger.IsEnabled(LogLevel.Trace))
  117. this.perfPeriodLogStrings?.Enqueue(DateTime.Now.ToString("HH:mm:ss.fff") + " - "
  118. + " From_CommOnDataReceived_To_HandlerProcessed elapsed " + (this.perfWatch_From_CommOnDataReceived_To_HandlerProcessed?.ElapsedMilliseconds ?? -1));
  119. }
  120. };
  121. this.Communicator.OnRawDataWriting += (s, a) =>
  122. {
  123. if (perfLogger.IsEnabled(LogLevel.Trace))
  124. {
  125. this.perfPeriodLogStrings?.Enqueue(DateTime.Now.ToString("HH:mm:ss.fff") + " - "
  126. + " From_CommOnDataReceived_To_CommOnDataWriting elapsed " + (this.perfWatch_From_CommOnDataReceived_To_CommOnDataWriting?.ElapsedMilliseconds ?? -1));
  127. }
  128. };
  129. }
  130. //public void Dispose()
  131. //{
  132. // this.Communicator.Dispose();
  133. //}
  134. public async Task<bool> Start()
  135. {
  136. this.Context.Handler.Init(this.Context);
  137. var r = await this.Communicator.Start();
  138. return r;
  139. }
  140. public Task<bool> Stop()
  141. {
  142. this.perfPeriodToLogFileTimer?.Stop();
  143. this.Communicator.Dispose();
  144. this.Context.Dispose();
  145. if (this.Context.Handler is IDisposable dp)
  146. dp.Dispose();
  147. return Task.FromResult(true);
  148. }
  149. public Task Test(params object[] parameters)
  150. {
  151. return this.Context.Handler.Test(parameters);
  152. }
  153. }
  154. /// <summary>
  155. /// used for scenario of FC as master to actively polling devices.
  156. /// </summary>
  157. /// <typeparam name="TRaw"></typeparam>
  158. /// <typeparam name="TMessage"></typeparam>
  159. [MetaPartsDescriptor(
  160. "lang-zh-cn:能自动发送消息的设备处理器lang-en-us:AutoPollingDeviceProcessor",
  161. "lang-zh-cn:自动发送消息型处理器lang-en-us:Auto send polling message processor for comm with devices")]
  162. public class HalfDuplexActivePollingDeviceProcessor<TRaw, TMessage> : GenericDeviceProcessor<TRaw, TMessage> where TMessage : MessageBase
  163. {
  164. [ParamsJsonSchemas("HalfDuplexActivePollingDeviceProcessorCtorSchema")]
  165. public HalfDuplexActivePollingDeviceProcessor(IDeviceHandler<TRaw, TMessage> handler, ICommunicator<TRaw, TMessage> communicator, int autoPollingInterval, IServiceProvider services)
  166. : base(handler, communicator, services)
  167. {
  168. base.Context = new Context<TRaw, TMessage>(this, handler, communicator, base.Context.Incoming,
  169. new TimeWindowWithActivePollingOutgoing<TRaw, TMessage>(base.Context.Incoming, autoPollingInterval, services));
  170. this.Context.Outgoing.OnWriting += (s, a) =>
  171. {
  172. if (a.ExtraControlParameter != null)
  173. this.Communicator.Write(a.Message, a.ExtraControlParameter);
  174. else
  175. this.Communicator.Write(a.Message);
  176. };
  177. }
  178. }
  179. /// <summary>
  180. /// used for scenario of FC as slave to receive polling from devices.
  181. /// </summary>
  182. /// <typeparam name="TRaw"></typeparam>
  183. /// <typeparam name="TMessage"></typeparam>
  184. public class HalfDuplexNegativePollingDeviceProcessor<TRaw, TMessage> : GenericDeviceProcessor<TRaw, TMessage> where TMessage : MessageBase
  185. {
  186. public HalfDuplexNegativePollingDeviceProcessor(IDeviceHandler<TRaw, TMessage> handler, ICommunicator<TRaw, TMessage> communicator, IServiceProvider services)
  187. : base(handler, communicator, services)
  188. {
  189. base.Context = new Context<TRaw, TMessage>(this, handler, communicator, base.Context.Incoming,
  190. new TimeWindowWithNegativePollingOutgoing<TRaw, TMessage>(base.Context.Incoming, services));
  191. this.Context.Outgoing.OnWriting += (s, a) =>
  192. {
  193. if (a.ExtraControlParameter != null)
  194. this.Communicator.Write(a.Message, a.ExtraControlParameter);
  195. else
  196. this.Communicator.Write(a.Message);
  197. };
  198. }
  199. }
  200. }