private void init (string hostname, IPAddress address, int port, bool secure #if SSHARP , EthernetAdapterType adapter #endif ) { _hostname = hostname ?? convertToString (address); _address = address; _port = port; _secure = secure; #if SSHARP _adapter = adapter; #endif _listener = new HttpListener (); _listener.Prefixes.Add ( String.Format ("http{0}://{1}:{2}/", secure ? "s" : "", _hostname, port)); _logger = _listener.Log; _services = new WebSocketServiceManager (_logger); _sync = new object (); var os = Environment.OSVersion; #if NETCF _windows = os.Platform != PlatformID.Unix; #else _windows = os.Platform != PlatformID.Unix && os.Platform != PlatformID.MacOSX; #endif }
/// <summary> /// Initializes a new instance of the <see cref="HttpServer"/> class with /// the specified HTTP URL. /// </summary> /// <remarks> /// <para> /// An instance initialized by this constructor listens for the incoming requests on /// the host name and port in <paramref name="url"/>. /// </para> /// <para> /// If <paramref name="url"/> doesn't include a port, either port 80 or 443 is used on /// which to listen. It's determined by the scheme (http or https) in <paramref name="url"/>. /// (Port 80 if the scheme is http.) /// </para> /// </remarks> /// <param name="url"> /// A <see cref="string"/> that represents the HTTP URL of the server. /// </param> /// <param name="adapter"> /// An EthernetAdapterType for the EthernetAdapter to use for the connection /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="url"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="url"/> is empty. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="url"/> is invalid. /// </para> /// </exception> public HttpServer (string url, EthernetAdapterType adapter) { #endif if (url == null) throw new ArgumentNullException ("url"); if (url.Length == 0) throw new ArgumentException ("An empty string.", "url"); Uri uri; string msg; if (!tryCreateUri (url, out uri, out msg)) throw new ArgumentException (msg, "url"); var host = getHost (uri); var addr = host.ToIPAddress (); if (!addr.IsLocal ()) throw new ArgumentException ("The host part isn't a local host name: " + url, "url"); init (host, addr, uri.Port, uri.Scheme == "https" #if SSHARP , adapter #endif ); }
public ViscaOverIpSocket(string ipAddress, EthernetAdapterType adapterType, int port) { _ipAddress = ipAddress; _port = port; _socket = new UDPServer(IPAddress.Parse(ipAddress), port, 1000, adapterType); CrestronEnvironment.ProgramStatusEventHandler += type => { _programStopping = type == eProgramStatusEventType.Stopping; }; }
internal EndPointListener(IPEndPoint endpoint, bool secure, string certificateFolderPath, #if !NETCF || BCC || SSL ServerSslConfiguration sslConfig, #endif bool reuseAddress, #if SSHARP EthernetAdapterType adapter, #endif Logger logger) { _logger = logger; #if !NETCF || BCC || SSL if (secure) { var cert = getCertificate(endpoint.Port, certificateFolderPath, sslConfig.ServerCertificate); if (cert == null) { throw new ArgumentException("No server certificate could be found."); } _secure = true; _sslConfig = new ServerSslConfiguration( cert, sslConfig.ClientCertificateRequired, sslConfig.EnabledSslProtocols, sslConfig.CheckCertificateRevocation ); _sslConfig.ClientCertificateValidationCallback = sslConfig.ClientCertificateValidationCallback; } #endif _endpoint = endpoint; _prefixes = new Dictionary <HttpListenerPrefix, HttpListener> (); _unregistered = new Dictionary <HttpConnection, HttpConnection> (); _unregisteredSync = ((ICollection)_unregistered).SyncRoot; #if SSHARP _socket = new CrestronListenerSocket(IPAddress.Any, endpoint.Port, 16, adapter); #else _socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); if (reuseAddress) { _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); } #endif _socket.Bind(endpoint); _socket.Listen(500); _socket.BeginAccept(onAccept, this); }
/// <summary> /// Initializes a new instance of the <see cref="HttpServer"/> class with /// the specified <paramref name="address"/>, <paramref name="port"/>, /// and <paramref name="secure"/>. /// </summary> /// <remarks> /// An instance initialized by this constructor listens for the incoming requests on /// <paramref name="address"/> and <paramref name="port"/>. /// </remarks> /// <param name="address"> /// A <see cref="IPAddress"/> that represents the local IP address of the server. /// </param> /// <param name="port"> /// An <see cref="int"/> that represents the port number on which to listen. /// </param> /// <param name="secure"> /// A <see cref="bool"/> that indicates providing a secure connection or not. /// (<c>true</c> indicates providing a secure connection.) /// </param> /// <param name="adapter"> /// An EthernetAdapterType for the EthernetAdapter to use for the connection /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="address"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="address"/> isn't a local IP address. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="port"/> isn't between 1 and 65535 inclusive. /// </exception> public HttpServer (IPAddress address, int port, bool secure, EthernetAdapterType adapter) { if (address == null) throw new ArgumentNullException ("address"); if (!address.IsLocal ()) throw new ArgumentException ("Not a local IP address: " + address, "address"); if (!port.IsPortNumber ()) throw new ArgumentOutOfRangeException ( "port", "Not between 1 and 65535 inclusive: " + port); init (null, address, port, secure, adapter); }
/// <summary> /// Initializes a new instance of the <see cref="HttpServer"/> class with the specified /// <paramref name="port"/> and <paramref name="secure"/>. /// </summary> /// <remarks> /// An instance initialized by this constructor listens for the incoming requests /// on <paramref name="port"/>. /// </remarks> /// <param name="port"> /// An <see cref="int"/> that represents the port number on which to listen. /// </param> /// <param name="secure"> /// A <see cref="bool"/> that indicates providing a secure connection or not. /// (<c>true</c> indicates providing a secure connection.) /// </param> /// <param name="adapter"> /// An EthernetAdapterType for the EthernetAdapter to use for the connection /// </param> /// <exception cref="ArgumentException"> /// Pair of <paramref name="port"/> and <paramref name="secure"/> is invalid. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="port"/> isn't between 1 and 65535 inclusive. /// </exception> public HttpServer (int port, bool secure, EthernetAdapterType adapter) { #endif if (!port.IsPortNumber ()) throw new ArgumentOutOfRangeException ("port", "Not between 1 and 65535 inclusive: " + port); init ("*", IPAddress.Any, port, secure #if SSHARP , adapter #endif ); Log.Info ("HttpServer created on port {0} on adapter {1} with security {2}", port, adapter, secure); }
public CodecFeedbackServer(CiscoCodec codec, EthernetAdapterType ethernetAdapter, int feedbackListenerPort) { AdapterForIPAddress = ethernetAdapter; Codec = codec; server = new HttpServer(OnReceivedData, EthernetAdapterType.EthernetUnknownAdapter); server.Port = feedbackListenerPort; server.ServerName = "Cisco Codec Feedback Listener"; server.Active = true; server.KeepAlive = true; server.EnableNagle = true; #if DEBUG CrestronConsole.PrintLine("Created Codec Feedback HttpServer"); CrestronConsole.PrintLine(" {0,50} = {1}", "server.EthernetAdapterToBindTo", server.EthernetAdapterToBindTo); CrestronConsole.PrintLine(" {0,50} = {1}", "server.ServerName", server.ServerName); CrestronConsole.PrintLine(" {0,50} = {1}", "server.ValidateRequests", server.ValidateRequests); CrestronConsole.PrintLine(" {0,50} = {1}", "server.BindV4", server.BindV4); CrestronConsole.PrintLine(" {0,50} = {1}", "server.BindingV4.BindingAddress", server.BindingV4.BindingAddress); CrestronConsole.PrintLine(" {0,50} = {1}", "server.BindingV4.EnableNagle", server.BindingV4.EnableNagle); CrestronConsole.PrintLine(" {0,50} = {1}", "server.BindingV4.EndPointAddress", server.BindingV4.EndPointAddress); CrestronConsole.PrintLine(" {0,50} = {1}", "server.BindingV4.EndPointPortNumber", server.BindingV4.EndPointPortNumber); CrestronConsole.PrintLine(" {0,50} = {1}", "server.BindingV4.Port", server.BindingV4.Port); #endif }
protected object ConnectionThreadProcess(object o) { var memoryStream = new MemoryStream(); var reader = new StreamReader(memoryStream); var receivedAnything = false; while (true) { var connectCount = 0; while (_remainConnected && !Connected) { connectCount++; _client.AddressClientConnectedTo = _currentAddress; Debug.WriteInfo(GetType().Name, "Address to connect to set to {0}", _currentAddress); var result = _client.ConnectToServer(); if (result == SocketErrorCodes.SOCKET_OK) { CloudLog.Notice("{0} connected to {1}", GetType().Name, _client.AddressClientConnectedTo); receivedAnything = false; break; } TryAnotherAddress(); if (connectCount <= 4 || connectCount > 10) { continue; } if (connectCount == 10) { CloudLog.Error("{0} failed to connect to any address, will keep trying in background", GetType().Name); } else { CloudLog.Warn("{0} cannot connect to address: {1}", GetType().Name, _currentAddress); } CrestronEnvironment.AllowOtherAppsToRun(); } _pollTimer = new CTimer(specific => DoNothing(), null, 30000, 30000); _adapterType = _client.EthernetAdapter; while (true) { var dataCount = _client.ReceiveData(); if (dataCount <= 0) { Debug.WriteWarn(GetType().Name, "Disconnected!"); _pollTimer.Stop(); _pollTimer.Dispose(); _pollTimer = null; if (_remainConnected) { if (!receivedAnything) { CloudLog.Warn( "{0} connected but didn't receive anything." + "Will wait for 1 minute before reconnection attempt. Upgrade may be in progress.", GetType().Name); Thread.Sleep(60000); } break; } Debug.WriteWarn("Exiting Thread", Thread.CurrentThread.Name); return(null); } receivedAnything = true; #if DEBUG Debug.WriteInfo(GetType().Name, "{0} bytes in buffer", dataCount); #endif for (var i = 0; i < dataCount; i++) { var b = _client.IncomingDataBuffer[i]; if (b != 0) { memoryStream.WriteByte(b); continue; } memoryStream.Position = 0; try { var data = JToken.Parse(reader.ReadToEnd()); memoryStream.SetLength(0); #if DEBUG Debug.WriteInfo(_name + " Rx", Debug.AnsiBlue + data.ToString(Formatting.None) + Debug.AnsiReset); #endif if (data["method"] != null) { OnRequestReceived(this, new QsysRequest(data)); } else if (data["id"] != null) { var id = data["id"].Value <int>(); if (_requests.ContainsKey(id)) { var request = _requests[id]; _requests.Remove(id); OnResponseReceived(this, new QsysResponse(data, request)); } } } catch (Exception e) { CloudLog.Exception("Error occured processing a complete data parcel from Core", e); } } CrestronEnvironment.AllowOtherAppsToRun(); Thread.Sleep(0); } } }
/// <summary> /// Create an instance of a Cisco VC Codec /// </summary> /// <param name="controlSystem"></param> /// <param name="hostNameOrIPAddress">The IP Address or hostname of the codec</param> /// <param name="username">Username to login to the system</param> /// <param name="password">Password to login to the system</param> /// <param name="ethernetAdapter">Ther EthernetAdapterType of the control system used to connect and receive data</param> /// <param name="feedbackListenerPort">The port to be used for the feedback server on the control system</param> /// <param name="feedbackSlot">The slot on the codec to use for registering feedback. Should be 1-4 (3 is reserved for TMS so avoid that value)</param> public CiscoCodec(CrestronControlSystem controlSystem, string hostNameOrIPAddress, string username, string password, EthernetAdapterType ethernetAdapter, int feedbackListenerPort, int feedbackSlot) { ControlSystem = controlSystem; HttpClient = new CodecHTTPClient(hostNameOrIPAddress, username, password); FeedbackServer = new CodecFeedbackServer(this, ethernetAdapter, feedbackListenerPort); FeedbackServer.ReceivedData += new CodecFeedbackServerReceiveEventHandler(FeedbackServer_ReceivedData); FeedbackServer.IncomingCallEvent += new CodecIncomingCallEventHandler(FeedbackServer_IncomingCallEvent); FeedbackServer.WidgetActionEvent += new CodecUserInterfaceWidgetActionEventHandler(FeedbackServer_WidgetActionEvent); FeedbackSlot = feedbackSlot; CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler); SystemUnit = new SystemUnit(this); SystemUnit.State.SystemStateChange += new SystemUnitStateSystemChangeEventHandler(State_SystemStateChange); Audio = new Audio(this); Calls = new Calls(this); Conference = new Conference(this); Network = new Network(this); Phonebook = new Phonebook(this); Cameras = new Cameras(this); Video = new Video(this); Capabilities = new Capabilities(this); Standby = new Standby(this); UserInterface = new UserInterface(this); }
/// <summary> /// Determines whether the specified <see cref="System.Net.IPAddress"/> represents /// a local IP address. /// </summary> /// <returns> /// <c>true</c> if <paramref name="address"/> represents a local IP address; /// otherwise, <c>false</c>. /// <remarks> /// This local means NOT REMOTE for the current host. /// </remarks> /// </returns> /// <param name="address"> /// A <see cref="System.Net.IPAddress"/> to test. /// </param> /// <param name="adapter">adapter number to test against</param> /// <param name="adapterType">EthernetAdapterType to test against</param> public static bool IsLocal(this IPAddress address, EthernetAdapterType adapterType) { return (address.IsLocal(adapterType == EthernetAdapterType.EthernetUnknownAdapter ? (short)-1 : CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(adapterType))); }
private static void addPrefix(string uriPrefix, HttpListener listener #if SSHARP , EthernetAdapterType adapter #endif ) { var pref = new HttpListenerPrefix(uriPrefix); var addr = convertToIPAddress(pref.Host); if (!addr.IsLocal()) { throw new HttpListenerException(87, "Includes an invalid host."); } int port; #if SSHARP if (!Int32Ex.TryParse(pref.Port, out port)) #else if (!Int32.TryParse(pref.Port, out port)) #endif { throw new HttpListenerException(87, "Includes an invalid port."); } if (!port.IsPortNumber()) { throw new HttpListenerException(87, "Includes an invalid port."); } var path = pref.Path; if (path.IndexOf('%') != -1) { throw new HttpListenerException(87, "Includes an invalid path."); } if (path.IndexOf("//", StringComparison.Ordinal) != -1) { throw new HttpListenerException(87, "Includes an invalid path."); } var endpoint = new IPEndPoint(addr, port); EndPointListener lsnr; if (_endpoints.TryGetValue(endpoint, out lsnr)) { if (lsnr.IsSecure ^ pref.IsSecure) { throw new HttpListenerException(87, "Includes an invalid scheme."); } } else { lsnr = new EndPointListener(endpoint, pref.IsSecure, listener.CertificateFolderPath, #if !NETCF || BCC || SSL listener.SslConfiguration, #endif listener.ReuseAddress, #if SSHARP adapter, #endif listener.Log); _endpoints.Add(endpoint, lsnr); } lsnr.AddPrefix(pref, listener); }
public CrestronIPEndPoint(long address, int port, EthernetAdapterType adapterType) : base(address, port) { AdapterType = adapterType; }
public CrestronIPEndPoint(long address, int port) : base(address, port) { AdapterType = EthernetAdapterType.EthernetUnknownAdapter; }
private object ConnectionThreadProcess(object o) { try { while (true) { var connectCount = 0; while (_remainConnected && !Connected) { if (_client.ClientStatus == SocketStatus.SOCKET_STATUS_LINK_LOST) { Thread.Sleep(5000); continue; } connectCount++; var result = _client.ConnectToServer(); if (result == SocketErrorCodes.SOCKET_OK) { CrestronConsole.PrintLine("{0} connected to {1}", GetType().Name, _client.AddressClientConnectedTo); try { OnConnect(); OnStatusChanged(SocketStatusEventType.Connected); } catch (Exception e) { CloudLog.Exception(e); } break; } if (connectCount <= 2 || connectCount > 5) { continue; } if (connectCount == 5) { CloudLog.Error("{0} failed to connect to address: {1}, will keep trying in background", GetType().Name, _client.AddressClientConnectedTo); } CrestronEnvironment.AllowOtherAppsToRun(); } _adapterType = _client.EthernetAdapter; while (true) { var dataCount = _client.ReceiveData(); if (dataCount <= 0) { CrestronConsole.PrintLine("{0} Disconnected!", GetType().Name); try { OnStatusChanged(SocketStatusEventType.Disconnected); OnDisconnect(); } catch (Exception e) { CloudLog.Exception(e); } if (_remainConnected) { Thread.Sleep(2000); if (_client.ClientStatus == SocketStatus.SOCKET_STATUS_LINK_LOST) { CloudLog.Warn("{0} Ethernet Link Lost! - sleeping thread until back up", GetType().Name); } break; } CrestronConsole.PrintLine("Exiting {0}", Thread.CurrentThread.Name); return(null); } //CrestronConsole.PrintLine("{0} {1} bytes in buffer", GetType().Name, dataCount); try { OnReceive(_client.IncomingDataBuffer, dataCount); } catch (Exception e) { CloudLog.Exception(e); } CrestronEnvironment.AllowOtherAppsToRun(); Thread.Sleep(0); } } } catch (Exception e) { if (_remainConnected) { CloudLog.Exception("Error in handler thread while connected / connecting", e); } return(null); } }
public ViscaOverIpSocket(string ipAddress, EthernetAdapterType adapterType) : this(ipAddress, adapterType, 52381) { }
protected object ConnectionThreadProcess(object o) { var index = 0; var bytes = new byte[_client.IncomingDataBuffer.Length]; try { while (true) { var connectCount = 0; while (_remainConnected && !Connected) { connectCount++; var result = _client.ConnectToServer(); if (result == SocketErrorCodes.SOCKET_OK) { CloudLog.Notice("{0} connected to {1}", GetType().Name, _client.AddressClientConnectedTo); break; } if (connectCount <= 2 || connectCount > 5) { continue; } if (connectCount == 5) { CloudLog.Error("{0} failed to connect to address: {1}, will keep trying in background", GetType().Name, _client.AddressClientConnectedTo); } else { CloudLog.Warn("{0} cannot connect to address: {1}", GetType().Name, _client.AddressClientConnectedTo); } CrestronEnvironment.AllowOtherAppsToRun(); } _pollTimer = new CTimer(specific => Send("show device status all"), null, 1000, 30000); _adapterType = _client.EthernetAdapter; while (true) { var dataCount = _client.ReceiveData(); if (dataCount <= 0) { CloudLog.Debug("{0} Disconnected!", GetType().Name); _pollTimer.Stop(); _pollTimer.Dispose(); if (_remainConnected) { break; } CloudLog.Debug("Exiting {0}", Thread.CurrentThread.Name); return(null); } var promptReceived = false; if (dataCount >= 7) { var lastBytes = new byte[7]; Array.Copy(_client.IncomingDataBuffer, dataCount - 7, lastBytes, 0, 7); var endString = Encoding.UTF8.GetString(lastBytes, 0, lastBytes.Length); if (endString == "Zyper$ ") { promptReceived = true; } } #if DEBUG //CrestronConsole.PrintLine("{0} {1} bytes in buffer, promptReceived = {2}", GetType().Name, dataCount, // promptReceived); //Tools.PrintBytes(_client.IncomingDataBuffer, 0, dataCount, true); #endif for (var i = 0; i < dataCount; i++) { bytes[index] = _client.IncomingDataBuffer[i]; index++; } if (promptReceived) { if (bytes[0] == 0xFF) { #if DEBUG var mode = 0; foreach (var b in bytes) { if (b == 0xFF) { mode = 0; CrestronConsole.Print("ZeeVee Socket Telnet Command Received:"); continue; } if (mode == 0) { switch (b) { case 254: CrestronConsole.Print(" DONT"); break; case 253: CrestronConsole.Print(" DO"); break; case 252: CrestronConsole.Print(" WONT"); break; case 251: CrestronConsole.Print(" WILL"); break; default: CrestronConsole.Print(" {0}", b); break; } mode = 1; continue; } if (mode != 1) { continue; } switch (b) { case 1: CrestronConsole.PrintLine(" Echo"); break; case 3: CrestronConsole.PrintLine(" Suppress Go Ahead"); break; case 5: CrestronConsole.PrintLine(" Status"); break; case 6: CrestronConsole.PrintLine(" Timing Mark"); break; case 24: CrestronConsole.PrintLine(" Terminal Type"); break; case 31: CrestronConsole.PrintLine(" Window Size"); break; case 32: CrestronConsole.PrintLine(" Terminal Speed"); break; case 33: CrestronConsole.PrintLine(" Remote Flow Control"); break; case 34: CrestronConsole.PrintLine(" Linemode"); break; case 36: CrestronConsole.PrintLine(" Environment Variables"); break; default: CrestronConsole.PrintLine(" {0}", b); break; } mode = 2; } #endif index = 0; } else { var data = Encoding.UTF8.GetString(bytes, 0, index - 7); #if DEBUG CrestronConsole.PrintLine("Received response from ZeeVee:\r\n{0}", data); #endif OnReceivedData(this, data); index = 0; } } CrestronEnvironment.AllowOtherAppsToRun(); Thread.Sleep(0); } } } catch (Exception e) { CloudLog.Exception(string.Format("Error in {0}, {1}", Thread.CurrentThread.Name, e.Message), e); CrestronConsole.PrintLine("Error in {0}", Thread.CurrentThread.Name); CrestronConsole.PrintLine("Index = {0}", index); CrestronConsole.Print("Bytes: "); Tools.PrintBytes(bytes, 0, index, true); if (_pollTimer != null && !_pollTimer.Disposed) { _pollTimer.Stop(); _pollTimer.Dispose(); } if (_client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED) { _client.DisconnectFromServer(); } return(null); } }