CoreProfileHandler.cs 66 KB

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