CoreProfileHandler.cs 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695
  1. using Dapper;
  2. using EVCB_OCPP.Domain;
  3. using EVCB_OCPP.Domain.Models.Database;
  4. using EVCB_OCPP.Packet.Features;
  5. using EVCB_OCPP.Packet.Messages;
  6. using EVCB_OCPP.Packet.Messages.Core;
  7. using EVCB_OCPP.Packet.Messages.SubTypes;
  8. using EVCB_OCPP.WSServer.Dto;
  9. using EVCB_OCPP.WSServer.Helper;
  10. using EVCB_OCPP.WSServer.Service;
  11. using Microsoft.Data.SqlClient;
  12. using Microsoft.EntityFrameworkCore;
  13. using Microsoft.Extensions.Configuration;
  14. using Microsoft.Extensions.Logging;
  15. using Newtonsoft.Json;
  16. using Newtonsoft.Json.Linq;
  17. using OCPPServer.Protocol;
  18. using System.Data;
  19. using System.Diagnostics;
  20. using System.Globalization;
  21. using SuperSocket.SocketBase;
  22. namespace EVCB_OCPP.WSServer.Message;
  23. public class ID_CreditDeductResult
  24. {
  25. public int txId { set; get; }
  26. public string creditNo { set; get; }
  27. public bool deductResult { set; get; }
  28. public bool isDonateInvoice { set; get; }
  29. public decimal amount { set; get; }
  30. public string approvalNo { set; get; }
  31. }
  32. public class ID_ReaderStatus
  33. {
  34. public int ConnectorId { set; get; }
  35. public string creditNo { set; get; }
  36. public string SerialNo { set; get; }
  37. public int readerStatus { set; get; }
  38. public string VEMData { set; get; }
  39. public DateTime Timestamp { set; get; }
  40. }
  41. internal partial class ProfileHandler
  42. {
  43. private readonly ILogger logger;
  44. private readonly BlockingTreePrintService blockingTreePrintService;
  45. private readonly GoogleGetTimePrintService googleGetTimePrintService;
  46. private readonly ServerMessageService messageService;
  47. //private readonly string webConnectionString;// = ConfigurationManager.ConnectionStrings[].ConnectionString;
  48. private readonly IDbContextFactory<MainDBContext> maindbContextFactory;
  49. private readonly SqlConnectionFactory<WebDBConetext> webDbConnectionFactory;
  50. private readonly MeterValueDbService meterValueDbService;
  51. //private readonly IDbContextFactory<MeterValueDBContext> metervaluedbContextFactory;
  52. private readonly IBusinessServiceFactory businessServiceFactory;
  53. private readonly IMainDbService mainDbService;
  54. private OuterHttpClient httpClient;
  55. public ProfileHandler(
  56. IConfiguration configuration,
  57. IDbContextFactory<MainDBContext> maindbContextFactory,
  58. SqlConnectionFactory<WebDBConetext> webDbConnectionFactory,
  59. //IDbContextFactory<MeterValueDBContext> metervaluedbContextFactory,
  60. MeterValueDbService meterValueDbService,
  61. IBusinessServiceFactory businessServiceFactory,
  62. IMainDbService mainDbService,
  63. ILogger<ProfileHandler> logger,
  64. BlockingTreePrintService blockingTreePrintService,
  65. GoogleGetTimePrintService googleGetTimePrintService,
  66. ServerMessageService messageService,
  67. OuterHttpClient httpClient)
  68. {
  69. //webConnectionString = configuration.GetConnectionString("WebDBContext");
  70. this.logger = logger;
  71. this.blockingTreePrintService = blockingTreePrintService;
  72. this.googleGetTimePrintService = googleGetTimePrintService;
  73. this.messageService = messageService;
  74. this.maindbContextFactory = maindbContextFactory;
  75. this.webDbConnectionFactory = webDbConnectionFactory;
  76. this.meterValueDbService = meterValueDbService;
  77. this.mainDbService = mainDbService;
  78. //this.metervaluedbContextFactory = metervaluedbContextFactory;
  79. this.businessServiceFactory = businessServiceFactory;
  80. this.httpClient = httpClient;
  81. }
  82. async internal Task<MessageResult> ExecuteCoreRequest(Actions action, ClientData session, IRequest request)
  83. {
  84. Stopwatch watch = new Stopwatch();
  85. //if (action == Actions.Heartbeat || action == Actions.StopTransaction)
  86. //{
  87. // watch.Start();
  88. //}
  89. watch.Start();
  90. MessageResult result = new MessageResult() { Success = false };
  91. try
  92. {
  93. switch (action)
  94. {
  95. case Actions.DataTransfer:
  96. {
  97. DataTransferRequest _request = request as DataTransferRequest;
  98. var confirm = new DataTransferConfirmation() { status = DataTransferStatus.UnknownMessageId };
  99. if (_request.messageId == "ID_CreditDeductResult")
  100. {
  101. var creditDeductResult = JsonConvert.DeserializeObject<ID_CreditDeductResult>(_request.data);
  102. if (session.CustomerId == new Guid("009E603C-79CD-4620-A2B8-D9349C0E8AD8"))
  103. {
  104. var report = new
  105. {
  106. ChargeBoxId = session.ChargeBoxId,
  107. IsDonateInvoice = creditDeductResult.isDonateInvoice,
  108. CreditNo = creditDeductResult.creditNo,
  109. DeductResult = creditDeductResult.deductResult,
  110. SessionId = creditDeductResult.txId,
  111. ApprovalNo = creditDeductResult.approvalNo,
  112. TotalCost = creditDeductResult.amount,
  113. };
  114. var response = await httpClient.Post(GlobalConfig.TCC_API_URL + "prepare_issue_invoice", new Dictionary<string, string>()
  115. {
  116. { "PartnerId",session.CustomerId.ToString()}
  117. }, report, GlobalConfig.TCC_SALTKEY);
  118. logger.LogDebug(JsonConvert.SerializeObject(response));
  119. }
  120. confirm.status = DataTransferStatus.Accepted;
  121. confirm.data = JsonConvert.SerializeObject(new { txId = creditDeductResult.txId, creditNo = creditDeductResult.creditNo, msgId = _request.messageId });
  122. }
  123. if (_request.messageId == "ID_ReaderStatus")
  124. {
  125. if (session.CustomerId == new Guid("009E603C-79CD-4620-A2B8-D9349C0E8AD8"))
  126. {
  127. var preauth_status = JsonConvert.DeserializeObject<ID_ReaderStatus>(_request.data);
  128. var report = new
  129. {
  130. ChargeBoxId = session.ChargeBoxId,
  131. ConnectorId = preauth_status.ConnectorId,
  132. CreditNo = preauth_status.creditNo,
  133. ReaderStatus = preauth_status.readerStatus,
  134. SerialNo = preauth_status.SerialNo,
  135. VEMData = preauth_status.VEMData,
  136. Timestamp = preauth_status.Timestamp
  137. };
  138. var response = await httpClient.Post(GlobalConfig.TCC_API_URL + "preauth_status", new Dictionary<string, string>()
  139. {
  140. { "PartnerId",session.CustomerId.ToString()}
  141. }, report, GlobalConfig.TCC_SALTKEY);
  142. confirm.status = DataTransferStatus.Accepted;
  143. }
  144. }
  145. if (_request.messageId == "ID_OCMF")
  146. {
  147. JObject jo = JObject.Parse(_request.data);
  148. logger.LogDebug("{0}\r\n{1}\r\n{2}", jo["txId"].Value<int>(), jo["dataString"].Value<string>(), jo["publicKey"].Value<string>());
  149. await mainDbService.AddOCMF(new OCMF()
  150. {
  151. TransactionId = jo["txId"].Value<int>(),
  152. DataString = jo["dataString"].Value<string>(),
  153. PublicKey = jo["publicKey"].Value<string>()
  154. });
  155. confirm.status = DataTransferStatus.Accepted;
  156. confirm.data = JsonConvert.SerializeObject(new { txId = jo["txId"].Value<int>(), msgId = _request.messageId });
  157. }
  158. if (_request.messageId == "Authorize")
  159. {
  160. string iso15118_token = string.Empty;
  161. JObject jo = JObject.Parse(_request.data);
  162. if (jo.ContainsKey("idToken"))
  163. {
  164. iso15118_token = jo["idToken"]["idToken"].Value<string>();
  165. }
  166. confirm.status = DataTransferStatus.Accepted;
  167. confirm.data = JsonConvert.SerializeObject(
  168. new {
  169. certificateStatus = iso15118_token == "12345678901234" ? "Accepted" : "CertificateExpired",
  170. idTokenInfo = new { status = iso15118_token == "12345678901234" ? "Accepted" : "Invalid"
  171. } });
  172. }
  173. result.Message = confirm;
  174. result.Success = true;
  175. }
  176. break;
  177. case Actions.BootNotification:
  178. {
  179. BootNotificationRequest _request = request as BootNotificationRequest;
  180. int heartbeat_interval = GlobalConfig.GetHEARTBEAT_INTERVAL();
  181. //var _machine = db.Machine.FirstOrDefault(x => x.ChargeBoxId == session.ChargeBoxId);
  182. Machine _machine = new();
  183. _machine.ChargeBoxSerialNumber = string.IsNullOrEmpty(_request.chargeBoxSerialNumber) ? string.Empty : _request.chargeBoxSerialNumber;
  184. _machine.ChargePointSerialNumber = string.IsNullOrEmpty(_request.chargePointSerialNumber) ? string.Empty : _request.chargePointSerialNumber;
  185. _machine.ChargePointModel = string.IsNullOrEmpty(_request.chargePointModel) ? string.Empty : _request.chargePointModel;
  186. _machine.ChargePointVendor = string.IsNullOrEmpty(_request.chargePointVendor) ? string.Empty : _request.chargePointVendor;
  187. _machine.FW_CurrentVersion = string.IsNullOrEmpty(_request.firmwareVersion) ? string.Empty : _request.firmwareVersion;
  188. _machine.Iccid = string.IsNullOrEmpty(_request.iccid) ? string.Empty : _request.iccid;
  189. //_machine.Iccid = DateTime.UtcNow.ToString("yy-MM-dd HH:mm");
  190. _machine.Imsi = string.IsNullOrEmpty(_request.imsi) ? string.Empty : _request.imsi;
  191. _machine.MeterSerialNumber = string.IsNullOrEmpty(_request.meterSerialNumber) ? string.Empty : _request.meterSerialNumber;
  192. _machine.MeterType = string.IsNullOrEmpty(_request.meterType) ? string.Empty : _request.meterType;
  193. await mainDbService.UpdateMachineBasicInfo(session.ChargeBoxId, _machine);
  194. var configValue = await mainDbService.GetMachineHeartbeatInterval(session.ChargeBoxId);
  195. if (configValue != null)
  196. {
  197. int.TryParse(configValue, out heartbeat_interval);
  198. }
  199. if (session.IsPending == true)
  200. {
  201. session.IsPending = false;
  202. }
  203. if (session.IsPending == null)
  204. {
  205. session.IsPending = true;
  206. }
  207. var confirm = new BootNotificationConfirmation() {
  208. currentTime = DateTime.UtcNow,
  209. interval = session.IsPending.Value ? 5 : heartbeat_interval,
  210. status = session.IsPending.Value ? RegistrationStatus.Pending : RegistrationStatus.Accepted
  211. };
  212. result.Message = confirm;
  213. result.Success = true;
  214. }
  215. break;
  216. case Actions.StatusNotification:
  217. {
  218. var statusNotificationTimer = Stopwatch.StartNew();
  219. long s1 = 0, s2 = 0, s3 = 0, s4 = 0, s5 = 0;
  220. //只保留最新上報狀況
  221. StatusNotificationRequest _request = request as StatusNotificationRequest;
  222. int preStatus = 0;
  223. ConnectorStatus _oldStatus;
  224. _oldStatus = await mainDbService.GetConnectorStatus(session.ChargeBoxId, _request.connectorId);
  225. s1 = statusNotificationTimer.ElapsedMilliseconds;
  226. if (_oldStatus != null && (_request.status != (ChargePointStatus)_oldStatus.Status || _request.status == ChargePointStatus.Faulted))
  227. {
  228. preStatus = _oldStatus.Status;
  229. await mainDbService.UpdateConnectorStatus(_oldStatus.Id, new ConnectorStatus()
  230. {
  231. CreatedOn = _request.timestamp.HasValue ? _request.timestamp.Value : DateTime.UtcNow,
  232. Status = (int)_request.status,
  233. ChargePointErrorCodeId = (int)_request.errorCode,
  234. ErrorInfo = string.IsNullOrEmpty(_request.info) ? string.Empty : _request.info,
  235. VendorId = string.IsNullOrEmpty(_request.vendorId) ? string.Empty : _request.vendorId,
  236. VendorErrorCode = string.IsNullOrEmpty(_request.vendorErrorCode) ? string.Empty : _request.vendorErrorCode
  237. });
  238. }
  239. s2 = statusNotificationTimer.ElapsedMilliseconds;
  240. if (_oldStatus == null)
  241. {
  242. await mainDbService.AddConnectorStatus(
  243. ChargeBoxId: session.ChargeBoxId,
  244. ConnectorId: (byte)_request.connectorId,
  245. CreatedOn: _request.timestamp.HasValue ? _request.timestamp.Value : DateTime.UtcNow,
  246. Status: (int)_request.status,
  247. ChargePointErrorCodeId: (int)_request.errorCode,
  248. ErrorInfo: string.IsNullOrEmpty(_request.info) ? string.Empty : _request.info,
  249. VendorId: string.IsNullOrEmpty(_request.vendorId) ? string.Empty : _request.vendorId,
  250. VendorErrorCode: string.IsNullOrEmpty(_request.vendorErrorCode) ? string.Empty : _request.vendorErrorCode);
  251. }
  252. s3 = statusNotificationTimer.ElapsedMilliseconds;
  253. if (_request.status == Packet.Messages.SubTypes.ChargePointStatus.Faulted)
  254. {
  255. await mainDbService.AddMachineError(ConnectorId: (byte)_request.connectorId,
  256. CreatedOn: _request.timestamp.HasValue ? _request.timestamp.Value : DateTime.UtcNow,
  257. Status: (int)_request.status,
  258. ChargeBoxId: session.ChargeBoxId,
  259. ErrorCodeId: (int)_request.errorCode,
  260. ErrorInfo: string.IsNullOrEmpty(_request.info) ? string.Empty : _request.info,
  261. PreStatus: _oldStatus == null ? -1 : preStatus,
  262. VendorErrorCode: string.IsNullOrEmpty(_request.vendorErrorCode) ? string.Empty : _request.vendorErrorCode,
  263. VendorId: string.IsNullOrEmpty(_request.vendorId) ? string.Empty : _request.vendorId);
  264. }
  265. s4 = statusNotificationTimer.ElapsedMilliseconds;
  266. if (_request.status == Packet.Messages.SubTypes.ChargePointStatus.Faulted)
  267. {
  268. //var businessService = BusinessServiceFactory.CreateBusinessService(session.CustomerId.ToString());
  269. //var businessService = await serviceProvider.GetService<BusinessServiceFactory>().CreateBusinessService(session.CustomerId.ToString());
  270. var businessService = await businessServiceFactory.CreateBusinessService(session.CustomerId.ToString());
  271. var notification = businessService.NotifyFaultStatus(new ErrorDetails()
  272. {
  273. ChargeBoxId = session.ChargeBoxId,
  274. ConnectorId = _request.connectorId,
  275. ErrorCode = _request.errorCode,
  276. Info = string.IsNullOrEmpty(_request.info) ? string.Empty : _request.info,
  277. OCcuredOn = _request.timestamp ?? DateTime.UtcNow,
  278. VendorErrorCode = string.IsNullOrEmpty(_request.vendorErrorCode) ? string.Empty : _request.vendorErrorCode,
  279. });
  280. }
  281. s5 = statusNotificationTimer.ElapsedMilliseconds;
  282. var confirm = new StatusNotificationConfirmation() { };
  283. result.Message = confirm;
  284. result.Success = true;
  285. statusNotificationTimer.Stop();
  286. if (statusNotificationTimer.ElapsedMilliseconds / 1000 > 1)
  287. {
  288. logger.LogCritical(string.Format("StatusNotification took {0}/{1}/{2}/{3}/{4}", s1, s2, s3, s4, s5));
  289. }
  290. }
  291. break;
  292. case Actions.Heartbeat:
  293. {
  294. var confirm = new HeartbeatConfirmation() { currentTime = DateTime.UtcNow };
  295. result.Message = confirm;
  296. result.Success = true;
  297. }
  298. break;
  299. case Actions.MeterValues:
  300. {
  301. var meterValueTimer = Stopwatch.StartNew();
  302. long s1 = 0, s2 = 0, s3 = 0, s4 = 0, s5 = 0, insertTasksCnt = 0;
  303. MeterValuesRequest _request = request as MeterValuesRequest;
  304. if (_request.meterValue.Count > 0)
  305. {
  306. s1 = meterValueTimer.ElapsedMilliseconds;
  307. foreach (var item in _request.meterValue)
  308. {
  309. if (_request.transactionId.HasValue)
  310. {
  311. decimal meterStart = 0;
  312. var energy_Register = item.sampledValue.Where(x => x.measurand == Measurand.Energy_Active_Import_Register).FirstOrDefault();
  313. if (energy_Register != null)
  314. {
  315. decimal energyRegister = decimal.Parse(energy_Register.value);
  316. energyRegister = energy_Register.unit.Value == UnitOfMeasure.kWh ? decimal.Multiply(energyRegister, 1000) : energyRegister;
  317. using (var maindb = await maindbContextFactory.CreateDbContextAsync())
  318. {
  319. meterStart = await maindb.TransactionRecord
  320. .Where(x => x.Id == _request.transactionId.Value).Select(x => x.MeterStart)
  321. .FirstOrDefaultAsync();
  322. }
  323. item.sampledValue.Add(new SampledValue()
  324. {
  325. context = ReadingContext.Sample_Periodic,
  326. format = ValueFormat.Raw,
  327. location = Location.Outlet,
  328. phase = item.sampledValue.Where(x => x.measurand == Measurand.Energy_Active_Import_Register).Select(x => x.phase).FirstOrDefault(),
  329. unit = UnitOfMeasure.Wh,
  330. measurand = Measurand.TotalEnergy,
  331. value = decimal.Subtract(energyRegister, meterStart).ToString()
  332. });
  333. }
  334. }
  335. }
  336. s2 = meterValueTimer.ElapsedMilliseconds;
  337. //List<Task> insertTasks = new();
  338. List <InsertMeterValueParam> datas= new();
  339. foreach (var item in _request.meterValue)
  340. {
  341. foreach (var sampleVaule in item.sampledValue)
  342. {
  343. decimal value = Convert.ToDecimal(sampleVaule.value);
  344. datas.Add(new InsertMeterValueParam(
  345. chargeBoxId: session.ChargeBoxId
  346. , connectorId: (byte)_request.connectorId
  347. , value: value
  348. , createdOn: item.timestamp
  349. , contextId: sampleVaule.context.HasValue ? (int)sampleVaule.context : 0
  350. , formatId: sampleVaule.format.HasValue ? (int)sampleVaule.format : 0
  351. , measurandId: sampleVaule.measurand.HasValue ? (int)sampleVaule.measurand : 0
  352. , phaseId: sampleVaule.phase.HasValue ? (int)sampleVaule.phase : 0
  353. , locationId: sampleVaule.location.HasValue ? (int)sampleVaule.location : 0
  354. , unitId: sampleVaule.unit.HasValue ? (int)sampleVaule.unit : 0
  355. , transactionId: _request.transactionId.HasValue ? _request.transactionId.Value : -1));
  356. //var task = meterValueDbService.InsertAsync(
  357. // chargeBoxId: session.ChargeBoxId
  358. // , connectorId: (byte)_request.connectorId
  359. // , value: value
  360. // , createdOn: item.timestamp
  361. // , contextId: sampleVaule.context.HasValue ? (int)sampleVaule.context : 0
  362. // , formatId: sampleVaule.format.HasValue ? (int)sampleVaule.format : 0
  363. // , measurandId: sampleVaule.measurand.HasValue ? (int)sampleVaule.measurand : 0
  364. // , phaseId: sampleVaule.phase.HasValue ? (int)sampleVaule.phase : 0
  365. // , locationId: sampleVaule.location.HasValue ? (int)sampleVaule.location : 0
  366. // , unitId: sampleVaule.unit.HasValue ? (int)sampleVaule.unit : 0
  367. // , transactionId: _request.transactionId.HasValue ? _request.transactionId.Value : -1);
  368. //var task = Task.Delay(2_000);
  369. //insertTasks.Add(task);
  370. }
  371. }
  372. //insertTasksCnt = insertTasks.Count;
  373. insertTasksCnt = datas.Count;
  374. s3 = meterValueTimer.ElapsedMilliseconds;
  375. //await Task.WhenAll(insertTasks);
  376. await meterValueDbService.InsertBundleAsync(datas);
  377. s4 = meterValueTimer.ElapsedMilliseconds;
  378. }
  379. // if (energy_kwh > 0)
  380. {
  381. try
  382. {
  383. if (session.IsBilling)
  384. {
  385. await messageService.SendDataTransferRequest(
  386. session.ChargeBoxId,
  387. messageId: "ID_TxEnergy",
  388. vendorId: "Phihong Technology",
  389. data: JsonConvert.SerializeObject(new { txId = _request.transactionId, ConnectorId = _request.connectorId })
  390. );
  391. }
  392. }
  393. catch (Exception ex)
  394. {
  395. logger.LogTrace(string.Format("{0} :{1}", session.ChargeBoxId + " RunningCost", ex.Message));
  396. }
  397. }
  398. s5 = meterValueTimer.ElapsedMilliseconds;
  399. meterValueTimer.Stop();
  400. if (meterValueTimer.ElapsedMilliseconds / 1000 > 1)
  401. {
  402. logger.LogCritical(string.Format("MeterValues took {0}/{1}/{2}/{3}/{4}:{5}", s1 / 1000, s2 / 1000, s3 / 1000, s4 / 1000, s5 / 1000, insertTasksCnt));
  403. }
  404. var confirm = new MeterValuesConfirmation() { };
  405. result.Message = confirm;
  406. result.Success = true;
  407. }
  408. break;
  409. case Actions.StartTransaction:
  410. {
  411. var timer = Stopwatch.StartNew();
  412. long t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0;
  413. StartTransactionRequest _request = request as StartTransactionRequest;
  414. int _transactionId = -1;
  415. var businessService = await businessServiceFactory.CreateBusinessService(session.CustomerId.ToString());
  416. t0 = timer.ElapsedMilliseconds;
  417. var _idTagInfo = new IdTagInfo() { expiryDate = DateTime.UtcNow.AddDays(1), status = AuthorizationStatus.Accepted };
  418. #region PnC 邏輯
  419. if (!string.IsNullOrEmpty(_request.idTag))
  420. {
  421. _request.idTag = _request.idTag.StartsWith("vid:") ? _request.idTag.Replace("vid:", "") : _request.idTag;
  422. }
  423. #endregion
  424. if (_request.idTag != "Backend")
  425. {
  426. var authorization_result = await businessService.Authorize(session.ChargeBoxId, _request.idTag);
  427. _idTagInfo = authorization_result.IdTagInfo;
  428. t1 = timer.ElapsedMilliseconds;
  429. if (_idTagInfo.status == AuthorizationStatus.Accepted && authorization_result.ChargePointFee != null)
  430. {
  431. var price = authorization_result.ChargePointFee.Where(x => x.IsAC == session.IsAC).First();
  432. if (price != null)
  433. {
  434. session.UserPrices[_request.idTag] = price.PerkWhFee.HasValue ? JsonConvert.SerializeObject(new List<ChargingPrice>() { new ChargingPrice() { StartTime = "00:00", EndTime = "23:59", Fee = price.PerkWhFee.Value } }) : price.PerHourFee.Value.ToString();
  435. session.UserPrices[_request.idTag] += "|+" + authorization_result.AccountBalance + "+" + "&" + price.ParkingFee + "&|" + price.Currency;
  436. }
  437. }
  438. }
  439. //特例****飛宏客戶旗下的電樁,若遇到Portal沒回應的狀況 ~允許充電
  440. if (session.CustomerId.ToString().ToUpper() == "8456AED9-6DD9-4BF3-A94C-9F5DCB9506F7" && _idTagInfo.status == AuthorizationStatus.ConcurrentTx)
  441. {
  442. _idTagInfo = new IdTagInfo() { expiryDate = DateTime.UtcNow.AddDays(1), status = AuthorizationStatus.Accepted };
  443. }
  444. string accountBalance = "0";
  445. if (session.CustomerId.ToString().ToUpper() == "10C7F5BD-C89A-4E2A-8611-B617E0B41A73")
  446. {
  447. using (SqlConnection conn = await webDbConnectionFactory.CreateAsync())
  448. {
  449. var parameters = new DynamicParameters();
  450. parameters.Add("@IdTag", _request.idTag, DbType.String, ParameterDirection.Input, 50);
  451. string strSql = "select parentIdTag from [dbo].[LocalListDetail] where ListId = 27 and IdTag=@IdTag; ";
  452. accountBalance = await conn.ExecuteScalarAsync<string>(strSql, parameters);
  453. }
  454. }
  455. var _CustomerId = await mainDbService.GetCustomerIdByChargeBoxId(session.ChargeBoxId);
  456. t2 = timer.ElapsedMilliseconds;
  457. var _existedTx = await mainDbService.TryGetDuplicatedTransactionId(session.ChargeBoxId, _CustomerId, _request.connectorId, _request.timestamp);
  458. t3 = timer.ElapsedMilliseconds;
  459. if (_existedTx != null)
  460. {
  461. _transactionId = _existedTx.Value;
  462. logger.LogError("Duplication ***************************************************** " + _existedTx);
  463. }
  464. else
  465. {
  466. TransactionRecord _newTransaction;//= new TransactionRecord();
  467. _newTransaction = new TransactionRecord()
  468. {
  469. ChargeBoxId = session.ChargeBoxId,
  470. ConnectorId = (byte)_request.connectorId,
  471. CreatedOn = DateTime.UtcNow,
  472. StartIdTag = _request.idTag,
  473. MeterStart = _request.meterStart,
  474. CustomerId = _CustomerId,
  475. StartTime = _request.timestamp.ToUniversalTime(),
  476. ReservationId = _request.reservationId.HasValue ? _request.reservationId.Value : 0,
  477. };
  478. if (session.UserPrices.ContainsKey(_request.idTag))
  479. {
  480. _newTransaction.Fee = !session.IsBilling ? string.Empty : session.UserPrices[_request.idTag];
  481. }
  482. else
  483. {
  484. _newTransaction.Fee = !session.IsBilling ? string.Empty : session.BillingMethod == 1 ? JsonConvert.SerializeObject(session.ChargingPrices) : session.ChargingFeebyHour.ToString();
  485. _newTransaction.Fee += !session.IsBilling ? string.Empty : "|+" + accountBalance + "+" + "&" + session.ParkingFee + "&|" + session.Currency;
  486. }
  487. //using (var db = await maindbContextFactory.CreateDbContextAsync())
  488. //{
  489. // await db.TransactionRecord.AddAsync(_newTransaction);
  490. // await db.SaveChangesAsync();
  491. // _transactionId = _newTransaction.Id;
  492. //}
  493. _transactionId = await mainDbService.AddNewTransactionRecord(_newTransaction);
  494. t4 = timer.ElapsedMilliseconds;
  495. logger.LogInformation("***************************************************** ");
  496. logger.LogInformation(string.Format("{0} :TransactionId {1} ", session.ChargeBoxId, _transactionId));
  497. logger.LogInformation("***************************************************** ");
  498. }
  499. var confirm = new StartTransactionConfirmation()
  500. {
  501. idTagInfo = _idTagInfo,
  502. transactionId = _transactionId
  503. };
  504. result.Message = confirm;
  505. result.Success = true;
  506. timer.Stop();
  507. t5 = timer.ElapsedMilliseconds;
  508. if (t5 > 1000)
  509. {
  510. logger.Log(LogLevel.Critical, "{action} {ChargeBoxId} time {t0}/{t1}/{t2}/{t3}/{t4}/{totalTime}", action.ToString(), session.ChargeBoxId, t0, t1, t2, t3, t4, t5);
  511. }
  512. }
  513. break;
  514. case Actions.StopTransaction:
  515. {
  516. StopTransactionRequest _request = request as StopTransactionRequest;
  517. //遠傳太久以前的停止充電 直接拒絕 避免電樁持續重送~~~~~~~
  518. if (_request.timestamp < new DateTime(2021, 11, 1))
  519. {
  520. var confirm = new StopTransactionConfirmation()
  521. {
  522. idTagInfo = new IdTagInfo()
  523. {
  524. status = AuthorizationStatus.Invalid
  525. }
  526. };
  527. result.Message = confirm;
  528. result.Success = true;
  529. return result;
  530. }
  531. long getDateTimeTime, getServiceTime, getTagInfoTime, dbOpTime = 0, meterValueTime = 0;
  532. var stopTrasactionTimer = Stopwatch.StartNew();
  533. int _ConnectorId = 0;
  534. var utcNow = DateTime.UtcNow;
  535. getDateTimeTime = stopTrasactionTimer.ElapsedMilliseconds;
  536. var businessService = await businessServiceFactory.CreateBusinessService(session.CustomerId.ToString());
  537. getServiceTime = stopTrasactionTimer.ElapsedMilliseconds;
  538. TransactionRecord transaction;
  539. transaction = await mainDbService.GetTransactionForStopTransaction(_request.transactionId, session.ChargeBoxId);
  540. var _idTagInfo = string.IsNullOrEmpty(_request.idTag) ? null : (
  541. _request.idTag == "Backend" ?
  542. new IdTagInfo()
  543. {
  544. expiryDate = utcNow.AddDays(1),
  545. status = AuthorizationStatus.Accepted
  546. } :
  547. (await businessService.Authorize(session.ChargeBoxId, _request.idTag, transaction?.ConnectorId)).IdTagInfo
  548. );
  549. getTagInfoTime = stopTrasactionTimer.ElapsedMilliseconds;
  550. //特例****飛宏客戶旗下的電樁,若遇到Portal沒回應的狀況 ~允許充電
  551. if (session.CustomerId.ToString().ToUpper() == "8456AED9-6DD9-4BF3-A94C-9F5DCB9506F7" && _idTagInfo != null && _idTagInfo.status == AuthorizationStatus.ConcurrentTx)
  552. {
  553. _idTagInfo = new IdTagInfo() { expiryDate = utcNow.AddDays(1), status = AuthorizationStatus.Accepted };
  554. }
  555. #region PnC 邏輯
  556. if (!string.IsNullOrEmpty(_request.idTag))
  557. {
  558. _request.idTag = _request.idTag.StartsWith("vid:") ? _request.idTag.Replace("vid:", "") : _request.idTag;
  559. }
  560. #endregion
  561. try
  562. {
  563. if (transaction is null)
  564. {
  565. result.Exception = new Exception("Can't find transactionId " + _request.transactionId);
  566. }
  567. else
  568. {
  569. #region 加入Transaction Start/StopSOC
  570. if (!session.IsAC && _request.transactionId > 0)
  571. {
  572. var SearchTime = transaction.StartTime;
  573. var txStopTime = _request.timestamp;
  574. List<int> SOCCollection = new List<int>();
  575. while (SearchTime.Date <= txStopTime.Date)
  576. {
  577. var searchResults = await meterValueDbService.GetTransactionSOC(transaction.Id, SearchTime.Date);
  578. SOCCollection.AddRange(searchResults);
  579. SearchTime = SearchTime.AddDays(1);
  580. }
  581. SOCCollection.Sort();
  582. logger.LogDebug(string.Format("SOCCollection:" + String.Join(",", SOCCollection.Select(x => x.ToString()).ToArray())));
  583. await mainDbService.UpdateTransactionSOC(
  584. transaction.Id,
  585. startsoc: SOCCollection.Count == 0 ? "" : SOCCollection.First().ToString("0"),
  586. stopsoc: SOCCollection.Count == 0 ? "" : SOCCollection.Last().ToString("0")
  587. );
  588. }
  589. #endregion
  590. _ConnectorId = transaction.ConnectorId;
  591. var confirm = new StopTransactionConfirmation()
  592. {
  593. idTagInfo = _idTagInfo
  594. };
  595. //Avoid rewrite transaction data
  596. if (transaction.StopTime != GlobalConfig.DefaultNullTime)
  597. {
  598. result.Message = confirm;
  599. result.Success = true;
  600. return result;
  601. }
  602. await mainDbService.UpdateTransaction(_request.transactionId,
  603. meterStop: _request.meterStop,
  604. stopTime: _request.timestamp.ToUniversalTime(),
  605. stopReasonId: _request.reason.HasValue ? (int)_request.reason.Value : 0,
  606. stopReason: _request.reason.HasValue ? _request.reason.Value.ToString() : Reason.Local.ToString(),
  607. stopIdTag: _request.idTag,
  608. receipt: string.Empty,
  609. cost: session.IsBilling ? -1 : 0);
  610. if (_request.transactionData == null || _request.transactionData.Count == 0)
  611. {
  612. _request.transactionData = new List<MeterValue>()
  613. {
  614. new MeterValue() { timestamp= _request.timestamp, sampledValue=new List<SampledValue>()}
  615. };
  616. }
  617. if (_request.transactionData != null && _request.transactionData.Count > 0)
  618. {
  619. //清除 StopTransaction TransactionData
  620. _request.transactionData[0].sampledValue.Clear();
  621. _request.transactionData[0].sampledValue.Add(new SampledValue()
  622. {
  623. context = ReadingContext.Transaction_End,
  624. format = ValueFormat.Raw,
  625. location = Location.Outlet,
  626. phase = _request.transactionData[0].sampledValue.Where(x => x.context.HasValue).Select(x => x.phase).FirstOrDefault(),
  627. unit = UnitOfMeasure.Wh,
  628. measurand = Measurand.TotalEnergy,
  629. value = decimal.Subtract(transaction.MeterStop, transaction.MeterStart).ToString()
  630. });
  631. }
  632. if (session.IsBilling)
  633. {
  634. await messageService.SendDataTransferRequest(
  635. session.ChargeBoxId,
  636. messageId: "ID_TxEnergy",
  637. vendorId: "Phihong Technology",
  638. data: JsonConvert.SerializeObject(new { txId = _request.transactionId, ConnectorId = transaction.ConnectorId })
  639. );
  640. }
  641. result.Message = confirm;
  642. result.Success = true;
  643. }
  644. dbOpTime = watch.ElapsedMilliseconds;
  645. #region Save MeterValue
  646. if (_request.transactionData != null &&
  647. _request.transactionData.Count > 0)
  648. {
  649. //List<Task> insertTasks = new();
  650. List<InsertMeterValueParam> datas = new();
  651. foreach (var item in _request.transactionData)
  652. {
  653. foreach (var sampleVaule in item.sampledValue)
  654. {
  655. decimal value = Convert.ToDecimal(sampleVaule.value);
  656. datas.Add(new InsertMeterValueParam(
  657. chargeBoxId: session.ChargeBoxId
  658. , connectorId: (byte)_ConnectorId
  659. , value: value
  660. , createdOn: item.timestamp
  661. , contextId: sampleVaule.context.HasValue ? (int)sampleVaule.context : 0
  662. , formatId: sampleVaule.format.HasValue ? (int)sampleVaule.format : 0
  663. , measurandId: sampleVaule.measurand.HasValue ? (int)sampleVaule.measurand : 0
  664. , phaseId: sampleVaule.phase.HasValue ? (int)sampleVaule.phase : 0
  665. , locationId: sampleVaule.location.HasValue ? (int)sampleVaule.location : 0
  666. , unitId: sampleVaule.unit.HasValue ? (int)sampleVaule.unit : 0
  667. , transactionId: _request.transactionId));
  668. //var task = meterValueDbService.InsertAsync(
  669. // chargeBoxId: session.ChargeBoxId
  670. // , connectorId: (byte)_ConnectorId
  671. // , value: value
  672. // , createdOn: item.timestamp
  673. // , contextId: sampleVaule.context.HasValue ? (int)sampleVaule.context : 0
  674. // , formatId: sampleVaule.format.HasValue ? (int)sampleVaule.format : 0
  675. // , measurandId: sampleVaule.measurand.HasValue ? (int)sampleVaule.measurand : 0
  676. // , phaseId: sampleVaule.phase.HasValue ? (int)sampleVaule.phase : 0
  677. // , locationId: sampleVaule.location.HasValue ? (int)sampleVaule.location : 0
  678. // , unitId: sampleVaule.unit.HasValue ? (int)sampleVaule.unit : 0
  679. // , transactionId: _request.transactionId);
  680. //insertTasks.Add(task);
  681. }
  682. }
  683. //await Task.WhenAll(insertTasks);
  684. await meterValueDbService.InsertBundleAsync(datas);
  685. }
  686. #endregion
  687. meterValueTime = watch.ElapsedMilliseconds;
  688. }
  689. catch (Exception ex)
  690. {
  691. result.Exception = new Exception("TransactionId " + _request.transactionId + " " + ex.Message);
  692. result.CallErrorMsg = "Reject Response Message";
  693. result.Success = false;
  694. logger.LogCritical("StopTransaction {msg} trace:{trace}", ex.Message, ex.StackTrace);
  695. // return result;
  696. }
  697. stopTrasactionTimer.Stop();
  698. if (stopTrasactionTimer.ElapsedMilliseconds > 1000)
  699. {
  700. logger.Log(LogLevel.Critical, "ExecuteCoreRequest {action} {ChargeBoxId} took {time} sec", action.ToString(), session.ChargeBoxId, stopTrasactionTimer.ElapsedMilliseconds / 1000);
  701. logger.Log(LogLevel.Critical, "{action} {ChargeBoxId} time {getDateTime}/{serviceTime}/{tagInfoTime}/{dbOpTime}/{meterValueTime}", action.ToString(), session.ChargeBoxId, getDateTimeTime, getServiceTime, getTagInfoTime, dbOpTime, meterValueTime);
  702. }
  703. }
  704. break;
  705. case Actions.Authorize:
  706. {
  707. AuthorizeRequest _request = request as AuthorizeRequest;
  708. var businessService = await businessServiceFactory.CreateBusinessService(session.CustomerId.ToString());
  709. var confirm = new AuthorizeConfirmation()
  710. {
  711. idTagInfo = new IdTagInfo() { expiryDate = DateTime.UtcNow.AddDays(1), status = AuthorizationStatus.Accepted }
  712. };
  713. if (_request.idTag != "Backend")
  714. {
  715. var authorization_result = await businessService.Authorize(session.ChargeBoxId, _request.idTag);
  716. confirm.idTagInfo = authorization_result.IdTagInfo;
  717. if (confirm.idTagInfo.status == AuthorizationStatus.Accepted && authorization_result.ChargePointFee != null)
  718. {
  719. var price = authorization_result.ChargePointFee.Where(x => x.IsAC == session.IsAC).First();
  720. if (price != null)
  721. {
  722. session.UserPrices[_request.idTag] = price.PerkWhFee.HasValue ? JsonConvert.SerializeObject(new List<ChargingPrice>() { new ChargingPrice() { StartTime = "00:00", EndTime = "23:59", Fee = price.PerkWhFee.Value } }) : price.PerHourFee.Value.ToString();
  723. session.UserPrices[_request.idTag] += "|+" + authorization_result.AccountBalance + "+" + "&" + price.ParkingFee + "&|" + price.Currency;
  724. session.UserDisplayPrices[_request.idTag] = price.DisplayMessage;
  725. }
  726. }
  727. }
  728. //特例****飛宏客戶旗下的電樁,若遇到Portal沒回應的狀況 ~允許充電
  729. if (session.CustomerId.ToString().ToUpper() == "8456AED9-6DD9-4BF3-A94C-9F5DCB9506F7" && confirm.idTagInfo.status == AuthorizationStatus.ConcurrentTx)
  730. {
  731. confirm.idTagInfo = new IdTagInfo() { expiryDate = DateTime.UtcNow.AddDays(1), status = AuthorizationStatus.Accepted };
  732. }
  733. result.Message = confirm;
  734. result.Success = true;
  735. }
  736. break;
  737. default:
  738. {
  739. logger.LogWarning(string.Format("Not Implement {0} Logic(ExecuteCoreRequest)", request.GetType().ToString().Replace("OCPPPackage.Messages.Core.", "")));
  740. }
  741. break;
  742. }
  743. }
  744. catch (Exception ex)
  745. {
  746. logger.LogCritical("chargeBoxId:{0} {1}", session?.ChargeBoxId, action);
  747. logger.LogCritical("Data {0}", request?.ToString());
  748. logger.LogCritical("Error {0}", ex.ToString());
  749. result.Exception = ex;
  750. }
  751. //if (action == Actions.Heartbeat)
  752. //{
  753. watch.Stop();
  754. if (watch.ElapsedMilliseconds / 1000 > 3)
  755. {
  756. logger.LogError("Processing " + action.ToString() + " costs " + watch.ElapsedMilliseconds / 1000 + " seconds"); ;
  757. }
  758. //}
  759. if (watch.ElapsedMilliseconds > 5_000)
  760. {
  761. //ThreadPool.GetAvailableThreads(out int workerThreads,out int completionThreads);
  762. //logger.LogInformation($"ThreadPool workerThreads:{workerThreads} completionThreads:{completionThreads}");
  763. //await blockingTreePrintService.PrintDbBlockingTree();
  764. //await googleGetTimePrintService.Print();
  765. }
  766. return result;
  767. }
  768. async internal Task<MessageResult> ExecuteCoreConfirm(Actions action, ClientData session, IConfirmation confirm, string requestId)
  769. {
  770. MessageResult result = new MessageResult() { Success = true };
  771. try
  772. {
  773. switch (action)
  774. {
  775. case Actions.DataTransfer:
  776. {
  777. DataTransferConfirmation _confirm = confirm as DataTransferConfirmation;
  778. DataTransferRequest _request = _confirm.GetRequest() as DataTransferRequest;
  779. using (var db = await maindbContextFactory.CreateDbContextAsync())
  780. {
  781. var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  782. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
  783. if (operation != null)
  784. {
  785. operation.FinishedOn = DateTime.UtcNow;
  786. operation.Status = 1;//電樁有回覆
  787. operation.EVSE_Status = (int)_confirm.status;
  788. operation.EVSE_Value = string.IsNullOrEmpty(_confirm.data) ? "" : _confirm.data;
  789. await db.SaveChangesAsync();
  790. }
  791. if (_request.messageId == "ID_FirmwareVersion")
  792. {
  793. var machine = new Machine() { Id = session.MachineId };
  794. if (machine != null)
  795. {
  796. db.ChangeTracker.AutoDetectChangesEnabled = false;
  797. //db.Configuration.ValidateOnSaveEnabled = false;
  798. db.Machine.Attach(machine);
  799. machine.BoardVersions = _confirm.data;
  800. db.Entry(machine).Property(x => x.BoardVersions).IsModified = true;
  801. await db.SaveChangesAsync();
  802. }
  803. }
  804. if (_request.messageId == "ID_TxEnergy") //計費
  805. {
  806. if (_confirm.status == DataTransferStatus.Accepted)
  807. {
  808. decimal couponPoint = 0m;
  809. string farewellMessage = string.Empty;
  810. string receipt = string.Empty;
  811. List<ChargingBill> bill = new List<ChargingBill>();
  812. List<ChargingPrice> chargingPrices = new List<ChargingPrice>();
  813. var txEnergy = JsonConvert.DeserializeObject<TransactionEnergy>(_confirm.data);
  814. var feedto = await db.TransactionRecord.Where(x => x.Id == txEnergy.TxId).Select(x => new { Id = x.Id, ConnectorId = x.ConnectorId, Fee = x.Fee, StopTime = x.StopTime, StartTime = x.StartTime }).FirstOrDefaultAsync();
  815. decimal chargedEnergy = 0m;
  816. if (feedto == null || string.IsNullOrEmpty(feedto.Fee)) return result;
  817. string currency = feedto.Fee.Substring(feedto.Fee.Length - 3);
  818. decimal chargingCost = 0;
  819. if (feedto.Fee.Length > 58)
  820. {
  821. chargingPrices = JsonConvert.DeserializeObject<List<ChargingPrice>>(feedto.Fee.Split('|')[0]);
  822. foreach (var item in txEnergy.PeriodEnergy)
  823. {
  824. DateTime dt = new DateTime(2021, 01, 01, int.Parse(item.Key), 0, 0, DateTimeKind.Utc);
  825. string startTime = dt.ToString("hh:mm tt", new CultureInfo("en-us"));
  826. decimal perfee = 0;
  827. //小數點無條件捨去到第4位
  828. var periodEnergy = (decimal)((int)Decimal.Multiply(item.Value, 10000) / (double)10000);
  829. chargedEnergy += periodEnergy;
  830. if (chargingPrices.Count == 1)
  831. {
  832. perfee = Decimal.Multiply(periodEnergy, chargingPrices[0].Fee);
  833. if (bill.Count == 0)
  834. {
  835. bill.Add(new ChargingBill()
  836. {
  837. StartTime = "12:00 AM",
  838. EndTime = "11:59 PM",
  839. Fee = chargingPrices[0].Fee
  840. });
  841. }
  842. bill[0].PeriodEnergy += periodEnergy;
  843. }
  844. else
  845. {
  846. var price = chargingPrices.Where(x => x.StartTime == startTime).FirstOrDefault();
  847. perfee = Decimal.Multiply(periodEnergy, price.Fee);
  848. bill.Add(new ChargingBill()
  849. {
  850. StartTime = price.StartTime,
  851. EndTime = price.EndTime,
  852. PeriodEnergy = periodEnergy,
  853. Fee = price.Fee,
  854. });
  855. }
  856. if (bill.Count > 0)
  857. {
  858. bill[bill.Count - 1].Total += DollarRounding(perfee, session.Currency);
  859. chargingCost += bill[bill.Count - 1].Total;
  860. if (bill.Count == 1)
  861. {
  862. bill[bill.Count - 1].Total = DollarRounding(Decimal.Multiply(bill[0].PeriodEnergy, bill[0].Fee), session.Currency);
  863. chargingCost = bill[bill.Count - 1].Total;
  864. }
  865. }
  866. }
  867. }
  868. else
  869. {
  870. //以小時計費
  871. foreach (var item in txEnergy.PeriodEnergy)
  872. { //小數點無條件捨去到第4位
  873. var periodEnergy = (decimal)((int)Decimal.Multiply(item.Value, 10000) / (double)10000);
  874. chargedEnergy += periodEnergy;
  875. }
  876. var fee = decimal.Parse(feedto.Fee.Split('|')[0]);
  877. var charging_stoptime = feedto.StopTime == GlobalConfig.DefaultNullTime ? DateTime.Parse(DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm")) : DateTime.Parse(feedto.StopTime.ToString("yyyy/MM/dd HH:mm"));
  878. var charging_starttime = DateTime.Parse(feedto.StartTime.ToString("yyyy/MM/dd HH:mm"));
  879. chargingCost = Decimal.Multiply((decimal)charging_stoptime.Subtract(charging_starttime).TotalHours, fee);
  880. chargingCost = DollarRounding(chargingCost, session.Currency);
  881. }
  882. // 計算停車費
  883. var parkingFee = decimal.Parse(feedto.Fee.Split('&')[1]);
  884. var stoptime = feedto.StopTime == GlobalConfig.DefaultNullTime ? DateTime.Parse(DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm")) : DateTime.Parse(feedto.StopTime.ToString("yyyy/MM/dd HH:mm"));
  885. var starttime = DateTime.Parse(feedto.StartTime.ToString("yyyy/MM/dd HH:mm"));
  886. var totalHours = stoptime.Subtract(starttime).TotalHours;
  887. var parkingCost = Decimal.Multiply((decimal)totalHours, parkingFee);
  888. parkingCost = DollarRounding(parkingCost, session.Currency);
  889. if (feedto.StopTime != GlobalConfig.DefaultNullTime)
  890. {
  891. //var customerInfo = await db.Customer
  892. // .Where(x => x.Id == session.CustomerId).Select(x => new { x.InstantStopTxReport, x.ApiUrl, x.ApiKey })
  893. // .FirstOrDefaultAsync();
  894. var customerInfo = await mainDbService.GetCustomer(session.CustomerId);
  895. decimal accountBalance = 0;
  896. decimal.TryParse(feedto.Fee.Split('+')[1], out accountBalance);
  897. var tx = await db.TransactionRecord.Where(x => x.Id == txEnergy.TxId).FirstOrDefaultAsync();
  898. if (tx == null)
  899. {
  900. logger.LogWarning("Tx is empty");
  901. return result;
  902. }
  903. if (tx.BillingDone) return result;
  904. var startTime = new DateTime(tx.StartTime.Year, tx.StartTime.Month, tx.StartTime.Day, tx.StartTime.Hour, 0, 0);
  905. List<ChargingBill> confirmbill = new List<ChargingBill>();
  906. receipt = string.Format("({0} )Energy:", chargedEnergy);
  907. while (startTime < tx.StopTime)
  908. {
  909. if (bill.Count == 1)
  910. {
  911. confirmbill = bill;
  912. receipt += string.Format("| {0} - {1}:| {2} kWh @ ${3}/kWh= ${4}", tx.StartTime.ToString("hh:mm tt", new CultureInfo("en-us")), tx.StopTime.ToString("hh:mm tt", new CultureInfo("en-us")),
  913. confirmbill[0].PeriodEnergy.ToString("0.0000"), bill[0].Fee, bill[0].Total);
  914. break;
  915. }
  916. if (bill.Count == 0)
  917. {
  918. receipt += string.Format("| {0} - {1} @ ${2}/hr= ${3}", feedto.StartTime.ToString("hh:mm tt", new CultureInfo("en-us")),
  919. feedto.StopTime.ToString("hh:mm tt", new CultureInfo("en-us")), feedto.Fee.Split('|')[0], chargingCost);
  920. break;
  921. }
  922. if (bill.Count > 1)
  923. {
  924. var time = startTime.ToString("hh:mm tt", new CultureInfo("en-us"));
  925. var tt = bill.Where(x => x.StartTime == time).FirstOrDefault();
  926. confirmbill.Add(tt);
  927. if (confirmbill.Count == 1)
  928. {
  929. confirmbill[0].StartTime = tx.StartTime.ToString("hh:mm tt", new CultureInfo("en-us"));
  930. }
  931. var stopTimeText = tx.StopTime.ToString("hh:mm tt", new CultureInfo("en-us"));
  932. if (confirmbill[confirmbill.Count - 1].StartTime.Contains(stopTimeText.Split(' ')[1]))
  933. {
  934. var subHourText = (int.Parse(stopTimeText.Split(':')[0])).ToString();
  935. subHourText = subHourText.Length == 1 ? "0" + subHourText : subHourText;
  936. if (confirmbill[confirmbill.Count - 1].StartTime.Contains(subHourText))
  937. {
  938. confirmbill[confirmbill.Count - 1].EndTime = stopTimeText;
  939. }
  940. }
  941. receipt += string.Format("| {0} - {1}:| {2} kWh @ ${3}/kWh= ${4}", confirmbill[confirmbill.Count - 1].StartTime, confirmbill[confirmbill.Count - 1].EndTime,
  942. confirmbill[confirmbill.Count - 1].PeriodEnergy.ToString("0.0000"), confirmbill[confirmbill.Count - 1].Fee, confirmbill[confirmbill.Count - 1].Total);
  943. if (confirmbill.Count == 24) break;
  944. }
  945. startTime = startTime.AddHours(1);
  946. }
  947. chargingCost = confirmbill.Count > 0 ? confirmbill.Sum(x => x.Total) : chargingCost;
  948. receipt += string.Format("|Total Energy Fee : ${0}", chargingCost);
  949. receipt += string.Format("|Parking Fee: | {0} - {1}: | {2} @ ${3}/hr= ${4}", feedto.StartTime.ToString("hh:mm tt", new CultureInfo("en-us")),
  950. feedto.StopTime.ToString("hh:mm tt", new CultureInfo("en-us")), (totalHours / 1 >= 1) ? string.Format("{0} hours {1} minutes", (int)totalHours / 1, ((totalHours % 1) * 60).ToString("0.0")) : string.Format("{0} minutes", ((totalHours % 1) * 60).ToString("0.0")), parkingFee, parkingCost);
  951. receipt += string.Format("|Stop Reason: {0}", tx.StopReason);
  952. tx.Cost = chargingCost + parkingCost;
  953. if (customerInfo != null && customerInfo.InstantStopTxReport)
  954. {
  955. var request = new
  956. {
  957. ChargeBoxId = tx.ChargeBoxId,
  958. ConnectorId = tx.ConnectorId,
  959. SessionId = tx.Id,
  960. MeterStart = tx.MeterStart,
  961. MeterStop = tx.MeterStop,
  962. IdTag = tx.StartIdTag,
  963. StartTime = tx.StartTime.ToString(GlobalConfig.UTC_DATETIMEFORMAT),
  964. StopTime = tx.StopTime.ToString(GlobalConfig.UTC_DATETIMEFORMAT),
  965. StopReason = tx.StopReasonId < 1 ? "Unknown" : (tx.StopReasonId > 12 ? "Unknown" : ((Reason)tx.StopReasonId).ToString()),
  966. Receipt = tx.Receipt,
  967. TotalCost = tx.Cost,
  968. Fee = tx.Fee
  969. };
  970. logger.LogDebug("completed_session " + JsonConvert.SerializeObject(request));
  971. var response = await httpClient.Post(customerInfo.ApiUrl + "completed_session", new Dictionary<string, string>()
  972. {
  973. { "PartnerId",session.CustomerId.ToString()}
  974. }, request, customerInfo.ApiKey);
  975. var _httpResult = JsonConvert.DeserializeObject<CPOOuterResponse>(response.Response);
  976. logger.LogDebug("completed_session Response" + response.Response);
  977. JObject jo = JObject.Parse(_httpResult.Data);
  978. if (jo.ContainsKey("CouponPoint"))
  979. {
  980. couponPoint = jo["CouponPoint"].Value<Decimal>();
  981. }
  982. if (jo.ContainsKey("FarewellMessage"))
  983. {
  984. farewellMessage = jo["FarewellMessage"].Value<string>();
  985. }
  986. }
  987. tx.Receipt = receipt;
  988. tx.BillingDone = true;
  989. db.ChangeTracker.AutoDetectChangesEnabled = false;
  990. //db.Configuration.ValidateOnSaveEnabled = false;
  991. db.TransactionRecord.Attach(tx);
  992. db.Entry(tx).Property(x => x.Cost).IsModified = true;
  993. db.Entry(tx).Property(x => x.Receipt).IsModified = true;
  994. db.Entry(tx).Property(x => x.BillingDone).IsModified = true;
  995. await db.SaveChangesAsync();
  996. await messageService.SendDataTransferRequest(
  997. session.ChargeBoxId,
  998. messageId: "FinalCost",
  999. vendorId: "Phihong Technology",
  1000. data: JsonConvert.SerializeObject(new
  1001. {
  1002. txId = txEnergy.TxId,
  1003. description = JsonConvert.SerializeObject(new
  1004. {
  1005. chargedEnergy = chargedEnergy,
  1006. chargingFee = chargingCost,
  1007. parkTime = (int)stoptime.Subtract(starttime).TotalSeconds,
  1008. parkingFee = parkingCost,
  1009. currency = currency,
  1010. couponPoint = couponPoint,
  1011. accountBalance = accountBalance - tx.Cost,
  1012. farewellMessage = farewellMessage
  1013. })
  1014. })
  1015. );
  1016. await meterValueDbService.InsertAsync(
  1017. chargeBoxId: session.ChargeBoxId,
  1018. connectorId: feedto.ConnectorId,
  1019. value: chargingCost,
  1020. createdOn: DateTime.UtcNow,
  1021. contextId: (int)ReadingContext.Sample_Periodic,
  1022. formatId: (int)ValueFormat.Raw,
  1023. measurandId: (int)Measurand.TotalCost,
  1024. phaseId: -1,
  1025. locationId: -1,
  1026. unitId: -1,
  1027. transactionId: feedto.Id);
  1028. using (SqlConnection conn = await webDbConnectionFactory.CreateAsync())
  1029. {
  1030. var parameters = new DynamicParameters();
  1031. parameters.Add("@IdTag", tx.StartIdTag, DbType.String, ParameterDirection.Input, 50);
  1032. parameters.Add("@parentIdTag", accountBalance - tx.Cost, DbType.String, ParameterDirection.Input, 50);
  1033. string strSql = "update [dbo].[LocalListDetail] set parentIdTag =@parentIdTag where ListId = 27 and IdTag=@IdTag; ";
  1034. await conn.ExecuteAsync(strSql, parameters);
  1035. }
  1036. #region 提供給PHA 過CDFA認證 使用
  1037. if (tx.CustomerId == Guid.Parse("10C7F5BD-C89A-4E2A-8611-B617E0B41A73"))
  1038. {
  1039. var mail_response = httpClient.PostFormDataAsync("https://evcb.zerovatech.com/CDFA/" + tx.Id, new Dictionary<string, string>()
  1040. {
  1041. { "email","2"},
  1042. { "to","wonderj@phihongusa.com;jessica_tseng@phihong.com.tw"}
  1043. //{ "to","jessica_tseng@phihong.com.tw"}
  1044. }, null);
  1045. logger.LogTrace(JsonConvert.SerializeObject(mail_response));
  1046. }
  1047. #endregion
  1048. }
  1049. else
  1050. {
  1051. await messageService.SendDataTransferRequest(
  1052. session.ChargeBoxId,
  1053. messageId: "RunningCost",
  1054. vendorId: "Phihong Technology",
  1055. data: JsonConvert.SerializeObject(new
  1056. {
  1057. txId = txEnergy.TxId,
  1058. description = JsonConvert.SerializeObject(new
  1059. {
  1060. chargedEnergy = chargedEnergy,
  1061. chargingFee = chargingCost,
  1062. parkTime = (int)stoptime.Subtract(starttime).TotalSeconds,
  1063. parkingFee = parkingCost,
  1064. currency = currency
  1065. })
  1066. })
  1067. );
  1068. await meterValueDbService.InsertAsync(
  1069. chargeBoxId: session.ChargeBoxId,
  1070. connectorId: (byte)feedto.ConnectorId,
  1071. value: chargingCost,
  1072. createdOn: DateTime.UtcNow,
  1073. contextId: (int)ReadingContext.Sample_Periodic,
  1074. formatId: (int)ValueFormat.Raw,
  1075. measurandId: (int)Measurand.ChargingCost,
  1076. phaseId: -1,
  1077. locationId: -1,
  1078. unitId: -1,
  1079. transactionId: feedto.Id
  1080. );
  1081. }
  1082. }
  1083. }
  1084. #region 台泥
  1085. if (_request.messageId == "ID_GetTxUserInfo")
  1086. {
  1087. var txUserInfo = JsonConvert.DeserializeObject<ID_GetTxUserInfo>(_confirm.data);
  1088. if (session.CustomerId == new Guid("009E603C-79CD-4620-A2B8-D9349C0E8AD8"))
  1089. {
  1090. var request = new
  1091. {
  1092. ChargeBoxId = session.ChargeBoxId,
  1093. ConnectorId = txUserInfo.ConnectorId,
  1094. SessionId = txUserInfo.TxId,
  1095. SerialNo = txUserInfo.SerialNo,
  1096. StartTime = txUserInfo.StartTime.ToString(GlobalConfig.UTC_DATETIMEFORMAT),
  1097. VEMData = txUserInfo.VEMData
  1098. };
  1099. var response = httpClient.Post(GlobalConfig.TCC_API_URL + "start_session", new Dictionary<string, string>()
  1100. {
  1101. { "PartnerId",session.CustomerId.ToString()}
  1102. }, request, GlobalConfig.TCC_SALTKEY);
  1103. logger.LogDebug(JsonConvert.SerializeObject(response));
  1104. }
  1105. }
  1106. #endregion
  1107. }
  1108. }
  1109. break;
  1110. case Actions.ChangeAvailability:
  1111. {
  1112. ChangeAvailabilityConfirmation _confirm = confirm as ChangeAvailabilityConfirmation;
  1113. ChangeAvailabilityRequest _request = _confirm.GetRequest() as ChangeAvailabilityRequest;
  1114. using (var db = await maindbContextFactory.CreateDbContextAsync())
  1115. {
  1116. var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  1117. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
  1118. if (operation != null)
  1119. {
  1120. operation.FinishedOn = DateTime.UtcNow;
  1121. operation.Status = 1;//電樁有回覆
  1122. operation.EVSE_Status = (int)_confirm.status;
  1123. operation.EVSE_Value = _confirm.status.ToString();
  1124. await db.SaveChangesAsync();
  1125. }
  1126. }
  1127. }
  1128. break;
  1129. case Actions.ClearCache:
  1130. {
  1131. ClearCacheConfirmation _confirm = confirm as ClearCacheConfirmation;
  1132. ClearCacheRequest _request = _confirm.GetRequest() as ClearCacheRequest;
  1133. using (var db = await maindbContextFactory.CreateDbContextAsync())
  1134. {
  1135. var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  1136. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
  1137. if (operation != null)
  1138. {
  1139. operation.FinishedOn = DateTime.UtcNow;
  1140. operation.Status = 1;//電樁有回覆
  1141. operation.EVSE_Status = (int)_confirm.status;
  1142. operation.EVSE_Value = _confirm.status.ToString();
  1143. await db.SaveChangesAsync();
  1144. }
  1145. }
  1146. }
  1147. break;
  1148. case Actions.RemoteStartTransaction:
  1149. {
  1150. RemoteStartTransactionConfirmation _confirm = confirm as RemoteStartTransactionConfirmation;
  1151. RemoteStartTransactionRequest _request = _confirm.GetRequest() as RemoteStartTransactionRequest;
  1152. using (var db = await maindbContextFactory.CreateDbContextAsync())
  1153. {
  1154. var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  1155. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
  1156. if (operation != null)
  1157. {
  1158. operation.FinishedOn = DateTime.UtcNow;
  1159. operation.Status = 1;//電樁有回覆
  1160. operation.EVSE_Status = (int)_confirm.status;
  1161. operation.EVSE_Value = _confirm.status.ToString();
  1162. await db.SaveChangesAsync();
  1163. }
  1164. }
  1165. }
  1166. break;
  1167. case Actions.RemoteStopTransaction:
  1168. {
  1169. RemoteStopTransactionConfirmation _confirm = confirm as RemoteStopTransactionConfirmation;
  1170. RemoteStopTransactionRequest _request = _confirm.GetRequest() as RemoteStopTransactionRequest;
  1171. using (var db = await maindbContextFactory.CreateDbContextAsync())
  1172. {
  1173. var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  1174. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
  1175. if (operation != null)
  1176. {
  1177. operation.FinishedOn = DateTime.UtcNow;
  1178. operation.Status = 1;//電樁有回覆
  1179. operation.EVSE_Status = (int)_confirm.status;
  1180. operation.EVSE_Value = _confirm.status.ToString();
  1181. await db.SaveChangesAsync();
  1182. }
  1183. }
  1184. }
  1185. break;
  1186. case Actions.Reset:
  1187. {
  1188. ResetConfirmation _confirm = confirm as ResetConfirmation;
  1189. ResetRequest _request = _confirm.GetRequest() as ResetRequest;
  1190. using (var db = await maindbContextFactory.CreateDbContextAsync())
  1191. {
  1192. var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  1193. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
  1194. if (operation != null)
  1195. {
  1196. operation.FinishedOn = DateTime.UtcNow;
  1197. operation.Status = 1;//電樁有回覆
  1198. operation.EVSE_Status = (int)_confirm.status;
  1199. operation.EVSE_Value = _confirm.status.ToString();
  1200. await db.SaveChangesAsync();
  1201. }
  1202. }
  1203. }
  1204. break;
  1205. case Actions.ChangeConfiguration:
  1206. {
  1207. ChangeConfigurationConfirmation _confirm = confirm as ChangeConfigurationConfirmation;
  1208. ChangeConfigurationRequest _request = _confirm.GetRequest() as ChangeConfigurationRequest;
  1209. using (var db = await maindbContextFactory.CreateDbContextAsync())
  1210. {
  1211. var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  1212. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
  1213. if (operation != null)
  1214. {
  1215. operation.FinishedOn = DateTime.UtcNow;
  1216. operation.Status = 1;//電樁有回覆
  1217. operation.EVSE_Status = (int)_confirm.status;
  1218. operation.EVSE_Value = _confirm.status.ToString();
  1219. }
  1220. if (_confirm.status == Packet.Messages.SubTypes.ConfigurationStatus.Accepted || _confirm.status == Packet.Messages.SubTypes.ConfigurationStatus.RebootRequired)
  1221. {
  1222. var configure = await db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId).ToListAsync();
  1223. var foundConfig = configure.Find(x => x.ConfigureName == _request.key);
  1224. if (foundConfig != null)
  1225. {
  1226. foundConfig.ReadOnly = false;
  1227. foundConfig.ConfigureSetting = _request.value;
  1228. }
  1229. else
  1230. {
  1231. await db.MachineConfigurations.AddAsync(new MachineConfiguration()
  1232. {
  1233. ChargeBoxId = session.ChargeBoxId,
  1234. ConfigureName = _request.key,
  1235. ReadOnly = false,
  1236. ConfigureSetting = _request.value
  1237. });
  1238. }
  1239. }
  1240. await db.SaveChangesAsync();
  1241. }
  1242. }
  1243. break;
  1244. case Actions.GetConfiguration:
  1245. {
  1246. try
  1247. {
  1248. GetConfigurationConfirmation _confirm = confirm as GetConfigurationConfirmation;
  1249. // GetConfigurationRequest _request = _confirm.GetRequest() as GetConfigurationRequest;
  1250. using (var db = await maindbContextFactory.CreateDbContextAsync())
  1251. {
  1252. var configure = await db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId).ToListAsync();
  1253. if (_confirm.configurationKey != null)
  1254. {
  1255. foreach (var item in _confirm.configurationKey)
  1256. {
  1257. string oldValue = string.Empty;
  1258. if (item.key == null)
  1259. {
  1260. logger.LogTrace("*********************");
  1261. }
  1262. var foundConfig = configure.Find(x => x.ConfigureName == item.key);
  1263. if (foundConfig != null)
  1264. {
  1265. if (foundConfig.ConfigureName == null)
  1266. {
  1267. logger.LogTrace("*********************");
  1268. }
  1269. if (foundConfig.ConfigureName == "SecurityProfile")
  1270. {
  1271. oldValue = foundConfig.ConfigureSetting;
  1272. }
  1273. foundConfig.ReadOnly = item.IsReadOnly;
  1274. foundConfig.ConfigureSetting = string.IsNullOrEmpty(item.value) ? string.Empty : item.value;
  1275. }
  1276. else
  1277. {
  1278. await db.MachineConfigurations.AddAsync(new MachineConfiguration()
  1279. {
  1280. ChargeBoxId = session.ChargeBoxId,
  1281. ConfigureName = item.key,
  1282. ReadOnly = item.IsReadOnly,
  1283. ConfigureSetting = string.IsNullOrEmpty(item.value) ? string.Empty : item.value,
  1284. Exists = true
  1285. });
  1286. }
  1287. }
  1288. }
  1289. if (_confirm.unknownKey != null)
  1290. {
  1291. foreach (var item in _confirm.unknownKey)
  1292. {
  1293. var foundConfig = configure.Find(x => x.ConfigureName == item);
  1294. if (foundConfig != null)
  1295. {
  1296. foundConfig.ReadOnly = true;
  1297. foundConfig.ConfigureSetting = string.Empty;
  1298. foundConfig.Exists = false;
  1299. }
  1300. else
  1301. {
  1302. await db.MachineConfigurations.AddAsync(new MachineConfiguration()
  1303. {
  1304. ChargeBoxId = session.ChargeBoxId,
  1305. ConfigureName = item
  1306. });
  1307. }
  1308. }
  1309. }
  1310. var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  1311. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
  1312. if (operation != null)
  1313. {
  1314. operation.FinishedOn = DateTime.UtcNow;
  1315. operation.Status = 1;//電樁有回覆
  1316. operation.EVSE_Status = 1;
  1317. operation.EVSE_Value = JsonConvert.SerializeObject(_confirm.configurationKey, Formatting.None);
  1318. }
  1319. await db.SaveChangesAsync();
  1320. }
  1321. }
  1322. catch (Exception ex)
  1323. {
  1324. logger.LogError(ex.ToString());
  1325. }
  1326. }
  1327. break;
  1328. case Actions.UnlockConnector:
  1329. {
  1330. UnlockConnectorConfirmation _confirm = confirm as UnlockConnectorConfirmation;
  1331. UnlockConnectorRequest _request = _confirm.GetRequest() as UnlockConnectorRequest;
  1332. using (var db = await maindbContextFactory.CreateDbContextAsync())
  1333. {
  1334. var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  1335. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
  1336. if (operation != null)
  1337. {
  1338. operation.FinishedOn = DateTime.UtcNow;
  1339. operation.Status = 1;//電樁有回覆
  1340. operation.EVSE_Status = (int)_confirm.status;
  1341. operation.EVSE_Value = _confirm.status.ToString();
  1342. await db.SaveChangesAsync();
  1343. }
  1344. }
  1345. }
  1346. break;
  1347. default:
  1348. {
  1349. logger.LogWarning(string.Format("Not Implement {0} Logic(ExecuteCoreConfirm)", confirm.GetType().ToString().Replace("OCPPPackage.Messages.Core.", "")));
  1350. }
  1351. break;
  1352. }
  1353. }
  1354. catch (Exception ex)
  1355. {
  1356. logger.LogDebug("123 " + action + " " + ex.ToString());
  1357. }
  1358. return result;
  1359. }
  1360. internal async Task<MessageResult> ReceivedCoreError(Actions action, string errorMsg, ClientData session, string requestId)
  1361. {
  1362. MessageResult result = new MessageResult() { Success = true };
  1363. switch (action)
  1364. {
  1365. case Actions.ChangeAvailability:
  1366. case Actions.ChangeConfiguration:
  1367. case Actions.ClearCache:
  1368. case Actions.RemoteStartTransaction:
  1369. case Actions.RemoteStopTransaction:
  1370. case Actions.Reset:
  1371. case Actions.GetConfiguration:
  1372. case Actions.UnlockConnector:
  1373. case Actions.DataTransfer:
  1374. {
  1375. if (action == Actions.DataTransfer)
  1376. {
  1377. logger.LogDebug(string.Format("DataTransfer Error {0}: {1}", session.ChargeBoxId, requestId));
  1378. }
  1379. using (var db = await maindbContextFactory.CreateDbContextAsync())
  1380. {
  1381. var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  1382. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
  1383. if (operation != null)
  1384. {
  1385. operation.FinishedOn = DateTime.UtcNow;
  1386. operation.Status = 1;//電樁有回覆
  1387. operation.EVSE_Status = (int)255;//錯誤
  1388. operation.EVSE_Value = errorMsg;
  1389. await db.SaveChangesAsync();
  1390. }
  1391. }
  1392. }
  1393. break;
  1394. default:
  1395. {
  1396. logger.LogWarning(string.Format("Not Implement {0} Logic(ReceivedCoreError)", action));
  1397. }
  1398. break;
  1399. }
  1400. return result;
  1401. }
  1402. /// <summary>
  1403. /// 依據幣值處理4捨5入
  1404. /// </summary>
  1405. /// <param name="money"></param>
  1406. /// <param name="currency"></param>
  1407. /// <returns></returns>
  1408. private decimal DollarRounding(decimal money, string currency)
  1409. {
  1410. if (currency == "USD" || currency == "EUR")
  1411. {
  1412. //0.4867
  1413. if ((double)((int)(money * 100) + 0.5) <= (double)(money * 100))
  1414. {
  1415. //money = Decimal.Add(money, (decimal)0.01);//0.4967
  1416. }
  1417. money = Math.Round(money, 2, MidpointRounding.AwayFromZero);
  1418. money = Decimal.Parse(money.ToString("0.00"));
  1419. }
  1420. else
  1421. {
  1422. if ((double)((int)(money) + 0.5) <= (double)money)
  1423. {
  1424. // money = (int) money + 1;
  1425. }
  1426. money = Math.Round(money, 0, MidpointRounding.AwayFromZero);
  1427. money = Decimal.Parse(money.ToString("0"));
  1428. }
  1429. return money;
  1430. }
  1431. }