CoreProfileHandler.cs 87 KB

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