GenericDeviceProcessor.cs 11 KB

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