CoreProfileHandler.cs 78 KB

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