using EVCB_OCPP.Domain; using SuperSocket.Common; using SuperWebSocket; using SuperWebSocket.SubProtocol; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Text; namespace OCPPServer.Protocol { public class OCPPWSServer : WebSocketServer { /// /// 可允許連線Clinet數 /// public int connectNum { get; set; } /// /// 是否限制連線Clinet數 /// public bool beConnectLimit { get; set; } /// /// Initializes a new instance of the class. /// /// The sub protocols. public OCPPWSServer(IEnumerable> subProtocols) : base(subProtocols) { } /// /// Initializes a new instance of the class. /// /// The sub protocol. public OCPPWSServer(ISubProtocol subProtocol) : base(subProtocol) { } /// /// Initializes a new instance of the class. /// public OCPPWSServer() : base(new List>()) { } protected override bool ValidateClientCertificate(ClientData session, object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { // Console.WriteLine(string.Format("{0} :{1}", session.ChargeBoxId + " ValidateClientCertificate", sslPolicyErrors)); return true; // return base.ValidateClientCertificate(session, sender, certificate, chain, sslPolicyErrors); } protected override bool ValidateHandshake(ClientData session, string origin) { string[] words = session.Path.Split('/'); session.ChargeBoxId = words.Last(); // Console.WriteLine(string.Format("{0} :ValidateHandshake: {1}", DateTime.Now.ToString("yy/MM/dd HH:mm:ss.fff"), session.Path)); bool isExistedSN = false; using (var db = new MainDBContext()) { var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefault(); session.CustomerId = machine == null ? Guid.Empty : machine.CustomerId; session.MachineId = machine == null ? String.Empty : machine.Id; isExistedSN = machine == null ? false : true; } if (!isExistedSN) { StringBuilder responseBuilder = new StringBuilder(); responseBuilder.AppendFormatWithCrCf(@"HTTP/{0} {1} {2}", "1.1", (int)HttpStatusCode.NotFound, @"Not Found"); responseBuilder.AppendWithCrCf(); string sb = responseBuilder.ToString(); byte[] data = Encoding.UTF8.GetBytes(sb); ((IWebSocketSession)session).SendRawData(data, 0, data.Length); return false; } return true; } } }