CoreProfileHandler.cs 96 KB

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