CoreProfileHandler.cs 69 KB

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