OuterBusinessService.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. await Task.Delay(10);
  78. IdTokenInfo result = new IdTokenInfo() { IdTagInfo = new IdTagInfo() { status = AuthorizationStatus.Invalid } };
  79. try
  80. {
  81. string requestParams = string.Format("charging_auth?ChargeBoxId={0}&IdTag={1}", chargeBoxId, idTag);
  82. // if (CustomerId.ToLower() == "9e6bfdcc-09fb-4dab-a428-43fe507600a3")
  83. {
  84. logger.LogInformation(chargeBoxId + " Charging Monitor======================================>");
  85. logger.LogInformation(signMaterial.APIUrl + requestParams);
  86. }
  87. var response = await httpClient.Post(signMaterial.APIUrl + requestParams, new Dictionary<string, string>()
  88. {
  89. { "PartnerId",signMaterial.Id}
  90. }, null, signMaterial.SaltKey).ConfigureAwait(false);
  91. // if (CustomerId.ToLower() == "9e6bfdcc-09fb-4dab-a428-43fe507600a3")
  92. {
  93. logger.LogInformation(JsonConvert.SerializeObject(response));
  94. }
  95. if (response.Success)
  96. {
  97. Console.WriteLine(response.Response);
  98. var _httpResult = JsonConvert.DeserializeObject<CPOOuterResponse>(response.Response);
  99. JObject jo = JObject.Parse(_httpResult.Data);
  100. if (jo.ContainsKey("ExpiryDate"))
  101. {
  102. DateTime dt = jo["ExpiryDate"].Value<DateTime>();
  103. result.IdTagInfo.expiryDate = dt;
  104. }
  105. if (jo.ContainsKey("ParentIdTag"))
  106. {
  107. string _Message = jo["ParentIdTag"].Value<string>();
  108. result.IdTagInfo.parentIdTag = _Message;
  109. }
  110. if (jo.ContainsKey("ChargePointFee"))
  111. {
  112. for(int i=0;i< jo["ChargePointFee"].Count();i++)
  113. {
  114. if(i==0)
  115. {
  116. result.ChargePointFee = new List<ChargePointFee>();
  117. }
  118. result.ChargePointFee.Add(jo["ChargePointFee"][i].ToObject<ChargePointFee>());
  119. }
  120. }
  121. if (jo.ContainsKey("ChargepointFee"))
  122. {
  123. for (int i = 0; i < jo["ChargepointFee"].Count(); i++)
  124. {
  125. if (i == 0)
  126. {
  127. result.ChargePointFee = new List<ChargePointFee>();
  128. }
  129. result.ChargePointFee.Add(jo["ChargepointFee"][i].ToObject<ChargePointFee>());
  130. }
  131. }
  132. if (jo.ContainsKey("AccountBalance"))
  133. {
  134. decimal accountBalance = jo["AccountBalance"].Value<decimal>();
  135. result.AccountBalance = accountBalance;
  136. }
  137. if (jo.ContainsKey("Status"))
  138. {
  139. string _Message = jo["Status"].Value<string>();
  140. result.IdTagInfo.status = (AuthorizationStatus)Enum.Parse(typeof(AuthorizationStatus), _Message);
  141. }
  142. }
  143. else
  144. {
  145. logger.LogError(chargeBoxId + " OuterBusinessService.Authorize Fail: " + response.Response);
  146. }
  147. }
  148. catch (Exception ex)
  149. {
  150. result.IdTagInfo.status = AuthorizationStatus.Invalid;
  151. logger.LogError(chargeBoxId + " OuterBusinessService.Authorize Ex: " + ex.ToString());
  152. }
  153. return result;
  154. }
  155. async public Task NotifyFaultStatus(ErrorDetails details)
  156. {
  157. try
  158. {
  159. if (signMaterial.CallsThirdParty)
  160. {
  161. var response = await httpClient.Post(signMaterial.APIUrl + "connectorfault", new Dictionary<string, string>()
  162. {
  163. { "PartnerId",signMaterial.Id}
  164. }, details, signMaterial.SaltKey).ConfigureAwait(false);
  165. }
  166. }
  167. catch (Exception ex)
  168. {
  169. logger.LogError(details.ChargeBoxId + " OuterBusinessService.NotifyFaultStatus Ex: " + ex.ToString());
  170. }
  171. }
  172. async public Task NotifyConnectorUnplugged(string chargeBoxId, string data)
  173. {
  174. try
  175. {
  176. JObject jo = JObject.Parse(data);
  177. var details = new { ChargeBoxId = chargeBoxId, SessionId = jo["idTx"].Value<Int32>(), Timestamp = jo["timestamp"].Value<DateTime>() };
  178. if (signMaterial.CallsThirdParty)
  179. {
  180. var response = await httpClient.Post(signMaterial.APIUrl + "connectorunplugged", new Dictionary<string, string>()
  181. {
  182. { "PartnerId",signMaterial.Id}
  183. }, details, signMaterial.SaltKey).ConfigureAwait(false);
  184. }
  185. }
  186. catch (Exception ex)
  187. {
  188. logger.LogError(chargeBoxId + " OuterBusinessService.NotifyConnectorUnplugged Ex: " + ex.ToString());
  189. }
  190. }
  191. private async Task<CustomerSignMaterial> GetSign(string customerId)
  192. {
  193. Guid Id = new Guid(customerId);
  194. CustomerSignMaterial _customer = new CustomerSignMaterial();
  195. //using (var db = new MainDBContext())
  196. //using (var db = maindbContextFactory.CreateDbContextAsync())
  197. //{
  198. // _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();
  199. //}
  200. var _customerDb = await mainDbService.GetCustomer(Id);
  201. if (_customerDb is not null)
  202. {
  203. _customer.Id = _customerDb.Id.ToString();
  204. _customer.APIUrl = _customerDb.ApiUrl;
  205. _customer.SaltKey = _customerDb.ApiKey;
  206. _customer.CallsThirdParty = _customerDb.CallPartnerApiOnSchedule;
  207. }
  208. return _customer;
  209. }
  210. public Task NotifyConnectorUnplugged(string data)
  211. {
  212. throw new NotImplementedException();
  213. }
  214. }
  215. }