ProtalServer.cs 104 KB

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