using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Crestron.SimplSharp; using Crestron.SimplSharp.CrestronSockets; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace PepperDash.Core { /// /// A class to handle basic TCP/IP communications with a server /// public class GenericTcpIpClient : Device, ISocketStatus, IAutoReconnect { /// /// Fires when data is received from the server and returns it as a Byte array /// public event EventHandler BytesReceived; /// /// Fires when data is received from the server and returns it as text /// public event EventHandler TextReceived; /// /// /// //public event GenericSocketStatusChangeEventDelegate SocketStatusChange; public event EventHandler ConnectionChange; private string _Hostname { get; set;} /// /// Address of server /// public string Hostname { get { return _Hostname; } set { _Hostname = value; if (Client != null) { Client.AddressClientConnectedTo = _Hostname; } } } /// /// Port on server /// public int Port { get; set; } /// /// Another damn S+ helper because S+ seems to treat large port nums as signed ints /// which screws up things /// public ushort UPort { get { return Convert.ToUInt16(Port); } set { Port = Convert.ToInt32(value); } } /// /// Defaults to 2000 /// public int BufferSize { get; set; } /// /// The actual client class /// public TCPClient Client { get; private set; } /// /// True if connected to the server /// public bool IsConnected { get { return Client != null && Client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED; } } /// /// S+ helper for IsConnected /// public ushort UIsConnected { get { return (ushort)(IsConnected ? 1 : 0); } } /// /// Status of the socket /// public SocketStatus ClientStatus { get { if (Client == null) return SocketStatus.SOCKET_STATUS_NO_CONNECT; return Client.ClientStatus; } } /// /// Contains the familiar Simpl analog status values. This drives the ConnectionChange event /// and IsConnected with be true when this == 2. /// public ushort UStatus { get { return (ushort)ClientStatus; } } /// /// Status of the socket /// public string ClientStatusText { get { return ClientStatus.ToString(); } } [Obsolete] /// /// Ushort representation of client status /// public ushort UClientStatus { get { return (ushort)ClientStatus; } } /// /// Connection failure reason /// public string ConnectionFailure { get { return ClientStatus.ToString(); } } /// /// If true, enables AutoConnect /// public bool AutoReconnect { get; set; } /// /// S+ helper for AutoReconnect /// public ushort UAutoReconnect { get { return (ushort)(AutoReconnect ? 1 : 0); } set { AutoReconnect = value == 1; } } /// /// Milliseconds to wait before attempting to reconnect. Defaults to 5000 /// public int AutoReconnectIntervalMs { get; set; } /// /// Set only when the disconnect method is called. /// bool DisconnectCalledByUser; /// /// /// public bool Connected { get { return Client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED; } } CTimer RetryTimer; /// /// Constructor /// /// /// /// /// public GenericTcpIpClient(string key, string address, int port, int bufferSize) : base(key) { Hostname = address; Port = port; BufferSize = bufferSize; AutoReconnectIntervalMs = 5000; CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler); } /// /// Constructor /// /// public GenericTcpIpClient(string key) : base(key) { CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler); AutoReconnectIntervalMs = 5000; BufferSize = 2000; } /// /// Default constructor for S+ /// public GenericTcpIpClient() : base("Uninitialized TcpIpClient") { CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler); AutoReconnectIntervalMs = 5000; BufferSize = 2000; } /// /// Just to help S+ set the key /// public void Initialize(string key) { Key = key; } /// /// Handles closing this up when the program shuts down /// void CrestronEnvironment_ProgramStatusEventHandler(eProgramStatusEventType programEventType) { if (programEventType == eProgramStatusEventType.Stopping) { Debug.Console(1, this, "Program stopping. Closing connection"); DisconnectClient(); } } /// /// /// /// public override bool Deactivate() { if (Client != null) { Client.SocketStatusChange -= this.Client_SocketStatusChange; DisconnectClient(); } return true; } /// /// Attempts to connect to the server /// public void Connect() { if (IsConnected) DisconnectClient(); if (string.IsNullOrEmpty(Hostname)) { Debug.Console(1, Debug.ErrorLogLevel.Warning, "GenericTcpIpClient '{0}': No address set", Key); return; } if (Port < 1 || Port > 65535) { { Debug.Console(1, Debug.ErrorLogLevel.Warning, "GenericTcpIpClient '{0}': Invalid port", Key); return; } } if (Client == null) { Client = new TCPClient(Hostname, Port, BufferSize); Client.SocketStatusChange -= Client_SocketStatusChange; Client.SocketStatusChange += Client_SocketStatusChange; } DisconnectCalledByUser = false; Client.ConnectToServerAsync(ConnectToServerCallback); // (null); } /// /// Attempts to disconnect the client /// public void Disconnect() { if (Client != null) { DisconnectCalledByUser = true; DisconnectClient(); Client = null; Debug.Console(1, this, "Disconnected"); } } /// /// Does the actual disconnect business /// public void DisconnectClient() { if (Client != null) { Debug.Console(1, this, "Disconnecting client"); if(IsConnected) Client.DisconnectFromServer(); } } /// /// Callback method for connection attempt /// /// void ConnectToServerCallback(TCPClient c) { Debug.Console(1, this, "Server connection result: {0}", c.ClientStatus); if (c.ClientStatus != SocketStatus.SOCKET_STATUS_CONNECTED) WaitAndTryReconnect(); } /// /// Disconnects, waits and attemtps to connect again /// void WaitAndTryReconnect() { DisconnectClient(); Debug.Console(1, "Attempting reconnect, status={0}", Client.ClientStatus); if(!DisconnectCalledByUser) RetryTimer = new CTimer(o => { Client.ConnectToServerAsync(ConnectToServerCallback); }, AutoReconnectIntervalMs); } /// /// Recieves incoming data /// /// /// void Receive(TCPClient client, int numBytes) { if (numBytes > 0) { var bytes = client.IncomingDataBuffer.Take(numBytes).ToArray(); var bytesHandler = BytesReceived; if (bytesHandler != null) bytesHandler(this, new GenericCommMethodReceiveBytesArgs(bytes)); var textHandler = TextReceived; if (textHandler != null) { var str = Encoding.GetEncoding(28591).GetString(bytes, 0, bytes.Length); textHandler(this, new GenericCommMethodReceiveTextArgs(str)); } } Client.ReceiveDataAsync(Receive); } /// /// General send method /// public void SendText(string text) { var bytes = Encoding.GetEncoding(28591).GetBytes(text); // Check debug level before processing byte array //if (Debug.Level == 2) // Debug.Console(2, this, "Sending {0} bytes: '{1}'", bytes.Length, ComTextHelper.GetEscapedText(bytes)); if(Client != null) Client.SendData(bytes, bytes.Length); } /// /// This is useful from console and...? /// public void SendEscapedText(string text) { var unescapedText = Regex.Replace(text, @"\\x([0-9a-fA-F][0-9a-fA-F])", s => { var hex = s.Groups[1].Value; return ((char)Convert.ToByte(hex, 16)).ToString(); }); SendText(unescapedText); } /// /// Sends Bytes to the server /// /// public void SendBytes(byte[] bytes) { //if (Debug.Level == 2) // Debug.Console(2, this, "Sending {0} bytes: '{1}'", bytes.Length, ComTextHelper.GetEscapedText(bytes)); if(Client != null) Client.SendData(bytes, bytes.Length); } /// /// Socket Status Change Handler /// /// /// void Client_SocketStatusChange(TCPClient client, SocketStatus clientSocketStatus) { Debug.Console(1, this, "Socket status change {0} ({1})", clientSocketStatus, ClientStatusText); if (client.ClientStatus != SocketStatus.SOCKET_STATUS_CONNECTED && !DisconnectCalledByUser && AutoReconnect) WaitAndTryReconnect(); // Probably doesn't need to be a switch since all other cases were eliminated switch (clientSocketStatus) { case SocketStatus.SOCKET_STATUS_CONNECTED: Client.ReceiveDataAsync(Receive); DisconnectCalledByUser = false; break; } var handler = ConnectionChange; if (handler != null) ConnectionChange(this, new GenericSocketStatusChageEventArgs(this)); // Relay the event //var handler = SocketStatusChange; //if (handler != null) // SocketStatusChange(this); } } /// /// Configuration properties for TCP/SSH Connections /// public class TcpSshPropertiesConfig { /// /// Address to connect to /// [JsonProperty(Required = Required.Always)] public string Address { get; set; } /// /// Port to connect to /// [JsonProperty(Required = Required.Always)] public int Port { get; set; } /// /// Username credential /// public string Username { get; set; } /// /// Passord credential /// public string Password { get; set; } /// /// Defaults to 32768 /// public int BufferSize { get; set; } /// /// Defaults to true /// public bool AutoReconnect { get; set; } /// /// Defaults to 5000ms /// public int AutoReconnectIntervalMs { get; set; } public TcpSshPropertiesConfig() { BufferSize = 32768; AutoReconnect = true; AutoReconnectIntervalMs = 5000; Username = ""; Password = ""; } } }