CoreProfileHandler.cs 95 KB

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