ProtalServer.cs 104 KB

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