WSServer.cs 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862
  1. using Evcb.Domain.Model;
  2. using Evcb.Domain.mongo;
  3. using Evcb.Repository;
  4. using Evcb.Service;
  5. using Evcb.Service.Helpers;
  6. using Evcb.Service.Service;
  7. using MongoDB.Driver;
  8. using Newtonsoft.Json;
  9. using Newtonsoft.Json.Linq;
  10. using NLog;
  11. using OCPPPacket.Packet.Feature;
  12. using OCPPPacket.Packet.Messages;
  13. using OCPPPacket.Packet.Messages.Basic;
  14. using OCPPPacket.Packet.Messages.Core;
  15. using OCPPPacket.Packet.Status;
  16. using OCPPServer.Handler;
  17. using OCPPServer.Protocol;
  18. using OCPPServer.SubProtocol;
  19. using Packet;
  20. using Packet.Cmd;
  21. using SuperSocket.SocketBase;
  22. using SuperSocket.SocketBase.Config;
  23. using System;
  24. using System.Collections.Generic;
  25. using System.Configuration;
  26. using System.Data.Entity;
  27. using System.Data.Entity.Validation;
  28. using System.Linq;
  29. using System.Net;
  30. using System.Net.Sockets;
  31. using System.Text;
  32. using System.Threading;
  33. using System.Threading.Tasks;
  34. using System.Xml.Linq;
  35. namespace OCPPServer
  36. {
  37. public class WSServer
  38. {
  39. private readonly Object _lockClientDic = new object();
  40. private readonly Object _lockConfirmPacketList = new object();
  41. private CancellationTokenSource _cts = new CancellationTokenSource();
  42. private CancellationToken _ct;
  43. private IMongoService mongoService = new MongoService();
  44. static private ILogger logger = NLog.LogManager.GetCurrentClassLogger();
  45. private List<string> _cmd202lst = new List<string>();
  46. private List<int> _needConfirmCmdList;
  47. public Dictionary<string, ClientData> ClientDic { get; set; }
  48. public string Listening { get; set; }
  49. public string ApiUrl { get; set; }
  50. public List<NeedConfirmPacket> NeedConfirmPacketList { get; set; }
  51. /// <summary>
  52. /// 上次校時時間
  53. /// </summary>
  54. private DateTime sendTiming { get; set; }
  55. /// <summary>
  56. /// 檢查軟韌體時間
  57. /// </summary>
  58. private DateTime checkUpdateDt { get; set; }
  59. /// <summary>
  60. /// 可允許連線Clinet數
  61. /// </summary>
  62. public int connectNum { get; set; }
  63. /// <summary>
  64. /// 是否限制連線Clinet數
  65. /// </summary>
  66. public bool beConnectLimit { get; set; }
  67. /// <summary>
  68. /// 是否紀錄與充電樁互傳命令 在 MachineConnectionLog
  69. /// </summary>
  70. private bool ENABLELOG_MACHINECMD = false;
  71. public WSServer()
  72. {
  73. using (var db = new PhihongDbContext())
  74. {
  75. _ct = _cts.Token;
  76. ClientDic = new Dictionary<string, ClientData>();
  77. NeedConfirmPacketList = new List<NeedConfirmPacket>();
  78. //需要確認回傳的指令
  79. _needConfirmCmdList = db.NeedConfirmCmd.Select(c => c.Id).ToList();
  80. //載入相關config
  81. ENABLELOG_MACHINECMD = ConfigurationManager.AppSettings.Get("EnableMachineConnectionLog").Equals("0") ? false : true;
  82. ApiUrl = ConfigurationManager.AppSettings.Get("ApiUrl");
  83. string serverIp = ConfigurationManager.AppSettings.Get("ServerIp");
  84. string serverPort = ConfigurationManager.AppSettings.Get("ServerPort");
  85. string wssserverPort = ConfigurationManager.AppSettings.Get("WSSServerPort");
  86. string serverSecurity = ConfigurationManager.AppSettings.Get("ServerSecurity");
  87. int maxRequestLength = int.Parse(ConfigurationManager.AppSettings.Get("MaxRequestLength"));
  88. var config = ConfigurationManager.GetSection("superSocket") as IConfigurationSource;
  89. ICertificateConfig Certificate = config.Servers.ElementAt(0).Certificate;
  90. sendTiming = DateTime.Now;
  91. checkUpdateDt = DateTime.Now;
  92. //載入OCPP Protocol
  93. var appServer = new OCPPWSServer(new OCPPSubProtocol());
  94. List<IListenerConfig> llistener = new List<IListenerConfig>();
  95. llistener.Add(new ListenerConfig { Ip = serverIp, Port = Convert.ToInt32(wssserverPort), Backlog = 100, Security = serverSecurity });
  96. llistener.Add(new ListenerConfig { Ip = serverIp, Port = Convert.ToInt32(serverPort), Backlog = 100, Security = "None" });
  97. IEnumerable<IListenerConfig> listeners = llistener;
  98. //設定server config
  99. var serverConfig = new ServerConfig
  100. {
  101. //Port = Convert.ToInt32(serverPort),
  102. //Ip = serverIp,
  103. MaxRequestLength = maxRequestLength,
  104. //Security = serverSecurity,
  105. Certificate = Certificate,
  106. Listeners = listeners
  107. };
  108. //Setup with listening port
  109. if (!appServer.Setup(serverConfig, logFactory: new OCPPLogFactory()))
  110. {
  111. Console.WriteLine("Failed to setup!");
  112. Console.ReadKey();
  113. return;
  114. }
  115. appServer.NewSessionConnected += AppServer_NewSessionConnected;
  116. appServer.SessionClosed += AppServer_SessionClosed;
  117. Console.WriteLine();
  118. string mac = ConfigurationManager.AppSettings.Get("mac");
  119. string limit = ConfigurationManager.AppSettings.Get("limit");
  120. string signature = ConfigurationManager.AppSettings.Get("Signature");
  121. appServer.beConnectLimit = true;
  122. Console.Write("<=============================================================== \n");
  123. Console.Write("Server Mac: {0}\n", mac);
  124. Console.Write("Connection Limit: {0}\n", limit);
  125. Console.Write("Signature: {0}\n", signature);
  126. var result = ConnectionLimitHepler.ConnectionLimitValidation(ConnectionLimitHepler.Key, signature, mac, limit);
  127. if (result.IsValid == true)
  128. {
  129. Console.Write("Verification Signature Result : correct\n");
  130. if (limit.Contains("∞") == false)
  131. {
  132. appServer.connectNum = Int32.Parse(limit);
  133. Console.Write("Real Connection Limit: {0}\n", appServer.connectNum);
  134. }
  135. else
  136. {
  137. appServer.connectNum = 0;
  138. appServer.beConnectLimit = false;
  139. Console.Write("Real Connection Limit: {0}\n", "∞");
  140. }
  141. }
  142. else
  143. {
  144. Console.Write("Verification Signature Result : incorrect\n");
  145. appServer.connectNum = 10;
  146. Console.Write("Real Connection Limit: {0}\n", appServer.connectNum);
  147. }
  148. Console.Write("===============================================================> \n");
  149. //Try to start the appServer
  150. if (!appServer.Start())
  151. {
  152. Console.WriteLine("Failed to start!");
  153. Console.ReadKey();
  154. return;
  155. }
  156. }
  157. }
  158. public void Start()
  159. {
  160. Task taskServerCommand = new Task(ServerCommandThread, _ct);
  161. taskServerCommand.Start();
  162. while (true)
  163. {
  164. var input = Console.ReadLine();
  165. switch (input.ToLower())
  166. {
  167. case "stop":
  168. //ListenerSocket.Shutdown(SocketShutdown.Both);
  169. //ListenerSocket.Close();
  170. Stop();
  171. logger.Info("server stop");
  172. Task.WaitAny(taskServerCommand);
  173. break;
  174. case "gc":
  175. logger.Info("Command GC");
  176. GC.Collect();
  177. break;
  178. case "lc":
  179. logger.Info("Command List Clients");
  180. var list = ClientDic.Select(c => c.Value).ToList();
  181. int i = 1;
  182. foreach (var c in list)
  183. {
  184. logger.Info(i + ":" + c.MachineCustomId);
  185. i++;
  186. }
  187. break;
  188. case "lcn":
  189. logger.Info("Command List Customer Name");
  190. var lcn = ClientDic.Select(c => c.Value.CustomerName).Distinct().ToList();
  191. int iLcn = 1;
  192. foreach (var c in lcn)
  193. {
  194. logger.Info(iLcn + ":" + c + ":" + ClientDic.Where(z => z.Value.CustomerName == c).Count().ToString());
  195. iLcn++;
  196. }
  197. break;
  198. case "help":
  199. logger.Info("Command help!!");
  200. logger.Info("lcn : List Customer Name");
  201. logger.Info("gc : GC Collect");
  202. logger.Info("lc : List Clients");
  203. logger.Info("cls : clear console");
  204. logger.Info("silent : silent");
  205. logger.Info("show : show log");
  206. logger.Info("rcl : show Real Connection Limit");
  207. break;
  208. case "cls":
  209. logger.Info("Command clear");
  210. Console.Clear();
  211. break;
  212. case "silent":
  213. logger.Info("Command silent");
  214. var xe = XElement.Load("NLog.config");
  215. var xns = xe.GetDefaultNamespace();
  216. var minlevelattr = xe.Descendants(xns + "rules").Elements(xns + "logger")
  217. .Where(c => c.Attribute("writeTo").Value.Equals("console")).Attributes("minlevel").FirstOrDefault();
  218. if (minlevelattr != null)
  219. {
  220. minlevelattr.Value = "info";
  221. }
  222. xe.Save("NLog.config");
  223. break;
  224. case "show":
  225. logger.Info("Command show");
  226. var xe1 = XElement.Load("NLog.config");
  227. var xns1 = xe1.GetDefaultNamespace();
  228. var minlevelattr1 = xe1.Descendants(xns1 + "rules").Elements(xns1 + "logger")
  229. .Where(c => c.Attribute("writeTo").Value.Equals("console")).Attributes("minlevel").FirstOrDefault();
  230. if (minlevelattr1 != null)
  231. {
  232. minlevelattr1.Value = "trace";
  233. }
  234. xe1.Save("NLog.config");
  235. break;
  236. case "rcl":
  237. logger.Info("Command rcln");
  238. if (beConnectLimit == true)
  239. {
  240. logger.Info("Real Connection Limit:" + connectNum);
  241. }
  242. else
  243. {
  244. logger.Info("Real Connection Limit:" + "∞");
  245. }
  246. break;
  247. default:
  248. break;
  249. }
  250. }
  251. }
  252. /// <summary>
  253. /// 處理電樁送的OCPP 訊息
  254. /// </summary>
  255. public void ReceivedMessage(ClientData ctdata, String msg)
  256. {
  257. using (var db = new PhihongDbContext())
  258. {
  259. IUnitOfWork uow = new UnitOfWork(db);
  260. IMachineService machineSrv = new MachineService(uow);
  261. ISocketCommandService socketCommandSrv = new SocketCommandService(uow);
  262. ICustomerService _customerService = new CustomerService();
  263. OCPPMessageHandler ocppMsgHandler = new OCPPMessageHandler();
  264. try
  265. {
  266. //檢查是否有Connection 沒有加入ClientDic
  267. if (ctdata.IsCheckIn)
  268. {
  269. lock (_lockClientDic)
  270. {
  271. if (!ClientDic.ContainsKey(ctdata.MachineCustomId))
  272. {
  273. ClientDic.Add(ctdata.MachineCustomId, ctdata);
  274. logger.Trace("Rejoin MachineCustomId: {0}", ctdata.MachineCustomId);
  275. }
  276. }
  277. }
  278. BaseMessage message = ocppMsgHandler.Parse(msg);
  279. CheckConfirmPacket(ctdata, message);
  280. if (message is CallResultMessage)
  281. {
  282. #region 處理CallResultMessage
  283. //更新充電樁的心跳包接收時間
  284. socketCommandSrv.UpdateHeartbeat(ctdata.MachineCustomId);
  285. CallResultMessage call = (CallResultMessage)message;
  286. string callResultAction = string.Empty;
  287. var result = ocppMsgHandler.OnCallResult(call.id, call.payload, ref ctdata.queue, out callResultAction);
  288. if (result.Success == true)
  289. {
  290. if (ENABLELOG_MACHINECMD)
  291. {
  292. MachineConnectionLog log = new MachineConnectionLog();
  293. log.MachineCustomId = ctdata.MachineCustomId;
  294. log.MachineId = ctdata.MachineId;
  295. log.IpPort = ctdata.LocalEndPoint.ToString();
  296. log.IsIllegal = false;
  297. if (msg.Length >= 2000)
  298. log.Data = msg.Substring(0, 1999);
  299. else
  300. log.Data = msg;
  301. log.IsDataOut = false;
  302. log.CmdNum = 0;
  303. log.CreatedOn = DateTime.Now;
  304. log.Msg = callResultAction;
  305. var ep = ((IPEndPoint)ctdata.RemoteEndPoint);
  306. log.ClientIpPort = ep.Address.ToString() + ":" + ep.Port.ToString();
  307. SaveMachineConnectionLog(log);
  308. if (msg.Length >= 2000) // GetConfiguration.conf封包
  309. {
  310. MachineConnectionLog log1 = new MachineConnectionLog();
  311. log1.MachineCustomId = ctdata.MachineCustomId;
  312. log1.MachineId = ctdata.MachineId;
  313. log1.IpPort = ctdata.LocalEndPoint.ToString();
  314. log1.IsIllegal = false;
  315. log1.IsDataOut = false;
  316. log1.CmdNum = 0;
  317. log1.Data = "config :" + msg.Substring(2000, msg.Length - 2000);
  318. log1.CreatedOn = DateTime.Now;
  319. log1.Msg = callResultAction;
  320. var ep1 = ((IPEndPoint)ctdata.RemoteEndPoint);
  321. log1.ClientIpPort = ep1.Address.ToString() + ":" + ep1.Port.ToString();
  322. SaveMachineConnectionLog(log1);
  323. }
  324. }
  325. if (!ctdata.IsCheckIn && (result.Payload is GetConfigurationConfirmation))
  326. {
  327. IRequest req = MakeRequestHandler.MakeChangeConfigurationRequest("HeartBeatInterval", "60");
  328. string uuid = ctdata.queue.store(req);
  329. Send(ctdata, ocppMsgHandler.GenerateCall(uuid, Actions.ChangeConfiguration.ToString(), req), "ChangeConfiguration Request");
  330. }
  331. //將OCPP CallResult Message的Payload所夾帶參數資訊進行處理
  332. var handleConfirmationResult = ocppMsgHandler.HandleConfirmation(call.id, (IConfirmation)result.Payload, callResultAction, db, ref ctdata);
  333. if (handleConfirmationResult.Success == true)
  334. {
  335. //do nothing
  336. }
  337. else
  338. {
  339. if (ENABLELOG_MACHINECMD)
  340. {
  341. //紀錄error type message
  342. MachineConnectionLog log1 = new MachineConnectionLog();
  343. log1.MachineCustomId = ctdata.MachineCustomId;
  344. log1.MachineId = ctdata.MachineId;
  345. log1.IpPort = ctdata.LocalEndPoint.ToString();
  346. log1.IsIllegal = true;
  347. log1.IsDataOut = false;
  348. log1.CmdNum = 0;
  349. log1.Data = msg;
  350. log1.CreatedOn = DateTime.Now;
  351. log1.Msg = handleConfirmationResult.Message;
  352. var ep1 = ((IPEndPoint)ctdata.RemoteEndPoint);
  353. log1.ClientIpPort = ep1.Address.ToString() + ":" + ep1.Port.ToString();
  354. SaveMachineConnectionLog(log1);
  355. }
  356. //送出錯誤訊息給電樁
  357. //Send(ctdata, handleConfirmationResult.Message);
  358. }
  359. }
  360. else
  361. {
  362. #region error type message 處理
  363. if(result.Message.Equals("none") == true)
  364. {
  365. //重複送相同Message, 不處理
  366. }
  367. else
  368. {
  369. if (ENABLELOG_MACHINECMD)
  370. {
  371. //紀錄error type message
  372. MachineConnectionLog log = new MachineConnectionLog();
  373. log.MachineCustomId = ctdata.MachineCustomId;
  374. log.MachineId = ctdata.MachineId;
  375. log.IpPort = ctdata.LocalEndPoint.ToString();
  376. log.IsIllegal = true;
  377. log.IsDataOut = false;
  378. log.CmdNum = 0;
  379. log.Data = msg;
  380. log.CreatedOn = DateTime.Now;
  381. //紀錄exception, 送出錯誤訊息給電樁
  382. if (result.Exception != null)
  383. {
  384. logger.Error(result.Exception, "OnCallResult error");
  385. log.Msg = result.Exception.ToString();
  386. }
  387. else
  388. {
  389. ////送出錯誤訊息給電樁
  390. //Send(ctdata, result.Message, "Error Message");
  391. log.Msg = result.Message;
  392. }
  393. var ep = ((IPEndPoint)ctdata.RemoteEndPoint);
  394. log.ClientIpPort = ep.Address.ToString() + ":" + ep.Port.ToString();
  395. SaveMachineConnectionLog(log);
  396. }
  397. Send(ctdata, result.Message, "Error Message");
  398. }
  399. #endregion error type message 處理
  400. }
  401. #endregion 處理CallResultMessage
  402. }
  403. else if (message is CallErrorMessage)
  404. {
  405. #region 處理CallErrorMessage
  406. //failedFlag = true;
  407. //更新充電樁的心跳包接收時間
  408. socketCommandSrv.UpdateHeartbeat(ctdata.MachineCustomId);
  409. CallErrorMessage call = (CallErrorMessage)message;
  410. var result = ocppMsgHandler.OnError(call.id, call.ErrorCode, call.ErrorDescription, call.payload);
  411. if (result.Success == true)
  412. {
  413. if (ENABLELOG_MACHINECMD)
  414. {
  415. MachineConnectionLog log = new MachineConnectionLog();
  416. log.MachineCustomId = ctdata.MachineCustomId;
  417. log.MachineId = ctdata.MachineId;
  418. log.IpPort = ctdata.LocalEndPoint.ToString();
  419. log.IsIllegal = false;
  420. log.Data = msg;//call.id.ToString() + "," + JsonConvert.SerializeObject(result.Payload); ;
  421. log.IsDataOut = false;
  422. log.CmdNum = 0;
  423. log.CreatedOn = DateTime.Now;
  424. log.Msg = call.ErrorCode;
  425. var ep = ((IPEndPoint)ctdata.RemoteEndPoint);
  426. log.ClientIpPort = ep.Address.ToString() + ":" + ep.Port.ToString();
  427. SaveMachineConnectionLog(log);
  428. }
  429. //重送上次未成功的訊息 或 移除Client
  430. }
  431. var handleErrorResult = ocppMsgHandler.HandleError(call.id, call.ErrorCode, call.ErrorDescription, call.payload);
  432. #endregion 處理CallErrorMessage
  433. }
  434. else if (message is CallMessage)
  435. {
  436. #region 處理CallMessage
  437. //處理OCPP Call Message
  438. CallMessage call = (CallMessage)message;
  439. var result = ocppMsgHandler.OnCall(call.id, call.action, call.payload);
  440. bool BootNotificationPending = false;
  441. if (result.Success == true)
  442. {
  443. //如果沒有 check in,設定為illegal的封包資料,紀錄之後,此筆放棄,處理下一個
  444. if (!ctdata.IsCheckIn)
  445. {
  446. if (ENABLELOG_MACHINECMD)
  447. {
  448. MachineConnectionLog log = new MachineConnectionLog();
  449. log.MachineCustomId = ctdata.MachineCustomId;
  450. log.MachineId = ctdata.MachineId;
  451. log.IpPort = ctdata.LocalEndPoint.ToString();
  452. log.IsIllegal = true;
  453. log.Data = msg;
  454. log.IsDataOut = false;
  455. log.CmdNum = 0;
  456. log.CreatedOn = DateTime.Now;
  457. log.Msg = call.action + " Request";
  458. var ep = ((IPEndPoint)ctdata.RemoteEndPoint);
  459. log.ClientIpPort = ep.Address.ToString() + ":" + ep.Port.ToString();
  460. SaveMachineConnectionLog(log);
  461. }
  462. //如果不是 BootNotificationRequest 就不處理,處理下一個指令
  463. if (!(result.Payload is BootNotificationRequest))
  464. {
  465. return;
  466. }
  467. else
  468. {
  469. if (ENABLELOG_MACHINECMD)
  470. {
  471. //紀錄收到BootNotificationRequest(目前還沒有CheckIn)
  472. MachineConnectionLog log2 = new MachineConnectionLog();
  473. log2.MachineCustomId = ctdata.MachineCustomId;
  474. log2.MachineId = ctdata.MachineId;
  475. log2.IpPort = ctdata.LocalEndPoint.ToString();
  476. log2.IsIllegal = false;
  477. log2.Data = msg;//call.id.ToString() + "," + call.action.ToString() + "," + JsonConvert.SerializeObject(result.Payload);
  478. log2.IsDataOut = false;
  479. log2.CmdNum = 0;
  480. log2.CreatedOn = DateTime.Now;
  481. log2.Msg = "first signin";
  482. var ep2 = ((IPEndPoint)ctdata.RemoteEndPoint);
  483. log2.ClientIpPort = ep2.Address.ToString() + ":" + ep2.Port.ToString();
  484. SaveMachineConnectionLog(log2);
  485. }
  486. //初始化client的CmdHelper instance
  487. var machine = machineSrv.GetByCustomId(ctdata.MachineCustomIdTemp);
  488. var customer = _customerService.GetByCustomerId(machine.CustomerId);
  489. ctdata.CmdHelper = new CmdHelper(customer.MachineCode1, customer.MachineCode2);
  490. }
  491. }
  492. else
  493. {
  494. //更新充電樁的心跳包接收時間
  495. socketCommandSrv.UpdateHeartbeat(ctdata.MachineCustomId);
  496. //當 Heartbeat 與 上一個 Heartbeat相差值小於2秒,送出ChangeConfiguration.req(HeartbeatInterval: 15) 給電樁
  497. if ((IRequest)result.Payload is HeartbeatRequest)
  498. {
  499. //var HeartbeatNow = db.MachineConnectionLog.Where(c => c.MachineCustomId == ctdata.MachineCustomId).OrderByDescending(c => c.Id).AsNoTracking().FirstOrDefault();
  500. //if (HeartbeatNow.Data.Contains("currentTime") == true)
  501. if (ctdata.heartbeatDate != null)
  502. {
  503. DateTime currenttime = DateTime.Now;
  504. //DateTime basetime = HeartbeatNow.CreatedOn;
  505. DateTime basetime = (DateTime)ctdata.heartbeatDate;
  506. TimeSpan ts = currenttime.Subtract(basetime).Duration();
  507. double seconddiff = ts.TotalSeconds;
  508. if ((seconddiff <= 2) && (ctdata.IsSendHeartbeatChangeConfiguration == false)) // Heartbeat 與上一個 Heartbeat時間小於 2秒
  509. {
  510. //當 Heartbeat 與 上一個 Heartbeat相差值小於2秒,判斷是否送出ChangeConfiguration.req(HeartbeatInterval: 15) 給電樁
  511. ctdata.IsSendHeartbeatChangeConfiguration = true;
  512. var machine = machineSrv.GetByCustomId(ctdata.MachineCustomId);
  513. //重發校時
  514. //設定心跳時間和心跳的timeout次數
  515. logger.Trace("set 心跳時間和心跳的timeout次數");
  516. Cmd1001 cmd1001temp = ctdata.CmdHelper.Create(1001) as Cmd1001;
  517. cmd1001temp.Type = 1;
  518. cmd1001temp.ParamIndex = 21;
  519. cmd1001temp.ParamAmt = 2;
  520. cmd1001temp.ParamByteLength = (ushort)((ushort)cmd1001temp.ParamAmt * 4);
  521. uint p21 = (uint)machine.HeartbeatInterval;
  522. cmd1001temp.ParamByteList.AddRange(CmdUtil.ToByteArray(p21).ToList());
  523. uint p22 = (uint)machine.HeartbeatTimeoutTimes;
  524. cmd1001temp.ParamByteList.AddRange(CmdUtil.ToByteArray(p22).ToList());
  525. cmd1001temp.Pack();
  526. ServerCommand sc = new ServerCommand();
  527. sc.OutCmdNum = cmd1001temp.Cmd;
  528. sc.CreatedOn = DateTime.Now;
  529. sc.MachineId = ctdata.MachineId;
  530. sc.MachineCustomId = ctdata.MachineCustomId;
  531. sc.OutTransData = cmd1001temp.byteList.ToArray();
  532. db.ServerCommand.Add(sc);
  533. db.SaveChanges();
  534. }
  535. }
  536. }
  537. if (ENABLELOG_MACHINECMD)
  538. {
  539. //紀錄電樁的連線資訊
  540. MachineConnectionLog log = new MachineConnectionLog();
  541. log.MachineCustomId = ctdata.MachineCustomId;
  542. log.MachineId = ctdata.MachineId;
  543. log.IpPort = ctdata.LocalEndPoint.ToString();
  544. log.IsIllegal = false;
  545. log.IsDataOut = false;
  546. log.CmdNum = 0;
  547. if (msg.Length > 2000)
  548. log.Data = msg.Substring(0, 1999);
  549. else
  550. log.Data = msg;//call.id.ToString() + "," +call.action.ToString() + "," + JsonConvert.SerializeObject(result.Payload);
  551. log.CreatedOn = DateTime.Now;
  552. if (call.action.Contains("DataTransfer"))
  553. {
  554. log.Msg = call.action + " Request(" + ((DataTransferRequest)(result.Payload)).messageId + ")";
  555. }
  556. else
  557. log.Msg = call.action + " Request";
  558. var ep = ((IPEndPoint)ctdata.RemoteEndPoint);
  559. log.ClientIpPort = ep.Address.ToString() + ":" + ep.Port.ToString();
  560. SaveMachineConnectionLog(log);
  561. if (msg.Length >= 2000) // BMS封包
  562. {
  563. MachineConnectionLog log1 = new MachineConnectionLog();
  564. log1.MachineCustomId = ctdata.MachineCustomId;
  565. log1.MachineId = ctdata.MachineId;
  566. log1.IpPort = ctdata.LocalEndPoint.ToString();
  567. log1.IsIllegal = false;
  568. log1.IsDataOut = false;
  569. log1.CmdNum = 0;
  570. log1.Data = "ChargingGunBMS :" + msg.Substring(2000, msg.Length - 2000);
  571. log1.CreatedOn = DateTime.Now;
  572. if (call.action.Contains("DataTransfer"))
  573. {
  574. log.Msg = call.action + " Request(" + ((DataTransferRequest)(result.Payload)).messageId + ")";
  575. }
  576. else
  577. log.Msg = call.action + " Request";
  578. var ep1 = ((IPEndPoint)ctdata.RemoteEndPoint);
  579. log1.ClientIpPort = ep1.Address.ToString() + ":" + ep1.Port.ToString();
  580. SaveMachineConnectionLog(log1);
  581. }
  582. }
  583. }
  584. //將OCPP Call Message的Payload所夾帶參數資訊進行處理
  585. var handleRequestResult = ocppMsgHandler.HandleRequest((IRequest)result.Payload, call.id, db, ref ctdata);
  586. if (handleRequestResult.Success == true)
  587. {
  588. //針對即將回傳給電樁的Confirm Message進行處理
  589. IConfirmation conf = (IConfirmation)handleRequestResult.Payload;
  590. if (!ctdata.IsCheckIn && (conf is BootNotificationConfirmation))
  591. {
  592. //後台接受電樁發送的BootNotification Request
  593. if (((BootNotificationConfirmation)conf).status == RegistrationStatus.Accepted)
  594. {
  595. //不存在機器,要紀錄起來
  596. var machine = machineSrv.GetByCustomId(ctdata.MachineCustomIdTemp);
  597. ctdata.CustomerId = machine.CustomerId;
  598. ctdata.CustomerName = machine.Customer.Name;
  599. ctdata.MachineId = machine.Id;
  600. string temp = String.Empty;
  601. temp = ctdata.MachineCustomId;
  602. ctdata.MachineCustomId = ctdata.MachineCustomIdTemp;
  603. ctdata.MachineCustomIdTemp = temp;
  604. OCPP_ClientDicAdded(ctdata);
  605. //確認是否已經有新增槍數
  606. machineSrv.CheckGunsByMachineCustomId(ctdata.MachineCustomId);
  607. uow.SaveChanges();
  608. //設定心跳時間和心跳的timeout次數
  609. logger.Trace("set 心跳時間和心跳的timeout次數");
  610. Cmd1001 cmd1001 = ctdata.CmdHelper.Create(1001) as Cmd1001;
  611. cmd1001.Type = 1;
  612. cmd1001.ParamIndex = 21;
  613. cmd1001.ParamAmt = 2;
  614. cmd1001.ParamByteLength = (ushort)((ushort)cmd1001.ParamAmt * 4);
  615. uint p21 = (uint)machine.HeartbeatInterval;
  616. cmd1001.ParamByteList.AddRange(CmdUtil.ToByteArray(p21).ToList());
  617. uint p22 = (uint)machine.HeartbeatTimeoutTimes;
  618. cmd1001.ParamByteList.AddRange(CmdUtil.ToByteArray(p22).ToList());
  619. cmd1001.Pack();
  620. ServerCommand sc = new ServerCommand();
  621. sc.OutCmdNum = cmd1001.Cmd;
  622. sc.CreatedOn = DateTime.Now;
  623. sc.MachineId = ctdata.MachineId;
  624. sc.MachineCustomId = ctdata.MachineCustomId;
  625. sc.OutTransData = cmd1001.byteList.ToArray();
  626. db.ServerCommand.Add(sc);
  627. db.SaveChanges();
  628. //設定樁的夥伴代碼
  629. Cmd1003 cmd1003 = ctdata.CmdHelper.Create(1003) as Cmd1003;
  630. cmd1003.ParamByteLength = 36;
  631. cmd1003.Type = 1;
  632. cmd1003.ParamIndex = 12;
  633. cmd1003.ParamByteList.AddRange(CmdUtil.ToByteArray(machine.PartnerPoleId, 36));
  634. cmd1003.Pack();
  635. ServerCommand sc1003 = new ServerCommand();
  636. sc1003.OutCmdNum = cmd1003.Cmd;
  637. sc1003.CreatedOn = DateTime.Now;
  638. sc1003.MachineId = ctdata.MachineId;
  639. sc1003.MachineCustomId = ctdata.MachineCustomId;
  640. sc1003.OutTransData = cmd1003.byteList.ToArray();
  641. db.ServerCommand.Add(sc1003);
  642. db.SaveChanges();
  643. SendElectricityRates(machine, ctdata);
  644. //設定GetConfiguration
  645. Cmd9029 cmd9029 = ctdata.CmdHelper.Create(9029) as Cmd9029;
  646. cmd9029.SerNum = 1;
  647. cmd9029.CmdSerNum = 1;
  648. cmd9029.ParamIndex = 1;
  649. //cmd1005.ParamAmt = 2;
  650. cmd9029.ParamByteLength = (ushort)4;
  651. uint p2 = 0x55;
  652. cmd9029.ParamByteList.AddRange(CmdUtil.ToByteArray(p2));
  653. //string type = "GetConfiguration";
  654. //cmd1005.ParamByteList.AddRange(CmdUtil.ToByteArray(type));
  655. cmd9029.Pack();
  656. ServerCommand sc9029 = new ServerCommand();
  657. sc9029.OutCmdNum = cmd9029.Cmd;
  658. sc9029.CreatedOn = DateTime.Now;
  659. sc9029.MachineId = machine.Id;
  660. sc9029.MachineCustomId = machine.CustomId;
  661. sc9029.OutTransData = cmd9029.byteList.ToArray();
  662. db.ServerCommand.Add(sc9029);
  663. db.SaveChanges();
  664. //后台服务器下发查询目前验证卡号名单版号
  665. var localauthTable = db.LocalAuthorization.Where(l => l.CustomId == ctdata.MachineCustomId).FirstOrDefault();
  666. if (localauthTable != null) //查詢電樁是否已建立 Local Authorization Table
  667. {
  668. //下發GetLocalListVersion.req
  669. logger.Trace("set CMD1011 to ServerCommand");
  670. Cmd1011 cmd1011 = ctdata.CmdHelper.Create(1011) as Cmd1011;
  671. cmd1011.CmdSerNum = ctdata.GetCmdSerNum();
  672. cmd1011.SerNum = ctdata.GetSerNum();
  673. cmd1011.Pack();
  674. ServerCommand sc1011 = new ServerCommand();
  675. sc1011.OutCmdNum = cmd1011.Cmd;
  676. sc1011.CreatedOn = DateTime.Now;
  677. sc1011.MachineId = ctdata.MachineId;
  678. sc1011.MachineCustomId = ctdata.MachineCustomId;
  679. sc1011.OutTransData = cmd1011.byteList.ToArray();
  680. db.ServerCommand.Add(sc1011);
  681. db.SaveChanges();
  682. }
  683. }
  684. else if (((BootNotificationConfirmation)conf).status == RegistrationStatus.Pending)
  685. {
  686. BootNotificationPending = true;
  687. }
  688. }
  689. //回傳Confirm Message給電樁
  690. string confirmType = string.Empty;
  691. if (call.action.Contains("DataTransfer"))
  692. {
  693. confirmType = call.action + " Confirm(" + ((DataTransferRequest)(result.Payload)).messageId + ")";
  694. }
  695. else
  696. confirmType = call.action + " Confirm";
  697. Send(ctdata, ocppMsgHandler.GenerateCallResult(call.id, conf), confirmType);
  698. //若BootNotification的status為Pending,後台送出 GetConfiguration Request 給電樁
  699. if (BootNotificationPending == true)
  700. {
  701. IRequest req = MakeRequestHandler.MakeGetConfigurationRequest();
  702. string uuid = ctdata.queue.store(req);
  703. Send(ctdata, ocppMsgHandler.GenerateCall(uuid, Actions.GetConfiguration.ToString(), req), "GetConfiguration Request");
  704. BootNotificationPending = false;
  705. }
  706. if (handleRequestResult.Message != null)
  707. {
  708. //送 UpdateFirmware封包給電樁
  709. if (handleRequestResult.Message.Contains("UpdateFirmware"))
  710. {
  711. //DataTransfer的下發升級指令
  712. Send(ctdata, handleRequestResult.Message, "UpdateFirmware Request");
  713. }
  714. //在回覆StartTransaction.conf後,下發SetChargingProfile.req
  715. if (handleRequestResult.Message.Contains("SetChargingProfile"))
  716. {
  717. //下發SetChargingProfile.req
  718. Send(ctdata, handleRequestResult.Message, "SetChargingProfile Request");
  719. }
  720. //下發 APP 餘額/卡片餘額
  721. if (handleRequestResult.Message.Contains("AccountBalance"))
  722. {
  723. //判斷是否為會員
  724. if (ocppMsgHandler.IsMemberCharging((IRequest)result.Payload, db) == false)
  725. {
  726. var machine = machineSrv.GetByCustomId(ctdata.MachineCustomId);
  727. SendElectricityRates(machine, ctdata);
  728. }
  729. //下發AccountBalance.req
  730. Send(ctdata, handleRequestResult.Message, "AccountBalance Request");
  731. }
  732. }
  733. }
  734. else
  735. {
  736. if (ENABLELOG_MACHINECMD)
  737. {
  738. //紀錄error type message
  739. MachineConnectionLog log = new MachineConnectionLog();
  740. log.MachineCustomId = ctdata.MachineCustomId;
  741. log.MachineId = ctdata.MachineId;
  742. log.IpPort = ctdata.LocalEndPoint.ToString();
  743. log.IsIllegal = true;
  744. log.IsDataOut = false;
  745. log.CmdNum = 0;
  746. if (msg.Length >= 2000)
  747. log.Data = msg.Substring(0, 1999);
  748. else
  749. log.Data = msg;
  750. log.CreatedOn = DateTime.Now;
  751. log.Msg = handleRequestResult.Message;
  752. var ep = ((IPEndPoint)ctdata.RemoteEndPoint);
  753. log.ClientIpPort = ep.Address.ToString() + ":" + ep.Port.ToString();
  754. SaveMachineConnectionLog(log);
  755. if (msg.Length >= 2000) // BMS錯誤封包
  756. {
  757. MachineConnectionLog log1 = new MachineConnectionLog();
  758. log1.MachineCustomId = ctdata.MachineCustomId;
  759. log1.MachineId = ctdata.MachineId;
  760. log1.IpPort = ctdata.LocalEndPoint.ToString();
  761. log1.IsIllegal = true;
  762. log1.IsDataOut = false;
  763. log1.CmdNum = 0;
  764. log1.Data = "ChargingGunBMS :" + msg.Substring(2000, msg.Length - 2000);
  765. log1.CreatedOn = DateTime.Now;
  766. log1.Msg = handleRequestResult.Message;
  767. var ep1 = ((IPEndPoint)ctdata.RemoteEndPoint);
  768. log1.ClientIpPort = ep1.Address.ToString() + ":" + ep1.Port.ToString();
  769. SaveMachineConnectionLog(log1);
  770. }
  771. }
  772. //送出錯誤訊息給電樁
  773. Send(ctdata, ocppMsgHandler.GenerateCallError(call.id, "NotImplemented", handleRequestResult.Message), "NotImplemented");
  774. }
  775. }
  776. else
  777. {
  778. #region error type 處理
  779. if (ENABLELOG_MACHINECMD)
  780. {
  781. //紀錄error type message
  782. MachineConnectionLog log = new MachineConnectionLog();
  783. log.MachineCustomId = ctdata.MachineCustomId;
  784. log.MachineId = ctdata.MachineId;
  785. log.IpPort = ctdata.LocalEndPoint.ToString();
  786. log.IsIllegal = true;
  787. log.IsDataOut = false;
  788. log.CmdNum = 0;
  789. log.Data = msg;
  790. log.CreatedOn = DateTime.Now;
  791. //紀錄exception, 送出錯誤訊息給電樁
  792. if (result.Exception != null)
  793. {
  794. logger.Error(result.Exception, "OnCall error");
  795. log.Msg = result.Exception.ToString();
  796. }
  797. else
  798. {
  799. Send(ctdata, result.Message, "Error Message");
  800. log.Msg = result.Message;
  801. }
  802. var ep = ((IPEndPoint)ctdata.RemoteEndPoint);
  803. log.ClientIpPort = ep.Address.ToString() + ":" + ep.Port.ToString();
  804. SaveMachineConnectionLog(log);
  805. }
  806. #endregion error type 處理
  807. }
  808. #endregion 處理CallMessage
  809. }
  810. }
  811. catch (SocketException e)
  812. {
  813. logger.Trace("disconnected:{0}", ctdata.MachineCustomId);
  814. RemoveClient(ctdata);
  815. return;
  816. }
  817. catch (ObjectDisposedException e)
  818. {
  819. logger.Trace("ObjectDisposedException:{0}", ctdata.MachineCustomId);
  820. //RemoveClientDic(client);
  821. return;
  822. }
  823. catch (DbEntityValidationException e)
  824. {
  825. StringBuilder sb = new StringBuilder();
  826. foreach (var eve in e.EntityValidationErrors)
  827. {
  828. sb.AppendLine(string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
  829. eve.Entry.Entity.GetType().Name,
  830. eve.Entry.State));
  831. foreach (var ve in eve.ValidationErrors)
  832. {
  833. sb.AppendLine(string.Format("- Property: \"{0}\", Error: \"{1}\"",
  834. ve.PropertyName,
  835. ve.ErrorMessage));
  836. }
  837. }
  838. logger.Warn(e);
  839. }
  840. catch (Exception e)
  841. {
  842. logger.Warn(e);
  843. }
  844. finally
  845. {
  846. uow.Dispose();
  847. }
  848. }
  849. }
  850. /// <summary>
  851. /// 增加電樁到ClientDic
  852. /// </summary>
  853. private void OCPP_ClientDicAdded(ClientData ctdata)
  854. {
  855. //刪除重複的機器
  856. if (ClientDic.ContainsKey(ctdata.MachineCustomId))
  857. {
  858. //刪除重複機器
  859. var dupClient = ClientDic[ctdata.MachineCustomId];
  860. RemoveClient(dupClient);
  861. }
  862. //刪掉剛連線的紀錄
  863. lock (_lockClientDic)
  864. {
  865. if (ClientDic.ContainsKey(ctdata.MachineCustomIdTemp))
  866. {
  867. ClientDic.Remove(ctdata.MachineCustomIdTemp);
  868. logger.Trace("delete connect record {0}", ctdata.MachineCustomId);
  869. }
  870. var oldMachineCustomId = ctdata.MachineCustomId;
  871. ctdata.MachineCustomIdTemp = ctdata.MachineCustomId;
  872. ctdata.IsCheckIn = true;
  873. logger.Trace("connect id {0} check in id {1}", oldMachineCustomId, ctdata.MachineCustomId);
  874. ClientDic.Add(ctdata.MachineCustomId, ctdata);
  875. }
  876. }
  877. /// <summary>
  878. /// 從ClientDic取出電樁
  879. /// </summary>
  880. private void OCPP_ClientDataRemoved(ClientData ctdata)
  881. {
  882. RemoveClient(ctdata);
  883. }
  884. private void AppServer_SessionClosed(ClientData session, CloseReason reason)
  885. {
  886. logger.Trace("Enter AppServer_SessionClosed()");
  887. lock (_lockClientDic)
  888. {
  889. ClientData client;
  890. if (!String.IsNullOrEmpty(session.Path))
  891. {
  892. string[] words = session.Path.Split('/');
  893. if (ClientDic.ContainsKey(words.Last()))
  894. {
  895. if (ClientDic.TryGetValue(words.Last(), out client))
  896. {
  897. ClientDic.Remove(words.Last());
  898. logger.Trace("RemoveClient ContainsKey" + words.Last());
  899. client = null;
  900. }
  901. }
  902. else
  903. {
  904. if((session.MachineCustomId != null) && (session.MachineCustomIdTemp != null))
  905. {
  906. if (ClientDic.TryGetValue(session.MachineCustomId, out client))
  907. {
  908. ClientDic.Remove(session.MachineCustomId);
  909. logger.Trace("RemoveClient ContainsKey" + words.Last());
  910. client = null;
  911. }
  912. else if (ClientDic.TryGetValue(session.MachineCustomIdTemp, out client))
  913. {
  914. ClientDic.Remove(session.MachineCustomIdTemp);
  915. logger.Trace("RemoveClient ContainsKey" + words.Last());
  916. client = null;
  917. }
  918. }
  919. }
  920. }
  921. }
  922. }
  923. private void AppServer_NewSessionConnected(ClientData client)
  924. {
  925. try
  926. {
  927. client.m_ReceiveData += new ClientData.OCPPClientDataEventHandler<ClientData, String>(ReceivedMessage);
  928. lock (_lockClientDic)
  929. {
  930. ClientDic.Add(client.MachineCustomId, client);
  931. }
  932. logger.Trace("client: " + client.MachineCustomId + " in");
  933. using (var db = new PhihongDbContext())
  934. {
  935. if (ENABLELOG_MACHINECMD)
  936. {
  937. // 紀錄電樁的新連線資訊
  938. MachineConnectionLog log = new MachineConnectionLog();
  939. log.MachineCustomId = client.MachineCustomId;
  940. log.MachineId = client.MachineId;
  941. log.IpPort = client.LocalEndPoint.ToString();
  942. log.IsIllegal = true;
  943. log.IsDataOut = false;
  944. log.CmdNum = 0;
  945. log.CreatedOn = DateTime.Now;
  946. var ep = ((IPEndPoint)client.RemoteEndPoint);
  947. log.ClientIpPort = ep.ToString();
  948. log.Msg = "connect";
  949. SaveMachineConnectionLog(log);
  950. }
  951. }
  952. }
  953. catch (Exception ex)
  954. {
  955. logger.Warn(ex);
  956. RemoveClient(client);
  957. }
  958. }
  959. public void Stop()
  960. {
  961. _cts.Cancel();
  962. var list = ClientDic.Select(c => c.Value).ToList();
  963. foreach (var c in list)
  964. {
  965. RemoveClient(c);
  966. }
  967. }
  968. public void RemoveClient(ClientData client)
  969. {
  970. logger.Trace("RemoveClient" + client.MachineCustomId);
  971. if (client != null)
  972. {
  973. try
  974. {
  975. client.Close(CloseReason.ServerClosing);
  976. }
  977. catch (Exception ex)
  978. {
  979. //logger.Warn("Close client socket error!!");
  980. logger.Warn(string.Format("Close client socket error!! {0} Msg:{1}", client.MachineCustomId, ex.Message));
  981. }
  982. client.m_ReceiveData -= new ClientData.OCPPClientDataEventHandler<ClientData, String>(ReceivedMessage);
  983. client.Close();
  984. // logger.Trace("Close client socket!!");
  985. logger.Trace("Close client socket!!" + client.MachineCustomId);
  986. RemoveClientDic(client);
  987. logger.Trace("RemoveClient null" + client.MachineCustomId);
  988. if (client != null)
  989. {
  990. client = null;
  991. }
  992. }
  993. }
  994. public void RemoveClientDic(ClientData client)
  995. {
  996. lock (_lockClientDic)
  997. {
  998. if (ClientDic.ContainsKey(client.MachineCustomId))
  999. {
  1000. ClientDic.Remove(client.MachineCustomId);
  1001. logger.Trace("RemoveClient ContainsKey" + client.MachineCustomId);
  1002. }
  1003. }
  1004. }
  1005. public void ServerCommandThread()
  1006. {
  1007. for (; ; )
  1008. {
  1009. if (_ct.IsCancellationRequested)
  1010. {
  1011. break;
  1012. }
  1013. logger.Trace("command loop");
  1014. logger.Trace("ClientDic:" + ClientDic.Count().ToString());
  1015. logger.Trace("NeedConfirmPacketList:" + NeedConfirmPacketList.Count().ToString());
  1016. try
  1017. {
  1018. var redirect = ConfigurationManager.AppSettings.Get("Redirect");
  1019. if (redirect.Equals("1"))
  1020. {
  1021. System.Threading.Thread.Sleep(1000);
  1022. continue;
  1023. }
  1024. using (var db = new PhihongDbContext())
  1025. {
  1026. ProcessServerCommand(db);
  1027. ProcessConfirmPacket();
  1028. System.Threading.Thread.Sleep(1000);
  1029. //每小時發送校時
  1030. var ts = DateTime.Now - sendTiming;
  1031. if (ts.TotalHours > 1)
  1032. {
  1033. Timing(db);
  1034. sendTiming = DateTime.Now;
  1035. }
  1036. //每5分鐘檢查
  1037. ts = DateTime.Now - checkUpdateDt;
  1038. if (ts.TotalMinutes > 5)
  1039. {
  1040. logger.Trace("check sw update");
  1041. CheckSW(db);
  1042. logger.Trace("check fw update");
  1043. CheckFW(db);
  1044. checkUpdateDt = DateTime.Now;
  1045. }
  1046. }
  1047. }
  1048. catch (Exception ex)
  1049. {
  1050. logger.Error("server stop");
  1051. logger.Error(ex);
  1052. }
  1053. }
  1054. }
  1055. private void ProcessServerCommand(PhihongDbContext db)
  1056. {
  1057. OCPPMessageHandler ocppMsgHandler = new OCPPMessageHandler();
  1058. string respone = String.Empty;
  1059. string messageType = string.Empty;
  1060. var machineList = ClientDic.Select(c => c.Key).ToList();
  1061. DateTime startDt = DateTime.Now.AddSeconds(-30);
  1062. var commandList = db.ServerCommand.Where(c => !c.UpdatedOn.HasValue && c.CreatedOn >= startDt && c.CreatedOn <= DateTime.Now).ToList().Where(c => machineList.Contains(c.MachineCustomId)).ToList();
  1063. //處理主機傳送的有指令
  1064. var cmdMachineList = commandList.Select(c => c.MachineCustomId).Distinct().ToList();
  1065. foreach (var cmdMachine in cmdMachineList)
  1066. {
  1067. ClientData client;
  1068. if (ClientDic.TryGetValue(cmdMachine, out client))
  1069. {
  1070. //有簽到或測試指令模式
  1071. if (client.IsCheckIn)
  1072. {
  1073. var cmdList = commandList.Where(c => c.MachineCustomId == cmdMachine && c.OutTransData != null).ToList();
  1074. foreach (var item in cmdList)
  1075. {
  1076. BaseCmd c = client.CmdHelper.UpPack(item.OutTransData.ToList());
  1077. int reservationId = 0;
  1078. int chargingProfileId = 0;
  1079. if (c is CmdError)
  1080. {
  1081. continue;
  1082. }
  1083. if (c is Cmd1005) //Remote結束充電
  1084. {
  1085. var cmd = c as Cmd1005;
  1086. //Cancel預約reservationId
  1087. if (cmd.ParamIndex == 10)
  1088. {
  1089. //槍號=> reservationID, OCPP 槍號從1 開始
  1090. reservationId = cmd.GunSerNo + 1;
  1091. }
  1092. }
  1093. else if (c is Cmd1007) //Remote啟動充電, 如果是發送充電指令的,送一次費率過去
  1094. {
  1095. var cmd = c as Cmd1007;
  1096. IMachineService machineSrv = new MachineService();
  1097. var machine = machineSrv.GetByCustomId(item.MachineCustomId);
  1098. SendElectricityRates(machine, client);
  1099. //產生定時充電/預約 reservationId
  1100. if (cmd.StartChargingType == 1 || cmd.StartChargingType == 2)
  1101. {
  1102. //槍號=> reservationID, OCPP 槍號從1 開始
  1103. reservationId = cmd.GunSerNo + 1;
  1104. }
  1105. client.CarType = Convert.ToInt32(cmd.VehicleType);
  1106. }
  1107. else if (c is Cmd9015) //ocpp command : SetChargingProfile
  1108. {
  1109. var cmd9015 = c as Cmd9015;
  1110. chargingProfileId = client.GetChargingProfileId();
  1111. }
  1112. respone = ocppMsgHandler.HandleServerCommand(c, client.MachineCustomId, ref client.queue, ref client.configurationKey, reservationId, chargingProfileId, out messageType, db);
  1113. item.OutTransData = CmdUtil.ToByteArray(respone, respone.Length);//System.Text.UTF8Encoding.Default.GetBytes(respone);//c.byteList.ToArray();
  1114. item.UpdatedOn = DateTime.Now;
  1115. db.SaveChanges();
  1116. Send(client, respone, messageType);
  1117. AddConfirmPacket(client, c, respone, item.Id, messageType);
  1118. respone = String.Empty;
  1119. Thread.Sleep(1);
  1120. }
  1121. }
  1122. }
  1123. }
  1124. }
  1125. /// <summary>
  1126. /// 送出指令
  1127. /// </summary>
  1128. /// <param name="client"></param>
  1129. /// <param name="cmd"></param>
  1130. /// <returns></returns>
  1131. private bool Send(ClientData client, string ocppmessage, string messageType)
  1132. {
  1133. try
  1134. {
  1135. if (String.IsNullOrEmpty(ocppmessage) == true)
  1136. return false;
  1137. using (var db = new PhihongDbContext())
  1138. {
  1139. if (ENABLELOG_MACHINECMD)
  1140. {
  1141. MachineConnectionLog log = new MachineConnectionLog();
  1142. log.MachineCustomId = client.MachineCustomId;
  1143. log.MachineId = client.MachineId;
  1144. log.IpPort = client.LocalEndPoint.ToString();
  1145. if (ocppmessage.Length > 2000)
  1146. log.Data = ocppmessage.Substring(0, 1999);
  1147. else
  1148. log.Data = ocppmessage;
  1149. //log.Data = ocppmessage;
  1150. log.IsDataOut = true;
  1151. log.CmdNum = 0;
  1152. log.CreatedOn = DateTime.Now;
  1153. log.Msg = messageType;
  1154. var ep = ((IPEndPoint)client.RemoteEndPoint);
  1155. log.ClientIpPort = ep.Address.ToString() + ":" + ep.Port.ToString();
  1156. SaveMachineConnectionLog(log);
  1157. if (ocppmessage.Length >= 2000) // BMS封包
  1158. {
  1159. MachineConnectionLog log1 = new MachineConnectionLog();
  1160. log1.MachineCustomId = client.MachineCustomId;
  1161. log1.MachineId = client.MachineId;
  1162. log1.IpPort = client.LocalEndPoint.ToString();
  1163. log1.IsIllegal = false;
  1164. log1.IsDataOut = false;
  1165. log1.CmdNum = 0;
  1166. log1.Data = "Key :" + ocppmessage.Substring(2000, ocppmessage.Length - 2000);
  1167. log1.CreatedOn = DateTime.Now;
  1168. log1.Msg = messageType;
  1169. var ep1 = ((IPEndPoint)client.RemoteEndPoint);
  1170. log1.ClientIpPort = ep1.Address.ToString() + ":" + ep1.Port.ToString();
  1171. SaveMachineConnectionLog(log1);
  1172. }
  1173. }
  1174. }
  1175. client.Send(ocppmessage);
  1176. }
  1177. catch (Exception ex)
  1178. {
  1179. RemoveClient(client);
  1180. logger.Error(ex);
  1181. return false;
  1182. }
  1183. return true;
  1184. }
  1185. /// <summary>
  1186. /// 判斷數據包的指令,是否需要確認
  1187. /// </summary>
  1188. /// <param name="cmd"></param>
  1189. public void AddConfirmPacket(ClientData client, BaseCmd cmd, string sentmessage, int id, string messageType)
  1190. {
  1191. if (String.IsNullOrEmpty(sentmessage) == true)
  1192. return;
  1193. NeedConfirmPacket p = new NeedConfirmPacket();
  1194. var array = JsonConvert.DeserializeObject<JArray>(sentmessage);
  1195. p.Id = id;
  1196. //p.CmdSerNum = cmd.CmdSerNum;
  1197. p.SentInterval = 10;
  1198. p.SentTimes = 3;
  1199. p.MachineCustomId = client.MachineCustomId;
  1200. p.SentMessage = sentmessage;
  1201. p.SentAction = messageType;
  1202. if (_needConfirmCmdList.Contains(cmd.Cmd))
  1203. {
  1204. p.SentUniqueId = array[1].ToString();
  1205. lock (_lockConfirmPacketList)
  1206. {
  1207. NeedConfirmPacketList.Add(p);
  1208. logger.Trace("Add NeedConfirmPacketList ");
  1209. }
  1210. }
  1211. }
  1212. private void Timing(PhihongDbContext db)
  1213. {
  1214. var list = ClientDic.Values.Where(c => c.IsCheckIn).ToList();
  1215. foreach (var item in list)
  1216. {
  1217. logger.Trace(item.MachineCustomId + ":sent commant timing");
  1218. Cmd1003 cmd3 = item.CmdHelper.Create(1003) as Cmd1003;
  1219. cmd3.ParamByteLength = 8;
  1220. cmd3.Type = 1;
  1221. cmd3.ParamIndex = 2;
  1222. cmd3.ParamByteList.AddRange(CmdUtil.ToByteArray(DateTime.Now));
  1223. cmd3.Pack();
  1224. ServerCommand sc2 = new ServerCommand();
  1225. sc2.OutCmdNum = cmd3.Cmd;
  1226. sc2.CreatedOn = DateTime.Now;
  1227. sc2.MachineId = item.MachineId;
  1228. sc2.MachineCustomId = item.MachineCustomId;
  1229. sc2.OutTransData = cmd3.byteList.ToArray();
  1230. db.ServerCommand.Add(sc2);
  1231. db.SaveChanges();
  1232. }
  1233. }
  1234. /// <summary>
  1235. /// 確認機器版本
  1236. /// </summary>
  1237. /// <param name="db"></param>
  1238. private void CheckSW(PhihongDbContext db)
  1239. {
  1240. OCPPMessageHandler ocppMsgHandler = new OCPPMessageHandler();
  1241. string respone = String.Empty;
  1242. if (ClientDic.Count() == 0)
  1243. return;
  1244. foreach (var item in ClientDic)
  1245. {
  1246. logger.Trace("check sw loop");
  1247. logger.Trace("check sw" + item.Value.MachineCustomId);
  1248. var machine = db.Machine.Where(c => c.Id == item.Value.MachineId).AsNoTracking().FirstOrDefault();
  1249. if (machine == null)
  1250. {
  1251. logger.Error("check sw,can't find machine " + item.Value.MachineCustomId);
  1252. continue;
  1253. }
  1254. if (machine.SW_AssignedMachineVersionId.HasValue)
  1255. {
  1256. logger.Trace(machine.CustomId + "asinged sw value");
  1257. var mv = db.MachineVersion.Include(c => c.PublishVersion)
  1258. .Include(c => c.PublishVersion.PublishVersionFiles)
  1259. .Include(c => c.PublishVersion.PublishVersionFiles.Select(z => z.UploadFile))
  1260. .Where(c => c.Id == machine.SW_AssignedMachineVersionId.Value).First();
  1261. logger.Trace(mv.Id + "get sw value");
  1262. if (!machine.SW_VersionReport.HasValue || machine.SW_VersionReport.Value != mv.PublishVersion.Version)
  1263. {
  1264. logger.Trace(machine.CustomId + "ready to sent commmand to update sw ");
  1265. UploadFile uploadFile;
  1266. //ipc 就更新清單,非ipc就更新檔案
  1267. if (mv.PublishVersion.UpdateJsonUploadFileId == null)
  1268. uploadFile = mv.PublishVersion.PublishVersionFiles.First().UploadFile;
  1269. else
  1270. uploadFile = db.UploadFile.Find(mv.PublishVersion.UpdateJsonUploadFileId.Value);
  1271. byte param = 0;
  1272. //DataTransfer的下發升級指令
  1273. respone = ocppMsgHandler.HandleUpdateFirmware(ref item.Value.queue, 1, (ProgramParam)param, uploadFile);
  1274. Send(item.Value, respone, "UpdateFirmware Request");
  1275. ////OCPP 的下發升級指令
  1276. //respone = String.Empty;
  1277. //string fileurl = @"http://" + uploadFile.FileUrl;
  1278. //respone = ocppMsgHandler.HandleOCPPUpdateFirmware(ref item.Value.queue, fileurl);
  1279. //Send(item.Value, respone);
  1280. logger.Trace(item.Key + ":sent command to update sw");
  1281. }
  1282. }
  1283. }
  1284. }
  1285. /// <summary>
  1286. /// 確認機器版本
  1287. /// </summary>
  1288. /// <param name="db"></param>
  1289. private void CheckFW(PhihongDbContext db)
  1290. {
  1291. OCPPMessageHandler ocppMsgHandler = new OCPPMessageHandler();
  1292. string respone = String.Empty;
  1293. foreach (var item in ClientDic)
  1294. {
  1295. logger.Trace("check fw loop");
  1296. logger.Trace("check fw" + item.Value.MachineCustomId);
  1297. var machine = db.Machine.Where(c => c.Id == item.Value.MachineId).AsNoTracking().FirstOrDefault();
  1298. if (machine == null)
  1299. {
  1300. logger.Error("check fw,can't find machine" + item.Value.MachineCustomId);
  1301. continue;
  1302. }
  1303. if (machine.FW_AssignedMachineVersionId.HasValue)
  1304. {
  1305. logger.Trace(machine.CustomId + "assigned fw update value");
  1306. var mv = db.MachineVersion.Include(c => c.PublishVersion)
  1307. .Include(c => c.PublishVersion.PublishVersionFiles)
  1308. .Include(c => c.PublishVersion.PublishVersionFiles.Select(z => z.UploadFile))
  1309. .Where(c => c.Id == machine.FW_AssignedMachineVersionId.Value).First();
  1310. logger.Trace(mv.Id + "get fw update value");
  1311. if (!machine.FW_VersionReport.HasValue || machine.FW_VersionReport.Value != mv.PublishVersion.Version)
  1312. {
  1313. logger.Trace(machine.CustomId + "ready to sent command to update fw");
  1314. UploadFile uploadFile;
  1315. List<UploadFile> ufList = new List<UploadFile>();
  1316. //ipc 就更新清單,非ipc就更新檔案
  1317. if (mv.PublishVersion.UpdateJsonUploadFileId == null)
  1318. {
  1319. ufList.AddRange(mv.PublishVersion.PublishVersionFiles.Select(c => c.UploadFile).ToList());
  1320. //uploadFile = mv.PublishVersion.PublishVersionFiles.First().UploadFile;
  1321. }
  1322. else
  1323. {
  1324. uploadFile = db.UploadFile.Find(mv.PublishVersion.UpdateJsonUploadFileId.Value);
  1325. ufList.Add(uploadFile);
  1326. }
  1327. foreach (var f in ufList)
  1328. {
  1329. byte param = 0;
  1330. if (mv.PublishVersion.UpdateJsonUploadFileId == null)
  1331. {
  1332. param = (byte)f.FwTagId.Value;
  1333. }
  1334. if (param == 28) // HMI-B2
  1335. continue;
  1336. //DataTransfer的下發升級指令
  1337. respone = ocppMsgHandler.HandleUpdateFirmware(ref item.Value.queue, 2, (ProgramParam)param, f);
  1338. Send(item.Value, respone, "DataTransfer Request(UpdateFirmware)");
  1339. ////OCPP 的下發升級指令
  1340. //respone = String.Empty;
  1341. //string fileurl = @"http://" + f.FileUrl;
  1342. //respone = ocppMsgHandler.HandleOCPPUpdateFirmware(ref item.Value.queue, fileurl);
  1343. //Send(item.Value, respone);
  1344. logger.Trace(item.Key + ":send command to update fw");
  1345. }
  1346. }
  1347. }
  1348. }
  1349. }
  1350. /// <summary>
  1351. /// 處理需確認的數據包
  1352. /// </summary>
  1353. private void ProcessConfirmPacket()
  1354. {
  1355. List<NeedConfirmPacket> removeList = new List<NeedConfirmPacket>();
  1356. //處理需要重送的數據包
  1357. var count = NeedConfirmPacketList.Count;
  1358. for (int i = 0; i < count; i++)
  1359. {
  1360. var item = NeedConfirmPacketList[i];
  1361. //這個要移除,不處理
  1362. if (item.SentTimes <= 0 && item.SentInterval <= 0)
  1363. {
  1364. removeList.Add(item);
  1365. continue;
  1366. }
  1367. //要處理送出
  1368. if (--item.SentInterval <= 0)
  1369. {
  1370. ClientData client;
  1371. if (ClientDic.TryGetValue(item.MachineCustomId, out client))
  1372. {
  1373. //有簽到或測試指令模式
  1374. if (client.IsCheckIn)
  1375. {
  1376. Send(client, item.SentMessage, item.SentAction);
  1377. }
  1378. }
  1379. //如果已經到了次數限制,3,就不再送了
  1380. if (--item.SentTimes <= 0)
  1381. {
  1382. item.SentTimes = 0;
  1383. item.SentInterval = 0;
  1384. removeList.Add(item);
  1385. }
  1386. else
  1387. {
  1388. //把間隔秒數set 3
  1389. item.SentInterval = 10;
  1390. }
  1391. }
  1392. }
  1393. //移除已經結束的數據包
  1394. lock (_lockConfirmPacketList)
  1395. {
  1396. foreach (var item in removeList)
  1397. {
  1398. NeedConfirmPacketList.Remove(item);
  1399. logger.Trace("delete needConfirmPacketList MachineCustomId:{0},UUID:{1}", item.MachineCustomId, item.SentUniqueId);
  1400. }
  1401. }
  1402. }
  1403. /// <summary>
  1404. /// 送出電費及服務費率
  1405. /// </summary>
  1406. /// <param name="machine"></param>
  1407. /// <param name="client"></param>
  1408. private void SendElectricityRates(Machine machine, ClientData client)
  1409. {
  1410. using (var db = new PhihongDbContext())
  1411. {
  1412. if (machine.Customer.SinglePricePerKWH)
  1413. {
  1414. //設定每度費用
  1415. Cmd2301 cmd2301 = client.CmdHelper.Create(2301) as Cmd2301;
  1416. cmd2301.CmdSerNum = client.GetCmdSerNum();
  1417. cmd2301.SerNum = client.GetSerNum();
  1418. cmd2301.PricePerKWH.RealValue = machine.PricePerKWH;
  1419. cmd2301.Pack();
  1420. ServerCommand sc1 = new ServerCommand();
  1421. sc1.OutCmdNum = cmd2301.Cmd;
  1422. sc1.CreatedOn = DateTime.Now;
  1423. sc1.MachineId = client.MachineId;
  1424. sc1.MachineCustomId = client.MachineCustomId;
  1425. sc1.OutTransData = cmd2301.byteList.ToArray();
  1426. db.ServerCommand.Add(sc1);
  1427. db.SaveChanges();
  1428. }
  1429. else
  1430. {
  1431. Cmd2303 cmd2303 = client.CmdHelper.Create(2303) as Cmd2303;
  1432. cmd2303.CmdSerNum = client.GetCmdSerNum();
  1433. cmd2303.SerNum = client.GetSerNum();
  1434. cmd2303.Section0000_0030.RealValue = machine.Section0000_0030;
  1435. cmd2303.Section0030_0100.RealValue = machine.Section0030_0100;
  1436. cmd2303.Section0100_0130.RealValue = machine.Section0100_0130;
  1437. cmd2303.Section0130_0200.RealValue = machine.Section0130_0200;
  1438. cmd2303.Section0200_0230.RealValue = machine.Section0200_0230;
  1439. cmd2303.Section0230_0300.RealValue = machine.Section0230_0300;
  1440. cmd2303.Section0300_0330.RealValue = machine.Section0300_0330;
  1441. cmd2303.Section0330_0400.RealValue = machine.Section0330_0400;
  1442. cmd2303.Section0400_0430.RealValue = machine.Section0400_0430;
  1443. cmd2303.Section0430_0500.RealValue = machine.Section0430_0500;
  1444. cmd2303.Section0500_0530.RealValue = machine.Section0500_0530;
  1445. cmd2303.Section0530_0600.RealValue = machine.Section0530_0600;
  1446. cmd2303.Section0600_0630.RealValue = machine.Section0600_0630;
  1447. cmd2303.Section0630_0700.RealValue = machine.Section0630_0700;
  1448. cmd2303.Section0700_0730.RealValue = machine.Section0700_0730;
  1449. cmd2303.Section0730_0800.RealValue = machine.Section0730_0800;
  1450. cmd2303.Section0800_0830.RealValue = machine.Section0800_0830;
  1451. cmd2303.Section0830_0900.RealValue = machine.Section0830_0900;
  1452. cmd2303.Section0900_0930.RealValue = machine.Section0900_0930;
  1453. cmd2303.Section0930_1000.RealValue = machine.Section0930_1000;
  1454. cmd2303.Section1000_1030.RealValue = machine.Section1000_1030;
  1455. cmd2303.Section1030_1100.RealValue = machine.Section1030_1100;
  1456. cmd2303.Section1100_1130.RealValue = machine.Section1100_1130;
  1457. cmd2303.Section1130_1200.RealValue = machine.Section1130_1200;
  1458. cmd2303.Section1200_1230.RealValue = machine.Section1200_1230;
  1459. cmd2303.Section1230_1300.RealValue = machine.Section1230_1300;
  1460. cmd2303.Section1300_1330.RealValue = machine.Section1300_1330;
  1461. cmd2303.Section1330_1400.RealValue = machine.Section1330_1400;
  1462. cmd2303.Section1400_1430.RealValue = machine.Section1400_1430;
  1463. cmd2303.Section1430_1500.RealValue = machine.Section1430_1500;
  1464. cmd2303.Section1500_1530.RealValue = machine.Section1500_1530;
  1465. cmd2303.Section1530_1600.RealValue = machine.Section1530_1600;
  1466. cmd2303.Section1600_1630.RealValue = machine.Section1600_1630;
  1467. cmd2303.Section1630_1700.RealValue = machine.Section1630_1700;
  1468. cmd2303.Section1700_1730.RealValue = machine.Section1700_1730;
  1469. cmd2303.Section1730_1800.RealValue = machine.Section1730_1800;
  1470. cmd2303.Section1800_1830.RealValue = machine.Section1800_1830;
  1471. cmd2303.Section1830_1900.RealValue = machine.Section1830_1900;
  1472. cmd2303.Section1900_1930.RealValue = machine.Section1900_1930;
  1473. cmd2303.Section1930_2000.RealValue = machine.Section1930_2000;
  1474. cmd2303.Section2000_2030.RealValue = machine.Section2000_2030;
  1475. cmd2303.Section2030_2100.RealValue = machine.Section2030_2100;
  1476. cmd2303.Section2100_2130.RealValue = machine.Section2100_2130;
  1477. cmd2303.Section2130_2200.RealValue = machine.Section2130_2200;
  1478. cmd2303.Section2200_2230.RealValue = machine.Section2200_2230;
  1479. cmd2303.Section2230_2300.RealValue = machine.Section2230_2300;
  1480. cmd2303.Section2300_2330.RealValue = machine.Section2300_2330;
  1481. cmd2303.Section2330_2400.RealValue = machine.Section2330_2400;
  1482. cmd2303.Pack();
  1483. ServerCommand sc2 = new ServerCommand();
  1484. sc2.OutCmdNum = cmd2303.Cmd;
  1485. sc2.CreatedOn = DateTime.Now;
  1486. sc2.MachineId = client.MachineId;
  1487. sc2.MachineCustomId = client.MachineCustomId;
  1488. sc2.OutTransData = cmd2303.byteList.ToArray();
  1489. db.ServerCommand.Add(sc2);
  1490. db.SaveChanges();
  1491. }
  1492. //設定每度服務費
  1493. Cmd2305 cmd2305 = client.CmdHelper.Create(2305) as Cmd2305;
  1494. cmd2305.CmdSerNum = client.GetCmdSerNum();
  1495. cmd2305.SerNum = client.GetSerNum();
  1496. cmd2305.FeePerKWH.RealValue = machine.FeePerKWH;
  1497. cmd2305.Pack();
  1498. ServerCommand sc3 = new ServerCommand();
  1499. sc3.OutCmdNum = cmd2305.Cmd;
  1500. sc3.CreatedOn = DateTime.Now;
  1501. sc3.MachineId = client.MachineId;
  1502. sc3.MachineCustomId = client.MachineCustomId;
  1503. sc3.OutTransData = cmd2305.byteList.ToArray();
  1504. db.ServerCommand.Add(sc3);
  1505. db.SaveChanges();
  1506. }
  1507. }
  1508. private void CheckConfirmPacket(ClientData client, BaseMessage message)
  1509. {
  1510. lock (_lockConfirmPacketList)
  1511. {
  1512. logger.Trace("CheckConfirmPacket NeedConfirmPacketList:" + NeedConfirmPacketList.Count().ToString());
  1513. //檢查 Call Message/ CallResult Message / CallError Message的 UniqueId屬性, 是否與 NeedConfirmPacket的 SentUniqueId屬性 一致
  1514. var item = NeedConfirmPacketList.Where(c => c.MachineCustomId == client.MachineCustomId && c.SentUniqueId == message.id).FirstOrDefault();
  1515. if (item != null)
  1516. {
  1517. logger.Trace("check CheckConfirmPacket MachineCustomId:{0},SentUniqueId:{1}", item.MachineCustomId, item.SentUniqueId);
  1518. using (var db = new PhihongDbContext())
  1519. {
  1520. var sc = db.ServerCommand.Where(c => c.Id == item.Id).FirstOrDefault();
  1521. object payload = null;
  1522. if (sc.OutCmdNum == 1001)
  1523. {
  1524. // 當 Heartbeat 與 上一個 Heartbeat相差值小於2秒,判斷是否送出ChangeConfiguration.req(HeartbeatInterval: 15) 給電樁
  1525. client.IsSendHeartbeatChangeConfiguration = false;
  1526. }
  1527. else if (sc.OutCmdNum == 9001)
  1528. {
  1529. sc.InCmdNum = 9002; /*9002為Cmd9002, 目前Packet Cmd沒有建立此Command*/
  1530. }
  1531. else if (sc.OutCmdNum == 9003)
  1532. {
  1533. sc.InCmdNum = 9004; /*9004為Cmd9004, 目前Packet Cmd沒有建立此Command*/
  1534. }
  1535. else if (sc.OutCmdNum == 9005)
  1536. {
  1537. sc.InCmdNum = 9006; /*9006為Cmd9006, 目前Packet Cmd沒有建立此Command*/
  1538. }
  1539. else if (sc.OutCmdNum == 9007)
  1540. {
  1541. sc.InCmdNum = 9008; /*9008為Cmd9008, 目前Packet Cmd沒有建立此Command*/
  1542. }
  1543. else if (sc.OutCmdNum == 9009)
  1544. {
  1545. sc.InCmdNum = 9010; /*9010為Cmd9010, 目前Packet Cmd沒有建立此Command*/
  1546. }
  1547. else if (sc.OutCmdNum == 9011)
  1548. {
  1549. sc.InCmdNum = 9012; /*9012為Cmd9012, 目前Packet Cmd沒有建立此Command*/
  1550. }
  1551. else if (sc.OutCmdNum == 9013)
  1552. {
  1553. sc.InCmdNum = 9014; /*9014為Cmd9014, 目前Packet Cmd沒有建立此Command*/
  1554. }
  1555. else if (sc.OutCmdNum == 9015)
  1556. {
  1557. sc.InCmdNum = 9016; /*9016為Cmd9016, 目前Packet Cmd沒有建立此Command*/
  1558. }
  1559. else if (sc.OutCmdNum == 9017)
  1560. {
  1561. sc.InCmdNum = 9018; /*9018為Cmd9018, 目前Packet Cmd沒有建立此Command*/
  1562. }
  1563. else if (sc.OutCmdNum == 9019)
  1564. {
  1565. sc.InCmdNum = 9020; /*9020為Cmd9020, 目前Packet Cmd沒有建立此Command*/
  1566. }
  1567. else if (sc.OutCmdNum == 9021)
  1568. {
  1569. sc.InCmdNum = 9022; /*9022為Cmd9022, 目前Packet Cmd沒有建立此Command*/
  1570. }
  1571. else if (sc.OutCmdNum == 9023)
  1572. {
  1573. sc.InCmdNum = 9024; /*9024為Cmd9024, 目前Packet Cmd沒有建立此Command*/
  1574. }
  1575. else if (sc.OutCmdNum == 9025)
  1576. {
  1577. sc.InCmdNum = 9026; /*9026為Cmd9026, 目前Packet Cmd沒有建立此Command*/
  1578. }
  1579. else if (sc.OutCmdNum == 9027)
  1580. {
  1581. sc.InCmdNum = 9028; /*9028為Cmd9028, 目前Packet Cmd沒有建立此Command*/
  1582. }
  1583. else if (sc.OutCmdNum == 9029)
  1584. {
  1585. sc.InCmdNum = 9030; /*9030為Cmd9030, 目前Packet Cmd沒有建立此Command*/
  1586. }
  1587. else if (sc.OutCmdNum == 9031)
  1588. {
  1589. sc.InCmdNum = 9032; /*9032為Cmd9032, 目前Packet Cmd沒有建立此Command*/
  1590. }
  1591. else
  1592. {
  1593. sc.InCmdNum = 0;
  1594. }
  1595. if (message is CallResultMessage)
  1596. {
  1597. CallResultMessage call = (CallResultMessage)message;
  1598. payload = call.payload;
  1599. }
  1600. else if (message is CallErrorMessage)
  1601. {
  1602. CallErrorMessage call = (CallErrorMessage)message;
  1603. payload = call.payload;
  1604. }
  1605. else if (message is CallMessage)
  1606. {
  1607. CallMessage call = (CallMessage)message;
  1608. payload = call.payload;
  1609. }
  1610. //sc.InTransData = CmdUtil.ToByteArray(message.ToString(), message.ToString().Length);//System.Text.UTF8Encoding.Default.GetBytes(message.ToString());
  1611. sc.InTransData = CmdUtil.ToByteArray(payload.ToString(), payload.ToString().Length);//System.Text.UTF8Encoding.Default.GetBytes(message.ToString());
  1612. sc.ReceivedOn = DateTime.Now;
  1613. db.SaveChanges();
  1614. item.SentInterval = 0;
  1615. item.SentTimes = 0;
  1616. logger.Trace("reply NeedConfirmPacket MachineCustomId:{0},SentUniqueId:{1}", item.MachineCustomId, item.SentUniqueId);
  1617. }
  1618. }
  1619. }
  1620. }
  1621. private void SaveMachineConnectionLog(MachineConnectionLog log)
  1622. {
  1623. if (System.Configuration.ConfigurationManager.AppSettings["mongoDb"] != null)
  1624. {
  1625. try
  1626. {
  1627. MMachineConnectionLog mlog = new MMachineConnectionLog();
  1628. mlog.MachineCustomId = log.MachineCustomId;
  1629. mlog.MachineId = log.MachineId;
  1630. mlog.IpPort = log.IpPort;
  1631. mlog.IsIllegal = log.IsIllegal;
  1632. mlog.IsDataOut = log.IsDataOut;
  1633. mlog.CmdNum = log.CmdNum;
  1634. mlog.CreatedOn = log.CreatedOn;
  1635. mlog.ClientIpPort = log.ClientIpPort;
  1636. mlog.Msg = log.Msg;
  1637. mlog.Data = log.Data;
  1638. IMongoDatabase database = mongoService.getMongoDatabase();
  1639. var mdb = database.GetCollection<MMachineConnectionLog>(Globals._col_MachineConnectionLog);
  1640. mdb.InsertOne(mlog);
  1641. }
  1642. catch (Exception e)
  1643. {
  1644. logger.Trace("mongo MachineConnectionLog error:" + e.Message);
  1645. }
  1646. }
  1647. else
  1648. {
  1649. using (var db = new PhihongDbContext())
  1650. {
  1651. db.MachineConnectionLog.Add(log);
  1652. db.SaveChanges();
  1653. }
  1654. }
  1655. }
  1656. }
  1657. }