ProtalServer.cs 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191
  1. using NLog;
  2. using OCPPServer.Protocol;
  3. using OCPPServer.SubProtocol;
  4. using SuperSocket.SocketBase;
  5. using SuperSocket.SocketBase.Config;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Xml.Linq;
  12. using EVCB_OCPP.Packet.Messages.Basic;
  13. using EVCB_OCPP.Packet.Messages.Core;
  14. using EVCB_OCPP.WSServer.Message;
  15. using EVCB_OCPP.Packet.Messages;
  16. using EVCB_OCPP.Domain;
  17. using EVCB_OCPP.Domain.Models.Database;
  18. using System.Threading;
  19. using System.Data.Entity;
  20. using EVCB_OCPP.Packet.Features;
  21. using EVCB_OCPP.Packet.Features.Core;
  22. using Newtonsoft.Json;
  23. using OCPPPackage.Profiles;
  24. using System.Threading.Tasks;
  25. using EVCB_OCPP.WSServer.Helper;
  26. using System.Data.SqlClient;
  27. using EVCB_OCPP.Packet.Messages.FirmwareManagement;
  28. using EVCB_OCPP.Packet.Messages.RemoteTrigger;
  29. using System.Configuration;
  30. using System.Net;
  31. using System.Net.Security;
  32. using System.Security.Cryptography.X509Certificates;
  33. using EVCB_OCPP.WSServer.Service;
  34. using EVCB_OCPP.Packet.Messages.SmartCharging;
  35. namespace EVCB_OCPP.WSServer
  36. {
  37. internal class ProtalServer
  38. {
  39. static private ILogger logger = NLog.LogManager.GetCurrentClassLogger();
  40. private Dictionary<string, ClientData> clientDic = new Dictionary<string, ClientData>();
  41. private readonly Object _lockClientDic = new object();
  42. private readonly Object _lockConfirmPacketList = new object();
  43. private ProfileHandler profileHandler = new ProfileHandler();
  44. private List<NeedConfirmMessage> needConfirmPacketList = new List<NeedConfirmMessage>();
  45. private DateTime checkUpdateDt = DateTime.Now;
  46. private LoadingBalanceService _loadingBalanceService = new LoadingBalanceService();
  47. private List<string> needConfirmActions = new List<string>()
  48. {
  49. "GetConfiguration",
  50. "ChangeConfiguration",
  51. "RemoteStartTransaction",
  52. "RemoteStopTransaction",
  53. "ChangeAvailability",
  54. "ClearCache",
  55. "DataTransfer",
  56. "Reset",
  57. "UnlockConnector",
  58. "TriggerMessage",
  59. "GetDiagnostics",
  60. "UpdateFirmware",
  61. "GetLocalListVersion",
  62. "SendLocalList",
  63. "SetChargingProfile",
  64. "ClearChargingProfile",
  65. "GetCompositeSchedule",
  66. "ReserveNow",
  67. "CancelReservation",
  68. };
  69. private List<Profile> profiles = new List<Profile>()
  70. {
  71. new CoreProfile(),
  72. new FirmwareManagementProfile(),
  73. new ReservationProfile(),
  74. new RemoteTriggerProfile(),
  75. new SmartChargingProfile(),
  76. new LocalAuthListManagementProfile()
  77. };
  78. private CancellationTokenSource _cts = new CancellationTokenSource();
  79. private CancellationToken _ct;
  80. internal ProtalServer()
  81. {
  82. _ct = _cts.Token;
  83. WarmUpLog();
  84. }
  85. internal void Start()
  86. {
  87. if (!GlobalConfig.LoadAPPConfig())
  88. {
  89. Console.WriteLine("Please check App.Config setting .");
  90. return;
  91. }
  92. OpenNetwork();
  93. Task serverCommandTask = new Task(ServerMessageTrigger, _ct);
  94. serverCommandTask.Start();
  95. Task serverUpdateTask = new Task(ServerUpdateTrigger, _ct);
  96. serverUpdateTask.Start();
  97. // Task serverHealthTask = new Task(HealthAlarmTrigger, _ct);
  98. // serverHealthTask.Start();
  99. while (true)
  100. {
  101. var input = Console.ReadLine();
  102. switch (input.ToLower())
  103. {
  104. case "stop":
  105. logger.Info("Command stop");
  106. Stop();
  107. break;
  108. case "gc":
  109. logger.Info("Command GC");
  110. GC.Collect();
  111. break;
  112. case "lc":
  113. {
  114. logger.Info("Command List Clients");
  115. Dictionary<string, ClientData> _copyClientDic = null;
  116. lock (_lockClientDic)
  117. {
  118. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  119. }
  120. var list = _copyClientDic.Select(c => c.Value).ToList();
  121. int i = 1;
  122. foreach (var c in list)
  123. {
  124. logger.Info(i + ":" + c.ChargeBoxId + " " + c.SessionID);
  125. i++;
  126. }
  127. }
  128. break;
  129. case "lcn":
  130. {
  131. logger.Info("Command List Customer Name");
  132. Dictionary<string, ClientData> _copyClientDic = null;
  133. lock (_lockClientDic)
  134. {
  135. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  136. }
  137. var lcn = clientDic.Select(c => c.Value.CustomerName).Distinct().ToList();
  138. int iLcn = 1;
  139. foreach (var c in lcn)
  140. {
  141. logger.Info(iLcn + ":" + c + ":" + clientDic.Where(z => z.Value.CustomerName == c).Count().ToString());
  142. iLcn++;
  143. }
  144. }
  145. break;
  146. case "help":
  147. logger.Info("Command help!!");
  148. logger.Info("lcn : List Customer Name");
  149. logger.Info("gc : GC Collect");
  150. logger.Info("lc : List Clients");
  151. logger.Info("cls : clear console");
  152. logger.Info("silent : silent");
  153. logger.Info("show : show log");
  154. // logger.Info("rcl : show Real Connection Limit");
  155. break;
  156. case "cls":
  157. logger.Info("Command clear");
  158. Console.Clear();
  159. break;
  160. case "silent":
  161. logger.Info("Command silent");
  162. var xe = XElement.Load("NLog.config");
  163. var xns = xe.GetDefaultNamespace();
  164. var minlevelattr = xe.Descendants(xns + "rules").Elements(xns + "logger")
  165. .Where(c => c.Attribute("writeTo").Value.Equals("console")).Attributes("minlevel").FirstOrDefault();
  166. if (minlevelattr != null)
  167. {
  168. minlevelattr.Value = "info";
  169. }
  170. xe.Save("NLog.config");
  171. break;
  172. case "show":
  173. logger.Info("Command show");
  174. var xe1 = XElement.Load("NLog.config");
  175. var xns1 = xe1.GetDefaultNamespace();
  176. var minlevelattr1 = xe1.Descendants(xns1 + "rules").Elements(xns1 + "logger")
  177. .Where(c => c.Attribute("writeTo").Value.Equals("console")).Attributes("minlevel").FirstOrDefault();
  178. if (minlevelattr1 != null)
  179. {
  180. minlevelattr1.Value = "trace";
  181. }
  182. xe1.Save("NLog.config");
  183. break;
  184. case "rcl":
  185. break;
  186. default:
  187. break;
  188. }
  189. }
  190. }
  191. internal void Stop()
  192. {
  193. if (_cts != null)
  194. {
  195. _cts.Cancel();
  196. }
  197. }
  198. private void CheckEVSEConfigure(string chargeBoxId)
  199. {
  200. int skipCount = 0;
  201. int takeCount = 8;
  202. using (var db = new MainDBContext())
  203. {
  204. string maxKeys = StandardConfiguration.AllConfigs.Skip(skipCount).Take(1).FirstOrDefault();
  205. if (maxKeys == StandardConfiguration.GetConfigurationMaxKeys)
  206. {
  207. var _Configure = db.MachineConfiguration.Where(x => x.ChargeBoxId == chargeBoxId && x.ConfigureName == maxKeys).Select(x => new { ConfigureSetting = x.ConfigureSetting, ConfigureName = x.ConfigureName }).FirstOrDefault();
  208. if (_Configure != null)
  209. {
  210. int cp_ConfiureCount = 0;
  211. int.TryParse(_Configure.ConfigureSetting, out cp_ConfiureCount);
  212. takeCount = takeCount > cp_ConfiureCount ? cp_ConfiureCount : takeCount;
  213. skipCount = 1;
  214. if (string.IsNullOrEmpty(_Configure.ConfigureSetting)) return;
  215. }
  216. }
  217. while (StandardConfiguration.AllConfigs.Count > skipCount)
  218. {
  219. string _key = StandardConfiguration.AllConfigs.Skip(skipCount).Take(1).FirstOrDefault();
  220. var _Configure = db.MachineConfiguration.Where(x => x.ChargeBoxId == chargeBoxId && x.ConfigureName == _key).Select(x => new { ConfigureSetting = x.ConfigureSetting, ConfigureName = x.ConfigureName }).FirstOrDefault();
  221. takeCount = StandardConfiguration.AllConfigs.Count - skipCount > takeCount ? takeCount : StandardConfiguration.AllConfigs.Count - skipCount;
  222. var _keys = StandardConfiguration.AllConfigs.Skip(skipCount).Take(takeCount).ToList();
  223. // Console.WriteLine("===============Skip:" + skipCount);
  224. if (_Configure == null)
  225. {
  226. // Console.WriteLine("_Configure == null===============Skip:" + skipCount);
  227. db.ServerMessage.Add(new ServerMessage()
  228. {
  229. ChargeBoxId = chargeBoxId,
  230. CreatedBy = "Server",
  231. CreatedOn = DateTime.Now,
  232. OutAction = Actions.GetConfiguration.ToString(),
  233. OutRequest = JsonConvert.SerializeObject(
  234. new GetConfigurationRequest()
  235. {
  236. key = _keys
  237. },
  238. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  239. SerialNo = Guid.NewGuid().ToString(),
  240. InMessage = string.Empty
  241. });
  242. db.SaveChanges();
  243. }
  244. skipCount = skipCount + takeCount;
  245. }
  246. }
  247. }
  248. private void OpenNetwork()
  249. {
  250. //載入OCPP Protocol
  251. var appServer = new OCPPWSServer(new List<OCPPSubProtocol>() { new OCPPSubProtocol(), new OCPPSubProtocol(" ocpp1.6") });
  252. List<IListenerConfig> llistener = new List<IListenerConfig>();
  253. //System.Net.IPAddress.Any.ToString()
  254. // llistener.Add(new ListenerConfig { Ip = "", Port = Convert.ToInt32(wssserverPort), Backlog = 100, Security = serverSecurity });
  255. llistener.Add(new ListenerConfig { Ip = System.Net.IPAddress.Any.ToString(), Port = Convert.ToInt32(GlobalConfig.GetWS_Port()), Backlog = 100, Security = "None" });
  256. llistener.Add(new ListenerConfig { Ip = System.Net.IPAddress.Any.ToString(), Port = Convert.ToInt32(GlobalConfig.GetWSS_Port()), Backlog = 100, Security = "tls" });
  257. var config = ConfigurationManager.GetSection("superSocket") as IConfigurationSource;
  258. ICertificateConfig Certificate = config.Servers.ElementAt(0).Certificate;
  259. IEnumerable<IListenerConfig> listeners = llistener;
  260. //設定server config
  261. var serverConfig = new ServerConfig
  262. {
  263. //Port = Convert.ToInt32(2012),
  264. //Ip = "172.17.40.13",
  265. MaxRequestLength = 4096,
  266. //Security = serverSecurity,
  267. Certificate = Certificate,
  268. Listeners = listeners,
  269. };
  270. //Setup with listening port
  271. if (!appServer.Setup(serverConfig, logFactory: new OCPPLogFactory()))
  272. {
  273. Console.WriteLine("Failed to setup!");
  274. return;
  275. }
  276. appServer.NewSessionConnected += AppServer_NewSessionConnected;
  277. appServer.SessionClosed += AppServer_SessionClosed;
  278. //Try to start the appServer
  279. if (!appServer.Start())
  280. {
  281. Console.WriteLine("Failed to start!");
  282. Console.ReadKey();
  283. return;
  284. }
  285. }
  286. private void AppServer_SessionClosed(ClientData session, CloseReason value)
  287. {
  288. // Console.WriteLine(session.RemoteEndPoint.Address);
  289. WriteMachineLog(session, string.Format("CloseReason: {0}", value), "Connection", "");
  290. RemoveClient(session);
  291. // close Connection
  292. }
  293. private void AppServer_NewSessionConnected(ClientData session)
  294. {
  295. try
  296. {
  297. lock (_lockClientDic)
  298. {
  299. bool isNotSupported = session.SecWebSocketProtocol.Contains("ocpp1.6") ? false : true;
  300. if (isNotSupported)
  301. {
  302. //logger.Debug(string.Format("ChargeBoxId:{0} SecWebSocketProtocol:{1} NotSupported", session.ChargeBoxId, session.SecWebSocketProtocol));
  303. WriteMachineLog(session, string.Format("SecWebSocketProtocol:{0} NotSupported", session.SecWebSocketProtocol), "Connection", "");
  304. return;
  305. }
  306. ClientData _removeClient = null;
  307. clientDic.TryGetValue(session.ChargeBoxId, out _removeClient);
  308. if (_removeClient != null)
  309. {
  310. WriteMachineLog(_removeClient, "Duplicate Logins", "Connection", "");
  311. _removeClient.Close(CloseReason.ServerShutdown);
  312. RemoveClient(_removeClient);
  313. }
  314. session.IsCheckIn = true;
  315. clientDic.Add(session.ChargeBoxId, session);
  316. session.m_ReceiveData += new ClientData.OCPPClientDataEventHandler<ClientData, String>(ReceivedMessage);
  317. // logger.Debug("------------New " + (session == null ? "Oops" : session.ChargeBoxId));
  318. WriteMachineLog(session, "NewSessionConnected", "Connection", "");
  319. using (var db = new MainDBContext())
  320. {
  321. var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault();
  322. if (machine != null)
  323. {
  324. machine.ConnectionType = session.Origin.Contains("https") ? 2 : 1;
  325. db.SaveChanges();
  326. }
  327. }
  328. CheckEVSEConfigure(session.ChargeBoxId);
  329. }
  330. }
  331. catch (Exception ex)
  332. {
  333. logger.Error(string.Format("NewSessionConnected Ex: {0}", ex.ToString()));
  334. }
  335. }
  336. private void ReceivedMessage(ClientData session, string rawdata)
  337. {
  338. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  339. MessageResult analysisResult = msgAnalyser.AnalysisReceiveData(session, rawdata);
  340. WriteMachineLog(session, rawdata,
  341. string.Format("{0} {1}", string.IsNullOrEmpty(analysisResult.Action) ? "unknown" : analysisResult.Action, analysisResult.Id == 2 ? "Request" : (analysisResult.Id == 3 ? "Confirmation" : "Error")), string.IsNullOrEmpty(analysisResult.CallErrorMsg) ? "" : analysisResult.Exception.Message);
  342. if (!analysisResult.Success)
  343. {
  344. //解析RawData就發生錯誤
  345. if (!string.IsNullOrEmpty(analysisResult.CallErrorMsg))
  346. {
  347. Send(session, analysisResult.CallErrorMsg, string.Format("{0} {1}", analysisResult.Action, "Error"));
  348. }
  349. else
  350. {
  351. BaseMessage _baseMsg = analysisResult.Message as BaseMessage;
  352. string replyMsg = msgAnalyser.GenerateCallError(_baseMsg.Id, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  353. string errorMsg = string.Empty;
  354. if (analysisResult.Exception != null)
  355. {
  356. errorMsg = analysisResult.Exception.ToString();
  357. }
  358. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  359. }
  360. }
  361. else
  362. {
  363. Actions action = Convertor.GetAction(analysisResult.Action);
  364. switch (analysisResult.Id)
  365. {
  366. case BasicMessageHandler.TYPENUMBER_CALL:
  367. {
  368. ProcessRequestMessage(analysisResult, session, action);
  369. }
  370. break;
  371. case BasicMessageHandler.TYPENUMBER_CALLRESULT:
  372. {
  373. ProcessConfirmationMessage(analysisResult, session, action);
  374. }
  375. break;
  376. case BasicMessageHandler.TYPENUMBER_CALLERROR:
  377. {
  378. //只處理 丟出Request 收到Error的訊息
  379. if (analysisResult.Success)
  380. {
  381. ProcessErrorMessage(analysisResult, session, action);
  382. }
  383. }
  384. break;
  385. default:
  386. {
  387. logger.Error(string.Format("Can't analyze messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  388. }
  389. break;
  390. }
  391. }
  392. }
  393. private void ProcessRequestMessage(MessageResult analysisResult, ClientData session, Actions action)
  394. {
  395. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  396. if (!session.IsCheckIn && action != Actions.BootNotification)
  397. {
  398. string response = msgAnalyser.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.GenericError, OCPPErrorDescription.NotChecked);
  399. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"));
  400. }
  401. else
  402. {
  403. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  404. switch (profileName)
  405. {
  406. case "Core":
  407. {
  408. bool oldstatus = session.IsCheckIn;
  409. var replyResult = profileHandler.ExecuteCoreRequest(action, session, (IRequest)analysisResult.Message);
  410. if (replyResult.Success)
  411. {
  412. string response = msgAnalyser.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  413. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation"));
  414. if (action == Actions.BootNotification && replyResult.Message is BootNotificationConfirmation)
  415. {
  416. if (((BootNotificationConfirmation)replyResult.Message).status == Packet.Messages.SubTypes.RegistrationStatus.Accepted)
  417. {
  418. session.IsCheckIn = true;
  419. if (!oldstatus)
  420. {
  421. using (var db = new MainDBContext())
  422. {
  423. var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault();
  424. if (machine != null)
  425. {
  426. machine.ConnectionType = session.Origin.Contains("https") ? 2 : 1;
  427. db.SaveChanges();
  428. }
  429. }
  430. // CheckEVSEConfigure(session.ChargeBoxId);
  431. }
  432. }
  433. }
  434. }
  435. else
  436. {
  437. string response = msgAnalyser.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  438. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  439. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  440. }
  441. if (action == Actions.StartTransaction)
  442. {
  443. var stationId = _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  444. var _powerDic = _loadingBalanceService.GetSettingPower(stationId, session.MachineId);
  445. if (_powerDic != null)
  446. {
  447. foreach (var kv in _powerDic)
  448. {
  449. try
  450. {
  451. string chargeBoxId = string.Empty;
  452. //set profile
  453. lock (_lockClientDic)
  454. {
  455. chargeBoxId = clientDic.Where(x => x.Value.MachineId == kv.Key).Select(x => x.Value.ChargeBoxId).FirstOrDefault();
  456. }
  457. if (chargeBoxId != null && kv.Value.HasValue)
  458. {
  459. profileHandler.SetChargingProfile(chargeBoxId, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  460. }
  461. }
  462. catch (Exception ex)
  463. {
  464. logger.Error(string.Format("Set Profile Exception: {0}", ex.ToString()));
  465. }
  466. }
  467. }
  468. }
  469. if (action == Actions.StopTransaction)
  470. {
  471. var stationId = _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  472. if (_loadingBalanceService.IsNeedtoCancelSetting(stationId, session.MachineId, session.ChargeBoxId))
  473. {
  474. //Clear current profile
  475. profileHandler.ClearChargingProfile(session.ChargeBoxId);
  476. var _powerDic = _loadingBalanceService.GetRerangeSettingPower(stationId);
  477. if (_powerDic != null)
  478. {
  479. foreach (var kv in _powerDic)
  480. {
  481. try
  482. {
  483. string chargeBoxId = string.Empty;
  484. //set profile
  485. lock (_lockClientDic)
  486. {
  487. chargeBoxId = clientDic.Where(x => x.Value.MachineId == kv.Key).Select(x => x.Value.ChargeBoxId).FirstOrDefault();
  488. }
  489. if (chargeBoxId != null && kv.Value.HasValue)
  490. {
  491. profileHandler.SetChargingProfile(chargeBoxId, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  492. }
  493. }
  494. catch (Exception ex)
  495. {
  496. logger.Error(string.Format("Set Profile Exception: {0}", ex.ToString()));
  497. }
  498. }
  499. }
  500. }
  501. }
  502. }
  503. break;
  504. case "FirmwareManagement":
  505. {
  506. var replyResult = profileHandler.ExecuteFirmwareManagementRequest(action, session, (IRequest)analysisResult.Message);
  507. if (replyResult.Success)
  508. {
  509. string response = msgAnalyser.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  510. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation"));
  511. }
  512. else
  513. {
  514. string response = msgAnalyser.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  515. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  516. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  517. }
  518. }
  519. break;
  520. default:
  521. {
  522. string replyMsg = msgAnalyser.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  523. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  524. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  525. }
  526. break;
  527. }
  528. }
  529. }
  530. private void ProcessConfirmationMessage(MessageResult analysisResult, ClientData session, Actions action)
  531. {
  532. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  533. if (ReConfirmMessage(analysisResult))
  534. {
  535. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  536. MessageResult confirmResult = null;
  537. switch (profileName)
  538. {
  539. case "Core":
  540. {
  541. confirmResult = profileHandler.ExecuteCoreConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  542. }
  543. break;
  544. case "FirmwareManagement":
  545. {
  546. confirmResult = profileHandler.ExecuteFirmwareManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  547. }
  548. break;
  549. case "RemoteTrigger":
  550. {
  551. confirmResult = profileHandler.ExecuteRemoteTriggerConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  552. }
  553. break;
  554. case "Reservation":
  555. {
  556. confirmResult = profileHandler.ExecuteReservationConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  557. }
  558. break;
  559. case "LocalAuthListManagement":
  560. {
  561. confirmResult = profileHandler.ExecuteLocalAuthListManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  562. }
  563. break;
  564. case "SmartCharging":
  565. {
  566. confirmResult = profileHandler.ExecuteSmartChargingConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  567. }
  568. break;
  569. default:
  570. {
  571. string replyMsg = msgAnalyser.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  572. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  573. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  574. }
  575. break;
  576. }
  577. if (confirmResult == null || !confirmResult.Success)
  578. {
  579. logger.Error(string.Format("Action:{0} MessageId:{1} ExecuteConfirm Error:{2} ",
  580. analysisResult.Action, analysisResult.UUID, confirmResult.Exception.ToString()));
  581. }
  582. }
  583. else
  584. {
  585. string replyMsg = msgAnalyser.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  586. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  587. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  588. }
  589. }
  590. private void ProcessErrorMessage(MessageResult analysisResult, ClientData session, Actions action)
  591. {
  592. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  593. if (ReConfirmMessage(analysisResult))
  594. {
  595. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  596. switch (profileName)
  597. {
  598. case "Core":
  599. {
  600. profileHandler.ReceivedCoreError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  601. }
  602. break;
  603. case "FirmwareManagement":
  604. {
  605. profileHandler.ReceivedFirmwareManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  606. }
  607. break;
  608. case "RemoteTrigger":
  609. {
  610. profileHandler.ReceivedRemoteTriggerError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  611. }
  612. break;
  613. case "Reservation":
  614. {
  615. profileHandler.ExecuteReservationError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  616. }
  617. break;
  618. case "LocalAuthListManagement":
  619. {
  620. profileHandler.ReceivedLocalAuthListManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  621. }
  622. break;
  623. case "SmartCharging":
  624. {
  625. profileHandler.ReceivedSmartChargingError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  626. }
  627. break;
  628. default:
  629. {
  630. string replyMsg = msgAnalyser.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  631. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  632. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  633. }
  634. break;
  635. }
  636. }
  637. else
  638. {
  639. string replyMsg = msgAnalyser.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  640. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  641. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  642. }
  643. }
  644. private void Send(ClientData session, string msg, string messageType, string errorMsg = "")
  645. {
  646. try
  647. {
  648. if (session != null)
  649. {
  650. WriteMachineLog(session, msg, messageType, errorMsg, true);
  651. session.Send(msg);
  652. }
  653. }
  654. catch (Exception ex)
  655. {
  656. logger.Error(string.Format("Send Ex:{0}", ex.ToString()));
  657. }
  658. }
  659. async private void ServerUpdateTrigger()
  660. {
  661. for (; ; )
  662. {
  663. if (_ct.IsCancellationRequested)
  664. {
  665. break;
  666. }
  667. var min_Interval = (DateTime.Now - checkUpdateDt).TotalMinutes;
  668. if (min_Interval > 3)
  669. {
  670. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  671. Dictionary<string, ClientData> _copyClientDic = null;
  672. lock (_lockClientDic)
  673. {
  674. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  675. }
  676. checkUpdateDt = DateTime.Now;
  677. using (var db = new MainDBContext())
  678. {
  679. //var needUpdateChargers = db.Machine.Where(x => x.FW_AssignedMachineVersionId.HasValue == true &&
  680. // x.FW_AssignedMachineVersionId != x.FW_VersionReport && x.Online == true)
  681. // .Select(x => new { x.Id, x.ChargeBoxId, x.FW_AssignedMachineVersionId }).ToList();
  682. var needUpdateChargers = db.Machine.Where(x => x.FW_AssignedMachineVersionId.HasValue == true &&
  683. x.FW_AssignedMachineVersionId != x.FW_VersionReport && x.Online == true)
  684. .Select(x => x.ChargeBoxId).AsNoTracking().ToList();
  685. foreach (var chargeBoxId in needUpdateChargers)
  686. {
  687. try
  688. {
  689. ClientData session;
  690. if (_copyClientDic.TryGetValue(chargeBoxId, out session))
  691. {
  692. string requestId = Guid.NewGuid().ToString();
  693. // using (var db = new MainDBContext())
  694. if (session.IsCheckIn)
  695. {
  696. var _request = new TriggerMessageRequest()
  697. {
  698. requestedMessage = Packet.Messages.SubTypes.MessageTrigger.FirmwareStatusNotification
  699. };
  700. var uuid = session.queue.store(_request);
  701. string rawRequest = msgAnalyser.GenerateRequest(uuid, _request.Action, _request);
  702. Send(session, rawRequest, string.Format("{0} {1}", _request.Action, "Request"), "");
  703. #region OCTT ,測試韌體更新方式
  704. //--------------------> OCTT ,測試韌體更新方式
  705. //{
  706. // var machine = db.Machine.Where(x => x.FW_AssignedMachineVersionId.HasValue == true &&
  707. // x.FW_AssignedMachineVersionId != x.FW_VersionReport && x.ChargeBoxId == session.ChargeBoxId)
  708. // .Select(x => new { x.Id, x.FW_AssignedMachineVersionId }).FirstOrDefault();
  709. // if (machine != null)
  710. // {
  711. // var mv = db.MachineVersion.Include(c => c.PublishVersion)
  712. // .Include(c => c.PublishVersion.PublishVersionFiles)
  713. // .Include(c => c.PublishVersion.PublishVersionFiles.Select(z => z.UploadFile))
  714. // .Where(c => c.Id == machine.FW_AssignedMachineVersionId.Value).First();
  715. // string downloadUrl = mv.PublishVersion.PublishVersionFiles.FirstOrDefault().UploadFile.FileUrl;
  716. // var _updateFWrequest = new UpdateFirmwareRequest()
  717. // {
  718. // location = new Uri(downloadUrl),
  719. // retries = 3,
  720. // retrieveDate = DateTime.Now,
  721. // retryInterval = 10
  722. // };
  723. // db.MachineOperateRecord.Add(new MachineOperateRecord()
  724. // {
  725. // CreatedOn = DateTime.Now,
  726. // ChargeBoxId = session.ChargeBoxId,
  727. // SerialNo = requestId,
  728. // RequestContent = JsonConvert.SerializeObject(_updateFWrequest, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  729. // EVSE_Status = 0,
  730. // EVSE_Value = "Fw Version:" + machine.FW_AssignedMachineVersionId,
  731. // Status = 0,
  732. // RequestType = 0,
  733. // });
  734. // db.ServerMessage.Add(new ServerMessage()
  735. // {
  736. // ChargeBoxId = session.ChargeBoxId,
  737. // CreatedBy = "Server",
  738. // CreatedOn = DateTime.Now,
  739. // OutAction = _updateFWrequest.Action.ToString(),
  740. // OutRequest = JsonConvert.SerializeObject(_updateFWrequest, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  741. // SerialNo = requestId,
  742. // InMessage = string.Empty
  743. // });
  744. // db.SaveChanges();
  745. // }
  746. //}
  747. #endregion
  748. }
  749. }
  750. }
  751. catch (Exception ex)
  752. {
  753. logger.Error(string.Format("serverUpdateTrigger ChargeBoxId:{0} Ex:{1}", chargeBoxId, ex.ToString()));
  754. }
  755. }
  756. }
  757. await Task.Delay(1000);
  758. // Thread.CurrentThread.Join(1000);
  759. }
  760. }
  761. }
  762. async private void ServerMessageTrigger()
  763. {
  764. for (; ; )
  765. {
  766. if (_ct.IsCancellationRequested)
  767. {
  768. break;
  769. }
  770. try
  771. {
  772. RemoveConfirmMessage();
  773. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  774. using (var db = new MainDBContext())
  775. {
  776. DateTime startDt = DateTime.Now.AddSeconds(-30);
  777. DateTime dt = new DateTime(1991, 1, 1);
  778. //Console.WriteLine(string.Format("{0} IN", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")));
  779. var commandList = db.ServerMessage.Where(c => c.ReceivedOn == dt && c.UpdatedOn == dt && c.CreatedOn >= startDt && c.CreatedOn <= DateTime.Now).AsNoTracking().ToList();
  780. //處理主機傳送的有指令
  781. var cmdMachineList = commandList.Select(c => c.ChargeBoxId).Distinct().ToList();
  782. if (commandList.Count > 0)
  783. {
  784. Console.WriteLine(string.Format("Now:{0} commandList Count:{1} ", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), commandList.Count));
  785. }
  786. foreach (var charger_SN in cmdMachineList)
  787. {
  788. ClientData session;
  789. string uuid = string.Empty;
  790. if (clientDic.TryGetValue(charger_SN, out session))
  791. {
  792. Console.WriteLine(string.Format("charger_SN:{0} startDt:{1} CreatedOn:{2}", charger_SN, startDt.ToString("yyyy/MM/dd HH:mm:ss"), DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")));
  793. if (session.IsCheckIn)
  794. {
  795. var cmdList = commandList.Where(c => c.ChargeBoxId == charger_SN).ToList();
  796. foreach (var item in cmdList)
  797. {
  798. IRequest request = null;
  799. Actions action = Actions.None;
  800. Enum.TryParse(item.OutAction, out action);
  801. Type _RequestType = null;
  802. for (int i = 0; i < profiles.Count; i++)
  803. {
  804. var feature = profiles[i].GetFeaturebyAction(item.OutAction);
  805. if (feature != null)
  806. {
  807. _RequestType = feature.GetRequestType();
  808. break;
  809. }
  810. }
  811. if (_RequestType != null)
  812. {
  813. request = JsonConvert.DeserializeObject(item.OutRequest, _RequestType) as IRequest;
  814. uuid = session.queue.store(request);
  815. string rawRequest = msgAnalyser.GenerateRequest(uuid, item.OutAction, request);
  816. Send(session, rawRequest, string.Format("{0} {1}", action, "Request"), "");
  817. }
  818. AddConfirmMessage(charger_SN, item.Id, item.SerialNo, item.OutAction, uuid);
  819. #region 更新資料表單一欄位
  820. var _UpdatedItem = new ServerMessage() { Id = item.Id, UpdatedOn = DateTime.Now };
  821. db.Configuration.AutoDetectChangesEnabled = false;//自動呼叫DetectChanges()比對所有的entry集合的每一個屬性Properties的新舊值
  822. db.Configuration.ValidateOnSaveEnabled = false;// 因為Entity有些欄位必填,若不避開會有Validate錯誤
  823. // var _UpdatedItem = db.ServerMessage.Where(x => x.Id == item.Id).FirstOrDefault();
  824. db.ServerMessage.Attach(_UpdatedItem);
  825. _UpdatedItem.UpdatedOn = DateTime.Now;
  826. db.Entry(_UpdatedItem).Property(x => x.UpdatedOn).IsModified = true;// 可以直接使用這方式強制某欄位要更新,只是查詢集合耗效能而己
  827. db.SaveChanges();
  828. #endregion
  829. }
  830. }
  831. }
  832. }
  833. db.ChangeTracker.DetectChanges();
  834. }
  835. await Task.Delay(1000);
  836. // Thread.CurrentThread.Join(1000);
  837. }
  838. catch (Exception ex)
  839. {
  840. logger.Error(string.Format("ServerMessageTrigger Ex:{0}", ex.ToString()));
  841. }
  842. }
  843. }
  844. async private void HealthAlarmTrigger()
  845. {
  846. }
  847. private void AddConfirmMessage(string chargePointSerialNumber, int table_id, string requestId, string action, string msg_id)
  848. {
  849. NeedConfirmMessage _needConfirmMsg = new NeedConfirmMessage();
  850. _needConfirmMsg.Id = table_id;
  851. _needConfirmMsg.SentAction = action;
  852. _needConfirmMsg.SentOn = DateTime.Now;
  853. _needConfirmMsg.SentTimes = 1;
  854. _needConfirmMsg.ChargePointSerialNumber = chargePointSerialNumber;
  855. _needConfirmMsg.RequestId = requestId;
  856. _needConfirmMsg.SentUniqueId = msg_id;
  857. if (needConfirmActions.Contains(action))
  858. {
  859. lock (_lockConfirmPacketList)
  860. {
  861. needConfirmPacketList.Add(_needConfirmMsg);
  862. if (action == "GetConfiguration")
  863. {
  864. Console.WriteLine("AddConfirmMessage: " + msg_id);
  865. }
  866. }
  867. }
  868. }
  869. private void RemoveConfirmMessage()
  870. {
  871. var before_3mins = DateTime.Now.AddMinutes(-3);
  872. lock (_lockConfirmPacketList)
  873. {
  874. var removeList = needConfirmPacketList.Where(x => x.SentTimes == 0 || x.SentOn < before_3mins).ToList();
  875. foreach (var item in removeList)
  876. {
  877. needConfirmPacketList.Remove(item);
  878. }
  879. }
  880. }
  881. private bool ReConfirmMessage(MessageResult analysisResult)
  882. {
  883. bool confirmed = false;
  884. if (needConfirmActions.Contains(analysisResult.Action))
  885. {
  886. if (analysisResult.Action == "GetConfiguration")
  887. {
  888. Console.WriteLine("ReConfirmMessage: " + analysisResult.UUID);
  889. }
  890. NeedConfirmMessage foundRequest = null;
  891. lock (_lockConfirmPacketList)
  892. {
  893. foundRequest = needConfirmPacketList.Where(x => x.SentUniqueId == analysisResult.UUID).FirstOrDefault();
  894. }
  895. if (foundRequest != null && foundRequest.Id > 0)
  896. {
  897. foundRequest.SentTimes = 0;
  898. foundRequest.SentInterval = 0;
  899. analysisResult.RequestId = foundRequest.RequestId;
  900. using (var db = new MainDBContext())
  901. {
  902. var sc = db.ServerMessage.Where(x => x.Id == foundRequest.Id).FirstOrDefault();
  903. sc.InMessage = JsonConvert.SerializeObject(analysisResult.Message, Formatting.None);
  904. sc.ReceivedOn = DateTime.Now;
  905. db.SaveChanges();
  906. Console.WriteLine(string.Format("Now:{0} ServerMessage Id:{1} ", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), foundRequest.Id));
  907. }
  908. confirmed = true;
  909. }
  910. else if (analysisResult.Action == Actions.TriggerMessage.ToString())
  911. {
  912. confirmed = true;
  913. }
  914. else
  915. {
  916. logger.Error(string.Format("Received no record Action:{0} MessageId:{1} ", analysisResult.Action, analysisResult.UUID));
  917. }
  918. }
  919. return confirmed;
  920. }
  921. private void RemoveClient(ClientData session)
  922. {
  923. Console.WriteLine("*********");
  924. if (session != null)
  925. {
  926. logger.Trace("RemoveClient[" + session.ChargeBoxId + "]");
  927. RemoveClientDic(session);
  928. try
  929. {
  930. session.m_ReceiveData -= new ClientData.OCPPClientDataEventHandler<ClientData, String>(ReceivedMessage);
  931. // session.Close(CloseReason.ServerShutdown);
  932. }
  933. catch (Exception ex)
  934. {
  935. //logger.Warn("Close client socket error!!");
  936. logger.Warn(string.Format("Close client socket error!! {0} Msg:{1}", session.ChargeBoxId, ex.Message));
  937. }
  938. if (session != null)
  939. {
  940. session = null;
  941. }
  942. }
  943. }
  944. private void RemoveClientDic(ClientData session)
  945. {
  946. if (!string.IsNullOrEmpty(session.ChargeBoxId))
  947. {
  948. lock (_lockClientDic)
  949. {
  950. if (clientDic.ContainsKey(session.ChargeBoxId))
  951. {
  952. if (clientDic[session.ChargeBoxId].SessionID == session.SessionID)
  953. {
  954. logger.Debug(String.Format("ChargeBoxId:{0} Remove SessionId:{1} Removed SessionId:{2}", session.ChargeBoxId, session.SessionID, clientDic[session.ChargeBoxId].SessionID));
  955. clientDic.Remove(session.ChargeBoxId);
  956. logger.Trace("RemoveClient ContainsKey " + session.ChargeBoxId);
  957. }
  958. }
  959. }
  960. }
  961. }
  962. private void WarmUpLog()
  963. {
  964. using (var log = new ConnectionLogDBContext())
  965. {
  966. log.MachineConnectionLog.ToList();
  967. }
  968. }
  969. private void WriteMachineLog(ClientData clientData, string data, string messageType, string errorMsg = "", bool isSent = false)
  970. {
  971. try
  972. {
  973. if (clientData == null || string.IsNullOrEmpty(data)) return;
  974. using (var db = new ConnectionLogDBContext())
  975. {
  976. string sp = "[dbo].[uspInsertMachineConnectionLog] @CreatedOn," +
  977. "@ChargeBoxId,@MessageType,@Data,@Msg,@IsSent,@EVSEEndPoint,@Session";
  978. var dd = DateTime.UtcNow;
  979. SqlParameter[] parameter =
  980. {
  981. new SqlParameter("CreatedOn",dd),
  982. new SqlParameter("ChargeBoxId",clientData.ChargeBoxId.Replace("'","''")),
  983. new SqlParameter("MessageType",messageType.Replace("'","''")),
  984. new SqlParameter("Data",data.Replace("'","''")),
  985. new SqlParameter("Msg",errorMsg.Replace("'","''")),
  986. new SqlParameter("IsSent",isSent),
  987. new SqlParameter("EVSEEndPoint",clientData.RemoteEndPoint==null?"123":clientData.RemoteEndPoint.ToString()),
  988. new SqlParameter("Session",clientData.SessionID==null?"123":clientData.SessionID)
  989. };
  990. db.Database.ExecuteSqlCommand(sp, parameter);
  991. }
  992. }
  993. catch (Exception ex)
  994. {
  995. Console.WriteLine(ex.ToString());
  996. }
  997. }
  998. }
  999. }