ServerMessageJob.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. using EVCB_OCPP.Domain;
  2. using EVCB_OCPP.Domain.Models.MainDb;
  3. using EVCB_OCPP.Packet.Features;
  4. using EVCB_OCPP.Packet.Messages;
  5. using EVCB_OCPP.WSServer.Message;
  6. using EVCB_OCPP.WSServer.Service;
  7. using EVCB_OCPP.WSServer.Service.WsService;
  8. using Microsoft.EntityFrameworkCore;
  9. using Microsoft.Extensions.Configuration;
  10. using Microsoft.Extensions.Logging;
  11. using Newtonsoft.Json;
  12. using Quartz;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.Diagnostics;
  16. using System.Linq;
  17. using System.Text;
  18. using System.Threading.Tasks;
  19. namespace EVCB_OCPP.WSServer.Jobs;
  20. [DisallowConcurrentExecution]
  21. public class ServerMessageJob : IJob
  22. {
  23. public ServerMessageJob(
  24. ProtalServer protalServer,
  25. ConfirmWaitingMessageSerevice confirmWaitingMessageSerevice,
  26. VendorIdReplaceService vendorIdReplaceService,
  27. IConfiguration configuration,
  28. IDbContextFactory<MainDBContext> maindbContextFactory,
  29. ILogger<ServerMessageJob> logger)
  30. {
  31. this.protalServer = protalServer;
  32. this.confirmWaitingMessageSerevice = confirmWaitingMessageSerevice;
  33. this.vendorIdReplaceService = vendorIdReplaceService;
  34. this.maindbContextFactory = maindbContextFactory;
  35. this.logger = logger;
  36. }
  37. private readonly ProtalServer protalServer;
  38. private readonly ConfirmWaitingMessageSerevice confirmWaitingMessageSerevice;
  39. private readonly VendorIdReplaceService vendorIdReplaceService;
  40. private readonly IDbContextFactory<MainDBContext> maindbContextFactory;
  41. private readonly ILogger<ServerMessageJob> logger;
  42. public async Task Execute(IJobExecutionContext context)
  43. {
  44. //logger.LogDebug("{0} Started", nameof(ServerMessageJob));
  45. try
  46. {
  47. await ExecuteTrigger();
  48. }
  49. catch (Exception ex)
  50. {
  51. logger.LogError("ServerMessageTrigger Ex:{0}", ex.ToString());
  52. }
  53. }
  54. private Task ExecuteTrigger()
  55. {
  56. var clientDic = protalServer.GetClientDic();
  57. confirmWaitingMessageSerevice.RemoveExpiredConfirmMessage();
  58. ResendServerMessage(clientDic);
  59. return SendNewServerMessage(clientDic);
  60. }
  61. private async Task SendNewServerMessage(Dictionary<string, WsClientData> clientDic)
  62. {
  63. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  64. DateTime dateTimeNow = DateTime.UtcNow;
  65. DateTime startDt = dateTimeNow.AddSeconds(-30);
  66. DateTime dt = new DateTime(1991, 1, 1);
  67. DateTime currentTime = dateTimeNow;
  68. List<ServerMessage> commandList;
  69. using (var db = await maindbContextFactory.CreateDbContextAsync())
  70. {
  71. commandList = await db.ServerMessage.Where(c => c.ReceivedOn == dt && c.UpdatedOn == dt && c.CreatedOn >= startDt && c.CreatedOn <= currentTime).AsNoTracking().ToListAsync();
  72. }
  73. //處理主機傳送的有指令
  74. var cmdMachineList = commandList.Select(c => c.ChargeBoxId).Distinct().ToList();
  75. if (commandList.Count > 0)
  76. {
  77. // Console.WriteLine(string.Format("Now:{0} commandList Count:{1} ", DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"), commandList.Count));
  78. }
  79. foreach (var charger_SN in cmdMachineList)
  80. {
  81. WsClientData session;
  82. string uuid = string.Empty;
  83. if (!clientDic.TryGetValue(charger_SN, out session))
  84. {
  85. continue;
  86. }
  87. //logger.LogDebug(string.Format("charger_SN:{0} startDt:{1} CreatedOn:{2}", charger_SN, startDt.ToString("yyyy/MM/dd HH:mm:ss"), DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss")));
  88. //if (session.IsCheckIn && !session.ISOCPP20)
  89. if (session.ISOCPP20)
  90. {
  91. continue;
  92. }
  93. string rawRequest = string.Empty;
  94. var cmdList = commandList.Where(c => c.ChargeBoxId == charger_SN).ToList();
  95. var profiles = protalServer.Profiles;
  96. foreach (var item in cmdList)
  97. {
  98. IRequest request = null;
  99. Actions action = Actions.None;
  100. Enum.TryParse(item.OutAction, out action);
  101. Type _RequestType = null;
  102. for (int i = 0; i < profiles.Count; i++)
  103. {
  104. var feature = profiles[i].GetFeaturebyAction(item.OutAction);
  105. if (feature != null)
  106. {
  107. _RequestType = feature.GetRequestType();
  108. break;
  109. }
  110. }
  111. if (_RequestType != null && item.CreatedBy != "Destroyer")
  112. {
  113. request = JsonConvert.DeserializeObject(item.OutRequest, _RequestType) as IRequest;
  114. uuid = session.queue.store(request);
  115. rawRequest = BasicMessageHandler.GenerateRequest(uuid, item.OutAction, request);
  116. protalServer.SendMsg(session, rawRequest, string.Format("{0} {1}", action, "Request"), "");
  117. }
  118. if (item.CreatedBy == "Destroyer")
  119. {
  120. if (_RequestType != null)
  121. {
  122. request = Activator.CreateInstance(_RequestType) as IRequest;
  123. uuid = session.queue.store(request);
  124. rawRequest = BasicMessageHandler.GenerateDestroyRequest(uuid, item.OutAction, item.OutRequest);
  125. protalServer.SendMsg(session, rawRequest, string.Format("{0} {1}", action, "Request"), "");
  126. }
  127. else
  128. {
  129. rawRequest = BasicMessageHandler.GenerateDestroyRequest(Guid.NewGuid().ToString(), item.OutAction, item.OutRequest);
  130. protalServer.SendMsg(session, rawRequest, string.Format("{0} {1}", action, "Request"), "");
  131. }
  132. }
  133. await confirmWaitingMessageSerevice.Add(charger_SN, item.Id, item.SerialNo, item.OutAction, uuid, item.CreatedBy, rawRequest);
  134. //protalServer.AddConfirmMessage(charger_SN, item.Id, item.SerialNo, item.OutAction, uuid, item.CreatedBy, rawRequest);
  135. await Task.Delay(100);
  136. }
  137. }
  138. }
  139. private void ResendServerMessage(Dictionary<string, WsClientData> clientDic)
  140. {
  141. DateTime dateTimeNow = DateTime.UtcNow;
  142. List<NeedConfirmMessage> resendList = confirmWaitingMessageSerevice.GetPendingMessages();
  143. foreach (var resendItem in resendList)
  144. {
  145. WsClientData session;
  146. if (clientDic.TryGetValue(resendItem.ChargePointSerialNumber, out session))
  147. {
  148. if (dateTimeNow.Subtract(resendItem.SentOn).TotalSeconds > 1)
  149. {
  150. confirmWaitingMessageSerevice.SignalMessageSended(resendItem);
  151. protalServer.SendMsg(session, resendItem.SentMessage, string.Format("{0} {1}", resendItem.SentAction, "Request"), "");
  152. }
  153. }
  154. }
  155. }
  156. }