ProtalServer.cs 103 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095
  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. Console.WriteLine("++++++++++++++++");
  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("009E603C-79CD-4620-A2B8-D9349C0E8AD8"))
  612. {
  613. var stationInfo = await GetStationInfo(session.MachineId);
  614. if (stationInfo != null)
  615. {
  616. session.StationLocation = string.Format("{0},{1}", stationInfo.Lat, stationInfo.Long);
  617. session.StationName = stationInfo.ZipCode;
  618. }
  619. using (var db = new MainDBContext())
  620. {
  621. db.ServerMessage.Add(new ServerMessage()
  622. {
  623. ChargeBoxId = session.ChargeBoxId,
  624. CreatedBy = "Server",
  625. CreatedOn = DateTime.UtcNow,
  626. OutAction = Actions.DataTransfer.ToString(),
  627. OutRequest = JsonConvert.SerializeObject(
  628. new DataTransferRequest()
  629. {
  630. messageId = "ID_Station_Location",
  631. vendorId = "Phihong Technology",
  632. data = JsonConvert.SerializeObject(new { stationName = session.StationName })
  633. },
  634. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  635. SerialNo = Guid.NewGuid().ToString(),
  636. InMessage = string.Empty
  637. });
  638. db.ServerMessage.Add(new ServerMessage()
  639. {
  640. ChargeBoxId = session.ChargeBoxId,
  641. CreatedBy = "Server",
  642. CreatedOn = DateTime.UtcNow,
  643. OutAction = Actions.ChangeConfiguration.ToString(),
  644. OutRequest = JsonConvert.SerializeObject(
  645. new ChangeConfigurationRequest()
  646. {
  647. key = "TimeOffset",
  648. value = "+08:00"
  649. },
  650. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  651. SerialNo = Guid.NewGuid().ToString(),
  652. InMessage = string.Empty
  653. });
  654. if (!TCCStationDic.ContainsKey(session.StationLocation))
  655. {
  656. _CheckWeatherDt = DateTime.UtcNow.AddDays(-1);
  657. }
  658. else
  659. {
  660. db.ServerMessage.Add(new ServerMessage()
  661. {
  662. ChargeBoxId = session.ChargeBoxId,
  663. CreatedBy = "Server",
  664. CreatedOn = DateTime.UtcNow,
  665. OutAction = Actions.DataTransfer.ToString(),
  666. OutRequest = JsonConvert.SerializeObject(
  667. new DataTransferRequest()
  668. {
  669. messageId = "ID_Weather_Info",
  670. vendorId = "Phihong Technology",
  671. data = JsonConvert.SerializeObject(
  672. new
  673. {
  674. weatherId = TCCStationDic[session.StationLocation].WeatherID,
  675. Temperature = TCCStationDic[session.StationLocation].Temperature
  676. })
  677. },
  678. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  679. SerialNo = Guid.NewGuid().ToString(),
  680. InMessage = string.Empty
  681. });
  682. }
  683. db.SaveChanges();
  684. }
  685. }
  686. }
  687. else
  688. {
  689. using (var db = new MainDBContext())
  690. {
  691. var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault();
  692. if (machine != null)
  693. {
  694. if (machine.ConnectorType.Contains("6") || machine.ConnectorType.Contains("7") || machine.ConnectorType.Contains("8") || machine.ConnectorType.Contains("9"))
  695. {
  696. session.IsAC = false;
  697. }
  698. machine.ConnectionType = session.Origin.Contains("https") ? 2 : 1;
  699. db.SaveChanges();
  700. }
  701. }
  702. await SetDefaultFee(session);
  703. }
  704. }
  705. #region 台泥
  706. if (action == Actions.StartTransaction && session.CustomerId == new Guid("009E603C-79CD-4620-A2B8-D9349C0E8AD8") && replyResult.Message is StartTransactionConfirmation)
  707. {
  708. StartTransactionConfirmation confirm = (StartTransactionConfirmation)replyResult.Message;
  709. StartTransactionRequest request = (StartTransactionRequest)analysisResult.Message;
  710. using (var db = new MainDBContext())
  711. {
  712. db.ServerMessage.Add(new ServerMessage()
  713. {
  714. ChargeBoxId = session.ChargeBoxId,
  715. CreatedBy = "Server",
  716. CreatedOn = DateTime.UtcNow,
  717. OutAction = Actions.DataTransfer.ToString(),
  718. OutRequest = JsonConvert.SerializeObject(
  719. new DataTransferRequest()
  720. {
  721. messageId = "ID_GetTxUserInfo",
  722. vendorId = "Phihong Technology",
  723. data = JsonConvert.SerializeObject(new { txId = confirm.transactionId, ConnectorId = request.connectorId })
  724. },
  725. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  726. SerialNo = Guid.NewGuid().ToString(),
  727. InMessage = string.Empty
  728. });
  729. db.SaveChanges();
  730. }
  731. }
  732. #endregion
  733. if (action == Actions.Authorize && replyResult.Message is AuthorizeConfirmation)
  734. {
  735. var authorizeRequest = (IRequest)analysisResult.Message as AuthorizeRequest;
  736. if (session.UserDisplayPrices.ContainsKey(authorizeRequest.idTag))
  737. {
  738. using (var db = new MainDBContext())
  739. {
  740. db.ServerMessage.Add(new ServerMessage()
  741. {
  742. ChargeBoxId = session.ChargeBoxId,
  743. CreatedBy = "Server",
  744. CreatedOn = DateTime.UtcNow,
  745. OutAction = Actions.DataTransfer.ToString(),
  746. OutRequest = JsonConvert.SerializeObject(
  747. new DataTransferRequest()
  748. {
  749. messageId = "SetUserPrice",
  750. vendorId = "Phihong Technology",
  751. data = JsonConvert.SerializeObject(
  752. new
  753. {
  754. idToken = authorizeRequest.idTag,
  755. price = session.UserDisplayPrices[authorizeRequest.idTag]
  756. })
  757. },
  758. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  759. SerialNo = Guid.NewGuid().ToString(),
  760. InMessage = string.Empty
  761. });
  762. db.SaveChanges();
  763. }
  764. }
  765. }
  766. }
  767. else
  768. {
  769. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  770. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  771. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  772. }
  773. if (action == Actions.StartTransaction)
  774. {
  775. var stationId = _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  776. var _powerDic = _loadingBalanceService.GetSettingPower(stationId, session.MachineId);
  777. if (_powerDic != null)
  778. {
  779. foreach (var kv in _powerDic)
  780. {
  781. try
  782. {
  783. string chargeBoxId = string.Empty;
  784. //set profile
  785. lock (_lockClientDic)
  786. {
  787. chargeBoxId = clientDic.Where(x => x.Value.MachineId == kv.Key).Select(x => x.Value.ChargeBoxId).FirstOrDefault();
  788. }
  789. if (chargeBoxId != null && kv.Value.HasValue)
  790. {
  791. profileHandler.SetChargingProfile(chargeBoxId, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  792. }
  793. }
  794. catch (Exception ex)
  795. {
  796. logger.Error(string.Format("Set Profile Exception: {0}", ex.ToString()));
  797. }
  798. }
  799. }
  800. }
  801. if (action == Actions.StopTransaction)
  802. {
  803. var stationId = _loadingBalanceService.GetStationIdByMachineId(session.MachineId);
  804. if (_loadingBalanceService.IsNeedtoCancelSetting(stationId, session.MachineId, session.ChargeBoxId))
  805. {
  806. //Clear current profile
  807. profileHandler.ClearChargingProfile(session.ChargeBoxId);
  808. var _powerDic = _loadingBalanceService.GetRerangeSettingPower(stationId);
  809. if (_powerDic != null)
  810. {
  811. foreach (var kv in _powerDic)
  812. {
  813. try
  814. {
  815. string chargeBoxId = string.Empty;
  816. //set profile
  817. lock (_lockClientDic)
  818. {
  819. chargeBoxId = clientDic.Where(x => x.Value.MachineId == kv.Key).Select(x => x.Value.ChargeBoxId).FirstOrDefault();
  820. }
  821. if (chargeBoxId != null && kv.Value.HasValue)
  822. {
  823. profileHandler.SetChargingProfile(chargeBoxId, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
  824. }
  825. }
  826. catch (Exception ex)
  827. {
  828. logger.Error(string.Format("Set Profile Exception: {0}", ex.ToString()));
  829. }
  830. }
  831. }
  832. }
  833. }
  834. }
  835. break;
  836. case "FirmwareManagement":
  837. {
  838. var replyResult = profileHandler.ExecuteFirmwareManagementRequest(action, session, (IRequest)analysisResult.Message);
  839. if (replyResult.Success)
  840. {
  841. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  842. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  843. }
  844. else
  845. {
  846. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  847. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  848. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  849. }
  850. }
  851. break;
  852. case "Security":
  853. {
  854. var replyResult = profileHandler.ExecuteSecurityRequest(action, session, (IRequest)analysisResult.Message);
  855. if (replyResult.Success)
  856. {
  857. string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
  858. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Confirmation", replyResult.Exception == null ? string.Empty : replyResult.Exception.ToString()));
  859. }
  860. else
  861. {
  862. string response = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  863. string errorMsg = replyResult.Exception != null ? replyResult.Exception.ToString() : string.Empty;
  864. Send(session, response, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  865. }
  866. }
  867. break;
  868. default:
  869. {
  870. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  871. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  872. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  873. }
  874. break;
  875. }
  876. }
  877. }
  878. async private void ProcessConfirmationMessage(MessageResult analysisResult, ClientData session, Actions action)
  879. {
  880. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  881. if (ReConfirmMessage(analysisResult))
  882. {
  883. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  884. MessageResult confirmResult = null;
  885. switch (profileName)
  886. {
  887. case "Core":
  888. {
  889. confirmResult = await profileHandler.ExecuteCoreConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  890. }
  891. break;
  892. case "FirmwareManagement":
  893. {
  894. confirmResult = profileHandler.ExecuteFirmwareManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  895. }
  896. break;
  897. case "RemoteTrigger":
  898. {
  899. confirmResult = profileHandler.ExecuteRemoteTriggerConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  900. }
  901. break;
  902. case "Reservation":
  903. {
  904. confirmResult = profileHandler.ExecuteReservationConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  905. }
  906. break;
  907. case "LocalAuthListManagement":
  908. {
  909. confirmResult = profileHandler.ExecuteLocalAuthListManagementConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  910. }
  911. break;
  912. case "SmartCharging":
  913. {
  914. confirmResult = profileHandler.ExecuteSmartChargingConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  915. }
  916. break;
  917. case "Security":
  918. {
  919. confirmResult = profileHandler.ExecuteSecurityConfirm(action, session, (IConfirmation)analysisResult.Message, analysisResult.RequestId);
  920. }
  921. break;
  922. default:
  923. {
  924. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  925. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  926. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  927. }
  928. break;
  929. }
  930. if (confirmResult == null || !confirmResult.Success)
  931. {
  932. logger.Error(string.Format("Action:{0} MessageId:{1} ExecuteConfirm Error:{2} ",
  933. analysisResult.Action, analysisResult.UUID, confirmResult.Exception.ToString()));
  934. }
  935. }
  936. else
  937. {
  938. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  939. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  940. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  941. }
  942. }
  943. private void ProcessErrorMessage(MessageResult analysisResult, ClientData session, Actions action)
  944. {
  945. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  946. if (ReConfirmMessage(analysisResult))
  947. {
  948. var profileName = profiles.Where(x => x.IsExisted(analysisResult.Action)).Select(x => x.Name).FirstOrDefault();
  949. switch (profileName)
  950. {
  951. case "Core":
  952. {
  953. profileHandler.ReceivedCoreError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  954. }
  955. break;
  956. case "FirmwareManagement":
  957. {
  958. profileHandler.ReceivedFirmwareManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  959. }
  960. break;
  961. case "RemoteTrigger":
  962. {
  963. profileHandler.ReceivedRemoteTriggerError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  964. }
  965. break;
  966. case "Reservation":
  967. {
  968. profileHandler.ExecuteReservationError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  969. }
  970. break;
  971. case "LocalAuthListManagement":
  972. {
  973. profileHandler.ReceivedLocalAuthListManagementError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  974. }
  975. break;
  976. case "SmartCharging":
  977. {
  978. profileHandler.ReceivedSmartChargingError(action, analysisResult.ReceivedErrorCode, session, analysisResult.RequestId);
  979. }
  980. break;
  981. default:
  982. {
  983. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  984. string errorMsg = string.Format("Couldn't find action name: {0} of profile", action);
  985. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  986. }
  987. break;
  988. }
  989. }
  990. else
  991. {
  992. string replyMsg = BasicMessageHandler.GenerateCallError(analysisResult.UUID, OCPPErrorCodes.InternalError, OCPPErrorDescription.InternalError);
  993. string errorMsg = string.Format("Action:{0} MessageId:{1} didn't exist in confirm message", analysisResult.Action, analysisResult.UUID);
  994. Send(session, replyMsg, string.Format("{0} {1}", analysisResult.Action, "Error"), errorMsg);
  995. }
  996. }
  997. private void Send(ClientData session, string msg, string messageType, string errorMsg = "")
  998. {
  999. try
  1000. {
  1001. if (session != null)
  1002. {
  1003. WriteMachineLog(session, msg, messageType, errorMsg, true);
  1004. session.Send(msg);
  1005. }
  1006. }
  1007. catch (Exception ex)
  1008. {
  1009. logger.Error(string.Format("Send Ex:{0}", ex.ToString()));
  1010. }
  1011. }
  1012. async private void ServerUpdateTrigger()
  1013. {
  1014. for (; ; )
  1015. {
  1016. if (_ct.IsCancellationRequested)
  1017. {
  1018. break;
  1019. }
  1020. var min_Interval = (DateTime.UtcNow - checkUpdateDt).TotalMinutes;
  1021. if (min_Interval > 3)
  1022. {
  1023. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1024. Dictionary<string, ClientData> _copyClientDic = null;
  1025. lock (_lockClientDic)
  1026. {
  1027. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1028. }
  1029. checkUpdateDt = DateTime.UtcNow;
  1030. using (var db = new MainDBContext())
  1031. {
  1032. //var needUpdateChargers = db.Machine.Where(x => x.FW_AssignedMachineVersionId.HasValue == true &&
  1033. // x.FW_AssignedMachineVersionId != x.FW_VersionReport && x.Online == true)
  1034. // .Select(x => new { x.Id, x.ChargeBoxId, x.FW_AssignedMachineVersionId }).ToList();
  1035. var needUpdateChargers = db.Machine.Where(x => x.FW_AssignedVersion.HasValue == true &&
  1036. x.FW_AssignedVersion != x.FW_VersionReport && x.Online == true)
  1037. .Select(x => x.ChargeBoxId).AsNoTracking().ToList();
  1038. foreach (var chargeBoxId in needUpdateChargers)
  1039. {
  1040. try
  1041. {
  1042. ClientData session;
  1043. if (_copyClientDic.TryGetValue(chargeBoxId, out session))
  1044. {
  1045. string requestId = Guid.NewGuid().ToString();
  1046. // using (var db = new MainDBContext())
  1047. if (session.IsCheckIn && !session.ISOCPP20)
  1048. {
  1049. var _request = new TriggerMessageRequest()
  1050. {
  1051. requestedMessage = Packet.Messages.SubTypes.MessageTrigger.FirmwareStatusNotification
  1052. };
  1053. var uuid = session.queue.store(_request);
  1054. string rawRequest = BasicMessageHandler.GenerateRequest(uuid, _request.Action, _request);
  1055. Send(session, rawRequest, string.Format("{0} {1}", _request.Action, "Request"), "");
  1056. #region OCTT ,測試韌體更新方式
  1057. //--------------------> OCTT ,測試韌體更新方式
  1058. //{
  1059. // var machine = db.Machine.Where(x => x.FW_AssignedMachineVersionId.HasValue == true &&
  1060. // x.FW_AssignedMachineVersionId != x.FW_VersionReport && x.ChargeBoxId == session.ChargeBoxId)
  1061. // .Select(x => new { x.Id, x.FW_AssignedMachineVersionId }).FirstOrDefault();
  1062. // if (machine != null)
  1063. // {
  1064. // var mv = db.MachineVersion.Include(c => c.PublishVersion)
  1065. // .Include(c => c.PublishVersion.PublishVersionFiles)
  1066. // .Include(c => c.PublishVersion.PublishVersionFiles.Select(z => z.UploadFile))
  1067. // .Where(c => c.Id == machine.FW_AssignedMachineVersionId.Value).First();
  1068. // string downloadUrl = mv.PublishVersion.PublishVersionFiles.FirstOrDefault().UploadFile.FileUrl;
  1069. // var _updateFWrequest = new UpdateFirmwareRequest()
  1070. // {
  1071. // location = new Uri(downloadUrl),
  1072. // retries = 3,
  1073. // retrieveDate = DateTime.UtcNow,
  1074. // retryInterval = 10
  1075. // };
  1076. // db.MachineOperateRecord.Add(new MachineOperateRecord()
  1077. // {
  1078. // CreatedOn = DateTime.UtcNow,
  1079. // ChargeBoxId = session.ChargeBoxId,
  1080. // SerialNo = requestId,
  1081. // RequestContent = JsonConvert.SerializeObject(_updateFWrequest, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1082. // EVSE_Status = 0,
  1083. // EVSE_Value = "Fw Version:" + machine.FW_AssignedMachineVersionId,
  1084. // Status = 0,
  1085. // RequestType = 0,
  1086. // });
  1087. // db.ServerMessage.Add(new ServerMessage()
  1088. // {
  1089. // ChargeBoxId = session.ChargeBoxId,
  1090. // CreatedBy = "Server",
  1091. // CreatedOn = DateTime.UtcNow,
  1092. // OutAction = _updateFWrequest.Action.ToString(),
  1093. // OutRequest = JsonConvert.SerializeObject(_updateFWrequest, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1094. // SerialNo = requestId,
  1095. // InMessage = string.Empty
  1096. // });
  1097. // db.SaveChanges();
  1098. // }
  1099. //}
  1100. #endregion
  1101. }
  1102. }
  1103. }
  1104. catch (Exception ex)
  1105. {
  1106. logger.Error(string.Format("serverUpdateTrigger ChargeBoxId:{0} Ex:{1}", chargeBoxId, ex.ToString()));
  1107. }
  1108. }
  1109. }
  1110. await Task.Delay(1000);
  1111. // Thread.CurrentThread.Join(1000);
  1112. }
  1113. }
  1114. }
  1115. string webConnectionString = ConfigurationManager.ConnectionStrings["WebDBContext"].ConnectionString;
  1116. async private void ServerMessageTrigger()
  1117. {
  1118. for (; ; )
  1119. {
  1120. if (_ct.IsCancellationRequested)
  1121. {
  1122. break;
  1123. }
  1124. try
  1125. {
  1126. RemoveConfirmMessage();
  1127. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1128. using (var db = new MainDBContext())
  1129. {
  1130. DateTime startDt = DateTime.UtcNow.AddSeconds(-30);
  1131. DateTime dt = new DateTime(1991, 1, 1);
  1132. DateTime currentTime = DateTime.UtcNow;
  1133. var commandList = db.ServerMessage.Where(c => c.ReceivedOn == dt && c.UpdatedOn == dt && c.CreatedOn >= startDt && c.CreatedOn <= currentTime).AsNoTracking().ToList();
  1134. //處理主機傳送的有指令
  1135. var cmdMachineList = commandList.Select(c => c.ChargeBoxId).Distinct().ToList();
  1136. if (commandList.Count > 0)
  1137. {
  1138. // Console.WriteLine(string.Format("Now:{0} commandList Count:{1} ", DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"), commandList.Count));
  1139. }
  1140. foreach (var charger_SN in cmdMachineList)
  1141. {
  1142. ClientData session;
  1143. string uuid = string.Empty;
  1144. if (clientDic.TryGetValue(charger_SN, out session))
  1145. {
  1146. //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")));
  1147. if (session.IsCheckIn && !session.ISOCPP20)
  1148. {
  1149. var cmdList = commandList.Where(c => c.ChargeBoxId == charger_SN).ToList();
  1150. foreach (var item in cmdList)
  1151. {
  1152. IRequest request = null;
  1153. Actions action = Actions.None;
  1154. Enum.TryParse(item.OutAction, out action);
  1155. Type _RequestType = null;
  1156. for (int i = 0; i < profiles.Count; i++)
  1157. {
  1158. var feature = profiles[i].GetFeaturebyAction(item.OutAction);
  1159. if (feature != null)
  1160. {
  1161. _RequestType = feature.GetRequestType();
  1162. break;
  1163. }
  1164. }
  1165. if (_RequestType != null && item.CreatedBy != "Destroyer")
  1166. {
  1167. request = JsonConvert.DeserializeObject(item.OutRequest, _RequestType) as IRequest;
  1168. uuid = session.queue.store(request);
  1169. string rawRequest = BasicMessageHandler.GenerateRequest(uuid, item.OutAction, request);
  1170. Send(session, rawRequest, string.Format("{0} {1}", action, "Request"), "");
  1171. }
  1172. if (item.CreatedBy == "Destroyer")
  1173. {
  1174. if (_RequestType != null)
  1175. {
  1176. request = Activator.CreateInstance(_RequestType) as IRequest;
  1177. uuid = session.queue.store(request);
  1178. string rawRequest = BasicMessageHandler.GenerateDestroyRequest(uuid, item.OutAction, item.OutRequest);
  1179. Send(session, rawRequest, string.Format("{0} {1}", action, "Request"), "");
  1180. }
  1181. else
  1182. {
  1183. string rawRequest = BasicMessageHandler.GenerateDestroyRequest(Guid.NewGuid().ToString(), item.OutAction, item.OutRequest);
  1184. Send(session, rawRequest, string.Format("{0} {1}", action, "Request"), "");
  1185. }
  1186. }
  1187. AddConfirmMessage(charger_SN, item.Id, item.SerialNo, item.OutAction, uuid);
  1188. #region 更新資料表單一欄位
  1189. var _UpdatedItem = new ServerMessage() { Id = item.Id, UpdatedOn = DateTime.UtcNow };
  1190. db.Configuration.AutoDetectChangesEnabled = false;//自動呼叫DetectChanges()比對所有的entry集合的每一個屬性Properties的新舊值
  1191. db.Configuration.ValidateOnSaveEnabled = false;// 因為Entity有些欄位必填,若不避開會有Validate錯誤
  1192. // var _UpdatedItem = db.ServerMessage.Where(x => x.Id == item.Id).FirstOrDefault();
  1193. db.ServerMessage.Attach(_UpdatedItem);
  1194. _UpdatedItem.UpdatedOn = DateTime.UtcNow;
  1195. db.Entry(_UpdatedItem).Property(x => x.UpdatedOn).IsModified = true;// 可以直接使用這方式強制某欄位要更新,只是查詢集合耗效能而己
  1196. db.SaveChanges();
  1197. await Task.Delay(100);
  1198. #endregion
  1199. }
  1200. }
  1201. }
  1202. }
  1203. }
  1204. await Task.Delay(500);
  1205. }
  1206. catch (Exception ex)
  1207. {
  1208. logger.Error(string.Format("ServerMessageTrigger Ex:{0}", ex.ToString()));
  1209. }
  1210. }
  1211. }
  1212. async private void HeartBeatCheckTrigger()
  1213. {
  1214. for (; ; )
  1215. {
  1216. if (_ct.IsCancellationRequested)
  1217. {
  1218. break;
  1219. }
  1220. try
  1221. {
  1222. if (DateTime.UtcNow.Subtract(lastcheckdt).TotalSeconds > 30)
  1223. {
  1224. lastcheckdt = DateTime.UtcNow;
  1225. Stopwatch watch = new Stopwatch();
  1226. Dictionary<string, ClientData> _copyClientDic = null;
  1227. lock (_lockClientDic)
  1228. {
  1229. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1230. }
  1231. var cdt = DateTime.UtcNow;
  1232. var clients = _copyClientDic.Where(x => x.Value.LastActiveTime > cdt.AddSeconds(-120)).Select(x => x.Value).ToList();
  1233. watch.Start();
  1234. foreach (var session in clients)
  1235. {
  1236. using (var db = new MainDBContext())
  1237. {
  1238. var machine = new Machine() { Id = session.MachineId };
  1239. if (machine != null)
  1240. {
  1241. db.Configuration.AutoDetectChangesEnabled = false;
  1242. db.Configuration.ValidateOnSaveEnabled = false;
  1243. db.Machine.Attach(machine);
  1244. machine.HeartbeatUpdatedOn = DateTime.UtcNow;
  1245. machine.ConnectionType = session.UriScheme.Equals("wss") ? 2 : 1;
  1246. db.Entry(machine).Property(x => x.HeartbeatUpdatedOn).IsModified = true;
  1247. db.Entry(machine).Property(x => x.ConnectionType).IsModified = true;
  1248. await db.SaveChangesAsync();
  1249. }
  1250. }
  1251. }
  1252. watch.Stop();
  1253. if (watch.ElapsedMilliseconds / 1000 > 5)
  1254. {
  1255. logger.Fatal("Update HeartBeatCheckTrigger cost " + watch.ElapsedMilliseconds / 1000 + " seconds.");
  1256. }
  1257. }
  1258. await Task.Delay(10000);
  1259. }
  1260. catch (Exception ex)
  1261. {
  1262. Console.WriteLine("***********************************************************");
  1263. logger.Error(string.Format("HeartBeatCheckTrigger Ex:{0}", ex.ToString()));
  1264. }
  1265. }
  1266. }
  1267. async private void ServerWeatherNotificationTrigger()
  1268. {
  1269. for (; ; )
  1270. {
  1271. if (_ct.IsCancellationRequested)
  1272. {
  1273. break;
  1274. }
  1275. var min_Interval = (DateTime.UtcNow - _CheckWeatherDt).TotalMinutes;
  1276. if (min_Interval > 30)
  1277. {
  1278. // Console.WriteLine("in...............ServerWeatherNotificationTrigger");
  1279. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1280. Dictionary<string, ClientData> _copyClientDic = null;
  1281. lock (_lockClientDic)
  1282. {
  1283. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1284. }
  1285. _CheckWeatherDt = DateTime.UtcNow;
  1286. var locations = _copyClientDic.Where(x => !string.IsNullOrEmpty(x.Value.StationLocation)).Distinct().Select(x => x.Value.StationLocation).ToList();
  1287. // Console.WriteLine("in...............ServerWeatherNotificationTrigger");
  1288. foreach (var location in locations)
  1289. {
  1290. try
  1291. { //query weather
  1292. var httpResult = await httpClient.GetWeather("https://api.weatherapi.com/v1/current.json?key=874346abc0874e69a9423510222201&q=" + location, null, null);
  1293. string temp = "17";
  1294. string weather_code = "1183";
  1295. if (httpResult.Status == System.Net.HttpStatusCode.OK)
  1296. {
  1297. try
  1298. {
  1299. var jsonResult = JsonConvert.DeserializeObject(httpResult.Response) as JObject;
  1300. temp = jsonResult["current"]["temp_c"].ToString();
  1301. weather_code = jsonResult["current"]["condition"]["code"].ToString();
  1302. }
  1303. catch (Exception ex)
  1304. {
  1305. ;
  1306. }
  1307. }
  1308. #region 台泥氣象Mapping
  1309. switch (weather_code)
  1310. {
  1311. case "1000":
  1312. weather_code = "1";
  1313. break;
  1314. case "1003":
  1315. case "1006":
  1316. case "1009":
  1317. weather_code = "2";
  1318. break;
  1319. case "1063":
  1320. case "1072":
  1321. case "1150":
  1322. case "1153":
  1323. case "1168":
  1324. case "1171":
  1325. case "1180":
  1326. case "1183":
  1327. case "1186":
  1328. case "1189":
  1329. case "1192":
  1330. case "1195":
  1331. case "1198":
  1332. case "1201":
  1333. case "1237":
  1334. case "1240":
  1335. case "1243":
  1336. case "1246":
  1337. case "1261":
  1338. case "1264":
  1339. weather_code = "3";
  1340. break;
  1341. case "1087":
  1342. case "1273":
  1343. case "1276":
  1344. case "1279":
  1345. case "1282":
  1346. weather_code = "4";
  1347. break;
  1348. case "1066":
  1349. case "1069":
  1350. case "1114":
  1351. case "1117":
  1352. case "1204":
  1353. case "1207":
  1354. case "1210":
  1355. case "1213":
  1356. case "1216":
  1357. case "1219":
  1358. case "1222":
  1359. case "1225":
  1360. case "1249":
  1361. case "1252":
  1362. case "1255":
  1363. case "1258":
  1364. weather_code = "5";
  1365. break;
  1366. case "1030":
  1367. case "1135":
  1368. case "1147":
  1369. weather_code = "2";
  1370. break;
  1371. default:
  1372. weather_code = "2";
  1373. break;
  1374. }
  1375. #endregion
  1376. if (TCCStationDic.ContainsKey(location))
  1377. {
  1378. TCCStationDic[location].Temperature = (int)double.Parse(temp);
  1379. TCCStationDic[location].WeatherID = int.Parse(weather_code);
  1380. }
  1381. else
  1382. {
  1383. TCCStationDic.Add(location, new TCCWeatherDto() { WeatherID = int.Parse(weather_code), Temperature = (int)double.Parse(temp) });
  1384. }
  1385. }
  1386. catch (Exception ex)
  1387. {
  1388. logger.Error(string.Format("ServerWeatherNotificationTrigger ChargeBoxId:{0} Ex:{1}", location, ex.ToString()));
  1389. }
  1390. }
  1391. var clients = _copyClientDic.Where(x => x.Value.CustomerId == new Guid("009E603C-79CD-4620-A2B8-D9349C0E8AD8")).
  1392. Select(x => new { ChargeBoxId = x.Value.ChargeBoxId, StationLocation = x.Value.StationLocation }).ToList();
  1393. using (var db = new MainDBContext())
  1394. {
  1395. foreach (var client in clients)
  1396. {
  1397. try
  1398. {
  1399. if (string.IsNullOrEmpty(client.StationLocation))
  1400. {
  1401. Console.WriteLine(client.StationLocation + " is empty");
  1402. continue;
  1403. }
  1404. if (TCCStationDic.ContainsKey(client.StationLocation))
  1405. {
  1406. db.ServerMessage.Add(new ServerMessage()
  1407. {
  1408. ChargeBoxId = client.ChargeBoxId,
  1409. CreatedBy = "Server",
  1410. CreatedOn = DateTime.UtcNow,
  1411. OutAction = Actions.DataTransfer.ToString(),
  1412. OutRequest = JsonConvert.SerializeObject(
  1413. new DataTransferRequest()
  1414. {
  1415. messageId = "ID_Weather_Info",
  1416. vendorId = "Phihong Technology",
  1417. data = JsonConvert.SerializeObject(
  1418. new
  1419. {
  1420. weatherId = TCCStationDic[client.StationLocation].WeatherID,
  1421. Temperature = TCCStationDic[client.StationLocation].Temperature
  1422. })
  1423. },
  1424. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1425. SerialNo = Guid.NewGuid().ToString(),
  1426. InMessage = string.Empty
  1427. });
  1428. await db.SaveChangesAsync();
  1429. }
  1430. }
  1431. catch (Exception ex)
  1432. {
  1433. logger.Error(string.Format("ServerWeatherNotificationTrigger ChargeBoxId:{0} Ex:{1}", client.ChargeBoxId, ex.ToString()));
  1434. }
  1435. }
  1436. }
  1437. }
  1438. await Task.Delay(1000);
  1439. }
  1440. }
  1441. async private void ServerSetFeeTrigger()
  1442. {
  1443. for (; ; )
  1444. {
  1445. if (_ct.IsCancellationRequested)
  1446. {
  1447. break;
  1448. }
  1449. var min_Interval = (DateTime.UtcNow - _CheckFeeDt).TotalMinutes;
  1450. if (min_Interval > 1)
  1451. {
  1452. BasicMessageHandler msgAnalyser = new BasicMessageHandler();
  1453. Dictionary<string, ClientData> _copyClientDic = null;
  1454. lock (_lockClientDic)
  1455. {
  1456. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1457. }
  1458. _CheckFeeDt = DateTime.UtcNow;
  1459. foreach (var item in _copyClientDic)
  1460. {
  1461. try
  1462. {
  1463. ClientData session = item.Value;
  1464. if (session.IsCheckIn)
  1465. {
  1466. string displayPriceText = await SetDefaultFee(session);
  1467. if (!string.IsNullOrEmpty(displayPriceText) && displayPriceText != session.DisplayPrice)
  1468. {
  1469. clientDic[item.Key].DisplayPrice = displayPriceText;
  1470. using (var db = new MainDBContext())
  1471. {
  1472. db.ServerMessage.Add(new ServerMessage()
  1473. {
  1474. ChargeBoxId = session.ChargeBoxId,
  1475. CreatedBy = "Server",
  1476. CreatedOn = DateTime.UtcNow,
  1477. OutAction = Actions.ChangeConfiguration.ToString(),
  1478. OutRequest = JsonConvert.SerializeObject(
  1479. new ChangeConfigurationRequest()
  1480. {
  1481. key = "DefaultPrice",
  1482. value = clientDic[item.Key].DisplayPrice
  1483. },
  1484. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1485. SerialNo = Guid.NewGuid().ToString(),
  1486. InMessage = string.Empty
  1487. }); ;
  1488. if (session.CustomerId == new Guid("10C7F5BD-C89A-4E2A-8611-B617E0B41A73"))
  1489. {
  1490. db.ServerMessage.Add(new ServerMessage()
  1491. {
  1492. ChargeBoxId = session.ChargeBoxId,
  1493. CreatedBy = "Server",
  1494. CreatedOn = DateTime.UtcNow,
  1495. OutAction = Actions.ChangeConfiguration.ToString(),
  1496. OutRequest = JsonConvert.SerializeObject(
  1497. new ChangeConfigurationRequest()
  1498. {
  1499. key = "ConnectionTimeOut",
  1500. value = "120"
  1501. },
  1502. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1503. SerialNo = Guid.NewGuid().ToString(),
  1504. InMessage = string.Empty
  1505. });
  1506. db.ServerMessage.Add(new ServerMessage()
  1507. {
  1508. ChargeBoxId = session.ChargeBoxId,
  1509. CreatedBy = "Server",
  1510. CreatedOn = DateTime.UtcNow,
  1511. OutAction = Actions.ChangeConfiguration.ToString(),
  1512. OutRequest = JsonConvert.SerializeObject(
  1513. new ChangeConfigurationRequest()
  1514. {
  1515. key = "MeterValueSampleInterval",
  1516. value = "3"
  1517. },
  1518. new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
  1519. SerialNo = Guid.NewGuid().ToString(),
  1520. InMessage = string.Empty
  1521. });
  1522. }
  1523. await db.SaveChangesAsync();
  1524. }
  1525. }
  1526. }
  1527. }
  1528. catch (Exception ex)
  1529. {
  1530. logger.Error(string.Format("ServerSetFeeTrigger ChargeBoxId:{0} Ex:{1}", item.Key, ex.ToString()));
  1531. }
  1532. }
  1533. }
  1534. await Task.Delay(1000);
  1535. }
  1536. }
  1537. async private Task<string> SetDefaultFee(ClientData client)
  1538. {
  1539. string displayPriceText = string.Empty;
  1540. string charingPriceText = string.Empty;
  1541. if (string.IsNullOrEmpty(client.ChargeBoxId)) return displayPriceText;
  1542. using (SqlConnection conn = new SqlConnection(webConnectionString))
  1543. {
  1544. var parameters = new DynamicParameters();
  1545. parameters.Add("@MachineId", client.MachineId, DbType.String, ParameterDirection.Input);
  1546. string displayPricestrSql = "";
  1547. string strSql = "";
  1548. if (client.IsAC)
  1549. {
  1550. displayPricestrSql = " SELECT [AC_BillingMethod] as BillingMethod,[AC_FeeName] as FeeName,[AC_Fee] as ChargingFeebyHour" +
  1551. " ,[AC_ParkingFee] as ParkingFee, [Currency] FROM[StationMachine] left join[dbo].[Station]" +
  1552. " on[StationMachine].StationId = Station.[Id] where StationMachine.MachineId=@MachineId and Station.IsBilling=1; ";
  1553. strSql = " SELECT CAST( [StartTime] as varchar(5)) StartTime,CAST( [EndTime] as varchar(5)) EndTime,[Fee] FROM[StationMachine] left join [dbo].[StationFee]" +
  1554. " on[StationMachine].StationId = StationFee.StationId where StationMachine.MachineId =@MachineId and StationFee.IsAC=1; ";
  1555. }
  1556. else
  1557. {
  1558. displayPricestrSql = " SELECT [DC_BillingMethod] as BillingMethod,[DC_FeeName] as FeeName,[DC_Fee] as ChargingFeebyHour" +
  1559. " ,[DC_ParkingFee] as ParkingFee, [Currency] FROM[StationMachine] left join[dbo].[Station]" +
  1560. " on[StationMachine].StationId = Station.[Id] where StationMachine.MachineId=@MachineId and Station.IsBilling=1; ";
  1561. strSql = " SELECT CAST( [StartTime] as varchar(5)) StartTime,CAST( [EndTime] as varchar(5)) EndTime,[Fee] FROM[StationMachine] left join [dbo].[StationFee]" +
  1562. " on[StationMachine].StationId = StationFee.StationId where StationMachine.MachineId =@MachineId and StationFee.IsAC=0; ";
  1563. }
  1564. var result = await conn.QueryAsync<StationFee>(displayPricestrSql, parameters);
  1565. if (result.Count() == 0)
  1566. {
  1567. return string.Empty;
  1568. }
  1569. var stationPrice = result.First();
  1570. if (stationPrice.BillingMethod == 1)
  1571. {
  1572. var chargingPriceResult = await conn.QueryAsync<ChargingPrice>(strSql, parameters);
  1573. client.ChargingPrices = chargingPriceResult.ToList();
  1574. if (string.IsNullOrEmpty(client.ChargingPrices[0].StartTime))
  1575. {
  1576. client.ChargingPrices = new List<ChargingPrice>();
  1577. }
  1578. }
  1579. displayPriceText = stationPrice.FeeName;
  1580. client.BillingMethod = stationPrice.BillingMethod;
  1581. client.Currency = stationPrice.Currency;
  1582. client.ChargingFeebyHour = stationPrice.ChargingFeebyHour;
  1583. client.ParkingFee = stationPrice.ParkingFee;
  1584. client.IsBilling = true;
  1585. }
  1586. return displayPriceText;
  1587. }
  1588. async private void HealthCheckTrigger()
  1589. {
  1590. for (; ; )
  1591. {
  1592. if (_ct.IsCancellationRequested)
  1593. {
  1594. break;
  1595. }
  1596. try
  1597. {
  1598. Dictionary<string, ClientData> _copyClientDic = null;
  1599. lock (_lockClientDic)
  1600. {
  1601. _copyClientDic = new Dictionary<string, ClientData>(clientDic);
  1602. }
  1603. var removeClients = _copyClientDic.Where(x => x.Value.LastActiveTime < DateTime.UtcNow.AddSeconds(-300)).Select(x => x.Value).ToList();
  1604. foreach (var session in removeClients)
  1605. {
  1606. Console.WriteLine(string.Format("Server forced to shut down ChargeBox ({0}: LastActiveTime{1})", session.ChargeBoxId, session.LastActiveTime));
  1607. RemoveClient(session);
  1608. }
  1609. await Task.Delay(60000);
  1610. }
  1611. catch (Exception ex)
  1612. {
  1613. logger.Error(string.Format("HealthAlarmTrigger Ex:{0}", ex.ToString()));
  1614. }
  1615. }
  1616. }
  1617. private void AddConfirmMessage(string chargePointSerialNumber, int table_id, string requestId, string action, string msg_id)
  1618. {
  1619. NeedConfirmMessage _needConfirmMsg = new NeedConfirmMessage();
  1620. _needConfirmMsg.Id = table_id;
  1621. _needConfirmMsg.SentAction = action;
  1622. _needConfirmMsg.SentOn = DateTime.UtcNow;
  1623. _needConfirmMsg.SentTimes = 1;
  1624. _needConfirmMsg.ChargePointSerialNumber = chargePointSerialNumber;
  1625. _needConfirmMsg.RequestId = requestId;
  1626. _needConfirmMsg.SentUniqueId = msg_id;
  1627. if (needConfirmActions.Contains(action))
  1628. {
  1629. lock (_lockConfirmPacketList)
  1630. {
  1631. needConfirmPacketList.Add(_needConfirmMsg);
  1632. }
  1633. }
  1634. }
  1635. private void RemoveConfirmMessage()
  1636. {
  1637. var before_3mins = DateTime.UtcNow.AddMinutes(-3);
  1638. lock (_lockConfirmPacketList)
  1639. {
  1640. var removeList = needConfirmPacketList.Where(x => x.SentTimes == 0 || x.SentOn < before_3mins).ToList();
  1641. foreach (var item in removeList)
  1642. {
  1643. needConfirmPacketList.Remove(item);
  1644. }
  1645. }
  1646. }
  1647. private bool ReConfirmMessage(MessageResult analysisResult)
  1648. {
  1649. bool confirmed = false;
  1650. if (needConfirmActions.Contains(analysisResult.Action))
  1651. {
  1652. NeedConfirmMessage foundRequest = null;
  1653. lock (_lockConfirmPacketList)
  1654. {
  1655. foundRequest = needConfirmPacketList.Where(x => x.SentUniqueId == analysisResult.UUID).FirstOrDefault();
  1656. }
  1657. if (foundRequest != null && foundRequest.Id > 0)
  1658. {
  1659. foundRequest.SentTimes = 0;
  1660. foundRequest.SentInterval = 0;
  1661. analysisResult.RequestId = foundRequest.RequestId;
  1662. using (var db = new MainDBContext())
  1663. {
  1664. var sc = db.ServerMessage.Where(x => x.Id == foundRequest.Id).FirstOrDefault();
  1665. sc.InMessage = JsonConvert.SerializeObject(analysisResult.Message, Formatting.None);
  1666. sc.ReceivedOn = DateTime.UtcNow;
  1667. db.SaveChanges();
  1668. // Console.WriteLine(string.Format("Now:{0} ServerMessage Id:{1} ", DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"), foundRequest.Id));
  1669. }
  1670. confirmed = true;
  1671. }
  1672. else if (analysisResult.Action == Actions.TriggerMessage.ToString())
  1673. {
  1674. confirmed = true;
  1675. }
  1676. else
  1677. {
  1678. logger.Error(string.Format("Received no record Action:{0} MessageId:{1} ", analysisResult.Action, analysisResult.UUID));
  1679. }
  1680. }
  1681. return confirmed;
  1682. }
  1683. private void RemoveClient(ClientData session)
  1684. {
  1685. if (session != null)
  1686. {
  1687. logger.Trace("RemoveClient[" + session.ChargeBoxId + "]");
  1688. if (session.Connected)
  1689. {
  1690. session.Close(CloseReason.ServerShutdown);
  1691. }
  1692. RemoveClientDic(session);
  1693. try
  1694. {
  1695. session.m_ReceiveData -= new ClientData.OCPPClientDataEventHandler<ClientData, String>(ReceivedMessage);
  1696. // session.Close(CloseReason.ServerShutdown);
  1697. }
  1698. catch (Exception ex)
  1699. {
  1700. //logger.Warn("Close client socket error!!");
  1701. logger.Warn(string.Format("Close client socket error!! {0} Msg:{1}", session.ChargeBoxId, ex.Message));
  1702. }
  1703. if (session != null)
  1704. {
  1705. session = null;
  1706. }
  1707. }
  1708. }
  1709. private void RemoveClientDic(ClientData session)
  1710. {
  1711. if (!string.IsNullOrEmpty(session.ChargeBoxId))
  1712. {
  1713. lock (_lockClientDic)
  1714. {
  1715. if (clientDic.ContainsKey(session.ChargeBoxId))
  1716. {
  1717. if (clientDic[session.ChargeBoxId].SessionID == session.SessionID)
  1718. {
  1719. logger.Debug(String.Format("ChargeBoxId:{0} Remove SessionId:{1} Removed SessionId:{2}", session.ChargeBoxId, session.SessionID, clientDic[session.ChargeBoxId].SessionID));
  1720. clientDic.Remove(session.ChargeBoxId);
  1721. logger.Trace("RemoveClient ContainsKey " + session.ChargeBoxId);
  1722. }
  1723. }
  1724. }
  1725. }
  1726. }
  1727. private void WarmUpLog()
  1728. {
  1729. using (var log = new ConnectionLogDBContext())
  1730. {
  1731. log.MachineConnectionLog.ToList();
  1732. }
  1733. }
  1734. private void WriteMachineLog(ClientData clientData, string data, string messageType, string errorMsg = "", bool isSent = false)
  1735. {
  1736. try
  1737. {
  1738. if (clientData == null || string.IsNullOrEmpty(data)) return;
  1739. if (clientData.ChargeBoxId == null)
  1740. {
  1741. logger.Fatal(clientData.Path + "]********************session ChargeBoxId null sessionId=" + clientData.SessionID);
  1742. }
  1743. using (var db = new ConnectionLogDBContext())
  1744. {
  1745. string sp = "[dbo].[uspInsertMachineConnectionLog] @CreatedOn," +
  1746. "@ChargeBoxId,@MessageType,@Data,@Msg,@IsSent,@EVSEEndPoint,@Session";
  1747. var dd = DateTime.UtcNow;
  1748. SqlParameter[] parameter =
  1749. {
  1750. new SqlParameter("CreatedOn",dd),
  1751. new SqlParameter("ChargeBoxId",clientData.ChargeBoxId==null?"unknown":clientData.ChargeBoxId.Replace("'","''")),
  1752. new SqlParameter("MessageType",messageType.Replace("'","''")),
  1753. new SqlParameter("Data",data.Replace("'","''")),
  1754. new SqlParameter("Msg",errorMsg.Replace("'","''")),
  1755. new SqlParameter("IsSent",isSent),
  1756. new SqlParameter("EVSEEndPoint",clientData.RemoteEndPoint==null?"123":clientData.RemoteEndPoint.ToString()),
  1757. new SqlParameter("Session",clientData.SessionID==null?"123":clientData.SessionID)
  1758. };
  1759. db.Database.ExecuteSqlCommand(sp, parameter);
  1760. }
  1761. }
  1762. catch (Exception ex)
  1763. {
  1764. Console.WriteLine(ex.ToString());
  1765. }
  1766. }
  1767. }
  1768. }