ProtalServer.cs 107 KB

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