CPOController.cs 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566
  1. using EVCB_OCPP.WEBAPI.Handlers;
  2. using EVCB_OCPP.WEBAPI.Models.WebAPI;
  3. using EVCB_OCPP.WEBAPI.Services;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Http;
  9. using System.Web.Http;
  10. using System.Web.Http.Description;
  11. using Newtonsoft.Json;
  12. using System.Threading.Tasks;
  13. using EVCB_OCPP.WEBAPI.Models.WebAPI.Dto;
  14. using System.Net.Http.Headers;
  15. using EVCB_OCPP.Packet.Messages.SubTypes;
  16. using System.Security.Cryptography.X509Certificates;
  17. using OCPPPackage.Profiles;
  18. namespace EVCB_OCPP.WEBAPI.Controllers.Version1
  19. {
  20. [RoutePrefix("api/v1/cpo")]
  21. [CPOAuthentication]
  22. public class CPOController : ApiController
  23. {
  24. private HttpClientService service = new HttpClientService();
  25. private bool ContainsChargePoint(string chargeBoxId, out string customerId)
  26. {
  27. customerId = string.Empty;
  28. if (!Request.Headers.Contains(EVCBConfiguration.Header_PartnerId)) return false;
  29. customerId = Request.Headers.GetValues(EVCBConfiguration.Header_PartnerId).First();
  30. ChargePointService _service = new ChargePointService();
  31. return _service.ContainsChargePoint(chargeBoxId, customerId);
  32. }
  33. [Route("station")]
  34. [ResponseType(typeof(CPOOuterResponse))]
  35. [HttpGet]
  36. public HttpResponseMessage Station()
  37. {
  38. var result = new CPOOuterResponse();
  39. HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
  40. try
  41. {
  42. if (Request.Headers.Contains(EVCBConfiguration.Header_PartnerId))
  43. {
  44. var _customerId = Request.Headers.GetValues(EVCBConfiguration.Header_PartnerId).First();
  45. ChargingStationService _service = new ChargingStationService();
  46. var _innerResponse = new { Stations = _service.GetStationsbyCustomerId(_customerId) };
  47. result.Data = JsonConvert.SerializeObject(_innerResponse, EVCBConfiguration.JSONSERIALIZER_FORMAT);
  48. result.StatusCode = (int)CPO_StatusCode.Success;
  49. result.StatusMessage = CPO_StatusMessage.Success;
  50. statusCode = HttpStatusCode.OK;
  51. }
  52. return Request.CreateResponse(statusCode, result);
  53. }
  54. catch (Exception ex)
  55. {
  56. result.ErrorDetail = ex.ToString();
  57. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
  58. result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
  59. return Request.CreateResponse(statusCode, result);
  60. }
  61. }
  62. [Route("information")]
  63. [ResponseType(typeof(CPOOuterResponse))]
  64. [HttpGet]
  65. public HttpResponseMessage BasicInformationofEVSEs(int StationId = -1, string ChargeBoxId = "", DateTime? DateFrom = null, DateTime? DateTo = null, int? Offset = 0, int? Limit = 1)
  66. {
  67. var result = new CPOOuterResponse();
  68. HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
  69. try
  70. {
  71. ChargePointService _CPService = new ChargePointService();
  72. var tt = _CPService.GetLastUpdatedTimebyMachineId("0da4f4a6-a952-46f0-b2f3-696385a9a56a");
  73. if (Request.Headers.Contains(EVCBConfiguration.Header_PartnerId))
  74. {
  75. var _customerId = Request.Headers.GetValues(EVCBConfiguration.Header_PartnerId).First();
  76. var _innerResponse = new { EVSEs = new List<EVSE>() };
  77. ChargingStationService _stationService = new ChargingStationService();
  78. if (StationId > -1)
  79. {
  80. if (_stationService.ContainsStation(_customerId, StationId))
  81. {
  82. if (DateTo.HasValue)
  83. {
  84. if (!DateFrom.HasValue)
  85. {
  86. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_PARAMETER_OUTOFRANGE_INCORRECT;
  87. result.StatusCode = (int)CPO_StatusCode.PARAMETER_OUTOFRANGE_INCORRECT;
  88. statusCode = HttpStatusCode.BadRequest;
  89. return Request.CreateResponse(statusCode, result);
  90. }
  91. }
  92. _innerResponse = new { EVSEs = _stationService.GetEVSEsbyStationId(StationId, DateFrom, DateTo, Offset.Value, Limit.Value) };
  93. }
  94. }
  95. else
  96. {
  97. _innerResponse = new { EVSEs = new List<EVSE>() };
  98. _innerResponse.EVSEs.Add(_CPService.GetEVSEsbyChargeBoxId(ChargeBoxId, DateFrom, DateTo));
  99. }
  100. result.Data = JsonConvert.SerializeObject(_innerResponse, EVCBConfiguration.JSONSERIALIZER_FORMAT);
  101. result.StatusCode = (int)CPO_StatusCode.Success;
  102. result.StatusMessage = CPO_StatusMessage.Success;
  103. statusCode = HttpStatusCode.OK;
  104. }
  105. return Request.CreateResponse(statusCode, result);
  106. }
  107. catch (Exception ex)
  108. {
  109. result.ErrorDetail = ex.ToString();
  110. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
  111. result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
  112. return Request.CreateResponse(statusCode, result);
  113. }
  114. }
  115. [Route("commands/start_session")]
  116. [ResponseType(typeof(CPOOuterResponse))]
  117. [HttpPost]
  118. async public Task<HttpResponseMessage> StartSession([FromBody] StartSessionRequest request)
  119. {
  120. var result = new CPOOuterResponse();
  121. HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
  122. var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
  123. try
  124. {
  125. string _CustomerId = string.Empty;
  126. if (!ContainsChargePoint(request.ChargeBoxId, out _CustomerId))
  127. {
  128. // 沒槍~ 沒得充...
  129. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CHARGEBOXID_DOESNT_EXIST;
  130. result.StatusCode = (int)CPO_StatusCode.CHARGEBOXID_ISNT_EXIST_OR_OFFLINE;
  131. result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
  132. statusCode = HttpStatusCode.BadRequest;
  133. return Request.CreateResponse(statusCode, result);
  134. }
  135. ChargePointService _CPService = new ChargePointService();
  136. if (!string.IsNullOrEmpty(request.ChargeBoxId) && request.ChargeBoxId.Length <= 25
  137. && _CPService.GetNumberofConnectors(request.ChargeBoxId) <= request.ConnectorId && request.ConnectorId > 0
  138. && !string.IsNullOrEmpty(request.Token) && request.Token.Length <= 20)
  139. {
  140. InternalHttpClient _client = new InternalHttpClient();
  141. CustomerService _customer = new CustomerService();
  142. //trigger to charge
  143. var _request = new StartTransactionRequest()
  144. {
  145. ConnectorId = request.ConnectorId,
  146. IdTag = request.Token
  147. };
  148. string[] parts = Request.RequestUri.ToString().Split('/');
  149. string urlformat = "{0}//{1}/api/v1/ocpp16/transaction?ChargeBoxId={3}";
  150. var _innerResult = await _client.Post(string.Format(urlformat, parts[0], parts[2], Request.RequestUri.Port, request.ChargeBoxId), new Dictionary<string, string>()
  151. {
  152. { "PartnerId",_CustomerId}
  153. }, _request, _customer.GetAPIKey(new Guid(_CustomerId)));
  154. _innerData = new { Result = string.IsNullOrEmpty(_innerResult.SerialNo) ? CommandResponseType.Rejected.ToString() : CommandResponseType.Accepted.ToString(), Timeout = 60 };
  155. result = GetErrorDescription(_innerResult);
  156. result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
  157. if (_innerResult.Status == HttpStatusCode.InternalServerError)
  158. {
  159. result.StatusCode = _innerResult.ErrorCode;
  160. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
  161. statusCode = HttpStatusCode.InternalServerError;
  162. }
  163. else
  164. {
  165. result.SerialNo = _innerResult.SerialNo;
  166. result.StatusCode = _innerResult.ErrorCode;
  167. result.StatusMessage = _innerResult.Message;
  168. statusCode = HttpStatusCode.OK;
  169. }
  170. }
  171. else
  172. {
  173. // 參數不符合定義
  174. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_PARAMETER_OUTOFRANGE_INCORRECT;
  175. result.StatusCode = (int)CPO_StatusCode.PARAMETER_OUTOFRANGE_INCORRECT;
  176. result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
  177. statusCode = HttpStatusCode.BadRequest;
  178. }
  179. return Request.CreateResponse(statusCode, result);
  180. }
  181. catch (Exception ex)
  182. {
  183. result.ErrorDetail = ex.ToString();
  184. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
  185. result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
  186. return Request.CreateResponse(statusCode, result);
  187. }
  188. }
  189. [Route("commands/stop_session")]
  190. [ResponseType(typeof(CPOOuterResponse))]
  191. [HttpPost]
  192. async public Task<HttpResponseMessage> StopSession(string ChargeBoxId, int SessionId)
  193. {
  194. var result = new CPOOuterResponse();
  195. HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
  196. var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
  197. try
  198. {
  199. string _CustomerId = string.Empty;
  200. if (!ContainsChargePoint(ChargeBoxId, out _CustomerId))
  201. {
  202. // 沒槍~ 沒得充...
  203. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CHARGEBOXID_DOESNT_EXIST;
  204. result.StatusCode = (int)CPO_StatusCode.CHARGEBOXID_ISNT_EXIST_OR_OFFLINE;
  205. result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
  206. statusCode = HttpStatusCode.BadRequest;
  207. return Request.CreateResponse(statusCode, result);
  208. }
  209. InternalHttpClient _client = new InternalHttpClient();
  210. CustomerService _customer = new CustomerService();
  211. string[] parts = Request.RequestUri.ToString().Split('/');
  212. string urlformat = "{0}//{1}/api/v1/ocpp16/transaction?ChargeBoxId={2}&TransactionId={3}";
  213. var _innerResult = await _client.Put(string.Format(urlformat, parts[0], parts[2], ChargeBoxId, SessionId), new Dictionary<string, string>()
  214. {
  215. { "PartnerId",_CustomerId}
  216. }, null, _customer.GetAPIKey(new Guid(_CustomerId)));
  217. _innerData = new { Result = string.IsNullOrEmpty(_innerResult.SerialNo) ? CommandResponseType.Rejected.ToString() : CommandResponseType.Accepted.ToString(), Timeout = 60 };
  218. result = GetErrorDescription(_innerResult);
  219. result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
  220. if (_innerResult.Success)
  221. {
  222. result.SerialNo = _innerResult.SerialNo;
  223. result.StatusCode = (int)CPO_StatusCode.Success;
  224. result.StatusMessage = CPO_StatusMessage.Success;
  225. statusCode = HttpStatusCode.OK;
  226. }
  227. else
  228. {
  229. result.StatusCode = _innerResult.ErrorCode;
  230. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
  231. statusCode = HttpStatusCode.BadRequest;
  232. }
  233. }
  234. catch (Exception ex)
  235. {
  236. result.ErrorDetail = ex.ToString();
  237. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
  238. result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
  239. return Request.CreateResponse(statusCode, result);
  240. }
  241. return Request.CreateResponse(statusCode, result);
  242. }
  243. [Route("commands/reserve_now")]
  244. [ResponseType(typeof(CPOOuterResponse))]
  245. [HttpPost]
  246. async public Task<HttpResponseMessage> ReserveNow([FromBody] ReserveNowRequest request)
  247. {
  248. var result = new CPOOuterResponse();
  249. HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
  250. var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
  251. try
  252. {
  253. string _CustomerId = string.Empty;
  254. if (!ContainsChargePoint(request.ChargeBoxId, out _CustomerId))
  255. {
  256. // 沒槍~ 沒得充...
  257. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CHARGEBOXID_DOESNT_EXIST;
  258. result.StatusCode = (int)CPO_StatusCode.CHARGEBOXID_ISNT_EXIST_OR_OFFLINE;
  259. result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
  260. statusCode = HttpStatusCode.BadRequest;
  261. return Request.CreateResponse(statusCode, result);
  262. }
  263. InternalHttpClient _client = new InternalHttpClient();
  264. CustomerService _customer = new CustomerService();
  265. string[] parts = Request.RequestUri.ToString().Split('/');
  266. string urlformat = "{0}//{1}/api/v1/ocpp16/reservation?ChargeBoxId={2}";
  267. var _innerRequest = new ReserveRequest()
  268. {
  269. ConnectorId = request.ConnectorId,
  270. IdTag = request.Token,
  271. ReservationId = request.ReservationId,
  272. ExpiryDate = request.ExpiryDate.ToString(EVCBConfiguration.UTC_DATETIMEFORMAT)
  273. };
  274. var _innerResult = await _client.Post(string.Format(urlformat, Request.RequestUri.Port, request.ChargeBoxId), new Dictionary<string, string>()
  275. {
  276. { "PartnerId",_CustomerId}
  277. }, _innerRequest, _customer.GetAPIKey(new Guid(_CustomerId)));
  278. _innerData = new { Result = string.IsNullOrEmpty(_innerResult.SerialNo) ? CommandResponseType.Rejected.ToString() : CommandResponseType.Accepted.ToString(), Timeout = 60 };
  279. result = GetErrorDescription(_innerResult);
  280. result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
  281. if (_innerResult.Success)
  282. {
  283. result.SerialNo = _innerResult.SerialNo;
  284. result.StatusCode = (int)CPO_StatusCode.Success;
  285. result.StatusMessage = CPO_StatusMessage.Success;
  286. statusCode = HttpStatusCode.OK;
  287. }
  288. else
  289. {
  290. result.StatusCode = _innerResult.ErrorCode;
  291. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
  292. statusCode = HttpStatusCode.BadRequest;
  293. }
  294. }
  295. catch (Exception ex)
  296. {
  297. result.ErrorDetail = ex.ToString();
  298. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
  299. result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
  300. return Request.CreateResponse(statusCode, result);
  301. }
  302. return Request.CreateResponse(statusCode, result);
  303. }
  304. [Route("commands/cancel_reservation")]
  305. [ResponseType(typeof(CPOOuterResponse))]
  306. [HttpPost]
  307. async public Task<HttpResponseMessage> CancelReservation(string ChargeBoxId, int ReservationId)
  308. {
  309. var result = new CPOOuterResponse();
  310. HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
  311. var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
  312. try
  313. {
  314. string _CustomerId = string.Empty;
  315. if (!ContainsChargePoint(ChargeBoxId, out _CustomerId))
  316. {
  317. // 沒槍~ 沒得充...
  318. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CHARGEBOXID_DOESNT_EXIST;
  319. result.StatusCode = (int)CPO_StatusCode.CHARGEBOXID_ISNT_EXIST_OR_OFFLINE;
  320. result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
  321. statusCode = HttpStatusCode.BadRequest;
  322. return Request.CreateResponse(statusCode, result);
  323. }
  324. InternalHttpClient _client = new InternalHttpClient();
  325. CustomerService _customer = new CustomerService();
  326. string[] parts = Request.RequestUri.ToString().Split('/');
  327. string urlformat = "{0}//{1}/api/v1/ocpp16/reservation?ChargeBoxId={2}&ReservationId={3}";
  328. var _innerResult = await _client.Delete(string.Format(urlformat, Request.RequestUri.Port, ChargeBoxId, ReservationId), new Dictionary<string, string>()
  329. {
  330. { "PartnerId",_CustomerId}
  331. }, _customer.GetAPIKey(new Guid(_CustomerId)));
  332. _innerData = new { Result = string.IsNullOrEmpty(_innerResult.SerialNo) ? CommandResponseType.Rejected.ToString() : CommandResponseType.Accepted.ToString(), Timeout = 60 };
  333. result = GetErrorDescription(_innerResult);
  334. result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
  335. if (_innerResult.Success)
  336. {
  337. result.SerialNo = _innerResult.SerialNo;
  338. result.StatusCode = (int)CPO_StatusCode.Success;
  339. result.StatusMessage = CPO_StatusMessage.Success;
  340. statusCode = HttpStatusCode.OK;
  341. }
  342. else
  343. {
  344. result.StatusCode = _innerResult.ErrorCode;
  345. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
  346. statusCode = HttpStatusCode.BadRequest;
  347. }
  348. }
  349. catch (Exception ex)
  350. {
  351. result.ErrorDetail = ex.ToString();
  352. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
  353. result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
  354. return Request.CreateResponse(statusCode, result);
  355. }
  356. return Request.CreateResponse(statusCode, result);
  357. }
  358. [Route("commands/chargingporfiles")]
  359. [ResponseType(typeof(CPOOuterResponse))]
  360. [HttpGet]
  361. async public Task<HttpResponseMessage> GetActiveChargingPorfile(string ChargeBoxId, int ConnectorId, int Duration)
  362. {
  363. var result = new CPOOuterResponse();
  364. HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
  365. var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
  366. try
  367. {
  368. string _CustomerId = string.Empty;
  369. if (!ContainsChargePoint(ChargeBoxId, out _CustomerId))
  370. {
  371. // 沒槍~ 沒得充...
  372. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CHARGEBOXID_DOESNT_EXIST;
  373. result.StatusCode = (int)CPO_StatusCode.CHARGEBOXID_ISNT_EXIST_OR_OFFLINE;
  374. result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
  375. statusCode = HttpStatusCode.BadRequest;
  376. return Request.CreateResponse(statusCode, result);
  377. }
  378. InternalHttpClient _client = new InternalHttpClient();
  379. CustomerService _customer = new CustomerService();
  380. string[] parts = Request.RequestUri.ToString().Split('/');
  381. string urlformat = "{0}//{1}/api/v1/ocpp16/compositeschedule?ChargeBoxId={2}&ConnectorId={3}&Duration={4}";
  382. var _innerResult = await _client.Get(string.Format(urlformat, Request.RequestUri.Port, ChargeBoxId, ConnectorId, Duration), new Dictionary<string, string>()
  383. {
  384. { "PartnerId",_CustomerId}
  385. }, _customer.GetAPIKey(new Guid(_CustomerId)));
  386. _innerData = new { Result = string.IsNullOrEmpty(_innerResult.SerialNo) ? CommandResponseType.Rejected.ToString() : CommandResponseType.Accepted.ToString(), Timeout = 60 };
  387. result = GetErrorDescription(_innerResult);
  388. result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
  389. if (_innerResult.Success)
  390. {
  391. result.SerialNo = _innerResult.SerialNo;
  392. result.StatusCode = (int)CPO_StatusCode.Success;
  393. result.StatusMessage = CPO_StatusMessage.Success;
  394. statusCode = HttpStatusCode.OK;
  395. }
  396. else
  397. {
  398. result.StatusCode = _innerResult.ErrorCode;
  399. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
  400. statusCode = HttpStatusCode.BadRequest;
  401. }
  402. }
  403. catch (Exception ex)
  404. {
  405. result.ErrorDetail = ex.ToString();
  406. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
  407. result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
  408. return Request.CreateResponse(statusCode, result);
  409. }
  410. return Request.CreateResponse(statusCode, result);
  411. }
  412. [Route("commands/chargingporfiles")]
  413. [ResponseType(typeof(CPOOuterResponse))]
  414. [HttpPut]
  415. async public Task<HttpResponseMessage> SetChargingProfile(string ChargeBoxId, [FromBody] ChargingProfileRequest request)
  416. {
  417. var result = new CPOOuterResponse();
  418. HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
  419. var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
  420. try
  421. {
  422. string _CustomerId = string.Empty;
  423. if (!ContainsChargePoint(ChargeBoxId, out _CustomerId))
  424. {
  425. // 沒槍~ 沒得充...
  426. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CHARGEBOXID_DOESNT_EXIST;
  427. result.StatusCode = (int)CPO_StatusCode.CHARGEBOXID_ISNT_EXIST_OR_OFFLINE;
  428. result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
  429. statusCode = HttpStatusCode.BadRequest;
  430. return Request.CreateResponse(statusCode, result);
  431. }
  432. InternalHttpClient _client = new InternalHttpClient();
  433. CustomerService _customer = new CustomerService();
  434. string[] parts = Request.RequestUri.ToString().Split('/');
  435. string urlformat = "{0}//{1}/api/v1/ocpp16/chargingprofile?ChargeBoxId={2}";
  436. var _innerResult = await _client.Post(string.Format(urlformat, Request.RequestUri.Port, ChargeBoxId), new Dictionary<string, string>()
  437. {
  438. { "PartnerId",_CustomerId}
  439. }, request, _customer.GetAPIKey(new Guid(_CustomerId)));
  440. _innerData = new { Result = string.IsNullOrEmpty(_innerResult.SerialNo) ? CommandResponseType.Rejected.ToString() : CommandResponseType.Accepted.ToString(), Timeout = 60 };
  441. result = GetErrorDescription(_innerResult);
  442. result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
  443. if (_innerResult.Success)
  444. {
  445. result.SerialNo = _innerResult.SerialNo;
  446. result.StatusCode = (int)CPO_StatusCode.Success;
  447. result.StatusMessage = CPO_StatusMessage.Success;
  448. statusCode = HttpStatusCode.OK;
  449. }
  450. else
  451. {
  452. result.StatusCode = _innerResult.ErrorCode;
  453. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
  454. statusCode = HttpStatusCode.BadRequest;
  455. }
  456. }
  457. catch (Exception ex)
  458. {
  459. result.ErrorDetail = ex.ToString();
  460. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
  461. result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
  462. return Request.CreateResponse(statusCode, result);
  463. }
  464. return Request.CreateResponse(statusCode, result);
  465. }
  466. [Route("commands/chargingporfiles")]
  467. [ResponseType(typeof(CPOOuterResponse))]
  468. [HttpDelete]
  469. async public Task<HttpResponseMessage> ClearChargingPorfile(string ChargeBoxId, int ChargeProfileId = -1)
  470. {
  471. var result = new CPOOuterResponse();
  472. HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
  473. var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
  474. try
  475. {
  476. string _CustomerId = string.Empty;
  477. if (!ContainsChargePoint(ChargeBoxId, out _CustomerId))
  478. {
  479. // 沒槍~ 沒得充...
  480. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CHARGEBOXID_DOESNT_EXIST;
  481. result.StatusCode = (int)CPO_StatusCode.CHARGEBOXID_ISNT_EXIST_OR_OFFLINE;
  482. result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
  483. statusCode = HttpStatusCode.BadRequest;
  484. return Request.CreateResponse(statusCode, result);
  485. }
  486. InternalHttpClient _client = new InternalHttpClient();
  487. CustomerService _customer = new CustomerService();
  488. string[] parts = Request.RequestUri.ToString().Split('/');
  489. string urlformat = "{0}//{1}/api/v1/ocpp16/chargingprofile?ChargeBoxId={2}{3}";
  490. var _innerResult = await _client.Delete(string.Format(urlformat, Request.RequestUri.Port, ChargeBoxId, ChargeProfileId == -1 ? "" : "&Id=" + ChargeProfileId), new Dictionary<string, string>()
  491. {
  492. { "PartnerId",_CustomerId}
  493. }, _customer.GetAPIKey(new Guid(_CustomerId)));
  494. _innerData = new { Result = string.IsNullOrEmpty(_innerResult.SerialNo) ? CommandResponseType.Rejected.ToString() : CommandResponseType.Accepted.ToString(), Timeout = 60 };
  495. result = GetErrorDescription(_innerResult);
  496. result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
  497. if (_innerResult.Success)
  498. {
  499. result.SerialNo = _innerResult.SerialNo;
  500. result.StatusCode = (int)CPO_StatusCode.Success;
  501. result.StatusMessage = CPO_StatusMessage.Success;
  502. statusCode = HttpStatusCode.OK;
  503. }
  504. else
  505. {
  506. result.StatusCode = _innerResult.ErrorCode;
  507. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
  508. statusCode = HttpStatusCode.BadRequest;
  509. }
  510. }
  511. catch (Exception ex)
  512. {
  513. result.ErrorDetail = ex.ToString();
  514. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
  515. result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
  516. return Request.CreateResponse(statusCode, result);
  517. }
  518. return Request.CreateResponse(statusCode, result);
  519. }
  520. [Route("commands/set_locallist")]
  521. [ResponseType(typeof(CPOOuterResponse))]
  522. [HttpPost]
  523. async public Task<HttpResponseMessage> SendLocalList(string ChargeBoxId, [FromBody] LocalListRequest request)
  524. {
  525. var result = new CPOOuterResponse();
  526. HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
  527. var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
  528. try
  529. {
  530. string _CustomerId = string.Empty;
  531. if (!ContainsChargePoint(ChargeBoxId, out _CustomerId))
  532. {
  533. // 沒槍~ 沒得充...
  534. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CHARGEBOXID_DOESNT_EXIST;
  535. result.StatusCode = (int)CPO_StatusCode.CHARGEBOXID_ISNT_EXIST_OR_OFFLINE;
  536. result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
  537. statusCode = HttpStatusCode.BadRequest;
  538. return Request.CreateResponse(statusCode, result);
  539. }
  540. InternalHttpClient _client = new InternalHttpClient();
  541. CustomerService _customer = new CustomerService();
  542. string[] parts = Request.RequestUri.ToString().Split('/');
  543. string urlformat = "{0}//{1}/api/v1/ocpp16/locallist?ChargeBoxId={2}";
  544. var _innerResult = await _client.Post(string.Format(urlformat, Request.RequestUri.Port, ChargeBoxId), new Dictionary<string, string>()
  545. {
  546. { "PartnerId",_CustomerId}
  547. }, request, _customer.GetAPIKey(new Guid(_CustomerId)));
  548. _innerData = new { Result = string.IsNullOrEmpty(_innerResult.SerialNo) ? CommandResponseType.Rejected.ToString() : CommandResponseType.Accepted.ToString(), Timeout = 60 };
  549. result = GetErrorDescription(_innerResult);
  550. result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
  551. if (_innerResult.Success)
  552. {
  553. result.SerialNo = _innerResult.SerialNo;
  554. result.StatusCode = (int)CPO_StatusCode.Success;
  555. result.StatusMessage = CPO_StatusMessage.Success;
  556. statusCode = HttpStatusCode.OK;
  557. }
  558. else
  559. {
  560. result.StatusCode = _innerResult.ErrorCode;
  561. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
  562. statusCode = HttpStatusCode.BadRequest;
  563. }
  564. }
  565. catch (Exception ex)
  566. {
  567. result.ErrorDetail = ex.ToString();
  568. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
  569. result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
  570. return Request.CreateResponse(statusCode, result);
  571. }
  572. return Request.CreateResponse(statusCode, result);
  573. }
  574. [Route("commands/locallistversion")]
  575. [ResponseType(typeof(CPOOuterResponse))]
  576. [HttpGet]
  577. async public Task<HttpResponseMessage> GetLocalListVersion(string ChargeBoxId)
  578. {
  579. var result = new CPOOuterResponse();
  580. HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
  581. var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
  582. try
  583. {
  584. string _CustomerId = string.Empty;
  585. if (!ContainsChargePoint(ChargeBoxId, out _CustomerId))
  586. {
  587. // 沒槍~ 沒得充...
  588. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CHARGEBOXID_DOESNT_EXIST;
  589. result.StatusCode = (int)CPO_StatusCode.CHARGEBOXID_ISNT_EXIST_OR_OFFLINE;
  590. result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
  591. statusCode = HttpStatusCode.BadRequest;
  592. return Request.CreateResponse(statusCode, result);
  593. }
  594. InternalHttpClient _client = new InternalHttpClient();
  595. CustomerService _customer = new CustomerService();
  596. string[] parts = Request.RequestUri.ToString().Split('/');
  597. string urlformat = "{0}//{1}/api/v1/ocpp16/locallistversion?ChargeBoxId={2}";
  598. var _innerResult = await _client.Get(string.Format(urlformat, Request.RequestUri.Port, ChargeBoxId), new Dictionary<string, string>()
  599. {
  600. { "PartnerId",_CustomerId}
  601. }, _customer.GetAPIKey(new Guid(_CustomerId)));
  602. _innerData = new { Result = string.IsNullOrEmpty(_innerResult.SerialNo) ? CommandResponseType.Rejected.ToString() : CommandResponseType.Accepted.ToString(), Timeout = 60 };
  603. result = GetErrorDescription(_innerResult);
  604. result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
  605. if (_innerResult.Success)
  606. {
  607. result.SerialNo = _innerResult.SerialNo;
  608. result.StatusCode = (int)CPO_StatusCode.Success;
  609. result.StatusMessage = CPO_StatusMessage.Success;
  610. statusCode = HttpStatusCode.OK;
  611. }
  612. else
  613. {
  614. result.StatusCode = _innerResult.ErrorCode;
  615. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
  616. statusCode = HttpStatusCode.BadRequest;
  617. }
  618. statusCode = HttpStatusCode.OK;
  619. }
  620. catch (Exception ex)
  621. {
  622. result.ErrorDetail = ex.ToString();
  623. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
  624. result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
  625. return Request.CreateResponse(statusCode, result);
  626. }
  627. return Request.CreateResponse(statusCode, result);
  628. }
  629. [Route("commands/results")]
  630. [ResponseType(typeof(CPOOuterResponse))]
  631. [HttpGet]
  632. async public Task<HttpResponseMessage> ExecutionofCmdSearch(string ChargeBoxId, CommandType? commandType, string SerialNo)
  633. {
  634. var result = new CPOOuterResponse();
  635. HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
  636. try
  637. {
  638. string _CustomerId = string.Empty;
  639. if (!ContainsChargePoint(ChargeBoxId, out _CustomerId))
  640. {
  641. // 沒槍~ 沒得充...
  642. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CHARGEBOXID_DOESNT_EXIST;
  643. result.StatusCode = (int)CPO_StatusCode.CHARGEBOXID_ISNT_EXIST_OR_OFFLINE;
  644. statusCode = HttpStatusCode.BadRequest;
  645. return Request.CreateResponse(statusCode, result);
  646. }
  647. InternalHttpClient _client = new InternalHttpClient();
  648. CustomerService _customer = new CustomerService();
  649. int? orderNo = (int?)null;
  650. switch (commandType.Value)
  651. {
  652. case CommandType.CancelReservation:
  653. {
  654. orderNo = 4;
  655. }
  656. break;
  657. case CommandType.ClearChargingProfile:
  658. {
  659. orderNo = 6;
  660. }
  661. break;
  662. case CommandType.GetAcitveChargingProfile:
  663. {
  664. orderNo = 7;
  665. }
  666. break;
  667. case CommandType.GetLocalListVersion:
  668. {
  669. orderNo = 9;
  670. }
  671. break;
  672. case CommandType.Start_Session:
  673. {
  674. orderNo = 10;
  675. }
  676. break;
  677. case CommandType.Stop_Session:
  678. {
  679. orderNo = 11;
  680. }
  681. break;
  682. case CommandType.Reserve_Now:
  683. {
  684. orderNo = 12;
  685. }
  686. break;
  687. case CommandType.SetLocalList:
  688. {
  689. orderNo = 14;
  690. }
  691. break;
  692. case CommandType.SetChargingProfile:
  693. {
  694. orderNo = 15;
  695. }
  696. break;
  697. default:
  698. break;
  699. }
  700. string[] parts = Request.RequestUri.ToString().Split('/');
  701. string urlformat = "{0}//{1}/api/v1/ocpp16/command?ChargeBoxId={2}{3}&SerialNo={4}";
  702. var _innerResult = await _client.Get(string.Format(urlformat, Request.RequestUri.Port, ChargeBoxId, orderNo.HasValue ? "&OrderNo=" + orderNo.Value : "", SerialNo), new Dictionary<string, string>()
  703. {
  704. { "PartnerId",_CustomerId}
  705. }, _customer.GetAPIKey(new Guid(_CustomerId)));
  706. result = GetErrorDescription(_innerResult);
  707. if (_innerResult.Success)
  708. {
  709. ComandExecution _execution = JsonConvert.DeserializeObject<ComandExecution>(_innerResult.Message);
  710. CommandResultType? _cmdResult = (CommandResultType?)null;
  711. switch (_execution.Code)
  712. {
  713. case 1:
  714. {
  715. _cmdResult = CommandResultType.Accepted;
  716. }
  717. break;
  718. case 9:
  719. {
  720. _cmdResult = CommandResultType.Notsupported;
  721. }
  722. break;
  723. case 10:
  724. {
  725. _cmdResult = CommandResultType.Unknown;
  726. }
  727. break;
  728. case 26:
  729. {
  730. _cmdResult = CommandResultType.Occupied;
  731. }
  732. break;
  733. case 31:
  734. {
  735. _cmdResult = CommandResultType.Rejected;
  736. }
  737. break;
  738. case 32:
  739. {
  740. _cmdResult = CommandResultType.Failed;
  741. }
  742. break;
  743. case 254:
  744. {
  745. _cmdResult = CommandResultType.EVSE_ERROR;
  746. }
  747. break;
  748. default:
  749. {
  750. if (_execution.Detail == "Timeout") _cmdResult = CommandResultType.Timeout;
  751. if (_execution.Detail == "Waited") _cmdResult = CommandResultType.Waited;
  752. }
  753. break;
  754. }
  755. if (!_cmdResult.HasValue)
  756. {
  757. result.StatusCode = (int)CPO_StatusCode.CANT_FOUND_DATA;
  758. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CANT_FIND_RESULT;
  759. statusCode = HttpStatusCode.NotFound;
  760. }
  761. else
  762. {
  763. var _innerData = new { Result = _cmdResult.Value.ToString(), Message = _execution.Detail };
  764. result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
  765. result.SerialNo = _innerResult.SerialNo;
  766. result.StatusCode = (int)CPO_StatusCode.Success;
  767. result.StatusMessage = CPO_StatusMessage.Success;
  768. statusCode = HttpStatusCode.OK;
  769. }
  770. }
  771. }
  772. catch (Exception ex)
  773. {
  774. result.ErrorDetail = ex.ToString();
  775. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
  776. result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
  777. return Request.CreateResponse(statusCode, result);
  778. }
  779. return Request.CreateResponse(statusCode, result);
  780. }
  781. [Route("version")]
  782. [ResponseType(typeof(CPOOuterResponse))]
  783. [HttpGet]
  784. public HttpResponseMessage Version(string ChargeBoxId)
  785. {
  786. var result = new CPOOuterResponse();
  787. HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
  788. try
  789. {
  790. ChargePointService _service = new ChargePointService();
  791. string version = _service.GetVersionbyChargeBoxId(ChargeBoxId);
  792. result.Data = version;
  793. result.StatusCode = (int)CPO_StatusCode.Success;
  794. result.StatusMessage = CPO_StatusMessage.Success;
  795. statusCode = HttpStatusCode.OK;
  796. }
  797. catch (Exception ex)
  798. {
  799. result.ErrorDetail = ex.ToString();
  800. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
  801. result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
  802. return Request.CreateResponse(statusCode, result);
  803. }
  804. return Request.CreateResponse(statusCode, result);
  805. }
  806. [Route("activesession")]
  807. [ResponseType(typeof(CPOOuterResponse))]
  808. [HttpGet]
  809. public HttpResponseMessage ActiveSession(string ChargeBoxId, string SessionId = "", string IdTag = "")
  810. {
  811. var result = new CPOOuterResponse();
  812. HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
  813. try
  814. {
  815. string _CustomerId = string.Empty;
  816. if (!ContainsChargePoint(ChargeBoxId, out _CustomerId))
  817. {
  818. // 沒槍~ 沒得充...
  819. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CHARGEBOXID_DOESNT_EXIST;
  820. result.StatusCode = (int)CPO_StatusCode.CHARGEBOXID_ISNT_EXIST_OR_OFFLINE;
  821. statusCode = HttpStatusCode.BadRequest;
  822. return Request.CreateResponse(statusCode, result);
  823. }
  824. // query meter value
  825. ChargePointService _service = new ChargePointService();
  826. var transactionDatas = _service.GetActiveSessionInfo(ChargeBoxId, new List<Packet.Messages.SubTypes.Measurand>()
  827. { Packet.Messages.SubTypes.Measurand.Voltage,
  828. Packet.Messages.SubTypes.Measurand.Current_Import,
  829. Packet.Messages.SubTypes.Measurand.SoC,
  830. Packet.Messages.SubTypes.Measurand.Power_Active_Import,
  831. Packet.Messages.SubTypes.Measurand.Energy_Active_Import_Interval
  832. }, SessionId, IdTag);
  833. if (transactionDatas == null)
  834. {
  835. result.StatusCode = (int)CPO_StatusCode.CANT_FOUND_DATA;
  836. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CANT_FIND_RESULT;
  837. statusCode = HttpStatusCode.NotFound;
  838. }
  839. else
  840. {
  841. List<ActiveSession> _innerData = new List<ActiveSession>();
  842. foreach (var transactionData in transactionDatas)
  843. {
  844. _innerData.Add(new ActiveSession()
  845. {
  846. ChargeBoxId = ChargeBoxId,
  847. SessionId = transactionData.Id,
  848. ElaspedTime = (int)DateTime.UtcNow.Subtract(transactionData.StartTime).TotalMinutes,
  849. ConnectorId = transactionData.ConnectorId,
  850. IdTag = transactionData.StartIdTag,
  851. Power = transactionData.MeterValues==null? "0":transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Power_Active_Import).Select(x => x.Value).FirstOrDefault(),
  852. Power_Format = transactionData.MeterValues == null ? UnitOfMeasure.W.ToString() : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Power_Active_Import).Select(x => x.Unit.ToString()).FirstOrDefault(),
  853. Current = transactionData.MeterValues == null ? "0" : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Current_Import).Select(x => x.Value).FirstOrDefault(),
  854. Current_Format = transactionData.MeterValues == null ? UnitOfMeasure.A.ToString() : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Current_Import).Select(x => x.Unit.ToString()).FirstOrDefault(),
  855. Energy = transactionData.MeterValues == null ? "0" : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Energy_Active_Import_Interval).Select(x => x.Value).FirstOrDefault(),
  856. Energy_Format = transactionData.MeterValues == null ? UnitOfMeasure.Wh.ToString() : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Energy_Active_Import_Interval).Select(x => x.Unit.ToString()).FirstOrDefault(),
  857. Voltage = transactionData.MeterValues == null ? "0" : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Voltage).Select(x => x.Value).FirstOrDefault(),
  858. Voltage_Format = transactionData.MeterValues == null ? UnitOfMeasure.V.ToString() : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.Voltage).Select(x => x.Unit.ToString()).FirstOrDefault(),
  859. SOC = transactionData.MeterValues == null ? "0" : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.SoC).Select(x => x.Unit.ToString()).FirstOrDefault() == null ? null : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.SoC).Select(x => x.Value).FirstOrDefault(),
  860. SOC_Format = transactionData.MeterValues == null ? UnitOfMeasure.Percent.ToString() : transactionData.MeterValues.Where(x => x.Measurand == Packet.Messages.SubTypes.Measurand.SoC).Select(x => x.Unit.ToString()).FirstOrDefault(),
  861. });
  862. }
  863. result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
  864. result.StatusCode = (int)CPO_StatusCode.Success;
  865. result.StatusMessage = CPO_StatusMessage.Success;
  866. statusCode = HttpStatusCode.OK;
  867. }
  868. return Request.CreateResponse(statusCode, result);
  869. }
  870. catch (Exception ex)
  871. {
  872. result.ErrorDetail = ex.ToString();
  873. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
  874. result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
  875. return Request.CreateResponse(statusCode, result);
  876. }
  877. }
  878. [Route("completedsession")]
  879. [ResponseType(typeof(CPOOuterResponse))]
  880. [HttpGet]
  881. public HttpResponseMessage CompletedSession(string ChargeBoxId, string SessionId = "", string IdTag = "",string StartTime="", string StopTime = "")
  882. {
  883. var result = new CPOOuterResponse();
  884. HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
  885. try
  886. {
  887. string _CustomerId = string.Empty;
  888. if (!ContainsChargePoint(ChargeBoxId, out _CustomerId))
  889. {
  890. // 沒槍~ 沒得充...
  891. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CHARGEBOXID_DOESNT_EXIST;
  892. result.StatusCode = (int)CPO_StatusCode.CHARGEBOXID_ISNT_EXIST_OR_OFFLINE;
  893. statusCode = HttpStatusCode.BadRequest;
  894. return Request.CreateResponse(statusCode, result);
  895. }
  896. DateTime startDt = string.IsNullOrEmpty(StartTime) ?new DateTime(1991,1,1):DateTime.Parse(StartTime);
  897. DateTime stopDt = string.IsNullOrEmpty(StopTime) ? new DateTime(1991, 1, 1) : DateTime.Parse(StopTime);
  898. // query meter value
  899. ChargePointService _service = new ChargePointService();
  900. var _innerData = _service.GetSessionDetail(ChargeBoxId, SessionId, IdTag, startDt, stopDt);
  901. if (_innerData == null)
  902. {
  903. result.StatusCode = (int)CPO_StatusCode.CANT_FOUND_DATA;
  904. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CANT_FIND_SESSIONDETAIL;
  905. statusCode = HttpStatusCode.NotFound;
  906. return Request.CreateResponse(statusCode, result);
  907. }
  908. result.Data = JsonConvert.SerializeObject(_innerData, EVCBConfiguration.JSONSERIALIZER_FORMAT);
  909. result.StatusCode = (int)CPO_StatusCode.Success;
  910. result.StatusMessage = CPO_StatusMessage.Success;
  911. statusCode = HttpStatusCode.OK;
  912. return Request.CreateResponse(statusCode, result);
  913. }
  914. catch (Exception ex)
  915. {
  916. result.ErrorDetail = ex.ToString();
  917. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
  918. result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
  919. return Request.CreateResponse(statusCode, result);
  920. }
  921. }
  922. [Route("statistics/charging_sessions")]
  923. [ResponseType(typeof(CPOOuterResponse))]
  924. [HttpPost]
  925. async public Task<HttpResponseMessage> ChargingSessionsStatistics([FromBody] StatisticsRequest request)
  926. {
  927. var result = new CPOOuterResponse();
  928. HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
  929. var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
  930. try
  931. {
  932. InternalHttpClient _client = new InternalHttpClient();
  933. CustomerService _customer = new CustomerService();
  934. string url = System.Web.Configuration.WebConfigurationManager.AppSettings["StatisticsAPI"] + 1;
  935. string chargeBoxIds = GetStatisticChargeBoxIds(request.ChargeBoxIds);
  936. HttpClientService service = new HttpClientService();
  937. Dictionary<string, string> postData = new Dictionary<string, string>()
  938. {
  939. { "ChargeBoxId", chargeBoxIds },
  940. { "Type", request.Type.ToString() },
  941. { "StartDate",request.DateFrom.ToString(EVCBConfiguration.DATETIMEFORMAT)},
  942. { "EndDate",request.DateTo.ToString(EVCBConfiguration.DATETIMEFORMAT)}
  943. };
  944. var _innerresult = await service.PostFormDataAsync(url, postData, null);
  945. if (_innerresult.StatusCode == HttpStatusCode.OK)
  946. {
  947. _innerresult.Response = _innerresult.Response.Replace("item", "Title");
  948. _innerresult.Response = _innerresult.Response.Replace("Data", "Count");
  949. result.Data = _innerresult.Response;
  950. result.StatusCode = (int)CPO_StatusCode.Success;
  951. result.StatusMessage = CPO_StatusMessage.Success;
  952. statusCode = HttpStatusCode.OK;
  953. }
  954. else
  955. {
  956. result.StatusCode = (int)CPO_StatusCode.CANT_FOUND_DATA;
  957. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
  958. statusCode = HttpStatusCode.BadRequest;
  959. }
  960. }
  961. catch (Exception ex)
  962. {
  963. result.ErrorDetail = ex.ToString();
  964. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
  965. result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
  966. return Request.CreateResponse(statusCode, result);
  967. }
  968. return Request.CreateResponse(statusCode, result);
  969. }
  970. [Route("statistics/energy_delivered")]
  971. [ResponseType(typeof(CPOOuterResponse))]
  972. [HttpPost]
  973. async public Task<HttpResponseMessage> Energy_Delivered([FromBody] StatisticsRequest request)
  974. {
  975. var result = new CPOOuterResponse();
  976. HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
  977. var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
  978. try
  979. {
  980. InternalHttpClient _client = new InternalHttpClient();
  981. CustomerService _customer = new CustomerService();
  982. string url = System.Web.Configuration.WebConfigurationManager.AppSettings["StatisticsAPI"] + 2;
  983. string chargeBoxIds = GetStatisticChargeBoxIds(request.ChargeBoxIds);
  984. HttpClientService service = new HttpClientService();
  985. Dictionary<string, string> postData = new Dictionary<string, string>()
  986. {
  987. { "ChargeBoxId",chargeBoxIds },
  988. { "Type", request.Type.ToString() },
  989. { "StartDate",request.DateFrom.ToString(EVCBConfiguration.DATETIMEFORMAT)},
  990. { "EndDate",request.DateTo.ToString(EVCBConfiguration.DATETIMEFORMAT)}
  991. };
  992. var _innerresult = await service.PostFormDataAsync(url, postData, null);
  993. if (_innerresult.StatusCode == HttpStatusCode.OK)
  994. {
  995. _innerresult.Response = _innerresult.Response.Replace("item", "Title");
  996. _innerresult.Response = _innerresult.Response.Replace("Data", "DeliveredEnergy");
  997. result.Data = _innerresult.Response;
  998. result.StatusCode = (int)CPO_StatusCode.Success;
  999. result.StatusMessage = CPO_StatusMessage.Success;
  1000. statusCode = HttpStatusCode.OK;
  1001. }
  1002. else
  1003. {
  1004. result.StatusCode = (int)CPO_StatusCode.CANT_FOUND_DATA;
  1005. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
  1006. statusCode = HttpStatusCode.BadRequest;
  1007. }
  1008. }
  1009. catch (Exception ex)
  1010. {
  1011. result.ErrorDetail = ex.ToString();
  1012. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
  1013. result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
  1014. return Request.CreateResponse(statusCode, result);
  1015. }
  1016. return Request.CreateResponse(statusCode, result);
  1017. }
  1018. [Route("statistics/time_of_use")]
  1019. [ResponseType(typeof(CPOOuterResponse))]
  1020. [HttpPost]
  1021. async public Task<HttpResponseMessage> Time_of_Use([FromBody] StatisticsRequest request)
  1022. {
  1023. var result = new CPOOuterResponse();
  1024. HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
  1025. var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
  1026. try
  1027. {
  1028. InternalHttpClient _client = new InternalHttpClient();
  1029. CustomerService _customer = new CustomerService();
  1030. string url = System.Web.Configuration.WebConfigurationManager.AppSettings["StatisticsAPI"] + 3;
  1031. string chargeBoxIds = GetStatisticChargeBoxIds(request.ChargeBoxIds);
  1032. HttpClientService service = new HttpClientService();
  1033. Dictionary<string, string> postData = new Dictionary<string, string>()
  1034. {
  1035. { "ChargeBoxId",chargeBoxIds },
  1036. { "StartDate",request.DateFrom.ToString(EVCBConfiguration.DATETIMEFORMAT)},
  1037. { "EndDate",request.DateTo.ToString(EVCBConfiguration.DATETIMEFORMAT)}
  1038. };
  1039. var _innerresult = await service.PostFormDataAsync(url, postData, null);
  1040. if (_innerresult.StatusCode == HttpStatusCode.OK)
  1041. {
  1042. _innerresult.Response = _innerresult.Response.Replace("item", "Title");
  1043. _innerresult.Response = _innerresult.Response.Replace("data", "Count");
  1044. _innerresult.Response = _innerresult.Response.Replace("data2", "DeliveredEnergy");
  1045. result.Data = _innerresult.Response;
  1046. result.StatusCode = (int)CPO_StatusCode.Success;
  1047. result.StatusMessage = CPO_StatusMessage.Success;
  1048. statusCode = HttpStatusCode.OK;
  1049. }
  1050. else
  1051. {
  1052. result.StatusCode = (int)CPO_StatusCode.CANT_FOUND_DATA;
  1053. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
  1054. statusCode = HttpStatusCode.BadRequest;
  1055. }
  1056. }
  1057. catch (Exception ex)
  1058. {
  1059. result.ErrorDetail = ex.ToString();
  1060. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
  1061. result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
  1062. return Request.CreateResponse(statusCode, result);
  1063. }
  1064. return Request.CreateResponse(statusCode, result);
  1065. }
  1066. [Route("statistics/peak_load")]
  1067. [ResponseType(typeof(CPOOuterResponse))]
  1068. [HttpPost]
  1069. async public Task<HttpResponseMessage> Peak_Load([FromBody] StatisticsRequest request)
  1070. {
  1071. var result = new CPOOuterResponse();
  1072. HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
  1073. var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
  1074. try
  1075. {
  1076. InternalHttpClient _client = new InternalHttpClient();
  1077. CustomerService _customer = new CustomerService();
  1078. string url = System.Web.Configuration.WebConfigurationManager.AppSettings["StatisticsAPI"] + 4;
  1079. string chargeBoxIds = GetStatisticChargeBoxIds(request.ChargeBoxIds);
  1080. HttpClientService service = new HttpClientService();
  1081. Dictionary<string, string> postData = new Dictionary<string, string>()
  1082. {
  1083. { "ChargeBoxId", chargeBoxIds },
  1084. { "StartDate",request.DateFrom.ToString(EVCBConfiguration.DATETIMEFORMAT)},
  1085. { "EndDate",request.DateTo.ToString(EVCBConfiguration.DATETIMEFORMAT)}
  1086. };
  1087. var _innerresult = await service.PostFormDataAsync(url, postData, null);
  1088. if (_innerresult.StatusCode == HttpStatusCode.OK)
  1089. {
  1090. _innerresult.Response = _innerresult.Response.Replace("item", "Title");
  1091. _innerresult.Response = _innerresult.Response.Replace("data", "DeliveredEnergy");
  1092. result.Data = _innerresult.Response;
  1093. result.StatusCode = (int)CPO_StatusCode.Success;
  1094. result.StatusMessage = CPO_StatusMessage.Success;
  1095. statusCode = HttpStatusCode.OK;
  1096. }
  1097. else
  1098. {
  1099. result.StatusCode = (int)CPO_StatusCode.CANT_FOUND_DATA;
  1100. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
  1101. statusCode = HttpStatusCode.BadRequest;
  1102. }
  1103. }
  1104. catch (Exception ex)
  1105. {
  1106. result.ErrorDetail = ex.ToString();
  1107. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
  1108. result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
  1109. return Request.CreateResponse(statusCode, result);
  1110. }
  1111. return Request.CreateResponse(statusCode, result);
  1112. }
  1113. [Route("statistics/sessions")]
  1114. [ResponseType(typeof(CPOOuterResponse))]
  1115. [HttpPost]
  1116. async public Task<HttpResponseMessage> Sessions([FromBody] StatisticsRequest request)
  1117. {
  1118. var result = new CPOOuterResponse();
  1119. HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
  1120. var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
  1121. try
  1122. {
  1123. InternalHttpClient _client = new InternalHttpClient();
  1124. CustomerService _customer = new CustomerService();
  1125. string url = System.Web.Configuration.WebConfigurationManager.AppSettings["StatisticsAPI"] + 6;
  1126. string chargeBoxIds = GetStatisticChargeBoxIds(request.ChargeBoxIds);
  1127. HttpClientService service = new HttpClientService();
  1128. Dictionary<string, string> postData = new Dictionary<string, string>()
  1129. {
  1130. { "ChargeBoxId", chargeBoxIds },
  1131. { "StartDate",request.DateFrom.ToString(EVCBConfiguration.DATETIMEFORMAT)},
  1132. { "EndDate",request.DateTo.ToString(EVCBConfiguration.DATETIMEFORMAT)}
  1133. };
  1134. var _innerresult = await service.PostFormDataAsync(url, postData, null);
  1135. if (_innerresult.StatusCode == HttpStatusCode.OK)
  1136. {
  1137. string titles = "\"Title\":[\"ChargeBox Id\",\"Connector Id\",\"Session Id\",\"DateFrom\",\"DateTo\",\"Duration(sec)\",\"Energy(kWh)\",\"Stop Reason\"],";
  1138. _innerresult.Response = _innerresult.Response.Replace("data", "Session");
  1139. _innerresult.Response = _innerresult.Response.Insert(1, titles);
  1140. result.Data = _innerresult.Response;
  1141. result.StatusCode = (int)CPO_StatusCode.Success;
  1142. result.StatusMessage = CPO_StatusMessage.Success;
  1143. statusCode = HttpStatusCode.OK;
  1144. }
  1145. else
  1146. {
  1147. result.StatusCode = (int)CPO_StatusCode.CANT_FOUND_DATA;
  1148. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
  1149. statusCode = HttpStatusCode.BadRequest;
  1150. }
  1151. }
  1152. catch (Exception ex)
  1153. {
  1154. result.ErrorDetail = ex.ToString();
  1155. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
  1156. result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
  1157. return Request.CreateResponse(statusCode, result);
  1158. }
  1159. return Request.CreateResponse(statusCode, result);
  1160. }
  1161. [Route("statistics/fault")]
  1162. [ResponseType(typeof(CPOOuterResponse))]
  1163. [HttpPost]
  1164. async public Task<HttpResponseMessage> Fault([FromBody] StatisticsRequest request)
  1165. {
  1166. var result = new CPOOuterResponse();
  1167. HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
  1168. var _innerData = new { Result = CommandResponseType.Rejected.ToString(), Timeout = 60 };
  1169. try
  1170. {
  1171. InternalHttpClient _client = new InternalHttpClient();
  1172. CustomerService _customer = new CustomerService();
  1173. string url = System.Web.Configuration.WebConfigurationManager.AppSettings["StatisticsAPI"] + 5;
  1174. string chargeBoxIds = GetStatisticChargeBoxIds(request.ChargeBoxIds);
  1175. HttpClientService service = new HttpClientService();
  1176. Dictionary<string, string> postData = new Dictionary<string, string>()
  1177. {
  1178. { "ChargeBoxId", chargeBoxIds},
  1179. { "StartDate",request.DateFrom.ToString(EVCBConfiguration.DATETIMEFORMAT)},
  1180. { "EndDate",request.DateTo.ToString(EVCBConfiguration.DATETIMEFORMAT)}
  1181. };
  1182. var _innerresult = await service.PostFormDataAsync(url, postData, null);
  1183. if (_innerresult.StatusCode == HttpStatusCode.OK)
  1184. {
  1185. _innerresult.Response = _innerresult.Response.Replace("item", "Title");
  1186. _innerresult.Response = _innerresult.Response.Replace("data", "Count");
  1187. _innerresult.Response = _innerresult.Response.Replace("data2", "CumulativePercentage");
  1188. result.Data = _innerresult.Response;
  1189. result.StatusCode = (int)CPO_StatusCode.Success;
  1190. result.StatusMessage = CPO_StatusMessage.Success;
  1191. statusCode = HttpStatusCode.OK;
  1192. }
  1193. else
  1194. {
  1195. result.StatusCode = (int)CPO_StatusCode.CANT_FOUND_DATA;
  1196. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_INNERSERVICE_ERROR;
  1197. statusCode = HttpStatusCode.BadRequest;
  1198. }
  1199. }
  1200. catch (Exception ex)
  1201. {
  1202. result.ErrorDetail = ex.ToString();
  1203. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_UNEXPECTEDERROR;
  1204. result.StatusCode = (int)CPO_StatusCode.UnexpectedError;
  1205. return Request.CreateResponse(statusCode, result);
  1206. }
  1207. return Request.CreateResponse(statusCode, result);
  1208. }
  1209. private string GetStatisticChargeBoxIds(List<string> chargeBoxIds)
  1210. {
  1211. string result = JsonConvert.SerializeObject(chargeBoxIds, Formatting.None).Replace("\"", "'");
  1212. result = result.Replace("[", "");
  1213. result = result.Replace("]", "");
  1214. return result;
  1215. }
  1216. private CPOOuterResponse GetErrorDescription(InternalHttpResult innerResponse)
  1217. {
  1218. CPOOuterResponse result = new CPOOuterResponse();
  1219. result.ErrorDetail = innerResponse.Exception == null ? null : innerResponse.Exception.ToString();
  1220. if (innerResponse.Status != HttpStatusCode.Accepted)
  1221. {
  1222. switch (innerResponse.ErrorCode)
  1223. {
  1224. #region Authorization
  1225. case 2000:
  1226. {
  1227. result.StatusCode = innerResponse.ErrorCode;
  1228. result.StatusMessage = string.Format("{0}-{1}", "InnerService", "Authorize Unexpected Error");
  1229. result.ErrorDetail = result.StatusMessage;
  1230. }
  1231. break;
  1232. case 2001:
  1233. case 2002:
  1234. case 2003:
  1235. {
  1236. result.StatusCode = innerResponse.ErrorCode;
  1237. result.StatusMessage = string.Format("{0}-{1}", "InnerService", innerResponse.Message);
  1238. }
  1239. break;
  1240. #endregion
  1241. case 2100:
  1242. case 2101:
  1243. case 2102:
  1244. case 2103:
  1245. case 2104:
  1246. case 2105:
  1247. case 2106:
  1248. {
  1249. result.StatusCode = innerResponse.ErrorCode;
  1250. result.StatusMessage = innerResponse.Message;
  1251. }
  1252. break;
  1253. case 2999:
  1254. {
  1255. result.StatusCode = innerResponse.ErrorCode;
  1256. result.StatusMessage = string.Format("{0}-{1}", "InnerService", "Unexpected Error");
  1257. result.ErrorDetail = result.StatusMessage;
  1258. }
  1259. break;
  1260. default:
  1261. {
  1262. result.StatusCode = 2998;
  1263. result.StatusMessage = CPO_StatusMessage.ERROR_MSG_CANT_FIND_ERRORCODE;
  1264. }
  1265. break;
  1266. }
  1267. }
  1268. return result;
  1269. }
  1270. }
  1271. }