CoreProfileHandler.cs 94 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.Helper;
  10. using EVCB_OCPP.WSServer.Service;
  11. using Microsoft.Data.SqlClient;
  12. using Microsoft.EntityFrameworkCore;
  13. using Microsoft.Extensions.Configuration;
  14. using Microsoft.Extensions.DependencyInjection;
  15. using Microsoft.Extensions.Logging;
  16. using MongoDB.Driver.Core.Servers;
  17. using Newtonsoft.Json;
  18. using Newtonsoft.Json.Linq;
  19. using OCPPPackage.Profiles;
  20. using OCPPServer.Protocol;
  21. using System;
  22. using System.Collections.Generic;
  23. using System.Configuration;
  24. using System.Data;
  25. using System.Diagnostics;
  26. using System.Globalization;
  27. using System.Linq;
  28. using System.Threading.Tasks;
  29. namespace EVCB_OCPP.WSServer.Message;
  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 = await db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefaultAsync();
  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. await db.SaveChangesAsync();
  169. }
  170. using (var db = await maindbContextFactory.CreateDbContextAsync())
  171. {
  172. var configVaule = await db.MachineConfigurations
  173. .Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.HeartbeatInterval)
  174. .Select(x => x.ConfigureSetting)
  175. .FirstOrDefaultAsync();
  176. if (configVaule != null)
  177. {
  178. int.TryParse(configVaule, out heartbeat_interval);
  179. }
  180. }
  181. var confirm = new BootNotificationConfirmation() { currentTime = DateTime.UtcNow, interval = session.IsPending ? heartbeat_interval : 5, status = session.IsPending ? Packet.Messages.SubTypes.RegistrationStatus.Accepted : RegistrationStatus.Pending };
  182. session.IsPending = !session.IsPending;
  183. result.Message = confirm;
  184. result.Success = true;
  185. }
  186. break;
  187. case Actions.StatusNotification:
  188. {
  189. //只保留最新上報狀況
  190. StatusNotificationRequest _request = request as StatusNotificationRequest;
  191. int preStatus = 0;
  192. ConnectorStatus _oldStatus;
  193. using (var db = await maindbContextFactory.CreateDbContextAsync())
  194. {
  195. _oldStatus = await db.ConnectorStatus.Where(x => x.ChargeBoxId == session.ChargeBoxId
  196. && x.ConnectorId == _request.connectorId).AsNoTracking().FirstOrDefaultAsync();
  197. }
  198. if (_oldStatus != null && (_request.status != (ChargePointStatus)_oldStatus.Status || _request.status == ChargePointStatus.Faulted))
  199. {
  200. using (var db = await maindbContextFactory.CreateDbContextAsync())
  201. {
  202. preStatus = _oldStatus.Status;
  203. db.ChangeTracker.AutoDetectChangesEnabled = false;
  204. db.ConnectorStatus.Attach(_oldStatus);
  205. _oldStatus.CreatedOn = _request.timestamp.HasValue ? _request.timestamp.Value : DateTime.UtcNow;
  206. _oldStatus.Status = (int)_request.status;
  207. _oldStatus.ChargePointErrorCodeId = (int)_request.errorCode;
  208. _oldStatus.ErrorInfo = string.IsNullOrEmpty(_request.info) ? string.Empty : _request.info;
  209. _oldStatus.VendorId = string.IsNullOrEmpty(_request.vendorId) ? string.Empty : _request.vendorId;
  210. _oldStatus.VendorErrorCode = string.IsNullOrEmpty(_request.vendorErrorCode) ? string.Empty : _request.vendorErrorCode;
  211. db.Entry(_oldStatus).Property(x => x.CreatedOn).IsModified = true;
  212. db.Entry(_oldStatus).Property(x => x.Status).IsModified = true;
  213. db.Entry(_oldStatus).Property(x => x.ChargePointErrorCodeId).IsModified = true;
  214. db.Entry(_oldStatus).Property(x => x.ErrorInfo).IsModified = true;
  215. db.Entry(_oldStatus).Property(x => x.VendorId).IsModified = true;
  216. db.Entry(_oldStatus).Property(x => x.VendorErrorCode).IsModified = true;
  217. await db.SaveChangesAsync();
  218. }
  219. }
  220. if (_oldStatus == null)
  221. {
  222. using (var db = await maindbContextFactory.CreateDbContextAsync())
  223. {
  224. var _currentStatus = new Domain.Models.Database.ConnectorStatus()
  225. {
  226. ChargeBoxId = session.ChargeBoxId,
  227. ConnectorId = (byte)_request.connectorId,
  228. CreatedOn = _request.timestamp.HasValue ? _request.timestamp.Value : DateTime.UtcNow,
  229. Status = (int)_request.status,
  230. ChargePointErrorCodeId = (int)_request.errorCode,
  231. ErrorInfo = string.IsNullOrEmpty(_request.info) ? string.Empty : _request.info,
  232. VendorId = string.IsNullOrEmpty(_request.vendorId) ? string.Empty : _request.vendorId,
  233. VendorErrorCode = string.IsNullOrEmpty(_request.vendorErrorCode) ? string.Empty : _request.vendorErrorCode,
  234. Id = Guid.NewGuid().ToString()
  235. };
  236. db.ConnectorStatus.Add(_currentStatus);
  237. await db.SaveChangesAsync();
  238. }
  239. }
  240. if (_request.status == Packet.Messages.SubTypes.ChargePointStatus.Faulted)
  241. {
  242. using (var db = await maindbContextFactory.CreateDbContextAsync())
  243. {
  244. db.MachineError.Add(new MachineError()
  245. {
  246. ConnectorId = (byte)_request.connectorId,
  247. CreatedOn = _request.timestamp.HasValue ? _request.timestamp.Value : DateTime.UtcNow,
  248. Status = (int)_request.status,
  249. ChargeBoxId = session.ChargeBoxId,
  250. ErrorCodeId = (int)_request.errorCode,
  251. ErrorInfo = string.IsNullOrEmpty(_request.info) ? string.Empty : _request.info,
  252. PreStatus = _oldStatus == null ? -1 : preStatus,
  253. VendorErrorCode = string.IsNullOrEmpty(_request.vendorErrorCode) ? string.Empty : _request.vendorErrorCode,
  254. VendorId = string.IsNullOrEmpty(_request.vendorId) ? string.Empty : _request.vendorId
  255. });
  256. await db.SaveChangesAsync();
  257. }
  258. }
  259. if (_request.status == Packet.Messages.SubTypes.ChargePointStatus.Faulted)
  260. {
  261. //var businessService = BusinessServiceFactory.CreateBusinessService(session.CustomerId.ToString());
  262. var businessService = await serviceProvider.GetService<BusinessServiceFactory>().CreateBusinessService(session.CustomerId.ToString());
  263. var notification = businessService.NotifyFaultStatus(new ErrorDetails()
  264. {
  265. ChargeBoxId = session.ChargeBoxId,
  266. ConnectorId = _request.connectorId,
  267. ErrorCode = _request.errorCode,
  268. Info = string.IsNullOrEmpty(_request.info) ? string.Empty : _request.info,
  269. OCcuredOn = _request.timestamp ?? DateTime.UtcNow,
  270. VendorErrorCode = string.IsNullOrEmpty(_request.vendorErrorCode) ? string.Empty : _request.vendorErrorCode,
  271. });
  272. }
  273. var confirm = new StatusNotificationConfirmation() { };
  274. result.Message = confirm;
  275. result.Success = true;
  276. }
  277. break;
  278. case Actions.Heartbeat:
  279. {
  280. var confirm = new HeartbeatConfirmation() { currentTime = DateTime.UtcNow };
  281. result.Message = confirm;
  282. result.Success = true;
  283. }
  284. break;
  285. case Actions.MeterValues:
  286. {
  287. MeterValuesRequest _request = request as MeterValuesRequest;
  288. if (_request.meterValue.Count > 0)
  289. {
  290. using (var db = await metervaluedbContextFactory.CreateDbContextAsync())
  291. {
  292. foreach (var item in _request.meterValue)
  293. {
  294. if (_request.transactionId.HasValue)
  295. {
  296. decimal meterStart = 0;
  297. var energy_Register = item.sampledValue.Where(x => x.measurand == Measurand.Energy_Active_Import_Register).FirstOrDefault();
  298. if (energy_Register != null)
  299. {
  300. decimal energyRegister = decimal.Parse(energy_Register.value);
  301. energyRegister = energy_Register.unit.Value == UnitOfMeasure.kWh ? decimal.Multiply(energyRegister, 1000) : energyRegister;
  302. using (var maindb = await maindbContextFactory.CreateDbContextAsync())
  303. {
  304. meterStart = await maindb.TransactionRecord
  305. .Where(x => x.Id == _request.transactionId.Value).Select(x => x.MeterStart)
  306. .FirstOrDefaultAsync();
  307. }
  308. item.sampledValue.Add(new SampledValue()
  309. {
  310. context = ReadingContext.Sample_Periodic,
  311. format = ValueFormat.Raw,
  312. location = Location.Outlet,
  313. phase = item.sampledValue.Where(x => x.measurand == Measurand.Energy_Active_Import_Register).Select(x => x.phase).FirstOrDefault(),
  314. unit = UnitOfMeasure.Wh,
  315. measurand = Measurand.TotalEnergy,
  316. value = decimal.Subtract(energyRegister, meterStart).ToString()
  317. });
  318. }
  319. }
  320. foreach (var sampleVaule in item.sampledValue)
  321. {
  322. decimal value = Convert.ToDecimal(sampleVaule.value);
  323. string sp = "[dbo].[uspInsertMeterValueRecord] @ChargeBoxId," +
  324. "@ConnectorId,@Value,@CreatedOn,@ContextId,@FormatId,@MeasurandId,@PhaseId,@LocationId,@UnitId,@TransactionId";
  325. List<SqlParameter> parameter = new List<SqlParameter>();
  326. parameter.AddInsertMeterValueRecordSqlParameters(
  327. chargeBoxId: session.ChargeBoxId
  328. ,connectorId: (byte)_request.connectorId
  329. ,value: value
  330. ,createdOn: item.timestamp
  331. ,contextId: sampleVaule.context.HasValue ? (int)sampleVaule.context : 0
  332. ,formatId: sampleVaule.format.HasValue ? (int)sampleVaule.format : 0
  333. ,measurandId: sampleVaule.measurand.HasValue ? (int)sampleVaule.measurand : 0
  334. ,phaseId: sampleVaule.phase.HasValue ? (int)sampleVaule.phase : 0
  335. ,locationId: sampleVaule.location.HasValue ? (int)sampleVaule.location : 0
  336. ,unitId: sampleVaule.unit.HasValue ? (int)sampleVaule.unit : 0
  337. ,transactionId: _request.transactionId.HasValue ? _request.transactionId.Value : -1);
  338. await db.Database.ExecuteSqlRawAsync(sp, parameter.ToArray());
  339. }
  340. }
  341. }
  342. }
  343. // if (energy_kwh > 0)
  344. {
  345. try
  346. {
  347. if (session.IsBilling)
  348. if (session.IsBilling)
  349. {
  350. using (var db = await maindbContextFactory.CreateDbContextAsync())
  351. {
  352. db.ServerMessage.Add(new ServerMessage()
  353. {
  354. ChargeBoxId = session.ChargeBoxId,
  355. CreatedBy = "Server",
  356. CreatedOn = DateTime.UtcNow,
  357. OutAction = Actions.DataTransfer.ToString(),
  358. OutRequest = JsonConvert.SerializeObject(
  359. new DataTransferRequest()
  360. {
  361. messageId = "ID_TxEnergy",
  362. vendorId = "Phihong Technology",
  363. data = JsonConvert.SerializeObject(new { txId = _request.transactionId, ConnectorId = _request.connectorId })
  364. },
  365. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  366. SerialNo = Guid.NewGuid().ToString(),
  367. InMessage = string.Empty
  368. });
  369. await db.SaveChangesAsync();
  370. }
  371. }
  372. }
  373. catch (Exception ex)
  374. {
  375. Console.WriteLine(string.Format("{0} :{1}", session.ChargeBoxId + " RunningCost", ex.Message));
  376. }
  377. }
  378. var confirm = new MeterValuesConfirmation() { };
  379. result.Message = confirm;
  380. result.Success = true;
  381. }
  382. break;
  383. case Actions.StartTransaction:
  384. {
  385. StartTransactionRequest _request = request as StartTransactionRequest;
  386. int _transactionId = -1;
  387. var businessService = await serviceProvider.GetService<BusinessServiceFactory>().CreateBusinessService(session.CustomerId.ToString());
  388. var _idTagInfo = new IdTagInfo() { expiryDate = DateTime.UtcNow.AddDays(1), status = AuthorizationStatus.Accepted };
  389. if (_request.idTag != "Backend")
  390. {
  391. var authorization_result = await businessService.Authorize(session.ChargeBoxId, _request.idTag);
  392. _idTagInfo = authorization_result.IdTagInfo;
  393. if (_idTagInfo.status == AuthorizationStatus.Accepted && authorization_result.ChargePointFee != null)
  394. {
  395. var price = authorization_result.ChargePointFee.Where(x => x.IsAC == session.IsAC).First();
  396. if (price != null)
  397. {
  398. if (session.UserPrices.ContainsKey(_request.idTag))
  399. {
  400. session.UserPrices[_request.idTag] = price.PerkWhFee.HasValue ? JsonConvert.SerializeObject(new List<ChargingPrice>() { new ChargingPrice() { StartTime = "00:00", EndTime = "23:59", Fee = price.PerkWhFee.Value } }) : price.PerHourFee.Value.ToString();
  401. session.UserPrices[_request.idTag] += "|+" + authorization_result.AccountBalance + "+" + "&" + price.ParkingFee + "&|" + price.Currency;
  402. }
  403. else
  404. {
  405. session.UserPrices.Add(_request.idTag, price.PerkWhFee.HasValue ? JsonConvert.SerializeObject(new List<ChargingPrice>() { new ChargingPrice() { StartTime = "00:00", EndTime = "23:59", Fee = price.PerkWhFee.Value } }) : price.PerHourFee.Value.ToString());
  406. session.UserPrices[_request.idTag] += "|+" + authorization_result.AccountBalance + "+" + "&" + price.ParkingFee + "&|" + price.Currency;
  407. }
  408. }
  409. }
  410. }
  411. //特例****飛宏客戶旗下的電樁,若遇到Portal沒回應的狀況 ~允許充電
  412. if (session.CustomerId.ToString().ToUpper() == "8456AED9-6DD9-4BF3-A94C-9F5DCB9506F7" && _idTagInfo.status == AuthorizationStatus.ConcurrentTx)
  413. {
  414. _idTagInfo = new IdTagInfo() { expiryDate = DateTime.UtcNow.AddDays(1), status = AuthorizationStatus.Accepted };
  415. }
  416. string accountBalance = "0";
  417. if (session.CustomerId.ToString().ToUpper() == "10C7F5BD-C89A-4E2A-8611-B617E0B41A73")
  418. {
  419. using (SqlConnection conn = new SqlConnection(webConnectionString))
  420. {
  421. var parameters = new DynamicParameters();
  422. parameters.Add("@IdTag", _request.idTag, DbType.String, ParameterDirection.Input, 50);
  423. string strSql = "select parentIdTag from [dbo].[LocalListDetail] where ListId = 27 and IdTag=@IdTag; ";
  424. accountBalance = await conn.ExecuteScalarAsync<string>(strSql, parameters);
  425. }
  426. }
  427. using (var db = await maindbContextFactory.CreateDbContextAsync())
  428. {
  429. var _CustomerId = await db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).Include(x => x.Customer).
  430. Select(x => x.CustomerId).FirstOrDefaultAsync();
  431. var _existedTx = await db.TransactionRecord.Where(x => x.CustomerId == _CustomerId && x.ChargeBoxId == session.ChargeBoxId
  432. && x.ConnectorId == _request.connectorId && x.StartTime == _request.timestamp).Select(C => new { C.Id }).AsNoTracking().FirstOrDefaultAsync();
  433. TransactionRecord _newTransaction = new TransactionRecord();
  434. if (_existedTx == null)
  435. {
  436. _newTransaction = new TransactionRecord()
  437. {
  438. ChargeBoxId = session.ChargeBoxId,
  439. ConnectorId = (byte)_request.connectorId,
  440. CreatedOn = DateTime.UtcNow,
  441. StartIdTag = _request.idTag,
  442. MeterStart = _request.meterStart,
  443. CustomerId = _CustomerId,
  444. StartTime = _request.timestamp.ToUniversalTime(),
  445. ReservationId = _request.reservationId.HasValue ? _request.reservationId.Value : 0,
  446. };
  447. if (session.UserPrices.ContainsKey(_request.idTag))
  448. {
  449. _newTransaction.Fee = !session.IsBilling ? string.Empty : session.UserPrices[_request.idTag];
  450. }
  451. else
  452. {
  453. _newTransaction.Fee = !session.IsBilling ? string.Empty : session.BillingMethod == 1 ? JsonConvert.SerializeObject(session.ChargingPrices) : session.ChargingFeebyHour.ToString();
  454. _newTransaction.Fee += !session.IsBilling ? string.Empty : "|+" + accountBalance + "+" + "&" + session.ParkingFee + "&|" + session.Currency;
  455. }
  456. db.TransactionRecord.Add(_newTransaction);
  457. await db.SaveChangesAsync();
  458. _transactionId = _newTransaction.Id;
  459. logger.LogInformation("***************************************************** ");
  460. logger.LogInformation(string.Format("{0} :TransactionId {1} ", session.ChargeBoxId, _newTransaction.Id));
  461. logger.LogInformation("***************************************************** ");
  462. }
  463. else
  464. {
  465. _transactionId = _existedTx.Id;
  466. logger.LogError("Duplication ***************************************************** " + _existedTx.Id);
  467. }
  468. }
  469. var confirm = new StartTransactionConfirmation()
  470. {
  471. idTagInfo = _idTagInfo,
  472. transactionId = _transactionId
  473. };
  474. result.Message = confirm;
  475. result.Success = true;
  476. }
  477. break;
  478. case Actions.StopTransaction:
  479. {
  480. StopTransactionRequest _request = request as StopTransactionRequest;
  481. int _ConnectorId = 0;
  482. var businessService = await serviceProvider.GetService<BusinessServiceFactory>().CreateBusinessService(session.CustomerId.ToString());
  483. var _idTagInfo = string.IsNullOrEmpty(_request.idTag) ? null : (_request.idTag == "Backend" ?
  484. new IdTagInfo() { expiryDate = DateTime.UtcNow.AddDays(1), status = AuthorizationStatus.Accepted } : (await businessService.Authorize(session.ChargeBoxId, _request.idTag)).IdTagInfo);
  485. //特例****飛宏客戶旗下的電樁,若遇到Portal沒回應的狀況 ~允許充電
  486. if (session.CustomerId.ToString().ToUpper() == "8456AED9-6DD9-4BF3-A94C-9F5DCB9506F7" && _idTagInfo != null && _idTagInfo.status == AuthorizationStatus.ConcurrentTx)
  487. {
  488. _idTagInfo = new IdTagInfo() { expiryDate = DateTime.UtcNow.AddDays(1), status = AuthorizationStatus.Accepted };
  489. }
  490. try
  491. {
  492. using (var db = await maindbContextFactory.CreateDbContextAsync())
  493. {
  494. var transaction = await db.TransactionRecord.Where(x => x.Id == _request.transactionId
  495. && x.ChargeBoxId == session.ChargeBoxId).FirstOrDefaultAsync();
  496. //遠傳太久以前的停止充電 直接拒絕 避免電樁持續重送~~~~~~~
  497. if (_request.timestamp < new DateTime(2021, 11, 1))
  498. {
  499. var confirm = new StopTransactionConfirmation()
  500. {
  501. idTagInfo = new IdTagInfo()
  502. {
  503. status = AuthorizationStatus.Invalid
  504. }
  505. };
  506. result.Message = confirm;
  507. result.Success = true;
  508. return result;
  509. }
  510. if (transaction != null)
  511. {
  512. var confirm = new StopTransactionConfirmation()
  513. {
  514. idTagInfo = _idTagInfo
  515. };
  516. //Avoid rewrite transaction data
  517. if (transaction.StopTime != GlobalConfig.DefaultNullTime)
  518. {
  519. result.Message = confirm;
  520. result.Success = true;
  521. return result;
  522. }
  523. _ConnectorId = transaction.ConnectorId;
  524. transaction.MeterStop = _request.meterStop;
  525. transaction.StopTime = _request.timestamp.ToUniversalTime();
  526. transaction.StopReasonId = _request.reason.HasValue ? (int)_request.reason.Value : 0;
  527. transaction.StopReason = _request.reason.HasValue ? _request.reason.Value.ToString() : Reason.Local.ToString();
  528. transaction.StopIdTag = _request.idTag;
  529. transaction.Receipt = string.Empty;
  530. transaction.Cost = session.IsBilling ? -1 : 0;
  531. if (_request.transactionData != null && _request.transactionData.Count > 0)
  532. {
  533. _request.transactionData[0].sampledValue.Add(new SampledValue()
  534. {
  535. context = ReadingContext.Transaction_End,
  536. format = ValueFormat.Raw,
  537. location = Location.Outlet,
  538. phase = _request.transactionData[0].sampledValue.Where(x => x.context.HasValue).Select(x => x.phase).FirstOrDefault(),
  539. unit = UnitOfMeasure.Wh,
  540. measurand = Measurand.TotalEnergy,
  541. value = decimal.Subtract(transaction.MeterStop, transaction.MeterStart).ToString()
  542. });
  543. }
  544. await db.SaveChangesAsync();
  545. if (session.IsBilling)
  546. {
  547. db.ServerMessage.Add(new ServerMessage()
  548. {
  549. ChargeBoxId = session.ChargeBoxId,
  550. CreatedBy = "Server",
  551. CreatedOn = DateTime.UtcNow,
  552. OutAction = Actions.DataTransfer.ToString(),
  553. OutRequest = JsonConvert.SerializeObject(
  554. new DataTransferRequest()
  555. {
  556. messageId = "ID_TxEnergy",
  557. vendorId = "Phihong Technology",
  558. data = JsonConvert.SerializeObject(new { txId = _request.transactionId, ConnectorId = transaction.ConnectorId })
  559. },
  560. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  561. SerialNo = Guid.NewGuid().ToString(),
  562. InMessage = string.Empty
  563. });
  564. await db.SaveChangesAsync();
  565. }
  566. result.Message = confirm;
  567. result.Success = true;
  568. }
  569. else
  570. {
  571. result.Exception = new Exception("Can't find transactionId " + _request.transactionId);
  572. }
  573. }
  574. #region Save MeterValue
  575. if (_request.transactionData != null &&
  576. _request.transactionData.Count > 0)
  577. {
  578. using (var _meterDb = await metervaluedbContextFactory.CreateDbContextAsync())
  579. {
  580. foreach (var item in _request.transactionData)
  581. foreach (var sampleVaule in item.sampledValue)
  582. {
  583. decimal value = Convert.ToDecimal(sampleVaule.value);
  584. string sp = "[dbo].[uspInsertMeterValueRecord] @ChargeBoxId," +
  585. "@ConnectorId,@Value,@CreatedOn,@ContextId,@FormatId,@MeasurandId,@PhaseId,@LocationId,@UnitId,@TransactionId";
  586. List<SqlParameter> parameter = new List<SqlParameter>();
  587. parameter.AddInsertMeterValueRecordSqlParameters(
  588. chargeBoxId: session.ChargeBoxId
  589. ,connectorId: (byte)_ConnectorId
  590. ,value: value
  591. ,createdOn: item.timestamp
  592. ,contextId: sampleVaule.context.HasValue ? (int)sampleVaule.context : 0
  593. ,formatId: sampleVaule.format.HasValue ? (int)sampleVaule.format : 0
  594. ,measurandId: sampleVaule.measurand.HasValue ? (int)sampleVaule.measurand : 0
  595. ,phaseId: sampleVaule.phase.HasValue ? (int)sampleVaule.phase : 0
  596. ,locationId: sampleVaule.location.HasValue ? (int)sampleVaule.location : 0
  597. ,unitId: sampleVaule.unit.HasValue ? (int)sampleVaule.unit : 0
  598. ,transactionId: _request.transactionId
  599. );
  600. _meterDb.Database.ExecuteSqlRaw(sp, parameter.ToArray());
  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 = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  700. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
  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 = await db.TransactionRecord.Where(x => x.Id == txEnergy.TxId).Select(x => new { Id = x.Id, ConnectorId = x.ConnectorId, Fee = x.Fee, StopTime = x.StopTime, StartTime = x.StartTime }).FirstOrDefaultAsync();
  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 = await db.Customer
  810. .Where(x => x.Id == session.CustomerId).Select(x => new { x.InstantStopTxReport, x.ApiUrl, x.ApiKey })
  811. .FirstOrDefaultAsync();
  812. decimal accountBalance = 0;
  813. decimal.TryParse(feedto.Fee.Split('+')[1], out accountBalance);
  814. var tx = await db.TransactionRecord.Where(x => x.Id == txEnergy.TxId).FirstOrDefaultAsync();
  815. if (tx == null)
  816. {
  817. Console.WriteLine("Tx is empty");
  818. return result;
  819. }
  820. if (tx.BillingDone) return result;
  821. var startTime = new DateTime(tx.StartTime.Year, tx.StartTime.Month, tx.StartTime.Day, tx.StartTime.Hour, 0, 0);
  822. List<ChargingBill> confirmbill = new List<ChargingBill>();
  823. receipt = string.Format("({0} )Energy:", chargedEnergy);
  824. while (startTime < tx.StopTime)
  825. {
  826. if (bill.Count == 1)
  827. {
  828. confirmbill = bill;
  829. 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")),
  830. confirmbill[0].PeriodEnergy.ToString("0.0000"), bill[0].Fee, bill[0].Total);
  831. break;
  832. }
  833. if (bill.Count == 0)
  834. {
  835. receipt += string.Format("| {0} - {1} @ ${2}/hr=${3}", feedto.StartTime.ToString("hh:mm tt", new CultureInfo("en-us")),
  836. feedto.StopTime.ToString("hh:mm tt", new CultureInfo("en-us")), feedto.Fee.Split('|')[0], chargingCost);
  837. break;
  838. }
  839. if (bill.Count > 1)
  840. {
  841. var time = startTime.ToString("hh:mm tt", new CultureInfo("en-us"));
  842. var tt = bill.Where(x => x.StartTime == time).FirstOrDefault();
  843. confirmbill.Add(tt);
  844. if (confirmbill.Count == 1)
  845. {
  846. confirmbill[0].StartTime = tx.StartTime.ToString("hh:mm tt", new CultureInfo("en-us"));
  847. }
  848. var stopTimeText = tx.StopTime.ToString("hh:mm tt", new CultureInfo("en-us"));
  849. if (confirmbill[confirmbill.Count - 1].StartTime.Contains(stopTimeText.Split(' ')[1]))
  850. {
  851. var subHourText = (int.Parse(stopTimeText.Split(':')[0])).ToString();
  852. subHourText = subHourText.Length == 1 ? "0" + subHourText : subHourText;
  853. if (confirmbill[confirmbill.Count - 1].StartTime.Contains(subHourText))
  854. {
  855. confirmbill[confirmbill.Count - 1].EndTime = stopTimeText;
  856. }
  857. }
  858. receipt += string.Format("| {0} - {1}:| {2} kWh @ ${3}/kWh=${4}", confirmbill[confirmbill.Count - 1].StartTime, confirmbill[confirmbill.Count - 1].EndTime,
  859. confirmbill[confirmbill.Count - 1].PeriodEnergy.ToString("0.0000"), confirmbill[confirmbill.Count - 1].Fee, confirmbill[confirmbill.Count - 1].Total);
  860. if (confirmbill.Count == 24) break;
  861. }
  862. startTime = startTime.AddHours(1);
  863. }
  864. if (session.CustomerId == new Guid("009E603C-79CD-4620-A2B8-D9349C0E8AD8"))
  865. {
  866. chargingCost = confirmbill.Count > 0 ? confirmbill.Sum(x => x.Total) : chargingCost;
  867. chargingCost = chargedEnergy == 0 ? 0 : (chargingCost + parkingCost < 1 ? 1 : chargingCost); //台泥最低一元
  868. receipt += string.Format("|Total Energy Fee : ${0}", chargingCost);
  869. receipt += string.Format("|Parking Fee: | {0} - {1} @ ${2}/hr=${3}", feedto.StartTime.ToString("hh:mm tt", new CultureInfo("en-us")),
  870. feedto.StopTime.ToString("hh:mm tt", new CultureInfo("en-us")), parkingFee, parkingCost);
  871. tx.Cost = chargingCost + parkingCost;
  872. }
  873. else
  874. {
  875. chargingCost = confirmbill.Count > 0 ? confirmbill.Sum(x => x.Total) : chargingCost;
  876. receipt += string.Format("|Total Energy Fee : ${0}", chargingCost);
  877. receipt += string.Format("|Parking Fee: | {0} - {1} @ ${2}/hr=${3}", feedto.StartTime.ToString("hh:mm tt", new CultureInfo("en-us")),
  878. feedto.StopTime.ToString("hh:mm tt", new CultureInfo("en-us")), parkingFee, parkingCost);
  879. tx.Cost = chargingCost + parkingCost;
  880. }
  881. if (customerInfo != null && customerInfo.InstantStopTxReport)
  882. {
  883. var request = new
  884. {
  885. ChargeBoxId = tx.ChargeBoxId,
  886. ConnectorId = tx.ConnectorId,
  887. SessionId = tx.Id,
  888. MeterStart = tx.MeterStart,
  889. MeterStop = tx.MeterStop,
  890. IdTag = tx.StartIdTag,
  891. StartTime = tx.StartTime.ToString(GlobalConfig.UTC_DATETIMEFORMAT),
  892. StopTime = tx.StopTime.ToString(GlobalConfig.UTC_DATETIMEFORMAT),
  893. StopReason = tx.StopReasonId < 1 ? "Unknown" : (tx.StopReasonId > 12 ? "Unknown" : ((Reason)tx.StopReasonId).ToString()),
  894. Receipt = tx.Receipt,
  895. TotalCost = tx.Cost,
  896. Fee = tx.Fee
  897. };
  898. logger.LogDebug("completed_session " + JsonConvert.SerializeObject(request));
  899. var response = await httpClient.Post(customerInfo.ApiUrl + "completed_session", new Dictionary<string, string>()
  900. {
  901. { "PartnerId",session.CustomerId.ToString()}
  902. }, request, customerInfo.ApiKey);
  903. var _httpResult = JsonConvert.DeserializeObject<CPOOuterResponse>(response.Response);
  904. logger.LogDebug("completed_session Response" + response.Response);
  905. JObject jo = JObject.Parse(_httpResult.Data);
  906. if (jo.ContainsKey("CouponPoint"))
  907. {
  908. couponPoint = jo["CouponPoint"].Value<Decimal>();
  909. }
  910. if (jo.ContainsKey("FarewellMessage"))
  911. {
  912. farewellMessage = jo["FarewellMessage"].Value<string>();
  913. }
  914. }
  915. tx.Receipt = receipt;
  916. tx.BillingDone = true;
  917. db.ChangeTracker.AutoDetectChangesEnabled = false;
  918. //db.Configuration.ValidateOnSaveEnabled = false;
  919. db.TransactionRecord.Attach(tx);
  920. db.Entry(tx).Property(x => x.Cost).IsModified = true;
  921. db.Entry(tx).Property(x => x.Receipt).IsModified = true;
  922. db.Entry(tx).Property(x => x.BillingDone).IsModified = true;
  923. db.ServerMessage.Add(new ServerMessage()
  924. {
  925. ChargeBoxId = session.ChargeBoxId,
  926. CreatedBy = "Server",
  927. CreatedOn = DateTime.UtcNow,
  928. OutAction = Actions.DataTransfer.ToString(),
  929. OutRequest = JsonConvert.SerializeObject(
  930. new DataTransferRequest()
  931. {
  932. messageId = "FinalCost",
  933. vendorId = "Phihong Technology",
  934. data = JsonConvert.SerializeObject(new
  935. {
  936. txId = txEnergy.TxId,
  937. description = JsonConvert.SerializeObject(new
  938. {
  939. chargedEnergy = chargedEnergy,
  940. chargingFee = chargingCost,
  941. parkTime = (int)stoptime.Subtract(starttime).TotalSeconds,
  942. parkingFee = parkingCost,
  943. currency = currency,
  944. couponPoint = couponPoint,
  945. accountBalance = accountBalance - tx.Cost,
  946. farewellMessage = farewellMessage
  947. })
  948. })
  949. },
  950. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  951. SerialNo = Guid.NewGuid().ToString(),
  952. InMessage = string.Empty
  953. }); ;
  954. await db.SaveChangesAsync();
  955. using (var meterdb = await metervaluedbContextFactory.CreateDbContextAsync())
  956. {
  957. string sp = "[dbo].[uspInsertMeterValueRecord] @ChargeBoxId," +
  958. "@ConnectorId,@Value,@CreatedOn,@ContextId,@FormatId,@MeasurandId,@PhaseId,@LocationId,@UnitId,@TransactionId";
  959. List<SqlParameter> parameter = new List<SqlParameter>();
  960. parameter.AddInsertMeterValueRecordSqlParameters(
  961. chargeBoxId: session.ChargeBoxId,
  962. connectorId: feedto.ConnectorId,
  963. value: chargingCost,
  964. createdOn: DateTime.UtcNow,
  965. contextId: (int)ReadingContext.Sample_Periodic,
  966. formatId: (int)ValueFormat.Raw,
  967. measurandId: (int)Measurand.TotalCost,
  968. phaseId: -1,
  969. locationId: -1,
  970. unitId: -1,
  971. transactionId: feedto.Id
  972. );
  973. meterdb.Database.ExecuteSqlRaw(sp, parameter.ToArray());
  974. }
  975. using (SqlConnection conn = new SqlConnection(webConnectionString))
  976. {
  977. var parameters = new DynamicParameters();
  978. parameters.Add("@IdTag", tx.StartIdTag, DbType.String, ParameterDirection.Input, 50);
  979. parameters.Add("@parentIdTag", accountBalance - tx.Cost, DbType.String, ParameterDirection.Input, 50);
  980. string strSql = "update [dbo].[LocalListDetail] set parentIdTag =@parentIdTag where ListId = 27 and IdTag=@IdTag; ";
  981. await conn.ExecuteAsync(strSql, parameters);
  982. }
  983. #region 提供給PHA 過CDFA認證 使用
  984. if (tx.CustomerId == Guid.Parse("10C7F5BD-C89A-4E2A-8611-B617E0B41A73"))
  985. {
  986. var mail_response = new OuterHttpClient().PostFormDataAsync("http://ocpp.phihong.com.tw/CDFA/" + tx.Id, new Dictionary<string, string>()
  987. {
  988. { "email","2"},
  989. { "to","wonderj@phihongusa.com;jessica_tseng@phihong.com.tw"}
  990. //{ "to","jessica_tseng@phihong.com.tw"}
  991. }, null);
  992. Console.WriteLine(JsonConvert.SerializeObject(mail_response));
  993. }
  994. #endregion
  995. }
  996. else
  997. {
  998. db.ServerMessage.Add(new ServerMessage()
  999. {
  1000. ChargeBoxId = session.ChargeBoxId,
  1001. CreatedBy = "Server",
  1002. CreatedOn = DateTime.UtcNow,
  1003. OutAction = Actions.DataTransfer.ToString(),
  1004. OutRequest = JsonConvert.SerializeObject(
  1005. new DataTransferRequest()
  1006. {
  1007. messageId = "RunningCost",
  1008. vendorId = "Phihong Technology",
  1009. data = JsonConvert.SerializeObject(new
  1010. {
  1011. txId = txEnergy.TxId,
  1012. description = JsonConvert.SerializeObject(new
  1013. {
  1014. chargedEnergy = chargedEnergy,
  1015. chargingFee = chargingCost,
  1016. parkTime = (int)stoptime.Subtract(starttime).TotalSeconds,
  1017. parkingFee = parkingCost,
  1018. currency = currency
  1019. })
  1020. })
  1021. },
  1022. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1023. SerialNo = Guid.NewGuid().ToString(),
  1024. InMessage = string.Empty
  1025. }); ;
  1026. await db.SaveChangesAsync();
  1027. using (var meterdb = await metervaluedbContextFactory.CreateDbContextAsync())
  1028. {
  1029. string sp = "[dbo].[uspInsertMeterValueRecord] @ChargeBoxId," +
  1030. "@ConnectorId,@Value,@CreatedOn,@ContextId,@FormatId,@MeasurandId,@PhaseId,@LocationId,@UnitId,@TransactionId";
  1031. List<SqlParameter> parameter = new List<SqlParameter>();
  1032. parameter.AddInsertMeterValueRecordSqlParameters(
  1033. chargeBoxId: session.ChargeBoxId,
  1034. connectorId: (byte)feedto.ConnectorId,
  1035. value: chargingCost,
  1036. createdOn: DateTime.UtcNow,
  1037. contextId: (int)ReadingContext.Sample_Periodic,
  1038. formatId: (int)ValueFormat.Raw,
  1039. measurandId: (int)Measurand.ChargingCost,
  1040. phaseId: -1,
  1041. locationId: -1,
  1042. unitId: -1,
  1043. transactionId: feedto.Id
  1044. );
  1045. meterdb.Database.ExecuteSqlRaw(sp, parameter.ToArray());
  1046. }
  1047. }
  1048. }
  1049. }
  1050. #region 台泥
  1051. if (_request.messageId == "ID_GetTxUserInfo")
  1052. {
  1053. var txUserInfo = JsonConvert.DeserializeObject<ID_GetTxUserInfo>(_confirm.data);
  1054. if (session.CustomerId == new Guid("009E603C-79CD-4620-A2B8-D9349C0E8AD8"))
  1055. {
  1056. var request = new
  1057. {
  1058. ChargeBoxId = session.ChargeBoxId,
  1059. ConnectorId = txUserInfo.ConnectorId,
  1060. SessionId = txUserInfo.TxId,
  1061. SerialNo = txUserInfo.SerialNo,
  1062. StartTime = txUserInfo.StartTime.ToString(GlobalConfig.UTC_DATETIMEFORMAT),
  1063. VEMData = txUserInfo.VEMData
  1064. };
  1065. var response = httpClient.Post(GlobalConfig.TCC_API_URL + "start_session", new Dictionary<string, string>()
  1066. {
  1067. { "PartnerId",session.CustomerId.ToString()}
  1068. }, request, GlobalConfig.TCC_SALTKEY);
  1069. logger.LogDebug(JsonConvert.SerializeObject(response));
  1070. }
  1071. }
  1072. #endregion
  1073. }
  1074. }
  1075. break;
  1076. case Actions.ChangeAvailability:
  1077. {
  1078. ChangeAvailabilityConfirmation _confirm = confirm as ChangeAvailabilityConfirmation;
  1079. ChangeAvailabilityRequest _request = _confirm.GetRequest() as ChangeAvailabilityRequest;
  1080. using (var db = await maindbContextFactory.CreateDbContextAsync())
  1081. {
  1082. var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  1083. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
  1084. if (operation != null)
  1085. {
  1086. operation.FinishedOn = DateTime.UtcNow;
  1087. operation.Status = 1;//電樁有回覆
  1088. operation.EVSE_Status = (int)_confirm.status;
  1089. operation.EVSE_Value = _confirm.status.ToString();
  1090. await db.SaveChangesAsync();
  1091. }
  1092. }
  1093. }
  1094. break;
  1095. case Actions.ClearCache:
  1096. {
  1097. ClearCacheConfirmation _confirm = confirm as ClearCacheConfirmation;
  1098. ClearCacheRequest _request = _confirm.GetRequest() as ClearCacheRequest;
  1099. using (var db = await maindbContextFactory.CreateDbContextAsync())
  1100. {
  1101. var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  1102. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
  1103. if (operation != null)
  1104. {
  1105. operation.FinishedOn = DateTime.UtcNow;
  1106. operation.Status = 1;//電樁有回覆
  1107. operation.EVSE_Status = (int)_confirm.status;
  1108. operation.EVSE_Value = _confirm.status.ToString();
  1109. await db.SaveChangesAsync();
  1110. }
  1111. }
  1112. }
  1113. break;
  1114. case Actions.RemoteStartTransaction:
  1115. {
  1116. RemoteStartTransactionConfirmation _confirm = confirm as RemoteStartTransactionConfirmation;
  1117. RemoteStartTransactionRequest _request = _confirm.GetRequest() as RemoteStartTransactionRequest;
  1118. using (var db = await maindbContextFactory.CreateDbContextAsync())
  1119. {
  1120. var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  1121. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
  1122. if (operation != null)
  1123. {
  1124. operation.FinishedOn = DateTime.UtcNow;
  1125. operation.Status = 1;//電樁有回覆
  1126. operation.EVSE_Status = (int)_confirm.status;
  1127. operation.EVSE_Value = _confirm.status.ToString();
  1128. await db.SaveChangesAsync();
  1129. }
  1130. }
  1131. }
  1132. break;
  1133. case Actions.RemoteStopTransaction:
  1134. {
  1135. RemoteStopTransactionConfirmation _confirm = confirm as RemoteStopTransactionConfirmation;
  1136. RemoteStopTransactionRequest _request = _confirm.GetRequest() as RemoteStopTransactionRequest;
  1137. using (var db = await maindbContextFactory.CreateDbContextAsync())
  1138. {
  1139. var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  1140. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
  1141. if (operation != null)
  1142. {
  1143. operation.FinishedOn = DateTime.UtcNow;
  1144. operation.Status = 1;//電樁有回覆
  1145. operation.EVSE_Status = (int)_confirm.status;
  1146. operation.EVSE_Value = _confirm.status.ToString();
  1147. await db.SaveChangesAsync();
  1148. }
  1149. }
  1150. }
  1151. break;
  1152. case Actions.Reset:
  1153. {
  1154. ResetConfirmation _confirm = confirm as ResetConfirmation;
  1155. ResetRequest _request = _confirm.GetRequest() as ResetRequest;
  1156. using (var db = await maindbContextFactory.CreateDbContextAsync())
  1157. {
  1158. var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  1159. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
  1160. if (operation != null)
  1161. {
  1162. operation.FinishedOn = DateTime.UtcNow;
  1163. operation.Status = 1;//電樁有回覆
  1164. operation.EVSE_Status = (int)_confirm.status;
  1165. operation.EVSE_Value = _confirm.status.ToString();
  1166. await db.SaveChangesAsync();
  1167. }
  1168. }
  1169. }
  1170. break;
  1171. case Actions.ChangeConfiguration:
  1172. {
  1173. ChangeConfigurationConfirmation _confirm = confirm as ChangeConfigurationConfirmation;
  1174. ChangeConfigurationRequest _request = _confirm.GetRequest() as ChangeConfigurationRequest;
  1175. using (var db = await maindbContextFactory.CreateDbContextAsync())
  1176. {
  1177. var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  1178. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
  1179. if (operation != null)
  1180. {
  1181. operation.FinishedOn = DateTime.UtcNow;
  1182. operation.Status = 1;//電樁有回覆
  1183. operation.EVSE_Status = (int)_confirm.status;
  1184. operation.EVSE_Value = _confirm.status.ToString();
  1185. }
  1186. if (_confirm.status == Packet.Messages.SubTypes.ConfigurationStatus.Accepted || _confirm.status == Packet.Messages.SubTypes.ConfigurationStatus.RebootRequired)
  1187. {
  1188. var configure = db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId).ToList();
  1189. var foundConfig = configure.Find(x => x.ConfigureName == _request.key);
  1190. if (foundConfig != null)
  1191. {
  1192. foundConfig.ReadOnly = false;
  1193. foundConfig.ConfigureSetting = _request.value;
  1194. }
  1195. else
  1196. {
  1197. db.MachineConfigurations.Add(new MachineConfiguration()
  1198. {
  1199. ChargeBoxId = session.ChargeBoxId,
  1200. ConfigureName = _request.key,
  1201. ReadOnly = false,
  1202. ConfigureSetting = _request.value
  1203. });
  1204. }
  1205. }
  1206. await db.SaveChangesAsync();
  1207. }
  1208. }
  1209. break;
  1210. case Actions.GetConfiguration:
  1211. {
  1212. try
  1213. {
  1214. GetConfigurationConfirmation _confirm = confirm as GetConfigurationConfirmation;
  1215. // GetConfigurationRequest _request = _confirm.GetRequest() as GetConfigurationRequest;
  1216. using (var db = await maindbContextFactory.CreateDbContextAsync())
  1217. {
  1218. var configure = db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId).ToList();
  1219. if (_confirm.configurationKey != null)
  1220. {
  1221. foreach (var item in _confirm.configurationKey)
  1222. {
  1223. string oldValue = string.Empty;
  1224. if (item.key == null)
  1225. {
  1226. Console.WriteLine("*********************");
  1227. }
  1228. var foundConfig = configure.Find(x => x.ConfigureName == item.key);
  1229. if (foundConfig != null)
  1230. {
  1231. if (foundConfig.ConfigureName == null)
  1232. {
  1233. Console.WriteLine("*********************");
  1234. }
  1235. if (foundConfig.ConfigureName == "SecurityProfile")
  1236. {
  1237. oldValue = foundConfig.ConfigureSetting;
  1238. }
  1239. foundConfig.ReadOnly = item.IsReadOnly;
  1240. foundConfig.ConfigureSetting = string.IsNullOrEmpty(item.value) ? string.Empty : item.value;
  1241. }
  1242. else
  1243. {
  1244. db.MachineConfigurations.Add(new MachineConfiguration()
  1245. {
  1246. ChargeBoxId = session.ChargeBoxId,
  1247. ConfigureName = item.key,
  1248. ReadOnly = item.IsReadOnly,
  1249. ConfigureSetting = string.IsNullOrEmpty(item.value) ? string.Empty : item.value,
  1250. Exists = true
  1251. });
  1252. }
  1253. }
  1254. }
  1255. if (_confirm.unknownKey != null)
  1256. {
  1257. foreach (var item in _confirm.unknownKey)
  1258. {
  1259. var foundConfig = configure.Find(x => x.ConfigureName == item);
  1260. if (foundConfig != null)
  1261. {
  1262. foundConfig.ReadOnly = true;
  1263. foundConfig.ConfigureSetting = string.Empty;
  1264. foundConfig.Exists = false;
  1265. }
  1266. else
  1267. {
  1268. db.MachineConfigurations.Add(new MachineConfiguration()
  1269. {
  1270. ChargeBoxId = session.ChargeBoxId,
  1271. ConfigureName = item
  1272. });
  1273. }
  1274. }
  1275. }
  1276. var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  1277. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
  1278. if (operation != null)
  1279. {
  1280. operation.FinishedOn = DateTime.UtcNow;
  1281. operation.Status = 1;//電樁有回覆
  1282. operation.EVSE_Status = 1;
  1283. operation.EVSE_Value = JsonConvert.SerializeObject(_confirm.configurationKey, Formatting.None);
  1284. }
  1285. await db.SaveChangesAsync();
  1286. }
  1287. }
  1288. catch (Exception ex)
  1289. {
  1290. logger.LogError(ex.ToString());
  1291. }
  1292. }
  1293. break;
  1294. case Actions.UnlockConnector:
  1295. {
  1296. UnlockConnectorConfirmation _confirm = confirm as UnlockConnectorConfirmation;
  1297. UnlockConnectorRequest _request = _confirm.GetRequest() as UnlockConnectorRequest;
  1298. using (var db = await maindbContextFactory.CreateDbContextAsync())
  1299. {
  1300. var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  1301. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
  1302. if (operation != null)
  1303. {
  1304. operation.FinishedOn = DateTime.UtcNow;
  1305. operation.Status = 1;//電樁有回覆
  1306. operation.EVSE_Status = (int)_confirm.status;
  1307. operation.EVSE_Value = _confirm.status.ToString();
  1308. await db.SaveChangesAsync();
  1309. }
  1310. }
  1311. }
  1312. break;
  1313. default:
  1314. {
  1315. Console.WriteLine(string.Format("Not Implement {0} Logic(ExecuteCoreConfirm)", confirm.GetType().ToString().Replace("OCPPPackage.Messages.Core.", "")));
  1316. }
  1317. break;
  1318. }
  1319. }
  1320. catch (Exception ex)
  1321. {
  1322. logger.LogDebug("123 " + action + " " + ex.ToString());
  1323. }
  1324. return result;
  1325. }
  1326. internal async Task<MessageResult> ReceivedCoreError(Actions action, string errorMsg, ClientData session, string requestId)
  1327. {
  1328. MessageResult result = new MessageResult() { Success = true };
  1329. switch (action)
  1330. {
  1331. case Actions.ChangeAvailability:
  1332. case Actions.ChangeConfiguration:
  1333. case Actions.ClearCache:
  1334. case Actions.RemoteStartTransaction:
  1335. case Actions.RemoteStopTransaction:
  1336. case Actions.Reset:
  1337. case Actions.GetConfiguration:
  1338. case Actions.UnlockConnector:
  1339. case Actions.DataTransfer:
  1340. {
  1341. if (action == Actions.DataTransfer)
  1342. {
  1343. logger.LogDebug(string.Format("DataTransfer Error {0}: {1}", session.ChargeBoxId, requestId));
  1344. }
  1345. using (var db = await maindbContextFactory.CreateDbContextAsync())
  1346. {
  1347. var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  1348. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
  1349. if (operation != null)
  1350. {
  1351. operation.FinishedOn = DateTime.UtcNow;
  1352. operation.Status = 1;//電樁有回覆
  1353. operation.EVSE_Status = (int)255;//錯誤
  1354. operation.EVSE_Value = errorMsg;
  1355. await db.SaveChangesAsync();
  1356. }
  1357. }
  1358. }
  1359. break;
  1360. default:
  1361. {
  1362. Console.WriteLine(string.Format("Not Implement {0} Logic(ReceivedCoreError)", action));
  1363. }
  1364. break;
  1365. }
  1366. return result;
  1367. }
  1368. /// <summary>
  1369. /// 依據幣值處理4捨5入
  1370. /// </summary>
  1371. /// <param name="money"></param>
  1372. /// <param name="currency"></param>
  1373. /// <returns></returns>
  1374. private decimal DollarRounding(decimal money, string currency)
  1375. {
  1376. if (currency == "USD" || currency == "EUR")
  1377. {
  1378. //0.4867
  1379. if ((double)((int)(money * 100) + 0.5) <= (double)(money * 100))
  1380. {
  1381. //money = Decimal.Add(money, (decimal)0.01);//0.4967
  1382. }
  1383. money = Math.Round(money, 2, MidpointRounding.AwayFromZero);
  1384. money = Decimal.Parse(money.ToString("0.00"));
  1385. }
  1386. else
  1387. {
  1388. if ((double)((int)(money) + 0.5) <= (double)money)
  1389. {
  1390. // money = (int) money + 1;
  1391. }
  1392. money = Math.Round(money, 0, MidpointRounding.AwayFromZero);
  1393. money = Decimal.Parse(money.ToString("0"));
  1394. }
  1395. return money;
  1396. }
  1397. }