CoreProfileHandler.cs 94 KB

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