OuterBusinessService.cs 9.0 KB

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