ProtalServer.cs 107 KB

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