OuterBusinessService.cs 11 KB

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