CoreProfileHandler.cs 100 KB

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