CoreProfileHandler.cs 100 KB

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