ProtalServer.cs 97 KB

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