CoreProfileHandler.cs 92 KB

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