ProtalServer.cs 104 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126
  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. Console.WriteLine("++++++++++++++++");
  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("009E603C-79CD-4620-A2B8-D9349C0E8AD8"))
  612. {
  613. var stationInfo = await GetStationInfo(session.MachineId);
  614. if (stationInfo != null)
  615. {
  616. session.StationLocation = string.Format("{0},{1}", stationInfo.Lat, stationInfo.Long);
  617. session.StationName = stationInfo.ZipCode;
  618. }
  619. using (var db = new MainDBContext())
  620. {
  621. db.ServerMessage.Add(new ServerMessage()
  622. {
  623. ChargeBoxId = session.ChargeBoxId,
  624. CreatedBy = "Server",
  625. CreatedOn = DateTime.UtcNow,
  626. OutAction = Actions.DataTransfer.ToString(),
  627. OutRequest = JsonConvert.SerializeObject(
  628. new DataTransferRequest()
  629. {
  630. messageId = "ID_Station_Location",
  631. vendorId = "Phihong Technology",
  632. data = JsonConvert.SerializeObject(new { stationName = session.StationName })
  633. },
  634. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  635. SerialNo = Guid.NewGuid().ToString(),
  636. InMessage = string.Empty
  637. });
  638. db.ServerMessage.Add(new ServerMessage()
  639. {
  640. ChargeBoxId = session.ChargeBoxId,
  641. CreatedBy = "Server",
  642. CreatedOn = DateTime.UtcNow,
  643. OutAction = Actions.ChangeConfiguration.ToString(),
  644. OutRequest = JsonConvert.SerializeObject(
  645. new ChangeConfigurationRequest()
  646. {
  647. key = "TimeOffset",
  648. value = "+08:00"
  649. },
  650. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  651. SerialNo = Guid.NewGuid().ToString(),
  652. InMessage = string.Empty
  653. });
  654. if (!TCCStationDic.ContainsKey(session.StationLocation))
  655. {
  656. _CheckWeatherDt = DateTime.UtcNow.AddDays(-1);
  657. }
  658. else
  659. {
  660. db.ServerMessage.Add(new ServerMessage()
  661. {
  662. ChargeBoxId = session.ChargeBoxId,
  663. CreatedBy = "Server",
  664. CreatedOn = DateTime.UtcNow,
  665. OutAction = Actions.DataTransfer.ToString(),
  666. OutRequest = JsonConvert.SerializeObject(
  667. new DataTransferRequest()
  668. {
  669. messageId = "ID_Weather_Info",
  670. vendorId = "Phihong Technology",
  671. data = JsonConvert.SerializeObject(
  672. new
  673. {
  674. weatherId = TCCStationDic[session.StationLocation].WeatherID,
  675. Temperature = TCCStationDic[session.StationLocation].Temperature
  676. })
  677. },
  678. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  679. SerialNo = Guid.NewGuid().ToString(),
  680. InMessage = string.Empty
  681. });
  682. }
  683. db.SaveChanges();
  684. }
  685. }
  686. }
  687. else
  688. {
  689. using (var db = new MainDBContext())
  690. {
  691. var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault();
  692. if (machine != null)
  693. {
  694. if (machine.ConnectorType.Contains("6") || machine.ConnectorType.Contains("7") || machine.ConnectorType.Contains("8") || machine.ConnectorType.Contains("9"))
  695. {
  696. session.IsAC = false;
  697. }
  698. machine.ConnectionType = session.Origin.Contains("https") ? 2 : 1;
  699. db.SaveChanges();
  700. }
  701. }
  702. await SetDefaultFee(session);
  703. }
  704. }
  705. #region 台泥
  706. if (action == Actions.StartTransaction && session.CustomerId == new Guid("009E603C-79CD-4620-A2B8-D9349C0E8AD8") && replyResult.Message is StartTransactionConfirmation)
  707. {
  708. StartTransactionConfirmation confirm = (StartTransactionConfirmation)replyResult.Message;
  709. StartTransactionRequest request = (StartTransactionRequest)analysisResult.Message;
  710. using (var db = new MainDBContext())
  711. {
  712. db.ServerMessage.Add(new ServerMessage()
  713. {
  714. ChargeBoxId = session.ChargeBoxId,
  715. CreatedBy = "Server",
  716. CreatedOn = DateTime.UtcNow,
  717. OutAction = Actions.DataTransfer.ToString(),
  718. OutRequest = JsonConvert.SerializeObject(
  719. new DataTransferRequest()
  720. {
  721. messageId = "ID_GetTxUserInfo",
  722. vendorId = "Phihong Technology",
  723. data = JsonConvert.SerializeObject(new { txId = confirm.transactionId, ConnectorId = request.connectorId })
  724. },
  725. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  726. SerialNo = Guid.NewGuid().ToString(),
  727. InMessage = string.Empty
  728. });
  729. db.SaveChanges();
  730. }
  731. }
  732. #endregion
  733. if (action == Actions.Authorize && replyResult.Message is AuthorizeConfirmation)
  734. {
  735. var authorizeRequest = (IRequest)analysisResult.Message as AuthorizeRequest;
  736. if (session.UserDisplayPrices.ContainsKey(authorizeRequest.idTag))
  737. {
  738. using (var db = new MainDBContext())
  739. {
  740. db.ServerMessage.Add(new ServerMessage()
  741. {
  742. ChargeBoxId = session.ChargeBoxId,
  743. CreatedBy = "Server",
  744. CreatedOn = DateTime.UtcNow,
  745. OutAction = Actions.DataTransfer.ToString(),
  746. OutRequest = JsonConvert.SerializeObject(
  747. new DataTransferRequest()
  748. {
  749. messageId = "SetUserPrice",
  750. vendorId = "Phihong Technology",
  751. data = JsonConvert.SerializeObject(
  752. new
  753. {
  754. idToken = authorizeRequest.idTag,
  755. price = session.UserDisplayPrices[authorizeRequest.idTag]
  756. })
  757. },
  758. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  759. SerialNo = Guid.NewGuid().ToString(),
  760. InMessage = string.Empty
  761. });
  762. db.SaveChanges();
  763. }
  764. }
  765. }
  766. }
  767. else
  768. {
  769. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  770. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  771. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  772. }
  773. if (action == Actions.StartTransaction)
  774. {
  775. var stationId = _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  776. var _powerDic = _loadingBalanceService.GetSettingPower(stationId, session.MachineId);
  777. if (_powerDic != null)
  778. {
  779. foreach (var kv in _powerDic)
  780. {
  781. try
  782. {
  783. string chargeBoxId = string.Empty;
  784. //set profile
  785. lock (_lockClientDic)
  786. {
  787. chargeBoxId = clientDic.Where(x => x.Value.MachineId == kv.Key).Select(x => x.Value.ChargeBoxId).FirstOrDefault();
  788. }
  789. if (chargeBoxId != null && kv.Value.HasValue)
  790. {
  791. profileHandler.SetChargingProfile(chargeBoxId, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  792. }
  793. }
  794. catch (Exception ex)
  795. {
  796. logger.Error(string.Format("Set Profile Exception: {0}", ex.ToString()));
  797. }
  798. }
  799. }
  800. }
  801. if (action == Actions.StopTransaction)
  802. {
  803. var stationId = _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  804. if (_loadingBalanceService.IsNeedtoCancelSetting(stationId, session.MachineId, session.ChargeBoxId))
  805. {
  806. //Clear current profile
  807. profileHandler.ClearChargingProfile(session.ChargeBoxId);
  808. var _powerDic = _loadingBalanceService.GetRerangeSettingPower(stationId);
  809. if (_powerDic != null)
  810. {
  811. foreach (var kv in _powerDic)
  812. {
  813. try
  814. {
  815. string chargeBoxId = string.Empty;
  816. //set profile
  817. lock (_lockClientDic)
  818. {
  819. chargeBoxId = clientDic.Where(x => x.Value.MachineId == kv.Key).Select(x => x.Value.ChargeBoxId).FirstOrDefault();
  820. }
  821. if (chargeBoxId != null && kv.Value.HasValue)
  822. {
  823. profileHandler.SetChargingProfile(chargeBoxId, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  824. }
  825. }
  826. catch (Exception ex)
  827. {
  828. logger.Error(string.Format("Set Profile Exception: {0}", ex.ToString()));
  829. }
  830. }
  831. }
  832. }
  833. }
  834. }
  835. break;
  836. case "FirmwareManagement":
  837. {
  838. var replyResult = profileHandler.ExecuteFirmwareManagementRequest(action, session, (IRequest)analysisResult.Message);
  839. if (replyResult.Success)
  840. {
  841. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  842. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  843. }
  844. else
  845. {
  846. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  847. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  848. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  849. }
  850. }
  851. break;
  852. case "Security":
  853. {
  854. var replyResult = profileHandler.ExecuteSecurityRequest(action, session, (IRequest)analysisResult.Message);
  855. if (replyResult.Success)
  856. {
  857. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  858. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  859. }
  860. else
  861. {
  862. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  863. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  864. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  865. }
  866. }
  867. break;
  868. default:
  869. {
  870. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  871. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  872. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  873. }
  874. break;
  875. }
  876. }
  877. }
  878. async private void ProcessConfirmationMessage(MessageResult analysisResult, ClientData session, Actions action)
  879. {
  880. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  881. if (ReConfirmMessage(analysisResult))
  882. {
  883. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  884. MessageResult confirmResult = null;
  885. switch (profileName)
  886. {
  887. case "Core":
  888. {
  889. confirmResult = await profileHandler.ExecuteCoreConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  890. }
  891. break;
  892. case "FirmwareManagement":
  893. {
  894. confirmResult = profileHandler.ExecuteFirmwareManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  895. }
  896. break;
  897. case "RemoteTrigger":
  898. {
  899. confirmResult = profileHandler.ExecuteRemoteTriggerConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  900. }
  901. break;
  902. case "Reservation":
  903. {
  904. confirmResult = profileHandler.ExecuteReservationConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  905. }
  906. break;
  907. case "LocalAuthListManagement":
  908. {
  909. confirmResult = profileHandler.ExecuteLocalAuthListManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  910. }
  911. break;
  912. case "SmartCharging":
  913. {
  914. confirmResult = profileHandler.ExecuteSmartChargingConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  915. }
  916. break;
  917. case "Security":
  918. {
  919. confirmResult = profileHandler.ExecuteSecurityConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  920. }
  921. break;
  922. default:
  923. {
  924. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  925. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  926. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  927. }
  928. break;
  929. }
  930. if (confirmResult == null || !confirmResult.Success)
  931. {
  932. logger.Error(string.Format("Action:{0} MessageId:{1} ExecuteConfirm Error:{2} ",
  933. analysisResult.Action, analysisResult.UUID, confirmResult.Exception.ToString()));
  934. }
  935. }
  936. else
  937. {
  938. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  939. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  940. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  941. }
  942. }
  943. private void ProcessErrorMessage(MessageResult analysisResult, ClientData session, Actions action)
  944. {
  945. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  946. if (ReConfirmMessage(analysisResult))
  947. {
  948. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  949. switch (profileName)
  950. {
  951. case "Core":
  952. {
  953. profileHandler.ReceivedCoreError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  954. }
  955. break;
  956. case "FirmwareManagement":
  957. {
  958. profileHandler.ReceivedFirmwareManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  959. }
  960. break;
  961. case "RemoteTrigger":
  962. {
  963. profileHandler.ReceivedRemoteTriggerError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  964. }
  965. break;
  966. case "Reservation":
  967. {
  968. profileHandler.ExecuteReservationError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  969. }
  970. break;
  971. case "LocalAuthListManagement":
  972. {
  973. profileHandler.ReceivedLocalAuthListManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  974. }
  975. break;
  976. case "SmartCharging":
  977. {
  978. profileHandler.ReceivedSmartChargingError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  979. }
  980. break;
  981. default:
  982. {
  983. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  984. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  985. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  986. }
  987. break;
  988. }
  989. }
  990. else
  991. {
  992. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  993. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  994. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  995. }
  996. }
  997. private void Send(ClientData session, string msg, string messageType, string errorMsg = "")
  998. {
  999. try
  1000. {
  1001. if (session != null)
  1002. {
  1003. WriteMachineLog(session, msg, messageType, errorMsg, true);
  1004. session.Send(msg);
  1005. }
  1006. }
  1007. catch (Exception ex)
  1008. {
  1009. logger.Error(string.Format("Send Ex:{0}", ex.ToString()));
  1010. }
  1011. }
  1012. async private void ServerUpdateTrigger()
  1013. {
  1014. for (; ; )
  1015. {
  1016. if (_ct.IsCancellationRequested)
  1017. {
  1018. break;
  1019. }
  1020. var min_Interval = (DateTime.UtcNow - checkUpdateDt).TotalMinutes;
  1021. if (min_Interval > 3)
  1022. {
  1023. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1024. Dictionary<string, ClientData> _copyClientDic = null;
  1025. lock (_lockClientDic)
  1026. {
  1027. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1028. }
  1029. checkUpdateDt = DateTime.UtcNow;
  1030. using (var db = new MainDBContext())
  1031. {
  1032. //var needUpdateChargers = db.Machine.Where(x => x.FW_AssignedMachineVersionId.HasValue == true &&
  1033. // x.FW_AssignedMachineVersionId != x.FW_VersionReport && x.Online == true)
  1034. // .Select(x => new { x.Id, x.ChargeBoxId, x.FW_AssignedMachineVersionId }).ToList();
  1035. var needUpdateChargers = db.Machine.Where(x => x.FW_AssignedVersion.HasValue == true &&
  1036. x.FW_AssignedVersion != x.FW_VersionReport && x.Online == true)
  1037. .Select(x => x.ChargeBoxId).AsNoTracking().ToList();
  1038. foreach (var chargeBoxId in needUpdateChargers)
  1039. {
  1040. try
  1041. {
  1042. ClientData session;
  1043. if (_copyClientDic.TryGetValue(chargeBoxId, out session))
  1044. {
  1045. string requestId = Guid.NewGuid().ToString();
  1046. // using (var db = new MainDBContext())
  1047. if (session.IsCheckIn && !session.ISOCPP20)
  1048. {
  1049. var _request = new TriggerMessageRequest()
  1050. {
  1051. requestedMessage = Packet.Messages.SubTypes.MessageTrigger.FirmwareStatusNotification
  1052. };
  1053. var uuid = session.queue.store(_request);
  1054. string rawRequest = BasicMessageHandler.GenerateRequest(uuid, _request.Action, _request);
  1055. Send(session, rawRequest, string.Format("{0} {1}", _request.Action, "Request"), "");
  1056. #region OCTT ,測試韌體更新方式
  1057. //--------------------> OCTT ,測試韌體更新方式
  1058. //{
  1059. // var machine = db.Machine.Where(x => x.FW_AssignedMachineVersionId.HasValue == true &&
  1060. // x.FW_AssignedMachineVersionId != x.FW_VersionReport && x.ChargeBoxId == session.ChargeBoxId)
  1061. // .Select(x => new { x.Id, x.FW_AssignedMachineVersionId }).FirstOrDefault();
  1062. // if (machine != null)
  1063. // {
  1064. // var mv = db.MachineVersion.Include(c => c.PublishVersion)
  1065. // .Include(c => c.PublishVersion.PublishVersionFiles)
  1066. // .Include(c => c.PublishVersion.PublishVersionFiles.Select(z => z.UploadFile))
  1067. // .Where(c => c.Id == machine.FW_AssignedMachineVersionId.Value).First();
  1068. // string downloadUrl = mv.PublishVersion.PublishVersionFiles.FirstOrDefault().UploadFile.FileUrl;
  1069. // var _updateFWrequest = new UpdateFirmwareRequest()
  1070. // {
  1071. // location = new Uri(downloadUrl),
  1072. // retries = 3,
  1073. // retrieveDate = DateTime.UtcNow,
  1074. // retryInterval = 10
  1075. // };
  1076. // db.MachineOperateRecord.Add(new MachineOperateRecord()
  1077. // {
  1078. // CreatedOn = DateTime.UtcNow,
  1079. // ChargeBoxId = session.ChargeBoxId,
  1080. // SerialNo = requestId,
  1081. // RequestContent = JsonConvert.SerializeObject(_updateFWrequest, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1082. // EVSE_Status = 0,
  1083. // EVSE_Value = "Fw Version:" + machine.FW_AssignedMachineVersionId,
  1084. // Status = 0,
  1085. // RequestType = 0,
  1086. // });
  1087. // db.ServerMessage.Add(new ServerMessage()
  1088. // {
  1089. // ChargeBoxId = session.ChargeBoxId,
  1090. // CreatedBy = "Server",
  1091. // CreatedOn = DateTime.UtcNow,
  1092. // OutAction = _updateFWrequest.Action.ToString(),
  1093. // OutRequest = JsonConvert.SerializeObject(_updateFWrequest, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1094. // SerialNo = requestId,
  1095. // InMessage = string.Empty
  1096. // });
  1097. // db.SaveChanges();
  1098. // }
  1099. //}
  1100. #endregion
  1101. }
  1102. }
  1103. }
  1104. catch (Exception ex)
  1105. {
  1106. logger.Error(string.Format("serverUpdateTrigger ChargeBoxId:{0} Ex:{1}", chargeBoxId, ex.ToString()));
  1107. }
  1108. }
  1109. }
  1110. await Task.Delay(1000);
  1111. // Thread.CurrentThread.Join(1000);
  1112. }
  1113. }
  1114. }
  1115. string webConnectionString = ConfigurationManager.ConnectionStrings["WebDBContext"].ConnectionString;
  1116. async private void ServerMessageTrigger()
  1117. {
  1118. for (; ; )
  1119. {
  1120. if (_ct.IsCancellationRequested)
  1121. {
  1122. break;
  1123. }
  1124. try
  1125. {
  1126. RemoveConfirmMessage();
  1127. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1128. using (var db = new MainDBContext())
  1129. {
  1130. DateTime startDt = DateTime.UtcNow.AddSeconds(-30);
  1131. DateTime dt = new DateTime(1991, 1, 1);
  1132. DateTime currentTime = DateTime.UtcNow;
  1133. var commandList = db.ServerMessage.Where(c => c.ReceivedOn == dt && c.UpdatedOn == dt && c.CreatedOn >= startDt && c.CreatedOn <= currentTime).AsNoTracking().ToList();
  1134. //處理主機傳送的有指令
  1135. var cmdMachineList = commandList.Select(c => c.ChargeBoxId).Distinct().ToList();
  1136. if (commandList.Count > 0)
  1137. {
  1138. // Console.WriteLine(string.Format("Now:{0} commandList Count:{1} ", DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"), commandList.Count));
  1139. }
  1140. var resendList = GetResendMessage();
  1141. foreach (var resendItem in resendList)
  1142. {
  1143. ClientData session;
  1144. if (clientDic.TryGetValue(resendItem.ChargePointSerialNumber, out session))
  1145. {
  1146. if (DateTime.UtcNow.Subtract(resendItem.SentOn).TotalSeconds > 1)
  1147. {
  1148. resendItem.SentTimes--;
  1149. resendItem.SentOn = DateTime.UtcNow;
  1150. Send(session, resendItem.SentMessage, string.Format("{0} {1}", resendItem.SentAction, "Request"), "");
  1151. }
  1152. }
  1153. }
  1154. foreach (var charger_SN in cmdMachineList)
  1155. {
  1156. ClientData session;
  1157. string uuid = string.Empty;
  1158. if (clientDic.TryGetValue(charger_SN, out session))
  1159. {
  1160. //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")));
  1161. if (session.IsCheckIn && !session.ISOCPP20)
  1162. {
  1163. string rawRequest = string.Empty;
  1164. var cmdList = commandList.Where(c => c.ChargeBoxId == charger_SN).ToList();
  1165. foreach (var item in cmdList)
  1166. {
  1167. IRequest request = null;
  1168. Actions action = Actions.None;
  1169. Enum.TryParse(item.OutAction, out action);
  1170. Type _RequestType = null;
  1171. for (int i = 0; i < profiles.Count; i++)
  1172. {
  1173. var feature = profiles[i].GetFeaturebyAction(item.OutAction);
  1174. if (feature != null)
  1175. {
  1176. _RequestType = feature.GetRequestType();
  1177. break;
  1178. }
  1179. }
  1180. if (_RequestType != null && item.CreatedBy != "Destroyer")
  1181. {
  1182. request = JsonConvert.DeserializeObject(item.OutRequest, _RequestType) as IRequest;
  1183. uuid = session.queue.store(request);
  1184. rawRequest = BasicMessageHandler.GenerateRequest(uuid, item.OutAction, request);
  1185. Send(session, rawRequest, string.Format("{0} {1}", action, "Request"), "");
  1186. }
  1187. if (item.CreatedBy == "Destroyer")
  1188. {
  1189. if (_RequestType != null)
  1190. {
  1191. request = Activator.CreateInstance(_RequestType) as IRequest;
  1192. uuid = session.queue.store(request);
  1193. rawRequest = BasicMessageHandler.GenerateDestroyRequest(uuid, item.OutAction, item.OutRequest);
  1194. Send(session, rawRequest, string.Format("{0} {1}", action, "Request"), "");
  1195. }
  1196. else
  1197. {
  1198. rawRequest = BasicMessageHandler.GenerateDestroyRequest(Guid.NewGuid().ToString(), item.OutAction, item.OutRequest);
  1199. Send(session, rawRequest, string.Format("{0} {1}", action, "Request"), "");
  1200. }
  1201. }
  1202. AddConfirmMessage(charger_SN, item.Id, item.SerialNo, item.OutAction, uuid, item.CreatedBy, rawRequest);
  1203. #region 更新資料表單一欄位
  1204. var _UpdatedItem = new ServerMessage() { Id = item.Id, UpdatedOn = DateTime.UtcNow };
  1205. db.Configuration.AutoDetectChangesEnabled = false;//自動呼叫DetectChanges()比對所有的entry集合的每一個屬性Properties的新舊值
  1206. db.Configuration.ValidateOnSaveEnabled = false;// 因為Entity有些欄位必填,若不避開會有Validate錯誤
  1207. // var _UpdatedItem = db.ServerMessage.Where(x => x.Id == item.Id).FirstOrDefault();
  1208. db.ServerMessage.Attach(_UpdatedItem);
  1209. _UpdatedItem.UpdatedOn = DateTime.UtcNow;
  1210. db.Entry(_UpdatedItem).Property(x => x.UpdatedOn).IsModified = true;// 可以直接使用這方式強制某欄位要更新,只是查詢集合耗效能而己
  1211. db.SaveChanges();
  1212. #endregion
  1213. await Task.Delay(100);
  1214. }
  1215. }
  1216. }
  1217. }
  1218. }
  1219. await Task.Delay(500);
  1220. }
  1221. catch (Exception ex)
  1222. {
  1223. logger.Error(string.Format("ServerMessageTrigger Ex:{0}", ex.ToString()));
  1224. }
  1225. }
  1226. }
  1227. async private void HeartBeatCheckTrigger()
  1228. {
  1229. for (; ; )
  1230. {
  1231. if (_ct.IsCancellationRequested)
  1232. {
  1233. break;
  1234. }
  1235. try
  1236. {
  1237. if (DateTime.UtcNow.Subtract(lastcheckdt).TotalSeconds > 30)
  1238. {
  1239. lastcheckdt = DateTime.UtcNow;
  1240. Stopwatch watch = new Stopwatch();
  1241. Dictionary<string, ClientData> _copyClientDic = null;
  1242. lock (_lockClientDic)
  1243. {
  1244. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1245. }
  1246. var cdt = DateTime.UtcNow;
  1247. var clients = _copyClientDic.Where(x => x.Value.LastActiveTime > cdt.AddSeconds(-120)).Select(x => x.Value).ToList();
  1248. watch.Start();
  1249. foreach (var session in clients)
  1250. {
  1251. using (var db = new MainDBContext())
  1252. {
  1253. var machine = new Machine() { Id = session.MachineId };
  1254. if (machine != null)
  1255. {
  1256. db.Configuration.AutoDetectChangesEnabled = false;
  1257. db.Configuration.ValidateOnSaveEnabled = false;
  1258. db.Machine.Attach(machine);
  1259. machine.HeartbeatUpdatedOn = DateTime.UtcNow;
  1260. machine.ConnectionType = session.UriScheme.Equals("wss") ? 2 : 1;
  1261. db.Entry(machine).Property(x => x.HeartbeatUpdatedOn).IsModified = true;
  1262. db.Entry(machine).Property(x => x.ConnectionType).IsModified = true;
  1263. await db.SaveChangesAsync();
  1264. }
  1265. }
  1266. }
  1267. watch.Stop();
  1268. if (watch.ElapsedMilliseconds / 1000 > 5)
  1269. {
  1270. logger.Fatal("Update HeartBeatCheckTrigger cost " + watch.ElapsedMilliseconds / 1000 + " seconds.");
  1271. }
  1272. }
  1273. await Task.Delay(10000);
  1274. }
  1275. catch (Exception ex)
  1276. {
  1277. Console.WriteLine("***********************************************************");
  1278. logger.Error(string.Format("HeartBeatCheckTrigger Ex:{0}", ex.ToString()));
  1279. }
  1280. }
  1281. }
  1282. async private void ServerWeatherNotificationTrigger()
  1283. {
  1284. for (; ; )
  1285. {
  1286. if (_ct.IsCancellationRequested)
  1287. {
  1288. break;
  1289. }
  1290. var min_Interval = (DateTime.UtcNow - _CheckWeatherDt).TotalMinutes;
  1291. if (min_Interval > 30)
  1292. {
  1293. // Console.WriteLine("in...............ServerWeatherNotificationTrigger");
  1294. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1295. Dictionary<string, ClientData> _copyClientDic = null;
  1296. lock (_lockClientDic)
  1297. {
  1298. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1299. }
  1300. _CheckWeatherDt = DateTime.UtcNow;
  1301. var locations = _copyClientDic.Where(x => !string.IsNullOrEmpty(x.Value.StationLocation)).Distinct().Select(x => x.Value.StationLocation).ToList();
  1302. // Console.WriteLine("in...............ServerWeatherNotificationTrigger");
  1303. foreach (var location in locations)
  1304. {
  1305. try
  1306. { //query weather
  1307. var httpResult = await httpClient.GetWeather("https://api.weatherapi.com/v1/current.json?key=874346abc0874e69a9423510222201&q=" + location, null, null);
  1308. string temp = "17";
  1309. string weather_code = "1183";
  1310. if (httpResult.Status == System.Net.HttpStatusCode.OK)
  1311. {
  1312. try
  1313. {
  1314. var jsonResult = JsonConvert.DeserializeObject(httpResult.Response) as JObject;
  1315. temp = jsonResult["current"]["temp_c"].ToString();
  1316. weather_code = jsonResult["current"]["condition"]["code"].ToString();
  1317. }
  1318. catch (Exception ex)
  1319. {
  1320. ;
  1321. }
  1322. }
  1323. #region 台泥氣象Mapping
  1324. switch (weather_code)
  1325. {
  1326. case "1000":
  1327. weather_code = "1";
  1328. break;
  1329. case "1003":
  1330. case "1006":
  1331. case "1009":
  1332. weather_code = "2";
  1333. break;
  1334. case "1063":
  1335. case "1072":
  1336. case "1150":
  1337. case "1153":
  1338. case "1168":
  1339. case "1171":
  1340. case "1180":
  1341. case "1183":
  1342. case "1186":
  1343. case "1189":
  1344. case "1192":
  1345. case "1195":
  1346. case "1198":
  1347. case "1201":
  1348. case "1237":
  1349. case "1240":
  1350. case "1243":
  1351. case "1246":
  1352. case "1261":
  1353. case "1264":
  1354. weather_code = "3";
  1355. break;
  1356. case "1087":
  1357. case "1273":
  1358. case "1276":
  1359. case "1279":
  1360. case "1282":
  1361. weather_code = "4";
  1362. break;
  1363. case "1066":
  1364. case "1069":
  1365. case "1114":
  1366. case "1117":
  1367. case "1204":
  1368. case "1207":
  1369. case "1210":
  1370. case "1213":
  1371. case "1216":
  1372. case "1219":
  1373. case "1222":
  1374. case "1225":
  1375. case "1249":
  1376. case "1252":
  1377. case "1255":
  1378. case "1258":
  1379. weather_code = "5";
  1380. break;
  1381. case "1030":
  1382. case "1135":
  1383. case "1147":
  1384. weather_code = "2";
  1385. break;
  1386. default:
  1387. weather_code = "2";
  1388. break;
  1389. }
  1390. #endregion
  1391. if (TCCStationDic.ContainsKey(location))
  1392. {
  1393. TCCStationDic[location].Temperature = (int)double.Parse(temp);
  1394. TCCStationDic[location].WeatherID = int.Parse(weather_code);
  1395. }
  1396. else
  1397. {
  1398. TCCStationDic.Add(location, new TCCWeatherDto() { WeatherID = int.Parse(weather_code), Temperature = (int)double.Parse(temp) });
  1399. }
  1400. }
  1401. catch (Exception ex)
  1402. {
  1403. logger.Error(string.Format("ServerWeatherNotificationTrigger ChargeBoxId:{0} Ex:{1}", location, ex.ToString()));
  1404. }
  1405. }
  1406. var clients = _copyClientDic.Where(x => x.Value.CustomerId == new Guid("009E603C-79CD-4620-A2B8-D9349C0E8AD8")).
  1407. Select(x => new { ChargeBoxId = x.Value.ChargeBoxId, StationLocation = x.Value.StationLocation }).ToList();
  1408. using (var db = new MainDBContext())
  1409. {
  1410. foreach (var client in clients)
  1411. {
  1412. try
  1413. {
  1414. if (string.IsNullOrEmpty(client.StationLocation))
  1415. {
  1416. Console.WriteLine(client.StationLocation + " is empty");
  1417. continue;
  1418. }
  1419. if (TCCStationDic.ContainsKey(client.StationLocation))
  1420. {
  1421. db.ServerMessage.Add(new ServerMessage()
  1422. {
  1423. ChargeBoxId = client.ChargeBoxId,
  1424. CreatedBy = "Server",
  1425. CreatedOn = DateTime.UtcNow,
  1426. OutAction = Actions.DataTransfer.ToString(),
  1427. OutRequest = JsonConvert.SerializeObject(
  1428. new DataTransferRequest()
  1429. {
  1430. messageId = "ID_Weather_Info",
  1431. vendorId = "Phihong Technology",
  1432. data = JsonConvert.SerializeObject(
  1433. new
  1434. {
  1435. weatherId = TCCStationDic[client.StationLocation].WeatherID,
  1436. Temperature = TCCStationDic[client.StationLocation].Temperature
  1437. })
  1438. },
  1439. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1440. SerialNo = Guid.NewGuid().ToString(),
  1441. InMessage = string.Empty
  1442. });
  1443. await db.SaveChangesAsync();
  1444. }
  1445. }
  1446. catch (Exception ex)
  1447. {
  1448. logger.Error(string.Format("ServerWeatherNotificationTrigger ChargeBoxId:{0} Ex:{1}", client.ChargeBoxId, ex.ToString()));
  1449. }
  1450. }
  1451. }
  1452. }
  1453. await Task.Delay(1000);
  1454. }
  1455. }
  1456. async private void ServerSetFeeTrigger()
  1457. {
  1458. for (; ; )
  1459. {
  1460. if (_ct.IsCancellationRequested)
  1461. {
  1462. break;
  1463. }
  1464. var min_Interval = (DateTime.UtcNow - _CheckFeeDt).TotalMinutes;
  1465. if (min_Interval > 1)
  1466. {
  1467. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1468. Dictionary<string, ClientData> _copyClientDic = null;
  1469. lock (_lockClientDic)
  1470. {
  1471. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1472. }
  1473. _CheckFeeDt = DateTime.UtcNow;
  1474. foreach (var item in _copyClientDic)
  1475. {
  1476. try
  1477. {
  1478. ClientData session = item.Value;
  1479. if (session.IsCheckIn)
  1480. {
  1481. string displayPriceText = await SetDefaultFee(session);
  1482. if (!string.IsNullOrEmpty(displayPriceText) && displayPriceText != session.DisplayPrice)
  1483. {
  1484. clientDic[item.Key].DisplayPrice = displayPriceText;
  1485. using (var db = new MainDBContext())
  1486. {
  1487. db.ServerMessage.Add(new ServerMessage()
  1488. {
  1489. ChargeBoxId = session.ChargeBoxId,
  1490. CreatedBy = "Server",
  1491. CreatedOn = DateTime.UtcNow,
  1492. OutAction = Actions.ChangeConfiguration.ToString(),
  1493. OutRequest = JsonConvert.SerializeObject(
  1494. new ChangeConfigurationRequest()
  1495. {
  1496. key = "DefaultPrice",
  1497. value = clientDic[item.Key].DisplayPrice
  1498. },
  1499. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1500. SerialNo = Guid.NewGuid().ToString(),
  1501. InMessage = string.Empty
  1502. }); ;
  1503. if (session.CustomerId == new Guid("10C7F5BD-C89A-4E2A-8611-B617E0B41A73"))
  1504. {
  1505. db.ServerMessage.Add(new ServerMessage()
  1506. {
  1507. ChargeBoxId = session.ChargeBoxId,
  1508. CreatedBy = "Server",
  1509. CreatedOn = DateTime.UtcNow,
  1510. OutAction = Actions.ChangeConfiguration.ToString(),
  1511. OutRequest = JsonConvert.SerializeObject(
  1512. new ChangeConfigurationRequest()
  1513. {
  1514. key = "ConnectionTimeOut",
  1515. value = "120"
  1516. },
  1517. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1518. SerialNo = Guid.NewGuid().ToString(),
  1519. InMessage = string.Empty
  1520. });
  1521. db.ServerMessage.Add(new ServerMessage()
  1522. {
  1523. ChargeBoxId = session.ChargeBoxId,
  1524. CreatedBy = "Server",
  1525. CreatedOn = DateTime.UtcNow,
  1526. OutAction = Actions.ChangeConfiguration.ToString(),
  1527. OutRequest = JsonConvert.SerializeObject(
  1528. new ChangeConfigurationRequest()
  1529. {
  1530. key = "MeterValueSampleInterval",
  1531. value = "3"
  1532. },
  1533. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1534. SerialNo = Guid.NewGuid().ToString(),
  1535. InMessage = string.Empty
  1536. });
  1537. }
  1538. await db.SaveChangesAsync();
  1539. }
  1540. }
  1541. }
  1542. }
  1543. catch (Exception ex)
  1544. {
  1545. logger.Error(string.Format("ServerSetFeeTrigger ChargeBoxId:{0} Ex:{1}", item.Key, ex.ToString()));
  1546. }
  1547. }
  1548. }
  1549. await Task.Delay(1000);
  1550. }
  1551. }
  1552. async private Task<string> SetDefaultFee(ClientData client)
  1553. {
  1554. string displayPriceText = string.Empty;
  1555. string charingPriceText = string.Empty;
  1556. if (string.IsNullOrEmpty(client.ChargeBoxId)) return displayPriceText;
  1557. using (SqlConnection conn = new SqlConnection(webConnectionString))
  1558. {
  1559. var parameters = new DynamicParameters();
  1560. parameters.Add("@MachineId", client.MachineId, DbType.String, ParameterDirection.Input);
  1561. string displayPricestrSql = "";
  1562. string strSql = "";
  1563. if (client.IsAC)
  1564. {
  1565. displayPricestrSql = " SELECT [AC_BillingMethod] as BillingMethod,[AC_FeeName] as FeeName,[AC_Fee] as ChargingFeebyHour" +
  1566. " ,[AC_ParkingFee] as ParkingFee, [Currency] FROM[StationMachine] left join[dbo].[Station]" +
  1567. " on[StationMachine].StationId = Station.[Id] where StationMachine.MachineId=@MachineId and Station.IsBilling=1; ";
  1568. strSql = " SELECT CAST( [StartTime] as varchar(5)) StartTime,CAST( [EndTime] as varchar(5)) EndTime,[Fee] FROM[StationMachine] left join [dbo].[StationFee]" +
  1569. " on[StationMachine].StationId = StationFee.StationId where StationMachine.MachineId =@MachineId and StationFee.IsAC=1; ";
  1570. }
  1571. else
  1572. {
  1573. displayPricestrSql = " SELECT [DC_BillingMethod] as BillingMethod,[DC_FeeName] as FeeName,[DC_Fee] as ChargingFeebyHour" +
  1574. " ,[DC_ParkingFee] as ParkingFee, [Currency] FROM[StationMachine] left join[dbo].[Station]" +
  1575. " on[StationMachine].StationId = Station.[Id] where StationMachine.MachineId=@MachineId and Station.IsBilling=1; ";
  1576. strSql = " SELECT CAST( [StartTime] as varchar(5)) StartTime,CAST( [EndTime] as varchar(5)) EndTime,[Fee] FROM[StationMachine] left join [dbo].[StationFee]" +
  1577. " on[StationMachine].StationId = StationFee.StationId where StationMachine.MachineId =@MachineId and StationFee.IsAC=0; ";
  1578. }
  1579. var result = await conn.QueryAsync<StationFee>(displayPricestrSql, parameters);
  1580. if (result.Count() == 0)
  1581. {
  1582. return string.Empty;
  1583. }
  1584. var stationPrice = result.First();
  1585. if (stationPrice.BillingMethod == 1)
  1586. {
  1587. var chargingPriceResult = await conn.QueryAsync<ChargingPrice>(strSql, parameters);
  1588. client.ChargingPrices = chargingPriceResult.ToList();
  1589. if (string.IsNullOrEmpty(client.ChargingPrices[0].StartTime))
  1590. {
  1591. client.ChargingPrices = new List<ChargingPrice>();
  1592. }
  1593. }
  1594. displayPriceText = stationPrice.FeeName;
  1595. client.BillingMethod = stationPrice.BillingMethod;
  1596. client.Currency = stationPrice.Currency;
  1597. client.ChargingFeebyHour = stationPrice.ChargingFeebyHour;
  1598. client.ParkingFee = stationPrice.ParkingFee;
  1599. client.IsBilling = true;
  1600. }
  1601. return displayPriceText;
  1602. }
  1603. async private void HealthCheckTrigger()
  1604. {
  1605. for (; ; )
  1606. {
  1607. if (_ct.IsCancellationRequested)
  1608. {
  1609. break;
  1610. }
  1611. try
  1612. {
  1613. Dictionary<string, ClientData> _copyClientDic = null;
  1614. lock (_lockClientDic)
  1615. {
  1616. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1617. }
  1618. var removeClients = _copyClientDic.Where(x => x.Value.LastActiveTime < DateTime.UtcNow.AddSeconds(-300)).Select(x => x.Value).ToList();
  1619. foreach (var session in removeClients)
  1620. {
  1621. Console.WriteLine(string.Format("Server forced to shut down ChargeBox ({0}: LastActiveTime{1})", session.ChargeBoxId, session.LastActiveTime));
  1622. RemoveClient(session);
  1623. }
  1624. await Task.Delay(60000);
  1625. }
  1626. catch (Exception ex)
  1627. {
  1628. logger.Error(string.Format("HealthAlarmTrigger Ex:{0}", ex.ToString()));
  1629. }
  1630. }
  1631. }
  1632. private List<NeedConfirmMessage> GetResendMessage()
  1633. {
  1634. List<NeedConfirmMessage> sendMessages = new List<NeedConfirmMessage>();
  1635. lock (_lockConfirmPacketList)
  1636. {
  1637. sendMessages = needConfirmPacketList.Where(x => x.SentTimes > 1 && x.CreatedBy == "Server").ToList();
  1638. }
  1639. return sendMessages;
  1640. }
  1641. private void AddConfirmMessage(string chargePointSerialNumber, int table_id, string requestId, string action, string msg_id, string createdBy, string sendMessage)
  1642. {
  1643. NeedConfirmMessage _needConfirmMsg = new NeedConfirmMessage();
  1644. _needConfirmMsg.Id = table_id;
  1645. _needConfirmMsg.SentAction = action;
  1646. _needConfirmMsg.SentOn = DateTime.UtcNow;
  1647. _needConfirmMsg.SentTimes = 4;
  1648. _needConfirmMsg.ChargePointSerialNumber = chargePointSerialNumber;
  1649. _needConfirmMsg.RequestId = requestId;
  1650. _needConfirmMsg.SentUniqueId = msg_id;
  1651. _needConfirmMsg.CreatedBy = createdBy;
  1652. _needConfirmMsg.SentMessage = sendMessage;
  1653. if (needConfirmActions.Contains(action))
  1654. {
  1655. lock (_lockConfirmPacketList)
  1656. {
  1657. needConfirmPacketList.Add(_needConfirmMsg);
  1658. }
  1659. }
  1660. }
  1661. private void RemoveConfirmMessage()
  1662. {
  1663. var before10Mins = DateTime.UtcNow.AddMinutes(-10);
  1664. lock (_lockConfirmPacketList)
  1665. {
  1666. var removeList = needConfirmPacketList.Where(x => x.SentTimes == 0 || x.SentOn < before10Mins).ToList();
  1667. foreach (var item in removeList)
  1668. {
  1669. needConfirmPacketList.Remove(item);
  1670. }
  1671. }
  1672. }
  1673. private bool ReConfirmMessage(MessageResult analysisResult)
  1674. {
  1675. bool confirmed = false;
  1676. if (needConfirmActions.Contains(analysisResult.Action))
  1677. {
  1678. NeedConfirmMessage foundRequest = null;
  1679. lock (_lockConfirmPacketList)
  1680. {
  1681. foundRequest = needConfirmPacketList.Where(x => x.SentUniqueId == analysisResult.UUID).FirstOrDefault();
  1682. }
  1683. if (foundRequest != null && foundRequest.Id > 0)
  1684. {
  1685. foundRequest.SentTimes = 0;
  1686. foundRequest.SentInterval = 0;
  1687. analysisResult.RequestId = foundRequest.RequestId;
  1688. using (var db = new MainDBContext())
  1689. {
  1690. var sc = db.ServerMessage.Where(x => x.Id == foundRequest.Id).FirstOrDefault();
  1691. sc.InMessage = JsonConvert.SerializeObject(analysisResult.Message, Formatting.None);
  1692. sc.ReceivedOn = DateTime.UtcNow;
  1693. db.SaveChanges();
  1694. // Console.WriteLine(string.Format("Now:{0} ServerMessage Id:{1} ", DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"), foundRequest.Id));
  1695. }
  1696. confirmed = true;
  1697. }
  1698. else if (analysisResult.Action == Actions.TriggerMessage.ToString())
  1699. {
  1700. confirmed = true;
  1701. }
  1702. else
  1703. {
  1704. logger.Error(string.Format("Received no record Action:{0} MessageId:{1} ", analysisResult.Action, analysisResult.UUID));
  1705. }
  1706. }
  1707. return confirmed;
  1708. }
  1709. private void RemoveClient(ClientData session)
  1710. {
  1711. if (session != null)
  1712. {
  1713. logger.Trace("RemoveClient[" + session.ChargeBoxId + "]");
  1714. if (session.Connected)
  1715. {
  1716. session.Close(CloseReason.ServerShutdown);
  1717. }
  1718. RemoveClientDic(session);
  1719. try
  1720. {
  1721. session.m_ReceiveData -= new ClientData.OCPPClientDataEventHandler<ClientData, String>(ReceivedMessage);
  1722. // session.Close(CloseReason.ServerShutdown);
  1723. }
  1724. catch (Exception ex)
  1725. {
  1726. //logger.Warn("Close client socket error!!");
  1727. logger.Warn(string.Format("Close client socket error!! {0} Msg:{1}", session.ChargeBoxId, ex.Message));
  1728. }
  1729. if (session != null)
  1730. {
  1731. session = null;
  1732. }
  1733. }
  1734. }
  1735. private void RemoveClientDic(ClientData session)
  1736. {
  1737. if (!string.IsNullOrEmpty(session.ChargeBoxId))
  1738. {
  1739. lock (_lockClientDic)
  1740. {
  1741. if (clientDic.ContainsKey(session.ChargeBoxId))
  1742. {
  1743. if (clientDic[session.ChargeBoxId].SessionID == session.SessionID)
  1744. {
  1745. logger.Debug(String.Format("ChargeBoxId:{0} Remove SessionId:{1} Removed SessionId:{2}", session.ChargeBoxId, session.SessionID, clientDic[session.ChargeBoxId].SessionID));
  1746. clientDic.Remove(session.ChargeBoxId);
  1747. logger.Trace("RemoveClient ContainsKey " + session.ChargeBoxId);
  1748. }
  1749. }
  1750. }
  1751. }
  1752. }
  1753. private void WarmUpLog()
  1754. {
  1755. using (var log = new ConnectionLogDBContext())
  1756. {
  1757. log.MachineConnectionLog.ToList();
  1758. }
  1759. }
  1760. private void WriteMachineLog(ClientData clientData, string data, string messageType, string errorMsg = "", bool isSent = false)
  1761. {
  1762. try
  1763. {
  1764. if (clientData == null || string.IsNullOrEmpty(data)) return;
  1765. if (clientData.ChargeBoxId == null)
  1766. {
  1767. logger.Fatal(clientData.Path + "]********************session ChargeBoxId null sessionId=" + clientData.SessionID);
  1768. }
  1769. using (var db = new ConnectionLogDBContext())
  1770. {
  1771. string sp = "[dbo].[uspInsertMachineConnectionLog] @CreatedOn," +
  1772. "@ChargeBoxId,@MessageType,@Data,@Msg,@IsSent,@EVSEEndPoint,@Session";
  1773. var dd = DateTime.UtcNow;
  1774. SqlParameter[] parameter =
  1775. {
  1776. new SqlParameter("CreatedOn",dd),
  1777. new SqlParameter("ChargeBoxId",clientData.ChargeBoxId==null?"unknown":clientData.ChargeBoxId.Replace("'","''")),
  1778. new SqlParameter("MessageType",messageType.Replace("'","''")),
  1779. new SqlParameter("Data",data.Replace("'","''")),
  1780. new SqlParameter("Msg",errorMsg.Replace("'","''")),
  1781. new SqlParameter("IsSent",isSent),
  1782. new SqlParameter("EVSEEndPoint",clientData.RemoteEndPoint==null?"123":clientData.RemoteEndPoint.ToString()),
  1783. new SqlParameter("Session",clientData.SessionID==null?"123":clientData.SessionID)
  1784. };
  1785. db.Database.ExecuteSqlCommand(sp, parameter);
  1786. }
  1787. }
  1788. catch (Exception ex)
  1789. {
  1790. Console.WriteLine(ex.ToString());
  1791. }
  1792. }
  1793. }
  1794. }