CoreProfileHandler.cs 95 KB

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