ProtalServer.cs 78 KB

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