CoreProfileHandler.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data.Entity;
  4. using System.Data.SqlClient;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using EVCB_OCPP.Domain;
  9. using EVCB_OCPP.Domain.Models.Database;
  10. using EVCB_OCPP.Packet.Features;
  11. using EVCB_OCPP.Packet.Messages;
  12. using EVCB_OCPP.Packet.Messages.Core;
  13. using EVCB_OCPP.Packet.Messages.SubTypes;
  14. using EVCB_OCPP.WSServer.Dto;
  15. using Newtonsoft.Json;
  16. using OCPPPackage.Profiles;
  17. using OCPPServer.Protocol;
  18. namespace EVCB_OCPP.WSServer.Message
  19. {
  20. internal partial class ProfileHandler
  21. {
  22. internal MessageResult ExecuteCoreRequest(Actions action, ClientData session, IRequest request)
  23. {
  24. MessageResult result = new MessageResult() { Success = false };
  25. switch (action)
  26. {
  27. case Actions.BootNotification:
  28. {
  29. BootNotificationRequest _request = request as BootNotificationRequest;
  30. int heartbeat_interval = GlobalConfig.DEFAULT_HEARTBEAT_INTERVAL;
  31. using (var db = new MainDBContext())
  32. {
  33. var _machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault();
  34. _machine.ChargeBoxSerialNumber = string.IsNullOrEmpty(_request.chargeBoxSerialNumber) ? string.Empty : _request.chargeBoxSerialNumber;
  35. _machine.ChargePointModel = string.IsNullOrEmpty(_request.chargePointModel) ? string.Empty : _request.chargePointModel;
  36. _machine.ChargePointVendor = string.IsNullOrEmpty(_request.chargePointVendor) ? string.Empty : _request.chargePointVendor;
  37. _machine.FW_CurrentVersion = string.IsNullOrEmpty(_request.firmwareVersion) ? string.Empty : _request.firmwareVersion;
  38. _machine.Iccid = string.IsNullOrEmpty(_request.iccid) ? string.Empty : _request.iccid;
  39. _machine.Imsi = string.IsNullOrEmpty(_request.imsi) ? string.Empty : _request.imsi;
  40. _machine.MeterSerialNumber = string.IsNullOrEmpty(_request.meterSerialNumber) ? string.Empty : _request.meterSerialNumber;
  41. _machine.MeterType = string.IsNullOrEmpty(_request.meterType) ? string.Empty : _request.meterType;
  42. db.SaveChanges();
  43. var configVaule = db.MachineConfigure.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.HeartbeatInterval)
  44. .Select(x => x.ConfigureSetting).FirstOrDefault();
  45. if (configVaule != null)
  46. {
  47. int.TryParse(configVaule, out heartbeat_interval);
  48. }
  49. }
  50. var confirm = new BootNotificationConfirmation() { currentTime = DateTime.Now, interval = heartbeat_interval, status = Packet.Messages.SubTypes.RegistrationStatus.Accepted };
  51. result.Message = confirm;
  52. result.Success = true;
  53. }
  54. break;
  55. case Actions.StatusNotification:
  56. {
  57. //只保留最新上報狀況
  58. StatusNotificationRequest _request = request as StatusNotificationRequest;
  59. List<string> removeIds = new List<string>();
  60. ConnectorErrorStauts _oldStatus = null;
  61. using (var oldDB = new MainDBContext())
  62. {
  63. if (_request.status == Packet.Messages.SubTypes.ChargePointStatus.Faulted)
  64. {
  65. _oldStatus = oldDB.ConnectorStatus.Where(x => x.ChargeBoxId == session.ChargeBoxId
  66. && x.ConnectorId == _request.connectorId).Select(x => new ConnectorErrorStauts
  67. {
  68. Status = x.Status,
  69. ChargePointErrorCodeId = x.ChargePointErrorCodeId,
  70. ErrorInfo = x.ErrorInfo,
  71. VendorId = x.VendorId,
  72. VendorErrorCode = x.VendorErrorCode
  73. }).FirstOrDefault();
  74. }
  75. removeIds = oldDB.ConnectorStatus.Where(x => x.ChargeBoxId == session.ChargeBoxId
  76. && x.ConnectorId == _request.connectorId).Select(x => x.Id).ToList();
  77. }
  78. using (var db = new MainDBContext())
  79. {
  80. foreach (var id in removeIds)
  81. {
  82. string query = "DELETE FROM [dbo].[ConnectorStatus] WHERE [Id]={0} ";
  83. db.Database.ExecuteSqlCommand(query, id);
  84. }
  85. db.SaveChanges();
  86. var _currentStatus = new Domain.Models.Database.ConnectorStatus()
  87. {
  88. ChargeBoxId = session.ChargeBoxId,
  89. ConnectorId = (byte)_request.connectorId,
  90. CreatedOn = _request.timestamp.HasValue ? _request.timestamp.Value : DateTime.Now,
  91. Status = (int)_request.status,
  92. ChargePointErrorCodeId = (int)_request.errorCode,
  93. ErrorInfo = _request.info,
  94. VendorId = _request.vendorId,
  95. VendorErrorCode = _request.vendorErrorCode,
  96. Id = Guid.NewGuid().ToString()
  97. };
  98. db.ConnectorStatus.Add(_currentStatus);
  99. if (_request.status == Packet.Messages.SubTypes.ChargePointStatus.Faulted)
  100. {
  101. db.MachineError.Add(new MachineError()
  102. {
  103. ConnectorId = (byte)_request.connectorId,
  104. CreatedOn = _request.timestamp.HasValue ? _request.timestamp.Value : DateTime.Now,
  105. Status = (int)_request.status,
  106. ChargeBoxId = session.ChargeBoxId,
  107. ErrorCodeId = (int)_request.errorCode,
  108. ErrorInfo = _request.info,
  109. PreStatus = _oldStatus.Status,
  110. VendorErrorCode = _request.vendorErrorCode,
  111. VendorId = _request.vendorId
  112. });
  113. }
  114. db.SaveChanges();
  115. }
  116. var confirm = new StatusNotificationConfirmation() { };
  117. result.Message = confirm;
  118. result.Success = true;
  119. }
  120. break;
  121. case Actions.Heartbeat:
  122. {
  123. using (var db = new MainDBContext())
  124. {
  125. var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault();
  126. if (machine != null)
  127. {
  128. db.Configuration.AutoDetectChangesEnabled = false;
  129. db.Configuration.ValidateOnSaveEnabled = false;
  130. db.Machine.Attach(machine);
  131. machine.HeartbeatUpdatedOn = DateTime.Now;
  132. db.Entry(machine).Property(x => x.HeartbeatUpdatedOn).IsModified = true;
  133. db.SaveChanges();
  134. }
  135. var confirm = new HeartbeatConfirmation() { currentTime = DateTime.Now };
  136. result.Message = confirm;
  137. result.Success = true;
  138. }
  139. }
  140. break;
  141. case Actions.MeterValues:
  142. {
  143. MeterValuesRequest _request = request as MeterValuesRequest;
  144. if (_request.meterValue.Count > 0)
  145. {
  146. using (var db = new MeterValueDBContext())
  147. {
  148. foreach (var item in _request.meterValue)
  149. {
  150. foreach (var sampleVaule in item.sampledValue)
  151. {
  152. string sp = "[dbo].[uspInsertMeterValueRecord] @ChargeBoxId," +
  153. "@ConnectorId,@Value,@CreatedOn,@ContextId,@FormatId,@MeasurandId,@PhaseId,@LocationId,@UnitId,@TransactionId";
  154. List<SqlParameter> parameter = new List<SqlParameter>
  155. {
  156. new SqlParameter("ChargeBoxId",session.ChargeBoxId),
  157. new SqlParameter("ConnectorId", (byte)_request.connectorId),
  158. new SqlParameter("Value",sampleVaule.value),
  159. new SqlParameter("CreatedOn",item.timestamp),
  160. new SqlParameter("ContextId",sampleVaule.context.HasValue ? (int)sampleVaule.context : 0),
  161. new SqlParameter("FormatId",sampleVaule.format.HasValue ? (int)sampleVaule.format : 0),
  162. new SqlParameter("MeasurandId",sampleVaule.measurand.HasValue ? (int)sampleVaule.measurand : 0),
  163. new SqlParameter("PhaseId",sampleVaule.phase.HasValue ? (int)sampleVaule.phase : 0),
  164. new SqlParameter("LocationId",sampleVaule.location.HasValue ? (int)sampleVaule.location : 0),
  165. new SqlParameter("UnitId",sampleVaule.unit.HasValue ? (int)sampleVaule.unit : 0),
  166. new SqlParameter("TransactionId",_request.transactionId.HasValue?_request.transactionId:-1),
  167. };
  168. db.Database.ExecuteSqlCommand(sp, parameter.ToArray());
  169. }
  170. }
  171. }
  172. }
  173. var confirm = new MeterValuesConfirmation() { };
  174. result.Message = confirm;
  175. result.Success = true;
  176. }
  177. break;
  178. case Actions.StartTransaction:
  179. {
  180. StartTransactionRequest _request = request as StartTransactionRequest;
  181. long _pastTime = DateTimeOffset.Now.AddYears(-20).ToUnixTimeSeconds();
  182. int _tranId = (int)(_pastTime % 100000000) * 10 + 1;
  183. //需處理StopTransactionOnInvalidId 情境,時間若和當前時間差距10秒,發動Authorize詢問後在回覆
  184. using (var db = new MainDBContext())
  185. {
  186. var _CustomerId = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).Include(x => x.Customer).
  187. Select(x => x.CustomerId).FirstOrDefault();
  188. db.TransactionRecord.Add(new TransactionRecord()
  189. {
  190. ChargeBoxId = session.ChargeBoxId,
  191. ConnectorId = (byte)_request.connectorId,
  192. CreatedOn = DateTime.Now,
  193. StartIdTag = _request.idTag,
  194. MeterStart = _request.meterStart,
  195. CustomerId = _CustomerId,
  196. StartTime = _request.timestamp,
  197. ReservationId = _request.reservationId.HasValue ? _request.reservationId.Value : 0,
  198. TransactionId = _tranId
  199. });
  200. db.SaveChanges();
  201. }
  202. var confirm = new StartTransactionConfirmation()
  203. {
  204. idTagInfo = new Packet.Messages.SubTypes.IdTagInfo()
  205. {
  206. status = Packet.Messages.SubTypes.AuthorizationStatus.Accepted
  207. },
  208. transactionId = _tranId
  209. };
  210. result.Message = confirm;
  211. result.Success = true;
  212. }
  213. break;
  214. case Actions.StopTransaction:
  215. {
  216. StopTransactionRequest _request = request as StopTransactionRequest;
  217. List<TransactionDataRecord> _TransactionDatas = new List<TransactionDataRecord>();
  218. if (_request.transactionData != null)
  219. {
  220. if (_request.transactionData.Count > 0)
  221. {
  222. foreach (var item in _request.transactionData)
  223. {
  224. foreach (var sampleVaule in item.sampledValue)
  225. {
  226. _TransactionDatas.Add(new TransactionDataRecord()
  227. {
  228. ChargeBoxId = session.ChargeBoxId,
  229. MeasuredOn = item.timestamp,
  230. TransactionId = _request.transactionId,
  231. ContextId = sampleVaule.context.HasValue ? (int)sampleVaule.context : 0,
  232. FormatId = sampleVaule.format.HasValue ? (int)sampleVaule.format : 0,
  233. LocationId = sampleVaule.location.HasValue ? (int)sampleVaule.location : 0,
  234. MeasurandId = sampleVaule.measurand.HasValue ? (int)sampleVaule.measurand : 0,
  235. PhaseId = sampleVaule.phase.HasValue ? (int)sampleVaule.phase : 0,
  236. UnitId = sampleVaule.unit.HasValue ? (int)sampleVaule.unit : 0,
  237. Value = sampleVaule.value
  238. });
  239. }
  240. }
  241. }
  242. }
  243. using (var db = new MainDBContext())
  244. {
  245. var transaction = db.TransactionRecord.Where(x => x.TransactionId == _request.transactionId
  246. && x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault();
  247. if (transaction != null)
  248. {
  249. transaction.MeterStop = _request.meterStop;
  250. transaction.StopTime = _request.timestamp;
  251. transaction.StopReasonId = _request.reason.HasValue ? (int)_request.reason.Value : 0;
  252. transaction.StopIdTag = _request.idTag;
  253. if (_TransactionDatas.Count > 0)
  254. {
  255. _TransactionDatas.ForEach(x => x.ConnectorId = (byte)transaction.ConnectorId);
  256. }
  257. db.SaveChanges();
  258. var confirm = new StopTransactionConfirmation()
  259. {
  260. idTagInfo = new Packet.Messages.SubTypes.IdTagInfo()
  261. {
  262. status = Packet.Messages.SubTypes.AuthorizationStatus.Accepted
  263. }
  264. };
  265. result.Message = confirm;
  266. result.Success = true;
  267. }
  268. else
  269. {
  270. result.Exception = new Exception("Can't find transactionId " + _request.transactionId);
  271. }
  272. }
  273. }
  274. break;
  275. case Actions.Authorize:
  276. {
  277. var confirm = new AuthorizeConfirmation()
  278. {
  279. idTagInfo = new Packet.Messages.SubTypes.IdTagInfo()
  280. {
  281. status = AuthorizationStatus.Accepted
  282. }
  283. };
  284. result.Message = confirm;
  285. result.Success = true;
  286. }
  287. break;
  288. default:
  289. {
  290. Console.WriteLine(string.Format("Not Implement {0} Logic", request.GetType().ToString().Replace("OCPPPackage.Messages.Core.", "")));
  291. }
  292. break;
  293. }
  294. return result;
  295. }
  296. internal MessageResult ExecuteCoreConfirm(Actions action, ClientData session, IConfirmation confirm, string requestId)
  297. {
  298. MessageResult result = new MessageResult() { Success = true };
  299. switch (action)
  300. {
  301. case Actions.ChangeAvailability:
  302. {
  303. ChangeAvailabilityConfirmation _confirm = confirm as ChangeAvailabilityConfirmation;
  304. ChangeAvailabilityRequest _request = _confirm.GetRequest() as ChangeAvailabilityRequest;
  305. using (var db = new MainDBContext())
  306. {
  307. var operation = db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  308. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefault();
  309. if (operation != null)
  310. {
  311. operation.FinishedOn = DateTime.Now;
  312. operation.Status = 1;//電樁有回覆
  313. operation.EVSE_Status = (int)_confirm.status;
  314. db.SaveChanges();
  315. }
  316. }
  317. }
  318. break;
  319. case Actions.ClearCache:
  320. {
  321. ClearCacheConfirmation _confirm = confirm as ClearCacheConfirmation;
  322. ClearCacheRequest _request = _confirm.GetRequest() as ClearCacheRequest;
  323. using (var db = new MainDBContext())
  324. {
  325. var operation = db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  326. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefault();
  327. if (operation != null)
  328. {
  329. operation.FinishedOn = DateTime.Now;
  330. operation.Status = 1;//電樁有回覆
  331. operation.EVSE_Status = (int)_confirm.status;
  332. db.SaveChanges();
  333. }
  334. }
  335. }
  336. break;
  337. case Actions.RemoteStartTransaction:
  338. {
  339. RemoteStartTransactionConfirmation _confirm = confirm as RemoteStartTransactionConfirmation;
  340. RemoteStartTransactionRequest _request = _confirm.GetRequest() as RemoteStartTransactionRequest;
  341. using (var db = new MainDBContext())
  342. {
  343. var operation = db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  344. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefault();
  345. if (operation != null)
  346. {
  347. operation.FinishedOn = DateTime.Now;
  348. operation.Status = 1;//電樁有回覆
  349. operation.EVSE_Status = (int)_confirm.status;
  350. db.SaveChanges();
  351. }
  352. }
  353. }
  354. break;
  355. case Actions.RemoteStopTransaction:
  356. {
  357. RemoteStopTransactionConfirmation _confirm = confirm as RemoteStopTransactionConfirmation;
  358. RemoteStopTransactionRequest _request = _confirm.GetRequest() as RemoteStopTransactionRequest;
  359. using (var db = new MainDBContext())
  360. {
  361. var operation = db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  362. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefault();
  363. if (operation != null)
  364. {
  365. operation.FinishedOn = DateTime.Now;
  366. operation.Status = 1;//電樁有回覆
  367. operation.EVSE_Status = (int)_confirm.status;
  368. db.SaveChanges();
  369. }
  370. }
  371. }
  372. break;
  373. case Actions.Reset:
  374. {
  375. ResetConfirmation _confirm = confirm as ResetConfirmation;
  376. ResetRequest _request = _confirm.GetRequest() as ResetRequest;
  377. using (var db = new MainDBContext())
  378. {
  379. var operation = db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  380. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefault();
  381. if (operation != null)
  382. {
  383. operation.FinishedOn = DateTime.Now;
  384. operation.Status = 1;//電樁有回覆
  385. operation.EVSE_Status = (int)_confirm.status;
  386. db.SaveChanges();
  387. }
  388. }
  389. }
  390. break;
  391. case Actions.ChangeConfiguration:
  392. {
  393. ChangeConfigurationConfirmation _confirm = confirm as ChangeConfigurationConfirmation;
  394. ChangeConfigurationRequest _request = _confirm.GetRequest() as ChangeConfigurationRequest;
  395. using (var db = new MainDBContext())
  396. {
  397. var operation = db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  398. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefault();
  399. if (operation != null)
  400. {
  401. operation.FinishedOn = DateTime.Now;
  402. operation.Status = 1;//電樁有回覆
  403. operation.EVSE_Status = (int)_confirm.status;
  404. operation.EVSE_Value = _confirm.status.ToString();
  405. }
  406. if (_confirm.status == Packet.Messages.SubTypes.ConfigurationStatus.Accepted || _confirm.status == Packet.Messages.SubTypes.ConfigurationStatus.RebootRequired)
  407. {
  408. var configure = db.MachineConfigure.Where(x => x.ChargeBoxId == session.ChargeBoxId).ToList();
  409. var foundConfig = configure.Find(x => x.ConfigureName == _request.key);
  410. if (foundConfig != null)
  411. {
  412. foundConfig.ReadOnly = false;
  413. foundConfig.ConfigureSetting = _request.value;
  414. }
  415. else
  416. {
  417. db.MachineConfigure.Add(new MachineConfigure()
  418. {
  419. ChargeBoxId = session.ChargeBoxId,
  420. ConfigureName = _request.key,
  421. ReadOnly = false,
  422. ConfigureSetting = _request.value
  423. });
  424. }
  425. }
  426. db.SaveChanges();
  427. }
  428. }
  429. break;
  430. case Actions.GetConfiguration:
  431. {
  432. GetConfigurationConfirmation _confirm = confirm as GetConfigurationConfirmation;
  433. GetConfigurationRequest _request = _confirm.GetRequest() as GetConfigurationRequest;
  434. using (var db = new MainDBContext())
  435. {
  436. var configure = db.MachineConfigure.Where(x => x.ChargeBoxId == session.ChargeBoxId).ToList();
  437. foreach (var item in _confirm.configurationKey)
  438. {
  439. var foundConfig = configure.Find(x => x.ConfigureName == item.key);
  440. if (foundConfig != null)
  441. {
  442. foundConfig.ReadOnly = item.IsReadOnly;
  443. foundConfig.ConfigureSetting = item.value;
  444. }
  445. else
  446. {
  447. db.MachineConfigure.Add(new MachineConfigure()
  448. {
  449. ChargeBoxId = session.ChargeBoxId,
  450. ConfigureName = item.key,
  451. ReadOnly = item.IsReadOnly,
  452. ConfigureSetting = item.value
  453. });
  454. }
  455. }
  456. var operation = db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  457. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefault();
  458. if (operation != null)
  459. {
  460. operation.FinishedOn = DateTime.Now;
  461. operation.Status = 1;//電樁有回覆
  462. operation.EVSE_Status = 1;
  463. operation.EVSE_Value = JsonConvert.SerializeObject(_confirm.configurationKey, Formatting.Indented);
  464. }
  465. db.SaveChanges();
  466. }
  467. }
  468. break;
  469. default:
  470. {
  471. Console.WriteLine(string.Format("Not Implement {0} Logic", confirm.GetType().ToString().Replace("OCPPPackage.Messages.Core.", "")));
  472. }
  473. break;
  474. }
  475. return result;
  476. }
  477. internal MessageResult ReceivedCoreError(Actions action, string errorMsg, ClientData session, string requestId)
  478. {
  479. MessageResult result = new MessageResult() { Success = true };
  480. switch (action)
  481. {
  482. case Actions.ChangeAvailability:
  483. case Actions.ChangeConfiguration:
  484. case Actions.ClearCache:
  485. case Actions.RemoteStartTransaction:
  486. case Actions.RemoteStopTransaction:
  487. case Actions.Reset:
  488. case Actions.GetConfiguration:
  489. {
  490. using (var db = new MainDBContext())
  491. {
  492. var operation = db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
  493. x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefault();
  494. if (operation != null)
  495. {
  496. operation.FinishedOn = DateTime.Now;
  497. operation.Status = 1;//電樁有回覆
  498. operation.EVSE_Status = (int)255;//錯誤
  499. operation.EVSE_Value = errorMsg;
  500. db.SaveChanges();
  501. }
  502. }
  503. }
  504. break;
  505. default:
  506. {
  507. Console.WriteLine(string.Format("Not Implement {0} Logic", action));
  508. }
  509. break;
  510. }
  511. return result;
  512. }
  513. }
  514. }