OuterBusinessService.cs 10 KB

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