ProtalServer.cs 106 KB

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