ProtalServer.cs 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470
  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. using System.Security.Authentication;
  36. using NLog.Fluent;
  37. using System.Diagnostics;
  38. using Packet20 = EVCB_OCPP.Packet20;
  39. namespace EVCB_OCPP.WSServer
  40. {
  41. public class DestroyRequest : IRequest
  42. {
  43. public string Action { get; set; }
  44. public bool TransactionRelated()
  45. {
  46. return false;
  47. }
  48. public bool Validate()
  49. {
  50. return true;
  51. }
  52. }
  53. internal class ProtalServer
  54. {
  55. static private ILogger logger = NLog.LogManager.GetCurrentClassLogger();
  56. private Dictionary<string, ClientData> clientDic = new Dictionary<string, ClientData>();
  57. private readonly Object _lockClientDic = new object();
  58. private readonly Object _lockConfirmPacketList = new object();
  59. private ProfileHandler profileHandler = new ProfileHandler();
  60. private List<NeedConfirmMessage> needConfirmPacketList = new List<NeedConfirmMessage>();
  61. private DateTime checkUpdateDt = DateTime.Now;
  62. private LoadingBalanceService _loadingBalanceService = new LoadingBalanceService();
  63. private List<string> needConfirmActions = new List<string>()
  64. {
  65. "GetConfiguration",
  66. "ChangeConfiguration",
  67. "RemoteStartTransaction",
  68. "RemoteStopTransaction",
  69. "ChangeAvailability",
  70. "ClearCache",
  71. "DataTransfer",
  72. "Reset",
  73. "UnlockConnector",
  74. "TriggerMessage",
  75. "GetDiagnostics",
  76. "UpdateFirmware",
  77. "GetLocalListVersion",
  78. "SendLocalList",
  79. "SetChargingProfile",
  80. "ClearChargingProfile",
  81. "GetCompositeSchedule",
  82. "ReserveNow",
  83. "CancelReservation",
  84. "ExtendedTriggerMessage"
  85. };
  86. private List<Profile> profiles = new List<Profile>()
  87. {
  88. new CoreProfile(),
  89. new FirmwareManagementProfile(),
  90. new ReservationProfile(),
  91. new RemoteTriggerProfile(),
  92. new SmartChargingProfile(),
  93. new LocalAuthListManagementProfile(),
  94. new SecurityProfile(),
  95. };
  96. private CancellationTokenSource _cts = new CancellationTokenSource();
  97. private CancellationToken _ct;
  98. internal ProtalServer()
  99. {
  100. _ct = _cts.Token;
  101. WarmUpLog();
  102. }
  103. internal void Start()
  104. {
  105. if (!GlobalConfig.LoadAPPConfig())
  106. {
  107. Console.WriteLine("Please check App.Config setting .");
  108. return;
  109. }
  110. OpenNetwork();
  111. Task serverCommandTask = new Task(ServerMessageTrigger, _ct);
  112. serverCommandTask.Start();
  113. Task serverUpdateTask = new Task(ServerUpdateTrigger, _ct);
  114. serverUpdateTask.Start();
  115. Task serverBeatTask = new Task(HeartBeatCheckTrigger, _ct);
  116. serverBeatTask.Start();
  117. Task serverHealthTask = new Task(HealthCheckTrigger, _ct);
  118. serverHealthTask.Start();
  119. while (true)
  120. {
  121. var input = Console.ReadLine();
  122. switch (input.ToLower())
  123. {
  124. case "stop":
  125. logger.Info("Command stop");
  126. Stop();
  127. break;
  128. case "gc":
  129. logger.Info("Command GC");
  130. GC.Collect();
  131. break;
  132. case "lc":
  133. {
  134. logger.Info("Command List Clients");
  135. Dictionary<string, ClientData> _copyClientDic = null;
  136. lock (_lockClientDic)
  137. {
  138. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  139. }
  140. var list = _copyClientDic.Select(c => c.Value).ToList();
  141. int i = 1;
  142. foreach (var c in list)
  143. {
  144. logger.Info(i + ":" + c.ChargeBoxId + " " + c.SessionID);
  145. i++;
  146. }
  147. }
  148. break;
  149. case "lcn":
  150. {
  151. logger.Info("Command List Customer Name");
  152. Dictionary<string, ClientData> _copyClientDic = null;
  153. lock (_lockClientDic)
  154. {
  155. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  156. }
  157. var lcn = clientDic.Select(c => c.Value.CustomerName).Distinct().ToList();
  158. int iLcn = 1;
  159. foreach (var c in lcn)
  160. {
  161. logger.Info(iLcn + ":" + c + ":" + clientDic.Where(z => z.Value.CustomerName == c).Count().ToString());
  162. iLcn++;
  163. }
  164. }
  165. break;
  166. case "help":
  167. logger.Info("Command help!!");
  168. logger.Info("lcn : List Customer Name");
  169. logger.Info("gc : GC Collect");
  170. logger.Info("lc : List Clients");
  171. logger.Info("cls : clear console");
  172. logger.Info("silent : silent");
  173. logger.Info("show : show log");
  174. // logger.Info("rcl : show Real Connection Limit");
  175. break;
  176. case "cls":
  177. logger.Info("Command clear");
  178. Console.Clear();
  179. break;
  180. case "silent":
  181. logger.Info("Command silent");
  182. var xe = XElement.Load("NLog.config");
  183. var xns = xe.GetDefaultNamespace();
  184. var minlevelattr = xe.Descendants(xns + "rules").Elements(xns + "logger")
  185. .Where(c => c.Attribute("writeTo").Value.Equals("console")).Attributes("minlevel").FirstOrDefault();
  186. if (minlevelattr != null)
  187. {
  188. minlevelattr.Value = "info";
  189. }
  190. xe.Save("NLog.config");
  191. break;
  192. case "show":
  193. logger.Info("Command show");
  194. var xe1 = XElement.Load("NLog.config");
  195. var xns1 = xe1.GetDefaultNamespace();
  196. var minlevelattr1 = xe1.Descendants(xns1 + "rules").Elements(xns1 + "logger")
  197. .Where(c => c.Attribute("writeTo").Value.Equals("console")).Attributes("minlevel").FirstOrDefault();
  198. if (minlevelattr1 != null)
  199. {
  200. minlevelattr1.Value = "trace";
  201. }
  202. xe1.Save("NLog.config");
  203. break;
  204. case "rcl":
  205. break;
  206. default:
  207. break;
  208. }
  209. }
  210. }
  211. internal void Stop()
  212. {
  213. if (_cts != null)
  214. {
  215. _cts.Cancel();
  216. }
  217. }
  218. private void CheckVersion(string chargeBoxId)
  219. {
  220. if (string.IsNullOrEmpty(chargeBoxId)) return;
  221. using (var db = new MainDBContext())
  222. {
  223. db.ServerMessage.Add(new ServerMessage()
  224. {
  225. ChargeBoxId = chargeBoxId,
  226. CreatedBy = "Server",
  227. CreatedOn = DateTime.Now,
  228. OutAction = Actions.DataTransfer.ToString(),
  229. OutRequest = JsonConvert.SerializeObject(
  230. new DataTransferRequest()
  231. {
  232. messageId = "ID_FirmwareVersion",
  233. vendorId = "Phihong Technology"
  234. },
  235. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  236. SerialNo = Guid.NewGuid().ToString(),
  237. InMessage = string.Empty
  238. });
  239. db.SaveChanges();
  240. }
  241. }
  242. private void CheckEVSEConfigure(string chargeBoxId)
  243. {
  244. if (string.IsNullOrEmpty(chargeBoxId)) return;
  245. using (var db = new MainDBContext())
  246. {
  247. db.ServerMessage.Add(new ServerMessage()
  248. {
  249. ChargeBoxId = chargeBoxId,
  250. CreatedBy = "Server",
  251. CreatedOn = DateTime.Now,
  252. OutAction = Actions.GetConfiguration.ToString(),
  253. OutRequest = JsonConvert.SerializeObject(
  254. new GetConfigurationRequest()
  255. {
  256. key = new List<string>()
  257. },
  258. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  259. SerialNo = Guid.NewGuid().ToString(),
  260. InMessage = string.Empty
  261. }); ;
  262. db.SaveChanges();
  263. }
  264. }
  265. private void OpenNetwork()
  266. {
  267. //載入OCPP Protocol
  268. var appServer = new OCPPWSServer(new List<OCPPSubProtocol>() { new OCPPSubProtocol(), new OCPPSubProtocol(" ocpp1.6") });
  269. List<IListenerConfig> llistener = new List<IListenerConfig>();
  270. //System.Net.IPAddress.Any.ToString()
  271. // llistener.Add(new ListenerConfig { Ip = "", Port = Convert.ToInt32(wssserverPort), Backlog = 100, Security = serverSecurity });
  272. llistener.Add(new ListenerConfig { Ip = System.Net.IPAddress.Any.ToString(), Port = Convert.ToInt32(GlobalConfig.GetWS_Port()), Backlog = 100, Security = "None" });
  273. llistener.Add(new ListenerConfig { Ip = System.Net.IPAddress.Any.ToString(), Port = Convert.ToInt32(GlobalConfig.GetWSS_Port()), Backlog = 100, Security = SslProtocols.Tls12.ToString() });
  274. // llistener.Add(new ListenerConfig { Ip = System.Net.IPAddress.Any.ToString(), Port = Convert.ToInt32(GlobalConfig.GetWSS_Port()), Backlog = 100, Security = SslProtocols.Tls11.ToString() });
  275. var config = ConfigurationManager.GetSection("superSocket") as IConfigurationSource;
  276. ICertificateConfig Certificate = config.Servers.ElementAt(0).Certificate;
  277. IEnumerable<IListenerConfig> listeners = llistener;
  278. //設定server config
  279. var serverConfig = new ServerConfig
  280. {
  281. //Port = Convert.ToInt32(2012),
  282. //Ip = "172.17.40.13",
  283. MaxRequestLength = 4096,
  284. //Security = serverSecurity,
  285. Certificate = Certificate,
  286. Listeners = listeners,
  287. // LogAllSocketException = true,
  288. KeepAliveTime = 10,
  289. // LogBasicSessionActivity = true
  290. };
  291. //Setup with listening port
  292. if (!appServer.Setup(serverConfig, logFactory: new OCPPLogFactory()))
  293. {
  294. Console.WriteLine("Failed to setup!");
  295. return;
  296. }
  297. appServer.NewSessionConnected += AppServer_NewSessionConnected;
  298. appServer.SessionClosed += AppServer_SessionClosed;
  299. //Try to start the appServer
  300. if (!appServer.Start())
  301. {
  302. Console.WriteLine("Failed to start!");
  303. Console.ReadKey();
  304. return;
  305. }
  306. }
  307. private void AppServer_SessionClosed(ClientData session, CloseReason value)
  308. {
  309. // Console.WriteLine(session.RemoteEndPoint.Address);
  310. WriteMachineLog(session, string.Format("CloseReason: {0}", value), "Connection", "");
  311. RemoveClient(session);
  312. // close Connection
  313. }
  314. private void AppServer_NewSessionConnected(ClientData session)
  315. {
  316. try
  317. {
  318. lock (_lockClientDic)
  319. {
  320. bool isNotSupported = session.SecWebSocketProtocol.Contains("ocpp1.6") ? false : true;
  321. if (isNotSupported)
  322. {
  323. //logger.Debug(string.Format("ChargeBoxId:{0} SecWebSocketProtocol:{1} NotSupported", session.ChargeBoxId, session.SecWebSocketProtocol));
  324. WriteMachineLog(session, string.Format("SecWebSocketProtocol:{0} NotSupported", session.SecWebSocketProtocol), "Connection", "");
  325. return;
  326. }
  327. ClientData _removeClient = null;
  328. clientDic.TryGetValue(session.ChargeBoxId, out _removeClient);
  329. if (_removeClient != null)
  330. {
  331. WriteMachineLog(_removeClient, "Duplicate Logins", "Connection", "");
  332. _removeClient.Close(CloseReason.ServerShutdown);
  333. RemoveClient(_removeClient);
  334. }
  335. session.IsCheckIn = true;
  336. clientDic.Add(session.ChargeBoxId, session);
  337. session.m_ReceiveData += new ClientData.OCPPClientDataEventHandler<ClientData, String>(ReceivedMessage);
  338. // logger.Debug("------------New " + (session == null ? "Oops" : session.ChargeBoxId));
  339. WriteMachineLog(session, "NewSessionConnected", "Connection", "");
  340. using (var db = new MainDBContext())
  341. {
  342. var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault();
  343. if (machine != null)
  344. {
  345. machine.ConnectionType = session.Origin.Contains("https") ? 2 : 1;
  346. db.SaveChanges();
  347. }
  348. }
  349. // CheckEVSEConfigure(session.ChargeBoxId);
  350. }
  351. }
  352. catch (Exception ex)
  353. {
  354. logger.Error(string.Format("NewSessionConnected Ex: {0}", ex.ToString()));
  355. }
  356. }
  357. async private void ReceivedMessage(ClientData session, string rawdata)
  358. {
  359. try
  360. {
  361. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  362. MessageResult analysisResult = msgAnalyser.AnalysisReceiveData(session, rawdata);
  363. WriteMachineLog(session, rawdata,
  364. string.Format("{0} {1}", string.IsNullOrEmpty(analysisResult.Action) ? "unknown" : analysisResult.Action, analysisResult.Id == 2 ? "Request" : (analysisResult.Id == 3 ? "Confirmation" : "Error")), analysisResult.Exception == null ? "" : analysisResult.Exception.Message);
  365. if(session.ResetSecurityProfile)
  366. {
  367. logger.Error(string.Format("[{0}] ChargeBoxId:{1} ResetSecurityProfile", DateTime.Now, session.ChargeBoxId));
  368. RemoveClient(session);
  369. return;
  370. }
  371. if (!analysisResult.Success)
  372. {
  373. //解析RawData就發生錯誤
  374. if (!string.IsNullOrEmpty(analysisResult.CallErrorMsg))
  375. {
  376. Send(session, analysisResult.CallErrorMsg, string.Format("{0} {1}", analysisResult.Action, "Error"));
  377. }
  378. else
  379. {
  380. if (analysisResult.Message == null)
  381. {
  382. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  383. string errorMsg = string.Empty;
  384. if (analysisResult.Exception != null)
  385. {
  386. errorMsg = analysisResult.Exception.ToString();
  387. }
  388. Send(session, replyMsg, string.Format("{0} {1}", "unknown", "Error"), "EVSE's sent essage has parsed Failed. ");
  389. }
  390. else
  391. {
  392. BaseMessage _baseMsg = analysisResult.Message as BaseMessage;
  393. string replyMsg = BasicMessageHandler.GenerateCallError(_baseMsg.Id, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  394. string errorMsg = string.Empty;
  395. if (analysisResult.Exception != null)
  396. {
  397. errorMsg = analysisResult.Exception.ToString();
  398. }
  399. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  400. }
  401. }
  402. }
  403. else
  404. {
  405. Actions action = Convertor.GetAction(analysisResult.Action);
  406. if (!session.IsOCPP16 && !(action != Actions.BootNotification || action != Actions.Heartbeat))
  407. {
  408. Send(session, "Backend doesn't support this message.", string.Format("{0} {1}", analysisResult.Action, "Error"));
  409. return;
  410. }
  411. switch (analysisResult.Id)
  412. {
  413. case BasicMessageHandler.TYPENUMBER_CALL:
  414. {
  415. if (session.IsOCPP16)
  416. {
  417. ProcessRequestMessage(analysisResult, session, action);
  418. }
  419. else
  420. {
  421. MessageResult result = new MessageResult() { Success = true };
  422. //ocpp20 處理
  423. switch (action)
  424. {
  425. case Actions.Heartbeat:
  426. {
  427. var confirm = new Packet20.Messages.HeartbeatResponse() { CurrentTime = DateTime.Now };
  428. result.Message = confirm;
  429. result.Success = true;
  430. string response = BasicMessageHandler.GenerateConfirmationofOCPP20(analysisResult.UUID, (Packet20.Messages.IConfirmation)result.Message);
  431. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Response"), result.Exception == null ? string.Empty : result.Exception.ToString());
  432. }
  433. break;
  434. case Actions.BootNotification:
  435. {
  436. Packet20.Messages.BootNotificationRequest _request = (Packet20.Messages.IRequest)analysisResult.Message as Packet20.Messages.BootNotificationRequest;
  437. int heartbeat_interval = GlobalConfig.GetHEARTBEAT_INTERVAL();
  438. //using (var db = new MainDBContext())
  439. //{
  440. // var _machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault();
  441. // _machine.ChargeBoxSerialNumber = string.IsNullOrEmpty(_request.chargeBoxSerialNumber) ? string.Empty : _request.chargeBoxSerialNumber;
  442. // _machine.ChargePointModel = string.IsNullOrEmpty(_request.chargePointModel) ? string.Empty : _request.chargePointModel;
  443. // _machine.ChargePointVendor = string.IsNullOrEmpty(_request.chargePointVendor) ? string.Empty : _request.chargePointVendor;
  444. // _machine.FW_CurrentVersion = string.IsNullOrEmpty(_request.firmwareVersion) ? string.Empty : _request.firmwareVersion;
  445. // _machine.Iccid = string.IsNullOrEmpty(_request.iccid) ? string.Empty : _request.iccid;
  446. // _machine.Imsi = string.IsNullOrEmpty(_request.imsi) ? string.Empty : _request.imsi;
  447. // _machine.MeterSerialNumber = string.IsNullOrEmpty(_request.meterSerialNumber) ? string.Empty : _request.meterSerialNumber;
  448. // _machine.MeterType = string.IsNullOrEmpty(_request.meterType) ? string.Empty : _request.meterType;
  449. // db.SaveChanges();
  450. // var configVaule = db.MachineConfiguration.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.HeartbeatInterval)
  451. // .Select(x => x.ConfigureSetting).FirstOrDefault();
  452. // if (configVaule != null)
  453. // {
  454. // int.TryParse(configVaule, out heartbeat_interval);
  455. // }
  456. //}
  457. var confirm = new Packet20.Messages.BootNotificationResponse() { CurrentTime = DateTime.Now, Interval = heartbeat_interval, Status = Packet20.DataTypes.EnumTypes.RegistrationStatusEnumType.Accepted };
  458. result.Message = confirm;
  459. result.Success = true;
  460. string response = BasicMessageHandler.GenerateConfirmationofOCPP20(analysisResult.UUID, (Packet20.Messages.IConfirmation)result.Message);
  461. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Response"), result.Exception == null ? string.Empty : result.Exception.ToString());
  462. }
  463. break;
  464. default:
  465. {
  466. logger.Error(string.Format("We don't implement messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  467. }
  468. break;
  469. }
  470. }
  471. }
  472. break;
  473. case BasicMessageHandler.TYPENUMBER_CALLRESULT:
  474. {
  475. ProcessConfirmationMessage(analysisResult, session, action);
  476. }
  477. break;
  478. case BasicMessageHandler.TYPENUMBER_CALLERROR:
  479. {
  480. //只處理 丟出Request 收到Error的訊息
  481. if (analysisResult.Success && analysisResult.Message != null)
  482. {
  483. ProcessErrorMessage(analysisResult, session, action);
  484. }
  485. }
  486. break;
  487. default:
  488. {
  489. logger.Error(string.Format("Can't analyze messagetype:{0} of raw data :{1} by {2}", analysisResult.Id, rawdata, session.ChargeBoxId));
  490. }
  491. break;
  492. }
  493. }
  494. await Task.Delay(10);
  495. }
  496. catch (Exception ex)
  497. {
  498. logger.Error(string.Format("**Exception :{0} ", ex.ToString()));
  499. if (ex.InnerException != null)
  500. {
  501. logger.Error(string.Format("**Inner exception :{0} ", ex.InnerException.ToString()));
  502. }
  503. }
  504. }
  505. async private void ProcessRequestMessage(MessageResult analysisResult, ClientData session, Actions action)
  506. {
  507. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  508. if (!session.IsCheckIn && action != Actions.BootNotification)
  509. {
  510. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.GenericError, OCPPErrorDescription.NotChecked);
  511. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"));
  512. }
  513. else
  514. {
  515. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  516. switch (profileName)
  517. {
  518. case "Core":
  519. {
  520. var replyResult = await profileHandler.ExecuteCoreRequest(action, session, (IRequest)analysisResult.Message).ConfigureAwait(false);
  521. if (replyResult.Success)
  522. {
  523. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  524. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation"), replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString());
  525. if (action == Actions.BootNotification && replyResult.Message is BootNotificationConfirmation)
  526. {
  527. if (((BootNotificationConfirmation)replyResult.Message).status == Packet.Messages.SubTypes.RegistrationStatus.Accepted)
  528. {
  529. using (var db = new MainDBContext())
  530. {
  531. var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault();
  532. if (machine != null)
  533. {
  534. machine.ConnectionType = session.Origin.Contains("https") ? 2 : 1;
  535. db.SaveChanges();
  536. }
  537. }
  538. if (session.ResetSecurityProfile)
  539. {
  540. //
  541. }
  542. else
  543. {
  544. CheckVersion(session.ChargeBoxId);
  545. CheckEVSEConfigure(session.ChargeBoxId);
  546. }
  547. }
  548. }
  549. }
  550. else
  551. {
  552. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  553. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  554. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  555. }
  556. if (action == Actions.StartTransaction)
  557. {
  558. var stationId = _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  559. var _powerDic = _loadingBalanceService.GetSettingPower(stationId, session.MachineId);
  560. if (_powerDic != null)
  561. {
  562. foreach (var kv in _powerDic)
  563. {
  564. try
  565. {
  566. string chargeBoxId = string.Empty;
  567. //set profile
  568. lock (_lockClientDic)
  569. {
  570. chargeBoxId = clientDic.Where(x => x.Value.MachineId == kv.Key).Select(x => x.Value.ChargeBoxId).FirstOrDefault();
  571. }
  572. if (chargeBoxId != null && kv.Value.HasValue)
  573. {
  574. profileHandler.SetChargingProfile(chargeBoxId, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  575. }
  576. }
  577. catch (Exception ex)
  578. {
  579. logger.Error(string.Format("Set Profile Exception: {0}", ex.ToString()));
  580. }
  581. }
  582. }
  583. }
  584. if (action == Actions.StopTransaction)
  585. {
  586. var stationId = _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  587. if (_loadingBalanceService.IsNeedtoCancelSetting(stationId, session.MachineId, session.ChargeBoxId))
  588. {
  589. //Clear current profile
  590. profileHandler.ClearChargingProfile(session.ChargeBoxId);
  591. var _powerDic = _loadingBalanceService.GetRerangeSettingPower(stationId);
  592. if (_powerDic != null)
  593. {
  594. foreach (var kv in _powerDic)
  595. {
  596. try
  597. {
  598. string chargeBoxId = string.Empty;
  599. //set profile
  600. lock (_lockClientDic)
  601. {
  602. chargeBoxId = clientDic.Where(x => x.Value.MachineId == kv.Key).Select(x => x.Value.ChargeBoxId).FirstOrDefault();
  603. }
  604. if (chargeBoxId != null && kv.Value.HasValue)
  605. {
  606. profileHandler.SetChargingProfile(chargeBoxId, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  607. }
  608. }
  609. catch (Exception ex)
  610. {
  611. logger.Error(string.Format("Set Profile Exception: {0}", ex.ToString()));
  612. }
  613. }
  614. }
  615. }
  616. }
  617. }
  618. break;
  619. case "FirmwareManagement":
  620. {
  621. var replyResult = profileHandler.ExecuteFirmwareManagementRequest(action, session, (IRequest)analysisResult.Message);
  622. if (replyResult.Success)
  623. {
  624. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  625. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  626. }
  627. else
  628. {
  629. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  630. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  631. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  632. }
  633. }
  634. break;
  635. case "Security":
  636. {
  637. var replyResult = profileHandler.ExecuteSecurityRequest(action, session, (IRequest)analysisResult.Message);
  638. if (replyResult.Success)
  639. {
  640. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  641. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  642. }
  643. else
  644. {
  645. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  646. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  647. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  648. }
  649. }
  650. break;
  651. default:
  652. {
  653. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  654. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  655. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  656. }
  657. break;
  658. }
  659. }
  660. }
  661. private void ProcessConfirmationMessage(MessageResult analysisResult, ClientData session, Actions action)
  662. {
  663. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  664. if (ReConfirmMessage(analysisResult))
  665. {
  666. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  667. MessageResult confirmResult = null;
  668. switch (profileName)
  669. {
  670. case "Core":
  671. {
  672. confirmResult = profileHandler.ExecuteCoreConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  673. }
  674. break;
  675. case "FirmwareManagement":
  676. {
  677. confirmResult = profileHandler.ExecuteFirmwareManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  678. }
  679. break;
  680. case "RemoteTrigger":
  681. {
  682. confirmResult = profileHandler.ExecuteRemoteTriggerConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  683. }
  684. break;
  685. case "Reservation":
  686. {
  687. confirmResult = profileHandler.ExecuteReservationConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  688. }
  689. break;
  690. case "LocalAuthListManagement":
  691. {
  692. confirmResult = profileHandler.ExecuteLocalAuthListManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  693. }
  694. break;
  695. case "SmartCharging":
  696. {
  697. confirmResult = profileHandler.ExecuteSmartChargingConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  698. }
  699. break;
  700. case "Security":
  701. {
  702. confirmResult = profileHandler.ExecuteSecurityConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  703. }
  704. break;
  705. default:
  706. {
  707. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  708. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  709. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  710. }
  711. break;
  712. }
  713. if (confirmResult == null || !confirmResult.Success)
  714. {
  715. logger.Error(string.Format("Action:{0} MessageId:{1} ExecuteConfirm Error:{2} ",
  716. analysisResult.Action, analysisResult.UUID, confirmResult.Exception.ToString()));
  717. }
  718. }
  719. else
  720. {
  721. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  722. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  723. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  724. }
  725. }
  726. private void ProcessErrorMessage(MessageResult analysisResult, ClientData session, Actions action)
  727. {
  728. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  729. if (ReConfirmMessage(analysisResult))
  730. {
  731. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  732. switch (profileName)
  733. {
  734. case "Core":
  735. {
  736. profileHandler.ReceivedCoreError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  737. }
  738. break;
  739. case "FirmwareManagement":
  740. {
  741. profileHandler.ReceivedFirmwareManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  742. }
  743. break;
  744. case "RemoteTrigger":
  745. {
  746. profileHandler.ReceivedRemoteTriggerError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  747. }
  748. break;
  749. case "Reservation":
  750. {
  751. profileHandler.ExecuteReservationError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  752. }
  753. break;
  754. case "LocalAuthListManagement":
  755. {
  756. profileHandler.ReceivedLocalAuthListManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  757. }
  758. break;
  759. case "SmartCharging":
  760. {
  761. profileHandler.ReceivedSmartChargingError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  762. }
  763. break;
  764. default:
  765. {
  766. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  767. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  768. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  769. }
  770. break;
  771. }
  772. }
  773. else
  774. {
  775. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  776. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  777. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  778. }
  779. }
  780. private void Send(ClientData session, string msg, string messageType, string errorMsg = "")
  781. {
  782. try
  783. {
  784. if (session != null)
  785. {
  786. WriteMachineLog(session, msg, messageType, errorMsg, true);
  787. session.Send(msg);
  788. }
  789. }
  790. catch (Exception ex)
  791. {
  792. logger.Error(string.Format("Send Ex:{0}", ex.ToString()));
  793. }
  794. }
  795. async private void ServerUpdateTrigger()
  796. {
  797. for (; ; )
  798. {
  799. if (_ct.IsCancellationRequested)
  800. {
  801. break;
  802. }
  803. var min_Interval = (DateTime.Now - checkUpdateDt).TotalMinutes;
  804. if (min_Interval > 3)
  805. {
  806. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  807. Dictionary<string, ClientData> _copyClientDic = null;
  808. lock (_lockClientDic)
  809. {
  810. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  811. }
  812. checkUpdateDt = DateTime.Now;
  813. using (var db = new MainDBContext())
  814. {
  815. //var needUpdateChargers = db.Machine.Where(x => x.FW_AssignedMachineVersionId.HasValue == true &&
  816. // x.FW_AssignedMachineVersionId != x.FW_VersionReport && x.Online == true)
  817. // .Select(x => new { x.Id, x.ChargeBoxId, x.FW_AssignedMachineVersionId }).ToList();
  818. var needUpdateChargers = db.Machine.Where(x => x.FW_AssignedVersion.HasValue == true &&
  819. x.FW_AssignedVersion != x.FW_VersionReport && x.Online == true)
  820. .Select(x => x.ChargeBoxId).AsNoTracking().ToList();
  821. foreach (var chargeBoxId in needUpdateChargers)
  822. {
  823. try
  824. {
  825. ClientData session;
  826. if (_copyClientDic.TryGetValue(chargeBoxId, out session))
  827. {
  828. string requestId = Guid.NewGuid().ToString();
  829. // using (var db = new MainDBContext())
  830. if (session.IsCheckIn && session.IsOCPP16)
  831. {
  832. var _request = new TriggerMessageRequest()
  833. {
  834. requestedMessage = Packet.Messages.SubTypes.MessageTrigger.FirmwareStatusNotification
  835. };
  836. var uuid = session.queue.store(_request);
  837. string rawRequest = BasicMessageHandler.GenerateRequest(uuid, _request.Action, _request);
  838. Send(session, rawRequest, string.Format("{0} {1}", _request.Action, "Request"), "");
  839. #region OCTT ,測試韌體更新方式
  840. //--------------------> OCTT ,測試韌體更新方式
  841. //{
  842. // var machine = db.Machine.Where(x => x.FW_AssignedMachineVersionId.HasValue == true &&
  843. // x.FW_AssignedMachineVersionId != x.FW_VersionReport && x.ChargeBoxId == session.ChargeBoxId)
  844. // .Select(x => new { x.Id, x.FW_AssignedMachineVersionId }).FirstOrDefault();
  845. // if (machine != null)
  846. // {
  847. // var mv = db.MachineVersion.Include(c => c.PublishVersion)
  848. // .Include(c => c.PublishVersion.PublishVersionFiles)
  849. // .Include(c => c.PublishVersion.PublishVersionFiles.Select(z => z.UploadFile))
  850. // .Where(c => c.Id == machine.FW_AssignedMachineVersionId.Value).First();
  851. // string downloadUrl = mv.PublishVersion.PublishVersionFiles.FirstOrDefault().UploadFile.FileUrl;
  852. // var _updateFWrequest = new UpdateFirmwareRequest()
  853. // {
  854. // location = new Uri(downloadUrl),
  855. // retries = 3,
  856. // retrieveDate = DateTime.Now,
  857. // retryInterval = 10
  858. // };
  859. // db.MachineOperateRecord.Add(new MachineOperateRecord()
  860. // {
  861. // CreatedOn = DateTime.Now,
  862. // ChargeBoxId = session.ChargeBoxId,
  863. // SerialNo = requestId,
  864. // RequestContent = JsonConvert.SerializeObject(_updateFWrequest, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  865. // EVSE_Status = 0,
  866. // EVSE_Value = "Fw Version:" + machine.FW_AssignedMachineVersionId,
  867. // Status = 0,
  868. // RequestType = 0,
  869. // });
  870. // db.ServerMessage.Add(new ServerMessage()
  871. // {
  872. // ChargeBoxId = session.ChargeBoxId,
  873. // CreatedBy = "Server",
  874. // CreatedOn = DateTime.Now,
  875. // OutAction = _updateFWrequest.Action.ToString(),
  876. // OutRequest = JsonConvert.SerializeObject(_updateFWrequest, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  877. // SerialNo = requestId,
  878. // InMessage = string.Empty
  879. // });
  880. // db.SaveChanges();
  881. // }
  882. //}
  883. #endregion
  884. }
  885. }
  886. }
  887. catch (Exception ex)
  888. {
  889. logger.Error(string.Format("serverUpdateTrigger ChargeBoxId:{0} Ex:{1}", chargeBoxId, ex.ToString()));
  890. }
  891. }
  892. }
  893. await Task.Delay(1000);
  894. // Thread.CurrentThread.Join(1000);
  895. }
  896. }
  897. }
  898. async private void ServerMessageTrigger()
  899. {
  900. for (; ; )
  901. {
  902. if (_ct.IsCancellationRequested)
  903. {
  904. break;
  905. }
  906. try
  907. {
  908. RemoveConfirmMessage();
  909. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  910. using (var db = new MainDBContext())
  911. {
  912. DateTime startDt = DateTime.Now.AddSeconds(-30);
  913. DateTime dt = new DateTime(1991, 1, 1);
  914. DateTime currentTime = DateTime.Now;
  915. var commandList = db.ServerMessage.Where(c => c.ReceivedOn == dt && c.UpdatedOn == dt && c.CreatedOn >= startDt && c.CreatedOn <= currentTime).AsNoTracking().ToList();
  916. //處理主機傳送的有指令
  917. var cmdMachineList = commandList.Select(c => c.ChargeBoxId).Distinct().ToList();
  918. if (commandList.Count > 0)
  919. {
  920. // Console.WriteLine(string.Format("Now:{0} commandList Count:{1} ", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), commandList.Count));
  921. }
  922. foreach (var charger_SN in cmdMachineList)
  923. {
  924. ClientData session;
  925. string uuid = string.Empty;
  926. if (clientDic.TryGetValue(charger_SN, out session))
  927. {
  928. 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")));
  929. if (session.IsCheckIn && session.IsOCPP16)
  930. {
  931. var cmdList = commandList.Where(c => c.ChargeBoxId == charger_SN).ToList();
  932. foreach (var item in cmdList)
  933. {
  934. IRequest request = null;
  935. Actions action = Actions.None;
  936. Enum.TryParse(item.OutAction, out action);
  937. Type _RequestType = null;
  938. for (int i = 0; i < profiles.Count; i++)
  939. {
  940. var feature = profiles[i].GetFeaturebyAction(item.OutAction);
  941. if (feature != null)
  942. {
  943. _RequestType = feature.GetRequestType();
  944. break;
  945. }
  946. }
  947. if (_RequestType != null && item.CreatedBy != "Destroyer")
  948. {
  949. request = JsonConvert.DeserializeObject(item.OutRequest, _RequestType) as IRequest;
  950. uuid = session.queue.store(request);
  951. string rawRequest = BasicMessageHandler.GenerateRequest(uuid, item.OutAction, request);
  952. Send(session, rawRequest, string.Format("{0} {1}", action, "Request"), "");
  953. }
  954. if (_RequestType != null && item.CreatedBy == "Destroyer")
  955. {
  956. Console.WriteLine("********************************");
  957. request = Activator.CreateInstance(_RequestType) as IRequest;
  958. Console.WriteLine("++++++++++++++++++++++++++++++++++++++++");
  959. uuid = session.queue.store(request);
  960. string rawRequest = BasicMessageHandler.GenerateDestroyRequest(uuid, item.OutAction, item.OutRequest);
  961. Send(session, rawRequest, string.Format("{0} {1}", action, "Request"), "");
  962. }
  963. AddConfirmMessage(charger_SN, item.Id, item.SerialNo, item.OutAction, uuid);
  964. #region 更新資料表單一欄位
  965. var _UpdatedItem = new ServerMessage() { Id = item.Id, UpdatedOn = DateTime.Now };
  966. db.Configuration.AutoDetectChangesEnabled = false;//自動呼叫DetectChanges()比對所有的entry集合的每一個屬性Properties的新舊值
  967. db.Configuration.ValidateOnSaveEnabled = false;// 因為Entity有些欄位必填,若不避開會有Validate錯誤
  968. // var _UpdatedItem = db.ServerMessage.Where(x => x.Id == item.Id).FirstOrDefault();
  969. db.ServerMessage.Attach(_UpdatedItem);
  970. _UpdatedItem.UpdatedOn = DateTime.Now;
  971. db.Entry(_UpdatedItem).Property(x => x.UpdatedOn).IsModified = true;// 可以直接使用這方式強制某欄位要更新,只是查詢集合耗效能而己
  972. db.SaveChanges();
  973. #endregion
  974. }
  975. }
  976. }
  977. }
  978. }
  979. await Task.Delay(1000);
  980. // Thread.CurrentThread.Join(1000);
  981. }
  982. catch (Exception ex)
  983. {
  984. logger.Error(string.Format("ServerMessageTrigger Ex:{0}", ex.ToString()));
  985. }
  986. }
  987. }
  988. DateTime lastcheckdt = new DateTime();
  989. async private void HeartBeatCheckTrigger()
  990. {
  991. for (; ; )
  992. {
  993. if (_ct.IsCancellationRequested)
  994. {
  995. break;
  996. }
  997. try
  998. {
  999. if (DateTime.Now.Subtract(lastcheckdt).TotalSeconds > 10)
  1000. {
  1001. Stopwatch watch = new Stopwatch();
  1002. Dictionary<string, ClientData> _copyClientDic = null;
  1003. lock (_lockClientDic)
  1004. {
  1005. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1006. }
  1007. var cdt = DateTime.Now;
  1008. var clients = _copyClientDic.Where(x => x.Value.LastActiveTime > cdt.AddSeconds(-30)).Select(x => x.Value).ToList();
  1009. watch.Start();
  1010. foreach (var session in clients)
  1011. {
  1012. using (var db = new MainDBContext())
  1013. {
  1014. var machine = new Machine() { Id = session.MachineId };
  1015. if (machine != null)
  1016. {
  1017. db.Configuration.AutoDetectChangesEnabled = false;
  1018. db.Configuration.ValidateOnSaveEnabled = false;
  1019. db.Machine.Attach(machine);
  1020. machine.HeartbeatUpdatedOn = DateTime.Now;
  1021. machine.ConnectionType = session.UriScheme.Equals("wss") ? 2 : 1;
  1022. db.Entry(machine).Property(x => x.HeartbeatUpdatedOn).IsModified = true;
  1023. db.Entry(machine).Property(x => x.ConnectionType).IsModified = true;
  1024. await db.SaveChangesAsync();
  1025. }
  1026. }
  1027. }
  1028. watch.Stop();
  1029. if (watch.ElapsedMilliseconds / 1000 > 5)
  1030. {
  1031. logger.Fatal("Update HeartBeatCheckTrigger cost " + watch.ElapsedMilliseconds / 1000 + " seconds.");
  1032. }
  1033. }
  1034. lastcheckdt = DateTime.Now;
  1035. await Task.Delay(10000);
  1036. }
  1037. catch (Exception ex)
  1038. {
  1039. logger.Error(string.Format("HealthAlarmTrigger Ex:{0}", ex.ToString()));
  1040. }
  1041. }
  1042. }
  1043. async private void HealthCheckTrigger()
  1044. {
  1045. for (; ; )
  1046. {
  1047. if (_ct.IsCancellationRequested)
  1048. {
  1049. break;
  1050. }
  1051. try
  1052. {
  1053. Dictionary<string, ClientData> _copyClientDic = null;
  1054. lock (_lockClientDic)
  1055. {
  1056. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1057. }
  1058. var removeClients = _copyClientDic.Where(x => x.Value.LastActiveTime < DateTime.Now.AddSeconds(-120)).Select(x => x.Value).ToList();
  1059. foreach (var session in removeClients)
  1060. {
  1061. Console.WriteLine(string.Format("Server forced to shut down ChargeBox ({0}: LastActiveTime{1})", session.ChargeBoxId, session.LastActiveTime));
  1062. RemoveClient(session);
  1063. }
  1064. await Task.Delay(60000);
  1065. }
  1066. catch (Exception ex)
  1067. {
  1068. logger.Error(string.Format("HealthAlarmTrigger Ex:{0}", ex.ToString()));
  1069. }
  1070. }
  1071. }
  1072. private void AddConfirmMessage(string chargePointSerialNumber, int table_id, string requestId, string action, string msg_id)
  1073. {
  1074. NeedConfirmMessage _needConfirmMsg = new NeedConfirmMessage();
  1075. _needConfirmMsg.Id = table_id;
  1076. _needConfirmMsg.SentAction = action;
  1077. _needConfirmMsg.SentOn = DateTime.Now;
  1078. _needConfirmMsg.SentTimes = 1;
  1079. _needConfirmMsg.ChargePointSerialNumber = chargePointSerialNumber;
  1080. _needConfirmMsg.RequestId = requestId;
  1081. _needConfirmMsg.SentUniqueId = msg_id;
  1082. if (needConfirmActions.Contains(action))
  1083. {
  1084. lock (_lockConfirmPacketList)
  1085. {
  1086. needConfirmPacketList.Add(_needConfirmMsg);
  1087. if (action == "GetConfiguration")
  1088. {
  1089. Console.WriteLine("AddConfirmMessage: " + msg_id);
  1090. }
  1091. }
  1092. }
  1093. }
  1094. private void RemoveConfirmMessage()
  1095. {
  1096. var before_3mins = DateTime.Now.AddMinutes(-3);
  1097. lock (_lockConfirmPacketList)
  1098. {
  1099. var removeList = needConfirmPacketList.Where(x => x.SentTimes == 0 || x.SentOn < before_3mins).ToList();
  1100. foreach (var item in removeList)
  1101. {
  1102. needConfirmPacketList.Remove(item);
  1103. }
  1104. }
  1105. }
  1106. private bool ReConfirmMessage(MessageResult analysisResult)
  1107. {
  1108. bool confirmed = false;
  1109. if (needConfirmActions.Contains(analysisResult.Action))
  1110. {
  1111. if (analysisResult.Action == "GetConfiguration")
  1112. {
  1113. Console.WriteLine("ReConfirmMessage: " + analysisResult.UUID);
  1114. }
  1115. NeedConfirmMessage foundRequest = null;
  1116. lock (_lockConfirmPacketList)
  1117. {
  1118. foundRequest = needConfirmPacketList.Where(x => x.SentUniqueId == analysisResult.UUID).FirstOrDefault();
  1119. }
  1120. if (foundRequest != null && foundRequest.Id > 0)
  1121. {
  1122. foundRequest.SentTimes = 0;
  1123. foundRequest.SentInterval = 0;
  1124. analysisResult.RequestId = foundRequest.RequestId;
  1125. using (var db = new MainDBContext())
  1126. {
  1127. var sc = db.ServerMessage.Where(x => x.Id == foundRequest.Id).FirstOrDefault();
  1128. sc.InMessage = JsonConvert.SerializeObject(analysisResult.Message, Formatting.None);
  1129. sc.ReceivedOn = DateTime.Now;
  1130. db.SaveChanges();
  1131. // Console.WriteLine(string.Format("Now:{0} ServerMessage Id:{1} ", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), foundRequest.Id));
  1132. }
  1133. confirmed = true;
  1134. }
  1135. else if (analysisResult.Action == Actions.TriggerMessage.ToString())
  1136. {
  1137. confirmed = true;
  1138. }
  1139. else
  1140. {
  1141. logger.Error(string.Format("Received no record Action:{0} MessageId:{1} ", analysisResult.Action, analysisResult.UUID));
  1142. }
  1143. }
  1144. return confirmed;
  1145. }
  1146. private void RemoveClient(ClientData session)
  1147. {
  1148. Console.WriteLine("*********");
  1149. if (session != null)
  1150. {
  1151. logger.Trace("RemoveClient[" + session.ChargeBoxId + "]");
  1152. if (session.Connected)
  1153. {
  1154. session.Close(CloseReason.ServerShutdown);
  1155. }
  1156. RemoveClientDic(session);
  1157. try
  1158. {
  1159. session.m_ReceiveData -= new ClientData.OCPPClientDataEventHandler<ClientData, String>(ReceivedMessage);
  1160. // session.Close(CloseReason.ServerShutdown);
  1161. }
  1162. catch (Exception ex)
  1163. {
  1164. //logger.Warn("Close client socket error!!");
  1165. logger.Warn(string.Format("Close client socket error!! {0} Msg:{1}", session.ChargeBoxId, ex.Message));
  1166. }
  1167. if (session != null)
  1168. {
  1169. session = null;
  1170. }
  1171. }
  1172. }
  1173. private void RemoveClientDic(ClientData session)
  1174. {
  1175. if (!string.IsNullOrEmpty(session.ChargeBoxId))
  1176. {
  1177. lock (_lockClientDic)
  1178. {
  1179. if (clientDic.ContainsKey(session.ChargeBoxId))
  1180. {
  1181. if (clientDic[session.ChargeBoxId].SessionID == session.SessionID)
  1182. {
  1183. logger.Debug(String.Format("ChargeBoxId:{0} Remove SessionId:{1} Removed SessionId:{2}", session.ChargeBoxId, session.SessionID, clientDic[session.ChargeBoxId].SessionID));
  1184. clientDic.Remove(session.ChargeBoxId);
  1185. logger.Trace("RemoveClient ContainsKey " + session.ChargeBoxId);
  1186. }
  1187. }
  1188. }
  1189. }
  1190. }
  1191. private void WarmUpLog()
  1192. {
  1193. using (var log = new ConnectionLogDBContext())
  1194. {
  1195. log.MachineConnectionLog.ToList();
  1196. }
  1197. }
  1198. private void WriteMachineLog(ClientData clientData, string data, string messageType, string errorMsg = "", bool isSent = false)
  1199. {
  1200. try
  1201. {
  1202. if (clientData == null || string.IsNullOrEmpty(data)) return;
  1203. if (clientData.ChargeBoxId == null)
  1204. {
  1205. logger.Fatal(clientData.Path + "]********************session ChargeBoxId null sessionId=" + clientData.SessionID);
  1206. }
  1207. using (var db = new ConnectionLogDBContext())
  1208. {
  1209. string sp = "[dbo].[uspInsertMachineConnectionLog] @CreatedOn," +
  1210. "@ChargeBoxId,@MessageType,@Data,@Msg,@IsSent,@EVSEEndPoint,@Session";
  1211. var dd = DateTime.UtcNow;
  1212. SqlParameter[] parameter =
  1213. {
  1214. new SqlParameter("CreatedOn",dd),
  1215. new SqlParameter("ChargeBoxId",clientData.ChargeBoxId==null?"unknown":clientData.ChargeBoxId.Replace("'","''")),
  1216. new SqlParameter("MessageType",messageType.Replace("'","''")),
  1217. new SqlParameter("Data",data.Replace("'","''")),
  1218. new SqlParameter("Msg",errorMsg.Replace("'","''")),
  1219. new SqlParameter("IsSent",isSent),
  1220. new SqlParameter("EVSEEndPoint",clientData.RemoteEndPoint==null?"123":clientData.RemoteEndPoint.ToString()),
  1221. new SqlParameter("Session",clientData.SessionID==null?"123":clientData.SessionID)
  1222. };
  1223. db.Database.ExecuteSqlCommand(sp, parameter);
  1224. }
  1225. }
  1226. catch (Exception ex)
  1227. {
  1228. Console.WriteLine(ex.ToString());
  1229. }
  1230. }
  1231. }
  1232. }