OuterBusinessService.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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.Configuration;
  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.Net;
  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 IConfiguration configuration;
  41. private readonly ILogger<OuterBusinessService> logger;
  42. private readonly IDbContextFactory<MainDBContext> maindbContextFactory;
  43. private readonly IMainDbService mainDbService;
  44. private readonly HttpClientService service;
  45. private readonly OuterHttpClient httpClient;
  46. private string _CustomerId = string.Empty;
  47. private CustomerSignMaterial signMaterial = null;
  48. public string CustomerId
  49. {
  50. get => _CustomerId;
  51. set
  52. {
  53. _CustomerId = value;
  54. signMaterial = GetSign(_CustomerId).Result;
  55. }
  56. }
  57. internal CustomerSignMaterial CustomerSignMaterial
  58. {
  59. get => signMaterial;
  60. set
  61. {
  62. signMaterial = value;
  63. _CustomerId = signMaterial.Id;
  64. }
  65. }
  66. public OuterBusinessService(
  67. IConfiguration configuration,
  68. ILogger<OuterBusinessService> logger,
  69. IDbContextFactory<MainDBContext> maindbContextFactory,
  70. IMainDbService mainDbService,
  71. HttpClientService service,
  72. OuterHttpClient httpClient)
  73. {
  74. this.configuration = configuration;
  75. this.logger = logger;
  76. this.maindbContextFactory = maindbContextFactory;
  77. this.mainDbService = mainDbService;
  78. this.service = service;
  79. this.httpClient = httpClient;
  80. }
  81. async public Task<IdTokenInfo> Authorize(string chargeBoxId, string idTag, int? connectorId = null)
  82. {
  83. await Task.Delay(10);
  84. IdTokenInfo info = new IdTokenInfo() { IdTagInfo = new IdTagInfo() { status = AuthorizationStatus.Invalid } };
  85. try
  86. {
  87. if (CustomerId.ToUpper() == "009E603C-79CD-4620-A2B8-D9349C0E8AD8")
  88. {
  89. info.IdTagInfo = new IdTagInfo() { status = AuthorizationStatus.Accepted };
  90. return info;
  91. }
  92. //OuterHttpClient _client = new OuterHttpClient();
  93. string url = configuration["LocalAuthAPI"];
  94. //HttpClientService service = new HttpClientService();
  95. Dictionary<string, string> postData = new Dictionary<string, string>()
  96. {
  97. { "ChargeBoxId", chargeBoxId },
  98. { "IdTag", idTag },
  99. };
  100. var _innerresult = await service.PostFormDataAsync(url, postData, null);
  101. if (_innerresult.StatusCode == HttpStatusCode.OK)
  102. {
  103. JObject jo = JObject.Parse(_innerresult.Response);
  104. if (jo["code"].ToString() == "1")
  105. {
  106. try
  107. {
  108. info.IdTagInfo.status = (AuthorizationStatus)Enum.Parse(typeof(AuthorizationStatus), jo["message"].ToString());
  109. }
  110. catch (Exception)
  111. {
  112. ;
  113. }
  114. }
  115. }
  116. }
  117. catch (Exception ex)
  118. {
  119. ;
  120. }
  121. return info;
  122. }
  123. async public Task<IdTokenInfo> Authorize_outer(string chargeBoxId, string idTag, int? connectorId = null)
  124. {
  125. //return new IdTokenInfo() { IdTagInfo = new IdTagInfo()
  126. //{
  127. // expiryDate = DateTime.UtcNow.AddDays(1),
  128. // status = AuthorizationStatus.Accepted
  129. //} };
  130. //await Task.Delay(10);
  131. IdTokenInfo result = new IdTokenInfo() { IdTagInfo = new IdTagInfo() { status = AuthorizationStatus.Invalid } };
  132. try
  133. {
  134. logger.LogInformation(chargeBoxId + " Charging Monitor======================================>");
  135. string requestParams = idTag.StartsWith("vid:") ? await GetRequestParamsAsPnC(chargeBoxId, idTag, connectorId) : GetRequestParamsAsNormal(chargeBoxId, idTag);
  136. HttpResult response = await httpClient.Post(signMaterial.APIUrl + requestParams, new Dictionary<string, string>()
  137. {
  138. { "PartnerId",signMaterial.Id}
  139. }, requestBody: null, saltkey: signMaterial.SaltKey).ConfigureAwait(false);
  140. logger.LogInformation($"{chargeBoxId} response : {JsonConvert.SerializeObject(response)}");
  141. if (response.Success)
  142. {
  143. //Console.WriteLine(response.Response);
  144. var _httpResult = JsonConvert.DeserializeObject<CPOOuterResponse>(response.Response);
  145. JObject jo = JObject.Parse(_httpResult.Data);
  146. if (jo.ContainsKey("ExpiryDate"))
  147. {
  148. DateTime dt = jo["ExpiryDate"].Value<DateTime>();
  149. result.IdTagInfo.expiryDate = dt;
  150. }
  151. if (jo.ContainsKey("ParentIdTag"))
  152. {
  153. string _Message = jo["ParentIdTag"].Value<string>();
  154. result.IdTagInfo.parentIdTag = _Message;
  155. }
  156. if (jo.ContainsKey("ChargePointFee"))
  157. {
  158. for(int i=0;i< jo["ChargePointFee"].Count();i++)
  159. {
  160. if(i==0)
  161. {
  162. result.ChargePointFee = new List<ChargePointFee>();
  163. }
  164. result.ChargePointFee.Add(jo["ChargePointFee"][i].ToObject<ChargePointFee>());
  165. }
  166. }
  167. if (jo.ContainsKey("ChargepointFee"))
  168. {
  169. for (int i = 0; i < jo["ChargepointFee"].Count(); i++)
  170. {
  171. if (i == 0)
  172. {
  173. result.ChargePointFee = new List<ChargePointFee>();
  174. }
  175. result.ChargePointFee.Add(jo["ChargepointFee"][i].ToObject<ChargePointFee>());
  176. }
  177. }
  178. if (jo.ContainsKey("AccountBalance"))
  179. {
  180. decimal accountBalance = jo["AccountBalance"].Value<decimal>();
  181. result.AccountBalance = accountBalance;
  182. }
  183. if (jo.ContainsKey("Status"))
  184. {
  185. string _Message = jo["Status"].Value<string>();
  186. result.IdTagInfo.status = (AuthorizationStatus)Enum.Parse(typeof(AuthorizationStatus), _Message);
  187. }
  188. }
  189. else
  190. {
  191. logger.LogError(chargeBoxId + " OuterBusinessService.Authorize Fail: " + response.Response);
  192. }
  193. }
  194. catch (Exception ex)
  195. {
  196. result.IdTagInfo.status = AuthorizationStatus.Invalid;
  197. logger.LogError(chargeBoxId + " OuterBusinessService.Authorize Ex: " + ex.ToString());
  198. }
  199. return result;
  200. }
  201. async public Task NotifyFaultStatus(ErrorDetails details)
  202. {
  203. try
  204. {
  205. if (signMaterial.CallsThirdParty)
  206. {
  207. var response = await httpClient.Post(signMaterial.APIUrl + "connectorfault", new Dictionary<string, string>()
  208. {
  209. { "PartnerId",signMaterial.Id}
  210. }, details, signMaterial.SaltKey).ConfigureAwait(false);
  211. }
  212. }
  213. catch (Exception ex)
  214. {
  215. logger.LogError(details.ChargeBoxId + " OuterBusinessService.NotifyFaultStatus Ex: " + ex.ToString());
  216. }
  217. }
  218. async public Task NotifyConnectorUnplugged(string chargeBoxId, string data)
  219. {
  220. try
  221. {
  222. JObject jo = JObject.Parse(data);
  223. var details = new { ChargeBoxId = chargeBoxId, SessionId = jo["idTx"].Value<Int32>(), Timestamp = jo["timestamp"].Value<DateTime>() };
  224. if (signMaterial.CallsThirdParty)
  225. {
  226. var response = await httpClient.Post(signMaterial.APIUrl + "connectorunplugged", new Dictionary<string, string>()
  227. {
  228. { "PartnerId",signMaterial.Id}
  229. }, details, signMaterial.SaltKey).ConfigureAwait(false);
  230. }
  231. }
  232. catch (Exception ex)
  233. {
  234. logger.LogError(chargeBoxId + " OuterBusinessService.NotifyConnectorUnplugged Ex: " + ex.ToString());
  235. }
  236. }
  237. private async Task<CustomerSignMaterial> GetSign(string customerId)
  238. {
  239. Guid Id = new Guid(customerId);
  240. CustomerSignMaterial _customer = new CustomerSignMaterial();
  241. //using (var db = new MainDBContext())
  242. //using (var db = maindbContextFactory.CreateDbContextAsync())
  243. //{
  244. // _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();
  245. //}
  246. var _customerDb = await mainDbService.GetCustomer(Id);
  247. if (_customerDb is not null)
  248. {
  249. _customer.Id = _customerDb.Id.ToString();
  250. _customer.APIUrl = _customerDb.ApiUrl;
  251. _customer.SaltKey = _customerDb.ApiKey;
  252. _customer.CallsThirdParty = _customerDb.CallPartnerApiOnSchedule;
  253. }
  254. return _customer;
  255. }
  256. private async ValueTask<string> GetRequestParamsAsPnC(string chargeBoxId, string idTag, int? connectorId)
  257. {
  258. idTag = idTag.Replace("vid:", "");
  259. if (connectorId is null)
  260. {
  261. using (var db = await maindbContextFactory.CreateDbContextAsync())
  262. {
  263. var connectorStatuses = await db.ConnectorStatuses.Where(x => x.ChargeBoxId == chargeBoxId).
  264. Select(x => new { x.ConnectorId, x.Status, x.CreatedOn }).ToListAsync();
  265. var connectorStatus = connectorStatuses.Where(x => x.Status == 2).OrderByDescending(x => x.CreatedOn).FirstOrDefault();
  266. if (connectorStatus != null)
  267. {
  268. connectorId = connectorStatus.ConnectorId;
  269. }
  270. }
  271. }
  272. return string.Format("charging_auth?ChargeBoxId={0}&ConnectorId={1}&IdTag={2}", chargeBoxId, connectorId, idTag);
  273. }
  274. private string GetRequestParamsAsNormal(string chargeBoxId, string idTag)
  275. {
  276. return string.Format("charging_auth?ChargeBoxId={0}&IdTag={1}", chargeBoxId, idTag);
  277. }
  278. public Task NotifyConnectorUnplugged(string data)
  279. {
  280. throw new NotImplementedException();
  281. }
  282. }
  283. }