CoreProfileHandler.cs 94 KB

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