ProtalServer.cs 108 KB

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