OuterBusinessService.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. using EVCB_OCPP.Domain;
  2. using EVCB_OCPP.Domain.Models.Database;
  3. using EVCB_OCPP.Packet.Messages.SubTypes;
  4. using EVCB_OCPP.WSServer.Dto;
  5. using Microsoft.EntityFrameworkCore;
  6. using Microsoft.Extensions.Logging;
  7. using Newtonsoft.Json;
  8. using Newtonsoft.Json.Linq;
  9. using NLog;
  10. using SuperSocket.SocketBase;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.Linq;
  14. using System.Threading.Tasks;
  15. namespace EVCB_OCPP.WSServer.Service
  16. {
  17. internal class CPOOuterResponse
  18. {
  19. public CPOOuterResponse()
  20. {
  21. StatusCode = 0;
  22. }
  23. public int StatusCode { set; get; }
  24. public string StatusMessage { set; get; }
  25. public string Data { set; get; }
  26. [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
  27. public string SerialNo { set; get; }
  28. [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
  29. public string ErrorDetail { set; get; }
  30. }
  31. internal class CustomerSignMaterial
  32. {
  33. internal bool CallsThirdParty { set; get; }
  34. internal string Id { set; get; }
  35. internal string APIUrl { set; get; }
  36. internal string SaltKey { set; get; }
  37. }
  38. public class OuterBusinessService : IBusinessService
  39. {
  40. private readonly ILogger<OuterBusinessService> logger;
  41. private readonly IDbContextFactory<MainDBContext> maindbContextFactory;
  42. private readonly IMainDbService mainDbService;
  43. private readonly OuterHttpClient httpClient;
  44. private string _CustomerId = string.Empty;
  45. private CustomerSignMaterial signMaterial = null;
  46. public string CustomerId
  47. {
  48. get => _CustomerId;
  49. set
  50. {
  51. _CustomerId = value;
  52. signMaterial = GetSign(_CustomerId).Result;
  53. }
  54. }
  55. internal CustomerSignMaterial CustomerSignMaterial
  56. {
  57. get => signMaterial;
  58. set
  59. {
  60. signMaterial = value;
  61. _CustomerId = signMaterial.Id;
  62. }
  63. }
  64. public OuterBusinessService(
  65. ILogger<OuterBusinessService> logger,
  66. IDbContextFactory<MainDBContext> maindbContextFactory,
  67. IMainDbService mainDbService,
  68. OuterHttpClient httpClient)
  69. {
  70. this.logger = logger;
  71. this.maindbContextFactory = maindbContextFactory;
  72. this.mainDbService = mainDbService;
  73. this.httpClient = httpClient;
  74. }
  75. async public Task<IdTokenInfo> Authorize(string chargeBoxId, string idTag)
  76. {
  77. //return new IdTokenInfo() { IdTagInfo = new IdTagInfo()
  78. //{
  79. // expiryDate = DateTime.UtcNow.AddDays(1),
  80. // status = AuthorizationStatus.Accepted
  81. //} };
  82. //await Task.Delay(10);
  83. IdTokenInfo result = new IdTokenInfo() { IdTagInfo = new IdTagInfo() { status = AuthorizationStatus.Invalid } };
  84. try
  85. {
  86. string requestParams = string.Format("charging_auth?ChargeBoxId={0}&IdTag={1}", chargeBoxId, idTag);
  87. // if (CustomerId.ToLower() == "9e6bfdcc-09fb-4dab-a428-43fe507600a3")
  88. {
  89. logger.LogInformation(chargeBoxId + " Charging Monitor======================================>");
  90. logger.LogInformation(signMaterial.APIUrl + requestParams);
  91. }
  92. var response = await httpClient.Post(signMaterial.APIUrl + requestParams, new Dictionary<string, string>()
  93. {
  94. { "PartnerId",signMaterial.Id}
  95. }, null, signMaterial.SaltKey).ConfigureAwait(false);
  96. // if (CustomerId.ToLower() == "9e6bfdcc-09fb-4dab-a428-43fe507600a3")
  97. {
  98. logger.LogInformation($"{chargeBoxId} response : {JsonConvert.SerializeObject(response)}" );
  99. }
  100. if (response.Success)
  101. {
  102. //Console.WriteLine(response.Response);
  103. var _httpResult = JsonConvert.DeserializeObject<CPOOuterResponse>(response.Response);
  104. JObject jo = JObject.Parse(_httpResult.Data);
  105. if (jo.ContainsKey("ExpiryDate"))
  106. {
  107. DateTime dt = jo["ExpiryDate"].Value<DateTime>();
  108. result.IdTagInfo.expiryDate = dt;
  109. }
  110. if (jo.ContainsKey("ParentIdTag"))
  111. {
  112. string _Message = jo["ParentIdTag"].Value<string>();
  113. result.IdTagInfo.parentIdTag = _Message;
  114. }
  115. if (jo.ContainsKey("ChargePointFee"))
  116. {
  117. for(int i=0;i< jo["ChargePointFee"].Count();i++)
  118. {
  119. if(i==0)
  120. {
  121. result.ChargePointFee = new List<ChargePointFee>();
  122. }
  123. result.ChargePointFee.Add(jo["ChargePointFee"][i].ToObject<ChargePointFee>());
  124. }
  125. }
  126. if (jo.ContainsKey("ChargepointFee"))
  127. {
  128. for (int i = 0; i < jo["ChargepointFee"].Count(); i++)
  129. {
  130. if (i == 0)
  131. {
  132. result.ChargePointFee = new List<ChargePointFee>();
  133. }
  134. result.ChargePointFee.Add(jo["ChargepointFee"][i].ToObject<ChargePointFee>());
  135. }
  136. }
  137. if (jo.ContainsKey("AccountBalance"))
  138. {
  139. decimal accountBalance = jo["AccountBalance"].Value<decimal>();
  140. result.AccountBalance = accountBalance;
  141. }
  142. if (jo.ContainsKey("Status"))
  143. {
  144. string _Message = jo["Status"].Value<string>();
  145. result.IdTagInfo.status = (AuthorizationStatus)Enum.Parse(typeof(AuthorizationStatus), _Message);
  146. }
  147. }
  148. else
  149. {
  150. logger.LogError(chargeBoxId + " OuterBusinessService.Authorize Fail: " + response.Response);
  151. }
  152. }
  153. catch (Exception ex)
  154. {
  155. result.IdTagInfo.status = AuthorizationStatus.Invalid;
  156. logger.LogError(chargeBoxId + " OuterBusinessService.Authorize Ex: " + ex.ToString());
  157. }
  158. return result;
  159. }
  160. async public Task NotifyFaultStatus(ErrorDetails details)
  161. {
  162. try
  163. {
  164. if (signMaterial.CallsThirdParty)
  165. {
  166. var response = await httpClient.Post(signMaterial.APIUrl + "connectorfault", new Dictionary<string, string>()
  167. {
  168. { "PartnerId",signMaterial.Id}
  169. }, details, signMaterial.SaltKey).ConfigureAwait(false);
  170. }
  171. }
  172. catch (Exception ex)
  173. {
  174. logger.LogError(details.ChargeBoxId + " OuterBusinessService.NotifyFaultStatus Ex: " + ex.ToString());
  175. }
  176. }
  177. async public Task NotifyConnectorUnplugged(string chargeBoxId, string data)
  178. {
  179. try
  180. {
  181. JObject jo = JObject.Parse(data);
  182. var details = new { ChargeBoxId = chargeBoxId, SessionId = jo["idTx"].Value<Int32>(), Timestamp = jo["timestamp"].Value<DateTime>() };
  183. if (signMaterial.CallsThirdParty)
  184. {
  185. var response = await httpClient.Post(signMaterial.APIUrl + "connectorunplugged", new Dictionary<string, string>()
  186. {
  187. { "PartnerId",signMaterial.Id}
  188. }, details, signMaterial.SaltKey).ConfigureAwait(false);
  189. }
  190. }
  191. catch (Exception ex)
  192. {
  193. logger.LogError(chargeBoxId + " OuterBusinessService.NotifyConnectorUnplugged Ex: " + ex.ToString());
  194. }
  195. }
  196. private async Task<CustomerSignMaterial> GetSign(string customerId)
  197. {
  198. Guid Id = new Guid(customerId);
  199. CustomerSignMaterial _customer = new CustomerSignMaterial();
  200. //using (var db = new MainDBContext())
  201. //using (var db = maindbContextFactory.CreateDbContextAsync())
  202. //{
  203. // _customer = await db.Customer.Where(x => x.Id == Id).Select(x => new CustomerSignMaterial() { Id = x.Id.ToString(), APIUrl = x.ApiUrl, SaltKey = x.ApiKey, CallsThirdParty = x.CallPartnerApiOnSchedule }).FirstOrDefaultAsync();
  204. //}
  205. var _customerDb = await mainDbService.GetCustomer(Id);
  206. if (_customerDb is not null)
  207. {
  208. _customer.Id = _customerDb.Id.ToString();
  209. _customer.APIUrl = _customerDb.ApiUrl;
  210. _customer.SaltKey = _customerDb.ApiKey;
  211. _customer.CallsThirdParty = _customerDb.CallPartnerApiOnSchedule;
  212. }
  213. return _customer;
  214. }
  215. public Task NotifyConnectorUnplugged(string data)
  216. {
  217. throw new NotImplementedException();
  218. }
  219. }
  220. }