OuterBusinessService.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. using EVCB_OCPP.Domain;
  2. using EVCB_OCPP.Domain.Models.MainDb;
  3. using EVCB_OCPP.Packet.Messages.SubTypes;
  4. using EVCB_OCPP.WSServer.Dto;
  5. using EVCB_OCPP.WSServer.Service.DbService;
  6. using Microsoft.EntityFrameworkCore;
  7. using Microsoft.Extensions.Logging;
  8. using Newtonsoft.Json;
  9. using Newtonsoft.Json.Linq;
  10. using NLog;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.Linq;
  14. using System.Threading.Tasks;
  15. namespace EVCB_OCPP.WSServer.Service.BusinessService
  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. internal bool InstantStopTxReport { set; get; }
  38. }
  39. public class OuterBusinessService : IBusinessService
  40. {
  41. private readonly ILogger<OuterBusinessService> logger;
  42. private readonly IDbContextFactory<MainDBContext> maindbContextFactory;
  43. private readonly IMainDbService mainDbService;
  44. private readonly OuterHttpClient httpClient;
  45. private string _CustomerId = string.Empty;
  46. private CustomerSignMaterial signMaterial = null;
  47. public string CustomerId
  48. {
  49. get => _CustomerId;
  50. set
  51. {
  52. _CustomerId = value;
  53. signMaterial = GetSign(_CustomerId).Result;
  54. }
  55. }
  56. internal CustomerSignMaterial CustomerSignMaterial
  57. {
  58. get => signMaterial;
  59. set
  60. {
  61. signMaterial = value;
  62. _CustomerId = signMaterial.Id;
  63. }
  64. }
  65. public OuterBusinessService(
  66. ILogger<OuterBusinessService> logger,
  67. IDbContextFactory<MainDBContext> maindbContextFactory,
  68. IMainDbService mainDbService,
  69. OuterHttpClient httpClient)
  70. {
  71. this.logger = logger;
  72. this.maindbContextFactory = maindbContextFactory;
  73. this.mainDbService = mainDbService;
  74. this.httpClient = httpClient;
  75. }
  76. async public Task<IdTokenInfo> Authorize(string chargeBoxId, string idTag, int? connectorId = null, string source = null)
  77. {
  78. //return new IdTokenInfo() { IdTagInfo = new IdTagInfo()
  79. //{
  80. // expiryDate = DateTime.UtcNow.AddDays(1),
  81. // status = AuthorizationStatus.Accepted
  82. //} };
  83. //await Task.Delay(10);
  84. IdTokenInfo result = new IdTokenInfo() { IdTagInfo = new IdTagInfo() { status = AuthorizationStatus.Invalid } };
  85. try
  86. {
  87. logger.LogInformation(chargeBoxId + " Charging Monitor======================================>");
  88. string requestParams = idTag.StartsWith("vid:") ? await GetRequestParamsAsPnC(chargeBoxId, idTag, connectorId, source) : GetRequestParamsAsNormal(chargeBoxId, idTag, source);
  89. logger.LogInformation($"{chargeBoxId} Authorize : {signMaterial.APIUrl + requestParams}");
  90. HttpResult response = await httpClient.Post(signMaterial.APIUrl + requestParams, new Dictionary<string, string>()
  91. {
  92. { "PartnerId",signMaterial.Id}
  93. }, requestBody: null, saltkey: signMaterial.SaltKey).ConfigureAwait(false);
  94. logger.LogInformation($"{chargeBoxId} response : {JsonConvert.SerializeObject(response)}");
  95. if (response.Success)
  96. {
  97. //Console.WriteLine(response.Response);
  98. var _httpResult = JsonConvert.DeserializeObject<CPOOuterResponse>(response.Response);
  99. JObject jo = JObject.Parse(_httpResult.Data);
  100. if (jo.ContainsKey("ExpiryDate"))
  101. {
  102. DateTime dt = jo["ExpiryDate"].Value<DateTime>();
  103. result.IdTagInfo.expiryDate = dt;
  104. }
  105. if (jo.ContainsKey("ParentIdTag"))
  106. {
  107. string _Message = jo["ParentIdTag"].Value<string>();
  108. result.IdTagInfo.parentIdTag = _Message;
  109. }
  110. if (jo.ContainsKey("ChargePointFee"))
  111. {
  112. for (int i = 0; i < jo["ChargePointFee"].Count(); i++)
  113. {
  114. if (i == 0)
  115. {
  116. result.ChargePointFee = new List<ChargePointFee>();
  117. }
  118. result.ChargePointFee.Add(jo["ChargePointFee"][i].ToObject<ChargePointFee>());
  119. }
  120. }
  121. if (jo.ContainsKey("ChargepointFee"))
  122. {
  123. for (int i = 0; i < jo["ChargepointFee"].Count(); i++)
  124. {
  125. if (i == 0)
  126. {
  127. result.ChargePointFee = new List<ChargePointFee>();
  128. }
  129. result.ChargePointFee.Add(jo["ChargepointFee"][i].ToObject<ChargePointFee>());
  130. }
  131. }
  132. if (jo.ContainsKey("AccountBalance"))
  133. {
  134. decimal accountBalance = jo["AccountBalance"].Value<decimal>();
  135. result.AccountBalance = accountBalance;
  136. }
  137. if (jo.ContainsKey("Status"))
  138. {
  139. string _Message = jo["Status"].Value<string>();
  140. result.IdTagInfo.status = (AuthorizationStatus)Enum.Parse(typeof(AuthorizationStatus), _Message);
  141. }
  142. }
  143. else
  144. {
  145. logger.LogError(chargeBoxId + " OuterBusinessService.Authorize Fail: " + response.Response);
  146. }
  147. }
  148. catch (Exception ex)
  149. {
  150. result.IdTagInfo.status = AuthorizationStatus.Invalid;
  151. logger.LogError(chargeBoxId + " OuterBusinessService.Authorize Ex: " + ex.ToString());
  152. }
  153. return result;
  154. }
  155. async public Task NotifyFaultStatus(ErrorDetails details)
  156. {
  157. try
  158. {
  159. if (signMaterial.CallsThirdParty)
  160. {
  161. var response = await httpClient.Post(signMaterial.APIUrl + "connectorfault", new Dictionary<string, string>()
  162. {
  163. { "PartnerId",signMaterial.Id}
  164. }, details, signMaterial.SaltKey).ConfigureAwait(false);
  165. }
  166. }
  167. catch (Exception ex)
  168. {
  169. logger.LogError(details.ChargeBoxId + " OuterBusinessService.NotifyFaultStatus Ex: " + ex.ToString());
  170. }
  171. }
  172. async public Task NotifyConnectorUnplugged(string chargeBoxId, string data)
  173. {
  174. try
  175. {
  176. JObject jo = JObject.Parse(data);
  177. var details = new { ChargeBoxId = chargeBoxId, SessionId = jo["idTx"].Value<int>(), Timestamp = jo["timestamp"].Value<DateTime>() };
  178. if (signMaterial.CallsThirdParty)
  179. {
  180. var response = await httpClient.Post(signMaterial.APIUrl + "connectorunplugged", new Dictionary<string, string>()
  181. {
  182. { "PartnerId",signMaterial.Id}
  183. }, details, signMaterial.SaltKey).ConfigureAwait(false);
  184. }
  185. }
  186. catch (Exception ex)
  187. {
  188. logger.LogError(chargeBoxId + " OuterBusinessService.NotifyConnectorUnplugged Ex: " + ex.ToString());
  189. }
  190. }
  191. private async Task<CustomerSignMaterial> GetSign(string customerId)
  192. {
  193. Guid Id = new Guid(customerId);
  194. CustomerSignMaterial _customer = new CustomerSignMaterial();
  195. //using (var db = new MainDBContext())
  196. //using (var db = maindbContextFactory.CreateDbContextAsync())
  197. //{
  198. // _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();
  199. //}
  200. var _customerDb = await mainDbService.GetCustomer(Id);
  201. if (_customerDb is not null)
  202. {
  203. _customer.Id = _customerDb.Id.ToString();
  204. _customer.APIUrl = _customerDb.ApiUrl;
  205. _customer.SaltKey = _customerDb.ApiKey;
  206. _customer.CallsThirdParty = _customerDb.CallPartnerApiOnSchedule;
  207. }
  208. return _customer;
  209. }
  210. private async ValueTask<string> GetRequestParamsAsPnC(string chargeBoxId, string idTag, int? connectorId, string source)
  211. {
  212. idTag = idTag.Replace("vid:", "");
  213. if (connectorId is null)
  214. {
  215. using (var db = await maindbContextFactory.CreateDbContextAsync())
  216. {
  217. var connectorStatuses = await db.ConnectorStatus.Where(x => x.ChargeBoxId == chargeBoxId).
  218. Select(x => new { x.ConnectorId, x.Status, x.CreatedOn }).ToListAsync();
  219. var connectorStatus = connectorStatuses.Where(x => x.Status == 2).OrderByDescending(x => x.CreatedOn).FirstOrDefault();
  220. if (connectorStatus != null)
  221. {
  222. connectorId = connectorStatus.ConnectorId;
  223. }
  224. }
  225. if (connectorId is null)
  226. {
  227. connectorId = -1;
  228. }
  229. }
  230. var requestParamString = string.Format("charging_auth?ChargeBoxId={0}&ConnectorId={1}&IdTag={2}", chargeBoxId, connectorId, idTag);
  231. if (!string.IsNullOrEmpty(source))
  232. {
  233. requestParamString += $"&Action={source}";
  234. }
  235. return requestParamString;
  236. }
  237. private string GetRequestParamsAsNormal(string chargeBoxId, string idTag, string source)
  238. {
  239. var requestParamString = string.Format("charging_auth?ChargeBoxId={0}&IdTag={1}", chargeBoxId, idTag);
  240. if (!string.IsNullOrEmpty(source))
  241. {
  242. requestParamString += $"&Action={source}";
  243. }
  244. return requestParamString;
  245. }
  246. public Task NotifyConnectorUnplugged(string data)
  247. {
  248. throw new NotImplementedException();
  249. }
  250. public async ValueTask<NotifyTransactionCompletedResult> NotifyTransactionCompleted(TransactionRecord tx, Dictionary<string, decimal> roundedPeriodEnergy = null)
  251. {
  252. if (signMaterial == null || !signMaterial.InstantStopTxReport)
  253. {
  254. return null;
  255. }
  256. var toReturn = new NotifyTransactionCompletedResult();
  257. //var PeriodEnergy = await mainDbService.GetTransactionPeriodEnergy(tx.Id);
  258. var request = new
  259. {
  260. ChargeBoxId = tx.ChargeBoxId,
  261. ConnectorId = tx.ConnectorId,
  262. SessionId = tx.Id,
  263. MeterStart = tx.MeterStart,
  264. MeterStop = tx.MeterStop,
  265. IdTag = tx.StartIdTag,
  266. StartTime = tx.StartTime.ToString(GlobalConfig.UTC_DATETIMEFORMAT),
  267. StopTime = tx.StopTime.ToString(GlobalConfig.UTC_DATETIMEFORMAT),
  268. StopReason = tx.StopReasonId < 1 ? "Unknown" : (tx.StopReasonId > 12 ? "Unknown" : ((Reason)tx.StopReasonId).ToString()),
  269. Receipt = tx.Receipt,
  270. TotalCost = tx.Cost,
  271. Fee = tx.Fee,
  272. PeriodEnergy = roundedPeriodEnergy,
  273. StartSOC = int.TryParse(tx.StartSoc, out int StartSOCint) ? StartSOCint : (int?)null,
  274. StopSOC = int.TryParse(tx.StopSoc, out int StopSOCint) ? StopSOCint : (int?)null
  275. };
  276. logger.LogDebug("completed_session " + JsonConvert.SerializeObject(request, GlobalConfig.JSONSERIALIZER_FORMAT));
  277. var response = await httpClient.Post(
  278. signMaterial.APIUrl + "completed_session",
  279. new Dictionary<string, string>()
  280. {
  281. { "PartnerId", CustomerId}
  282. },
  283. request,
  284. signMaterial.SaltKey);
  285. logger.LogDebug("completed_session Response" + response.Response);
  286. if (!response.Success)
  287. {
  288. toReturn.ErrorMsg = !string.IsNullOrEmpty(response.Response) ? response.Response : response.StatusCode.ToString();
  289. return toReturn;
  290. }
  291. if (!string.IsNullOrEmpty(response.Response))
  292. {
  293. var _httpResult = JsonConvert.DeserializeObject<CPOOuterResponse>(response.Response);
  294. logger.LogDebug("completed_session Response" + response.Response);
  295. JObject jo = JObject.Parse(_httpResult.Data);
  296. if (jo.ContainsKey("CouponPoint"))
  297. {
  298. toReturn.CouponPoint = jo["CouponPoint"].Value<Decimal>();
  299. }
  300. if (jo.ContainsKey("FarewellMessage"))
  301. {
  302. toReturn.FarewellMessage = jo["FarewellMessage"].Value<string>();
  303. }
  304. }
  305. return toReturn;
  306. }
  307. }
  308. }