OuterBusinessService.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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.Configuration;
  11. using System.Linq;
  12. using System.Net;
  13. using System.Security.Cryptography.X509Certificates;
  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. static private ILogger logger = NLog.LogManager.GetCurrentClassLogger();
  41. private OuterHttpClient httpClient = new OuterHttpClient();
  42. private CustomerSignMaterial signMaterial = null;
  43. private string CustomerId = string.Empty;
  44. public OuterBusinessService(string customerId)
  45. {
  46. CustomerId = customerId;
  47. signMaterial = GetSign(customerId);
  48. }
  49. async public Task<IdTokenInfo> Authorize(string chargeBoxId, string idTag, int? connectorId = -1)
  50. {
  51. await Task.Delay(10);
  52. IdTokenInfo info = new IdTokenInfo() { IdTagInfo = new IdTagInfo() { status = AuthorizationStatus.Invalid } };
  53. try
  54. {
  55. if (CustomerId.ToUpper() == "009E603C-79CD-4620-A2B8-D9349C0E8AD8")
  56. {
  57. info.IdTagInfo = new IdTagInfo() { status = AuthorizationStatus.Accepted };
  58. return info;
  59. }
  60. OuterHttpClient _client = new OuterHttpClient();
  61. string url = ConfigurationManager.AppSettings["LocalAuthAPI"];
  62. HttpClientService service = new HttpClientService();
  63. Dictionary<string, string> postData = new Dictionary<string, string>()
  64. {
  65. { "ChargeBoxId", chargeBoxId },
  66. { "IdTag", idTag },
  67. };
  68. var _innerresult = await service.PostFormDataAsync(url, postData, null);
  69. if (_innerresult.StatusCode == HttpStatusCode.OK)
  70. {
  71. JObject jo = JObject.Parse(_innerresult.Response);
  72. if (jo["code"].ToString() == "1")
  73. {
  74. try
  75. {
  76. info.IdTagInfo.status = (AuthorizationStatus)Enum.Parse(typeof(AuthorizationStatus), jo["message"].ToString());
  77. }
  78. catch (Exception)
  79. {
  80. ;
  81. }
  82. }
  83. }
  84. }
  85. catch (Exception ex)
  86. {
  87. ;
  88. }
  89. return info;
  90. }
  91. async public Task<IdTokenInfo> Authorize_outer(string chargeBoxId, string idTag,int? connectorId =-1)
  92. {
  93. await Task.Delay(10);
  94. IdTokenInfo result = new IdTokenInfo() { IdTagInfo = new IdTagInfo() { status = AuthorizationStatus.Invalid } };
  95. bool normaalAuth = true;
  96. try
  97. {
  98. #region PnC
  99. if (idTag.StartsWith("vid:"))
  100. {
  101. idTag = idTag.Replace("vid:","");
  102. normaalAuth = false;
  103. if(connectorId==-1)
  104. {
  105. using (var db = new MainDBContext())
  106. {
  107. var connectorStatuses = db.ConnectorStatus.Where(x => x.ChargeBoxId == chargeBoxId).
  108. Select(x => new { x.ConnectorId, x.Status, x.CreatedOn }).ToList();
  109. var connectorStatus = connectorStatuses.Where(x => x.Status == 2).OrderByDescending(x => x.CreatedOn).FirstOrDefault();
  110. if (connectorStatus != null) { connectorId = connectorStatus.ConnectorId; }
  111. }
  112. }
  113. }
  114. #endregion
  115. string requestParams = normaalAuth ? string.Format("charging_auth?ChargeBoxId={0}&IdTag={1}", chargeBoxId, idTag) :
  116. string.Format("charging_auth?ChargeBoxId={0}&ConnectorId={1}&IdTag={2}", chargeBoxId, connectorId, idTag);
  117. var response = await httpClient.Post(signMaterial.APIUrl + requestParams, new Dictionary<string, string>()
  118. {
  119. { "PartnerId",signMaterial.Id}
  120. }, null, signMaterial.SaltKey).ConfigureAwait(false);
  121. logger.Info(chargeBoxId + " Charging Monitor======================================>");
  122. logger.Info(signMaterial.APIUrl + requestParams);
  123. logger.Info(JsonConvert.SerializeObject(response));
  124. if (response.Success)
  125. {
  126. Console.WriteLine(response.Response);
  127. var _httpResult = JsonConvert.DeserializeObject<CPOOuterResponse>(response.Response);
  128. JObject jo = JObject.Parse(_httpResult.Data);
  129. if (jo.ContainsKey("ExpiryDate"))
  130. {
  131. DateTime dt = jo["ExpiryDate"].Value<DateTime>();
  132. result.IdTagInfo.expiryDate = dt;
  133. }
  134. if (jo.ContainsKey("ParentIdTag"))
  135. {
  136. string _Message = jo["ParentIdTag"].Value<string>();
  137. result.IdTagInfo.parentIdTag = _Message;
  138. }
  139. if (jo.ContainsKey("ChargePointFee"))
  140. {
  141. for (int i = 0; i < jo["ChargePointFee"].Count(); i++)
  142. {
  143. if (i == 0)
  144. {
  145. result.ChargePointFee = new List<ChargePointFee>();
  146. }
  147. result.ChargePointFee.Add(jo["ChargePointFee"][i].ToObject<ChargePointFee>());
  148. }
  149. }
  150. if (jo.ContainsKey("ChargepointFee"))
  151. {
  152. for (int i = 0; i < jo["ChargepointFee"].Count(); i++)
  153. {
  154. if (i == 0)
  155. {
  156. result.ChargePointFee = new List<ChargePointFee>();
  157. }
  158. result.ChargePointFee.Add(jo["ChargepointFee"][i].ToObject<ChargePointFee>());
  159. }
  160. }
  161. if (jo.ContainsKey("AccountBalance"))
  162. {
  163. decimal accountBalance = jo["AccountBalance"].Value<decimal>();
  164. result.AccountBalance = accountBalance;
  165. }
  166. if (jo.ContainsKey("Status"))
  167. {
  168. string _Message = jo["Status"].Value<string>();
  169. result.IdTagInfo.status = (AuthorizationStatus)Enum.Parse(typeof(AuthorizationStatus), _Message);
  170. }
  171. }
  172. else
  173. {
  174. logger.Error(chargeBoxId + " OuterBusinessService.Authorize Fail: " + response.Response);
  175. }
  176. }
  177. catch (Exception ex)
  178. {
  179. result.IdTagInfo.status = AuthorizationStatus.Invalid;
  180. logger.Error(chargeBoxId + " OuterBusinessService.Authorize Ex: " + ex.ToString());
  181. }
  182. return result;
  183. }
  184. async public Task NotifyFaultStatus(ErrorDetails details)
  185. {
  186. try
  187. {
  188. if (signMaterial.CallsThirdParty)
  189. {
  190. var response = await httpClient.Post(signMaterial.APIUrl + "connectorfault", new Dictionary<string, string>()
  191. {
  192. { "PartnerId",signMaterial.Id}
  193. }, details, signMaterial.SaltKey).ConfigureAwait(false);
  194. }
  195. }
  196. catch (Exception ex)
  197. {
  198. logger.Error(details.ChargeBoxId + " OuterBusinessService.NotifyFaultStatus Ex: " + ex.ToString());
  199. }
  200. }
  201. async public Task NotifyConnectorUnplugged(string chargeBoxId, string data)
  202. {
  203. try
  204. {
  205. JObject jo = JObject.Parse(data);
  206. var details = new { ChargeBoxId = chargeBoxId, SessionId = jo["idTx"].Value<Int32>(), Timestamp = jo["timestamp"].Value<DateTime>() };
  207. if (signMaterial.CallsThirdParty)
  208. {
  209. var response = await httpClient.Post(signMaterial.APIUrl + "connectorunplugged", new Dictionary<string, string>()
  210. {
  211. { "PartnerId",signMaterial.Id}
  212. }, details, signMaterial.SaltKey).ConfigureAwait(false);
  213. }
  214. }
  215. catch (Exception ex)
  216. {
  217. logger.Error(chargeBoxId + " OuterBusinessService.NotifyConnectorUnplugged Ex: " + ex.ToString());
  218. }
  219. }
  220. private CustomerSignMaterial GetSign(string customerId)
  221. {
  222. Guid Id = new Guid(customerId);
  223. CustomerSignMaterial _customer = new CustomerSignMaterial();
  224. using (var db = new MainDBContext())
  225. {
  226. _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();
  227. }
  228. return _customer;
  229. }
  230. public Task NotifyConnectorUnplugged(string data)
  231. {
  232. throw new NotImplementedException();
  233. }
  234. }
  235. }