OuterBusinessService.cs 11 KB

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