CoreProfileHandler.cs 91 KB

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