CoreProfileHandler.cs 95 KB

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