OuterBusinessService.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. using EVCB_OCPP.Domain;
  2. using EVCB_OCPP.Domain.Models.Database;
  3. using EVCB_OCPP.Packet.Messages.SubTypes;
  4. using EVCB_OCPP.WSServer.Dto;
  5. using Newtonsoft.Json;
  6. using Newtonsoft.Json.Linq;
  7. using NLog;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Security.Cryptography.X509Certificates;
  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. static private ILogger logger = NLog.LogManager.GetCurrentClassLogger();
  39. private OuterHttpClient httpClient = new OuterHttpClient();
  40. private CustomerSignMaterial signMaterial = null;
  41. private string CustomerId = string.Empty;
  42. public OuterBusinessService(string customerId)
  43. {
  44. CustomerId = customerId;
  45. signMaterial = GetSign(customerId);
  46. }
  47. async public Task<IdTokenInfo> Authorize(string chargeBoxId, string idTag,int? connectorId =-1)
  48. {
  49. await Task.Delay(10);
  50. IdTokenInfo result = new IdTokenInfo() { IdTagInfo = new IdTagInfo() { status = AuthorizationStatus.Invalid } };
  51. bool normaalAuth = true;
  52. try
  53. {
  54. #region PnC
  55. if (idTag.StartsWith("vid:"))
  56. {
  57. idTag = idTag.Replace("vid:","");
  58. normaalAuth = false;
  59. if(connectorId==-1)
  60. {
  61. using (var db = new MainDBContext())
  62. {
  63. var connectorStatuses = db.ConnectorStatus.Where(x => x.ChargeBoxId == chargeBoxId).
  64. Select(x => new { x.ConnectorId, x.Status, x.CreatedOn }).ToList();
  65. var connectorStatus = connectorStatuses.Where(x => x.Status == 2).OrderByDescending(x => x.CreatedOn).FirstOrDefault();
  66. if (connectorStatus != null) { connectorId = connectorStatus.ConnectorId; }
  67. }
  68. }
  69. }
  70. #endregion
  71. string requestParams = normaalAuth ? string.Format("charging_auth?ChargeBoxId={0}&IdTag={1}", chargeBoxId, idTag) :
  72. string.Format("charging_auth?ChargeBoxId={0}&ConnectorId={1}&IdTag={2}", chargeBoxId, connectorId, idTag);
  73. var response = await httpClient.Post(signMaterial.APIUrl + requestParams, new Dictionary<string, string>()
  74. {
  75. { "PartnerId",signMaterial.Id}
  76. }, null, signMaterial.SaltKey).ConfigureAwait(false);
  77. logger.Info(chargeBoxId + " Charging Monitor======================================>");
  78. logger.Info(signMaterial.APIUrl + requestParams);
  79. logger.Info(JsonConvert.SerializeObject(response));
  80. if (response.Success)
  81. {
  82. Console.WriteLine(response.Response);
  83. var _httpResult = JsonConvert.DeserializeObject<CPOOuterResponse>(response.Response);
  84. JObject jo = JObject.Parse(_httpResult.Data);
  85. if (jo.ContainsKey("ExpiryDate"))
  86. {
  87. DateTime dt = jo["ExpiryDate"].Value<DateTime>();
  88. result.IdTagInfo.expiryDate = dt;
  89. }
  90. if (jo.ContainsKey("ParentIdTag"))
  91. {
  92. string _Message = jo["ParentIdTag"].Value<string>();
  93. result.IdTagInfo.parentIdTag = _Message;
  94. }
  95. if (jo.ContainsKey("ChargePointFee"))
  96. {
  97. for (int i = 0; i < jo["ChargePointFee"].Count(); i++)
  98. {
  99. if (i == 0)
  100. {
  101. result.ChargePointFee = new List<ChargePointFee>();
  102. }
  103. result.ChargePointFee.Add(jo["ChargePointFee"][i].ToObject<ChargePointFee>());
  104. }
  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("AccountBalance"))
  118. {
  119. decimal accountBalance = jo["AccountBalance"].Value<decimal>();
  120. result.AccountBalance = accountBalance;
  121. }
  122. if (jo.ContainsKey("Status"))
  123. {
  124. string _Message = jo["Status"].Value<string>();
  125. result.IdTagInfo.status = (AuthorizationStatus)Enum.Parse(typeof(AuthorizationStatus), _Message);
  126. }
  127. }
  128. else
  129. {
  130. logger.Error(chargeBoxId + " OuterBusinessService.Authorize Fail: " + response.Response);
  131. }
  132. }
  133. catch (Exception ex)
  134. {
  135. result.IdTagInfo.status = AuthorizationStatus.Invalid;
  136. logger.Error(chargeBoxId + " OuterBusinessService.Authorize Ex: " + ex.ToString());
  137. }
  138. return result;
  139. }
  140. async public Task NotifyFaultStatus(ErrorDetails details)
  141. {
  142. try
  143. {
  144. if (signMaterial.CallsThirdParty)
  145. {
  146. var response = await httpClient.Post(signMaterial.APIUrl + "connectorfault", new Dictionary<string, string>()
  147. {
  148. { "PartnerId",signMaterial.Id}
  149. }, details, signMaterial.SaltKey).ConfigureAwait(false);
  150. }
  151. }
  152. catch (Exception ex)
  153. {
  154. logger.Error(details.ChargeBoxId + " OuterBusinessService.NotifyFaultStatus Ex: " + ex.ToString());
  155. }
  156. }
  157. async public Task NotifyConnectorUnplugged(string chargeBoxId, string data)
  158. {
  159. try
  160. {
  161. JObject jo = JObject.Parse(data);
  162. var details = new { ChargeBoxId = chargeBoxId, SessionId = jo["idTx"].Value<Int32>(), Timestamp = jo["timestamp"].Value<DateTime>() };
  163. if (signMaterial.CallsThirdParty)
  164. {
  165. var response = await httpClient.Post(signMaterial.APIUrl + "connectorunplugged", new Dictionary<string, string>()
  166. {
  167. { "PartnerId",signMaterial.Id}
  168. }, details, signMaterial.SaltKey).ConfigureAwait(false);
  169. }
  170. }
  171. catch (Exception ex)
  172. {
  173. logger.Error(chargeBoxId + " OuterBusinessService.NotifyConnectorUnplugged Ex: " + ex.ToString());
  174. }
  175. }
  176. private CustomerSignMaterial GetSign(string customerId)
  177. {
  178. Guid Id = new Guid(customerId);
  179. CustomerSignMaterial _customer = new CustomerSignMaterial();
  180. using (var db = new MainDBContext())
  181. {
  182. _customer = db.Customer.Where(x => x.Id == Id).Select(x => new CustomerSignMaterial() { Id = x.Id.ToString(), APIUrl = x.ApiUrl, SaltKey = x.ApiKey, CallsThirdParty = x.CallPartnerApiOnSchedule }).FirstOrDefault();
  183. }
  184. return _customer;
  185. }
  186. public Task NotifyConnectorUnplugged(string data)
  187. {
  188. throw new NotImplementedException();
  189. }
  190. }
  191. }