ProtalServer.cs.bak 107 KB

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