CoreProfileHandler.cs 96 KB

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