CoreProfileHandler.cs 75 KB

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