CoreProfileHandler.cs 81 KB

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