CoreProfileHandler.cs 97 KB

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