ProtalServer.cs 100 KB

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