CoreProfileHandler.cs 76 KB

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