ProtalServer.cs 104 KB

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