ProtalServer.cs 102 KB

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