CoreProfileHandler.cs 94 KB

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