Merge pull request #156 from PepperDash/release/1.2.0

1.2.0
This commit is contained in:
Andrew Welker
2023-03-01 11:01:37 -07:00
committed by GitHub
10 changed files with 748 additions and 202 deletions

View File

@@ -65,12 +65,9 @@ namespace PepperDash.Core
public bool IsConnected public bool IsConnected
{ {
// returns false if no client or not connected // returns false if no client or not connected
get { return ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED; } get { return Client != null && ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED; }
} }
private bool IsConnecting = false;
private bool DisconnectLogged = false;
/// <summary> /// <summary>
/// S+ helper for IsConnected /// S+ helper for IsConnected
/// </summary> /// </summary>
@@ -135,10 +132,10 @@ namespace PepperDash.Core
CTimer ReconnectTimer; CTimer ReconnectTimer;
//string PreviousHostname; //Lock object to prevent simulatneous connect/disconnect operations
//int PreviousPort; private CCriticalSection connectLock = new CCriticalSection();
//string PreviousUsername;
//string PreviousPassword; private bool DisconnectLogged = false;
/// <summary> /// <summary>
/// Typical constructor. /// Typical constructor.
@@ -154,6 +151,14 @@ namespace PepperDash.Core
Username = username; Username = username;
Password = password; Password = password;
AutoReconnectIntervalMs = 5000; AutoReconnectIntervalMs = 5000;
ReconnectTimer = new CTimer(o =>
{
if (ConnectEnabled)
{
Connect();
}
}, Timeout.Infinite);
} }
/// <summary> /// <summary>
@@ -162,9 +167,16 @@ namespace PepperDash.Core
public GenericSshClient() public GenericSshClient()
: base(SPlusKey) : base(SPlusKey)
{ {
StreamDebugging = new CommunicationStreamDebugging(SPlusKey);
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler); CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
AutoReconnectIntervalMs = 5000; AutoReconnectIntervalMs = 5000;
ReconnectTimer = new CTimer(o =>
{
if (ConnectEnabled)
{
Connect();
}
}, Timeout.Infinite);
} }
/// <summary> /// <summary>
@@ -195,104 +207,106 @@ namespace PepperDash.Core
/// </summary> /// </summary>
public void Connect() public void Connect()
{ {
if (IsConnecting)
{
Debug.Console(0, this, Debug.ErrorLogLevel.Warning, "Connection attempt in progress. Exiting Connect()");
return;
}
IsConnecting = true;
ConnectEnabled = true;
Debug.Console(1, this, "attempting connect");
// Cancel reconnect if running.
if (ReconnectTimer != null)
{
ReconnectTimer.Stop();
ReconnectTimer = null;
}
// Don't try to connect if already
if (IsConnected)
return;
// Don't go unless everything is here // Don't go unless everything is here
if (string.IsNullOrEmpty(Hostname) || Port < 1 || Port > 65535 if (string.IsNullOrEmpty(Hostname) || Port < 1 || Port > 65535
|| Username == null || Password == null) || Username == null || Password == null)
{ {
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Connect failed. Check hostname, port, username and password are set or not null"); Debug.Console(0, this, Debug.ErrorLogLevel.Error, "Connect failed. Check hostname, port, username and password are set or not null");
return; return;
} }
// Cleanup the old client if it already exists ConnectEnabled = true;
if (Client != null)
{
Debug.Console(1, this, "Cleaning up disconnected client");
Client.ErrorOccurred -= Client_ErrorOccurred;
KillClient(SocketStatus.SOCKET_STATUS_BROKEN_LOCALLY);
}
// This handles both password and keyboard-interactive (like on OS-X, 'nixes)
KeyboardInteractiveAuthenticationMethod kauth = new KeyboardInteractiveAuthenticationMethod(Username);
kauth.AuthenticationPrompt += new EventHandler<AuthenticationPromptEventArgs>(kauth_AuthenticationPrompt);
PasswordAuthenticationMethod pauth = new PasswordAuthenticationMethod(Username, Password);
Debug.Console(1, this, "Creating new SshClient");
ConnectionInfo connectionInfo = new ConnectionInfo(Hostname, Port, Username, pauth, kauth);
Client = new SshClient(connectionInfo);
Client.ErrorOccurred -= Client_ErrorOccurred;
Client.ErrorOccurred += Client_ErrorOccurred;
//Attempt to connect
ClientStatus = SocketStatus.SOCKET_STATUS_WAITING;
try try
{ {
Client.Connect(); connectLock.Enter();
TheStream = Client.CreateShellStream("PDTShell", 100, 80, 100, 200, 65534); if (IsConnected)
TheStream.DataReceived += Stream_DataReceived;
//TheStream.ErrorOccurred += TheStream_ErrorOccurred;
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Connected");
ClientStatus = SocketStatus.SOCKET_STATUS_CONNECTED;
IsConnecting = false;
DisconnectLogged = false;
return; // Success will not pass here
}
catch (SshConnectionException e)
{
var ie = e.InnerException; // The details are inside!!
var errorLogLevel = DisconnectLogged == true ? Debug.ErrorLogLevel.None : Debug.ErrorLogLevel.Error;
if (ie is SocketException)
Debug.Console(1, this, errorLogLevel, "'{0}' CONNECTION failure: Cannot reach host, ({1})", Key, ie.Message);
else if (ie is System.Net.Sockets.SocketException)
Debug.Console(1, this, errorLogLevel, "'{0}' Connection failure: Cannot reach host '{1}' on port {2}, ({3})",
Key, Hostname, Port, ie.GetType());
else if (ie is SshAuthenticationException)
{ {
Debug.Console(1, this, errorLogLevel, "Authentication failure for username '{0}', ({1})", Debug.Console(1, this, "Connection already connected. Exiting Connect()");
Username, ie.Message);
} }
else else
Debug.Console(1, this, errorLogLevel, "Error on connect:\r({0})", e); {
Debug.Console(1, this, "Attempting connect");
DisconnectLogged = true; // Cancel reconnect if running.
ClientStatus = SocketStatus.SOCKET_STATUS_CONNECT_FAILED; ReconnectTimer.Stop();
HandleConnectionFailure();
// Cleanup the old client if it already exists
if (Client != null)
{
Debug.Console(1, this, "Cleaning up disconnected client");
KillClient(SocketStatus.SOCKET_STATUS_BROKEN_LOCALLY);
}
// This handles both password and keyboard-interactive (like on OS-X, 'nixes)
KeyboardInteractiveAuthenticationMethod kauth = new KeyboardInteractiveAuthenticationMethod(Username);
kauth.AuthenticationPrompt += new EventHandler<AuthenticationPromptEventArgs>(kauth_AuthenticationPrompt);
PasswordAuthenticationMethod pauth = new PasswordAuthenticationMethod(Username, Password);
Debug.Console(1, this, "Creating new SshClient");
ConnectionInfo connectionInfo = new ConnectionInfo(Hostname, Port, Username, pauth, kauth);
Client = new SshClient(connectionInfo);
Client.ErrorOccurred -= Client_ErrorOccurred;
Client.ErrorOccurred += Client_ErrorOccurred;
//Attempt to connect
ClientStatus = SocketStatus.SOCKET_STATUS_WAITING;
try
{
Client.Connect();
TheStream = Client.CreateShellStream("PDTShell", 100, 80, 100, 200, 65534);
TheStream.DataReceived += Stream_DataReceived;
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Connected");
ClientStatus = SocketStatus.SOCKET_STATUS_CONNECTED;
DisconnectLogged = false;
}
catch (SshConnectionException e)
{
var ie = e.InnerException; // The details are inside!!
var errorLogLevel = DisconnectLogged == true ? Debug.ErrorLogLevel.None : Debug.ErrorLogLevel.Error;
if (ie is SocketException)
Debug.Console(1, this, errorLogLevel, "'{0}' CONNECTION failure: Cannot reach host, ({1})", Key, ie.Message);
else if (ie is System.Net.Sockets.SocketException)
Debug.Console(1, this, errorLogLevel, "'{0}' Connection failure: Cannot reach host '{1}' on port {2}, ({3})",
Key, Hostname, Port, ie.GetType());
else if (ie is SshAuthenticationException)
{
Debug.Console(1, this, errorLogLevel, "Authentication failure for username '{0}', ({1})",
Username, ie.Message);
}
else
Debug.Console(1, this, errorLogLevel, "Error on connect:\r({0})", ie.Message);
DisconnectLogged = true;
KillClient(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
if (AutoReconnect)
{
Debug.Console(1, this, "Checking autoreconnect: {0}, {1}ms", AutoReconnect, AutoReconnectIntervalMs);
ReconnectTimer.Reset(AutoReconnectIntervalMs);
}
}
catch (Exception e)
{
var errorLogLevel = DisconnectLogged == true ? Debug.ErrorLogLevel.None : Debug.ErrorLogLevel.Error;
Debug.Console(1, this, errorLogLevel, "Unhandled exception on connect:\r({0})", e.Message);
DisconnectLogged = true;
KillClient(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
if (AutoReconnect)
{
Debug.Console(1, this, "Checking autoreconnect: {0}, {1}ms", AutoReconnect, AutoReconnectIntervalMs);
ReconnectTimer.Reset(AutoReconnectIntervalMs);
}
}
}
} }
catch (Exception e) finally
{ {
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Unhandled exception on connect:\r({0})", e); connectLock.Leave();
ClientStatus = SocketStatus.SOCKET_STATUS_CONNECT_FAILED;
HandleConnectionFailure();
} }
ClientStatus = SocketStatus.SOCKET_STATUS_CONNECT_FAILED;
HandleConnectionFailure();
} }
/// <summary> /// <summary>
/// Disconnect the clients and put away it's resources. /// Disconnect the clients and put away it's resources.
/// </summary> /// </summary>
@@ -317,8 +331,7 @@ namespace PepperDash.Core
KillStream(); KillStream();
if (Client != null) if (Client != null)
{ {
IsConnecting = false;
Client.Disconnect(); Client.Disconnect();
Client = null; Client = null;
ClientStatus = status; ClientStatus = status;
@@ -365,6 +378,7 @@ namespace PepperDash.Core
TheStream.Close(); TheStream.Close();
TheStream.Dispose(); TheStream.Dispose();
TheStream = null; TheStream = null;
Debug.Console(1, this, "Disconnected stream");
} }
} }
@@ -415,13 +429,28 @@ namespace PepperDash.Core
/// </summary> /// </summary>
void Client_ErrorOccurred(object sender, Crestron.SimplSharp.Ssh.Common.ExceptionEventArgs e) void Client_ErrorOccurred(object sender, Crestron.SimplSharp.Ssh.Common.ExceptionEventArgs e)
{ {
if (e.Exception is SshConnectionException || e.Exception is System.Net.Sockets.SocketException) CrestronInvoke.BeginInvoke(o =>
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Disconnected by remote"); {
else if (e.Exception is SshConnectionException || e.Exception is System.Net.Sockets.SocketException)
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Unhandled SSH client error: {0}", e.Exception); Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Disconnected by remote");
else
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Unhandled SSH client error: {0}", e.Exception);
ClientStatus = SocketStatus.SOCKET_STATUS_BROKEN_REMOTELY; try
HandleConnectionFailure(); {
connectLock.Enter();
KillClient(SocketStatus.SOCKET_STATUS_BROKEN_REMOTELY);
}
finally
{
connectLock.Leave();
}
if (AutoReconnect && ConnectEnabled)
{
Debug.Console(1, this, "Checking autoreconnect: {0}, {1}ms", AutoReconnect, AutoReconnectIntervalMs);
ReconnectTimer.Reset(AutoReconnectIntervalMs);
}
});
} }
/// <summary> /// <summary>
@@ -463,8 +492,6 @@ namespace PepperDash.Core
Debug.Console(0, "Stack Trace: {0}", ex.StackTrace); Debug.Console(0, "Stack Trace: {0}", ex.StackTrace);
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Stream write failed. Disconnected, closing"); Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Stream write failed. Disconnected, closing");
ClientStatus = SocketStatus.SOCKET_STATUS_BROKEN_REMOTELY;
HandleConnectionFailure();
} }
} }
@@ -492,8 +519,6 @@ namespace PepperDash.Core
catch catch
{ {
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Stream write failed. Disconnected, closing"); Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Stream write failed. Disconnected, closing");
ClientStatus = SocketStatus.SOCKET_STATUS_BROKEN_REMOTELY;
HandleConnectionFailure();
} }
} }

View File

@@ -5,9 +5,7 @@ using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Crestron.SimplSharp; using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronSockets; using Crestron.SimplSharp.CrestronSockets;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace PepperDash.Core namespace PepperDash.Core
{ {
@@ -39,23 +37,24 @@ namespace PepperDash.Core
public event EventHandler<GenericSocketStatusChageEventArgs> ConnectionChange; public event EventHandler<GenericSocketStatusChageEventArgs> ConnectionChange;
private string _Hostname { get; set;} private string _hostname;
/// <summary> /// <summary>
/// Address of server /// Address of server
/// </summary> /// </summary>
public string Hostname { public string Hostname
{
get get
{ {
return _Hostname; return _hostname;
} }
set set
{ {
_Hostname = value; _hostname = value;
if (Client != null) if (_client != null)
{ {
_client.AddressClientConnectedTo = _hostname;
Client.AddressClientConnectedTo = _Hostname;
} }
} }
} }
@@ -83,14 +82,14 @@ namespace PepperDash.Core
/// <summary> /// <summary>
/// The actual client class /// The actual client class
/// </summary> /// </summary>
public TCPClient Client { get; private set; } private TCPClient _client;
/// <summary> /// <summary>
/// True if connected to the server /// Bool showing if socket is connected
/// </summary> /// </summary>
public bool IsConnected public bool IsConnected
{ {
get { return Client != null && Client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED; } get { return _client != null && _client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED; }
} }
/// <summary> /// <summary>
@@ -102,21 +101,19 @@ namespace PepperDash.Core
} }
/// <summary> /// <summary>
/// Status of the socket /// _client socket status Read only
/// </summary> /// </summary>
public SocketStatus ClientStatus public SocketStatus ClientStatus
{ {
get get
{ {
if (Client == null) return _client == null ? SocketStatus.SOCKET_STATUS_NO_CONNECT : _client.ClientStatus;
return SocketStatus.SOCKET_STATUS_NO_CONNECT;
return Client.ClientStatus;
} }
} }
/// <summary> /// <summary>
/// Contains the familiar Simpl analog status values. This drives the ConnectionChange event /// Contains the familiar Simpl analog status values. This drives the ConnectionChange event
/// and IsConnected with be true when this == 2. /// and IsConnected would be true when this == 2.
/// </summary> /// </summary>
public ushort UStatus public ushort UStatus
{ {
@@ -124,7 +121,7 @@ namespace PepperDash.Core
} }
/// <summary> /// <summary>
/// Status of the socket /// Status text shows the message associated with socket status
/// </summary> /// </summary>
public string ClientStatusText { get { return ClientStatus.ToString(); } } public string ClientStatusText { get { return ClientStatus.ToString(); } }
@@ -140,7 +137,7 @@ namespace PepperDash.Core
public string ConnectionFailure { get { return ClientStatus.ToString(); } } public string ConnectionFailure { get { return ClientStatus.ToString(); } }
/// <summary> /// <summary>
/// If true, enables AutoConnect /// bool to track if auto reconnect should be set on the socket
/// </summary> /// </summary>
public bool AutoReconnect { get; set; } public bool AutoReconnect { get; set; }
@@ -152,13 +149,14 @@ namespace PepperDash.Core
get { return (ushort)(AutoReconnect ? 1 : 0); } get { return (ushort)(AutoReconnect ? 1 : 0); }
set { AutoReconnect = value == 1; } set { AutoReconnect = value == 1; }
} }
/// <summary> /// <summary>
/// Milliseconds to wait before attempting to reconnect. Defaults to 5000 /// Milliseconds to wait before attempting to reconnect. Defaults to 5000
/// </summary> /// </summary>
public int AutoReconnectIntervalMs { get; set; } public int AutoReconnectIntervalMs { get; set; }
/// <summary> /// <summary>
/// Set only when the disconnect method is called. /// Set only when the disconnect method is called
/// </summary> /// </summary>
bool DisconnectCalledByUser; bool DisconnectCalledByUser;
@@ -167,10 +165,14 @@ namespace PepperDash.Core
/// </summary> /// </summary>
public bool Connected public bool Connected
{ {
get { return Client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED; } get { return _client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED; }
} }
CTimer RetryTimer; //Lock object to prevent simulatneous connect/disconnect operations
private CCriticalSection connectLock = new CCriticalSection();
// private Timer for auto reconnect
private CTimer RetryTimer;
/// <summary> /// <summary>
/// Constructor /// Constructor
@@ -183,13 +185,17 @@ namespace PepperDash.Core
: base(key) : base(key)
{ {
StreamDebugging = new CommunicationStreamDebugging(key); StreamDebugging = new CommunicationStreamDebugging(key);
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
AutoReconnectIntervalMs = 5000;
Hostname = address; Hostname = address;
Port = port; Port = port;
BufferSize = bufferSize; BufferSize = bufferSize;
AutoReconnectIntervalMs = 5000;
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler); RetryTimer = new CTimer(o =>
} {
Reconnect();
}, Timeout.Infinite);
}
/// <summary> /// <summary>
/// Constructor /// Constructor
@@ -202,6 +208,11 @@ namespace PepperDash.Core
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler); CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
AutoReconnectIntervalMs = 5000; AutoReconnectIntervalMs = 5000;
BufferSize = 2000; BufferSize = 2000;
RetryTimer = new CTimer(o =>
{
Reconnect();
}, Timeout.Infinite);
} }
/// <summary> /// <summary>
@@ -210,10 +221,14 @@ namespace PepperDash.Core
public GenericTcpIpClient() public GenericTcpIpClient()
: base(SplusKey) : base(SplusKey)
{ {
StreamDebugging = new CommunicationStreamDebugging(SplusKey);
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler); CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
AutoReconnectIntervalMs = 5000; AutoReconnectIntervalMs = 5000;
BufferSize = 2000; BufferSize = 2000;
RetryTimer = new CTimer(o =>
{
Reconnect();
}, Timeout.Infinite);
} }
/// <summary> /// <summary>
@@ -232,7 +247,7 @@ namespace PepperDash.Core
if (programEventType == eProgramStatusEventType.Stopping) if (programEventType == eProgramStatusEventType.Stopping)
{ {
Debug.Console(1, this, "Program stopping. Closing connection"); Debug.Console(1, this, "Program stopping. Closing connection");
Disconnect(); Deactivate();
} }
} }
@@ -242,9 +257,11 @@ namespace PepperDash.Core
/// <returns></returns> /// <returns></returns>
public override bool Deactivate() public override bool Deactivate()
{ {
if (Client != null) RetryTimer.Stop();
RetryTimer.Dispose();
if (_client != null)
{ {
Client.SocketStatusChange -= this.Client_SocketStatusChange; _client.SocketStatusChange -= this.Client_SocketStatusChange;
DisconnectClient(); DisconnectClient();
} }
return true; return true;
@@ -255,9 +272,6 @@ namespace PepperDash.Core
/// </summary> /// </summary>
public void Connect() public void Connect()
{ {
if (IsConnected)
DisconnectClient();
if (string.IsNullOrEmpty(Hostname)) if (string.IsNullOrEmpty(Hostname))
{ {
Debug.Console(1, Debug.ErrorLogLevel.Warning, "GenericTcpIpClient '{0}': No address set", Key); Debug.Console(1, Debug.ErrorLogLevel.Warning, "GenericTcpIpClient '{0}': No address set", Key);
@@ -271,36 +285,72 @@ namespace PepperDash.Core
} }
} }
if (Client == null) try
{ {
Client = new TCPClient(Hostname, Port, BufferSize); connectLock.Enter();
Client.SocketStatusChange -= Client_SocketStatusChange; if (IsConnected)
Client.SocketStatusChange += Client_SocketStatusChange; {
Debug.Console(1, this, "Connection already connected. Exiting Connect()");
}
else
{
//Stop retry timer if running
RetryTimer.Stop();
_client = new TCPClient(Hostname, Port, BufferSize);
_client.SocketStatusChange -= Client_SocketStatusChange;
_client.SocketStatusChange += Client_SocketStatusChange;
DisconnectCalledByUser = false;
_client.ConnectToServerAsync(ConnectToServerCallback);
}
}
finally
{
connectLock.Leave();
} }
DisconnectCalledByUser = false;
Client.ConnectToServerAsync(ConnectToServerCallback); // (null);
} }
private void Reconnect()
{
if (_client == null)
{
return;
}
try
{
connectLock.Enter();
if (IsConnected || DisconnectCalledByUser == true)
{
Debug.Console(1, this, "Reconnect no longer needed. Exiting Reconnect()");
}
else
{
Debug.Console(1, this, "Attempting reconnect now");
_client.ConnectToServerAsync(ConnectToServerCallback);
}
}
finally
{
connectLock.Leave();
}
}
/// <summary> /// <summary>
/// Attempts to disconnect the client /// Attempts to disconnect the client
/// </summary> /// </summary>
public void Disconnect() public void Disconnect()
{ {
DisconnectCalledByUser = true; try
// Stop trying reconnects, if we are
if (RetryTimer != null)
{ {
connectLock.Enter();
DisconnectCalledByUser = true;
// Stop trying reconnects, if we are
RetryTimer.Stop(); RetryTimer.Stop();
RetryTimer = null;
}
if (Client != null)
{
DisconnectClient(); DisconnectClient();
Client = null; }
Debug.Console(1, this, "Disconnected"); finally
{
connectLock.Leave();
} }
} }
@@ -309,11 +359,11 @@ namespace PepperDash.Core
/// </summary> /// </summary>
public void DisconnectClient() public void DisconnectClient()
{ {
if (Client != null) if (_client != null)
{ {
Debug.Console(1, this, "Disconnecting client"); Debug.Console(1, this, "Disconnecting client");
if(IsConnected) if (IsConnected)
Client.DisconnectFromServer(); _client.DisconnectFromServer();
} }
} }
@@ -323,9 +373,15 @@ namespace PepperDash.Core
/// <param name="c"></param> /// <param name="c"></param>
void ConnectToServerCallback(TCPClient c) void ConnectToServerCallback(TCPClient c)
{ {
Debug.Console(1, this, "Server connection result: {0}", c.ClientStatus); if (c.ClientStatus != SocketStatus.SOCKET_STATUS_CONNECTED)
if (c.ClientStatus != SocketStatus.SOCKET_STATUS_CONNECTED && AutoReconnect) {
WaitAndTryReconnect(); Debug.Console(0, this, "Server connection result: {0}", c.ClientStatus);
WaitAndTryReconnect();
}
else
{
Debug.Console(1, this, "Server connection result: {0}", c.ClientStatus);
}
} }
/// <summary> /// <summary>
@@ -333,24 +389,23 @@ namespace PepperDash.Core
/// </summary> /// </summary>
void WaitAndTryReconnect() void WaitAndTryReconnect()
{ {
DisconnectClient(); CrestronInvoke.BeginInvoke(o =>
if (Client != null)
{ {
Debug.Console(1, this, "Attempting reconnect, status={0}", Client.ClientStatus); try
{
if (!DisconnectCalledByUser) connectLock.Enter();
RetryTimer = new CTimer(o => if (!IsConnected && AutoReconnect && !DisconnectCalledByUser && _client != null)
{ {
if (Client == null) DisconnectClient();
{ Debug.Console(1, this, "Attempting reconnect, status={0}", _client.ClientStatus);
return; RetryTimer.Reset(AutoReconnectIntervalMs);
} }
}
Client.ConnectToServerAsync(ConnectToServerCallback); finally
}, AutoReconnectIntervalMs); {
} connectLock.Leave();
}
});
} }
/// <summary> /// <summary>
@@ -380,15 +435,13 @@ namespace PepperDash.Core
var str = Encoding.GetEncoding(28591).GetString(bytes, 0, bytes.Length); var str = Encoding.GetEncoding(28591).GetString(bytes, 0, bytes.Length);
if (StreamDebugging.RxStreamDebuggingIsEnabled) if (StreamDebugging.RxStreamDebuggingIsEnabled)
{
Debug.Console(0, this, "Received {1} characters of text: '{0}'", ComTextHelper.GetDebugText(str), str.Length); Debug.Console(0, this, "Received {1} characters of text: '{0}'", ComTextHelper.GetDebugText(str), str.Length);
}
textHandler(this, new GenericCommMethodReceiveTextArgs(str)); textHandler(this, new GenericCommMethodReceiveTextArgs(str));
}
}
} }
client.ReceiveDataAsync(Receive); client.ReceiveDataAsync(Receive);
} }
} }
@@ -402,10 +455,8 @@ namespace PepperDash.Core
// Check debug level before processing byte array // Check debug level before processing byte array
if (StreamDebugging.TxStreamDebuggingIsEnabled) if (StreamDebugging.TxStreamDebuggingIsEnabled)
Debug.Console(0, this, "Sending {0} characters of text: '{1}'", text.Length, ComTextHelper.GetDebugText(text)); Debug.Console(0, this, "Sending {0} characters of text: '{1}'", text.Length, ComTextHelper.GetDebugText(text));
if(Client != null) if (_client != null)
Client.SendData(bytes, bytes.Length); _client.SendData(bytes, bytes.Length);
} }
/// <summary> /// <summary>
@@ -429,8 +480,8 @@ namespace PepperDash.Core
{ {
if (StreamDebugging.TxStreamDebuggingIsEnabled) if (StreamDebugging.TxStreamDebuggingIsEnabled)
Debug.Console(0, this, "Sending {0} bytes: '{1}'", bytes.Length, ComTextHelper.GetEscapedText(bytes)); Debug.Console(0, this, "Sending {0} bytes: '{1}'", bytes.Length, ComTextHelper.GetEscapedText(bytes));
if(Client != null) if (_client != null)
Client.SendData(bytes, bytes.Length); _client.SendData(bytes, bytes.Length);
} }
/// <summary> /// <summary>
@@ -440,27 +491,20 @@ namespace PepperDash.Core
/// <param name="clientSocketStatus"></param> /// <param name="clientSocketStatus"></param>
void Client_SocketStatusChange(TCPClient client, SocketStatus clientSocketStatus) void Client_SocketStatusChange(TCPClient client, SocketStatus clientSocketStatus)
{ {
Debug.Console(1, this, "Socket status change {0} ({1})", clientSocketStatus, ClientStatusText); if (clientSocketStatus != SocketStatus.SOCKET_STATUS_CONNECTED)
if (client.ClientStatus != SocketStatus.SOCKET_STATUS_CONNECTED && !DisconnectCalledByUser && AutoReconnect) {
WaitAndTryReconnect(); Debug.Console(0, this, "Socket status change {0} ({1})", clientSocketStatus, ClientStatusText);
WaitAndTryReconnect();
// Probably doesn't need to be a switch since all other cases were eliminated }
switch (clientSocketStatus) else
{ {
case SocketStatus.SOCKET_STATUS_CONNECTED: Debug.Console(1, this, "Socket status change {0} ({1})", clientSocketStatus, ClientStatusText);
Client.ReceiveDataAsync(Receive); _client.ReceiveDataAsync(Receive);
DisconnectCalledByUser = false; }
break;
}
var handler = ConnectionChange; var handler = ConnectionChange;
if (handler != null) if (handler != null)
ConnectionChange(this, new GenericSocketStatusChageEventArgs(this)); ConnectionChange(this, new GenericSocketStatusChageEventArgs(this));
// Relay the event
//var handler = SocketStatusChange;
//if (handler != null)
// SocketStatusChange(this);
} }
} }
@@ -519,4 +563,4 @@ namespace PepperDash.Core
} }
} }

View File

@@ -572,6 +572,7 @@ namespace PepperDash.Core
String.Format( String.Format(
@"Debug settings file migration not necessary. Using file at \user\debugSettings\program{0}", @"Debug settings file migration not necessary. Using file at \user\debugSettings\program{0}",
InitialParametersClass.ApplicationNumber)); InitialParametersClass.ApplicationNumber));
return; return;
} }

View File

@@ -7,7 +7,7 @@
<ProjectGuid>{87E29B4C-569B-4368-A4ED-984AC1440C96}</ProjectGuid> <ProjectGuid>{87E29B4C-569B-4368-A4ED-984AC1440C96}</ProjectGuid>
<OutputType>Library</OutputType> <OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder> <AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>PepperDash_Core</RootNamespace> <RootNamespace>PepperDash.Core</RootNamespace>
<AssemblyName>PepperDash_Core</AssemblyName> <AssemblyName>PepperDash_Core</AssemblyName>
<ProjectTypeGuids>{0B4745B0-194B-4BB6-8E21-E9057CA92500};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> <ProjectTypeGuids>{0B4745B0-194B-4BB6-8E21-E9057CA92500};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<PlatformFamilyName>WindowsCE</PlatformFamilyName> <PlatformFamilyName>WindowsCE</PlatformFamilyName>
@@ -51,6 +51,10 @@
<SpecificVersion>False</SpecificVersion> <SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\..\..\..\ProgramData\Crestron\SDK\SimplSharpCustomAttributesInterface.dll</HintPath> <HintPath>..\..\..\..\..\..\..\..\ProgramData\Crestron\SDK\SimplSharpCustomAttributesInterface.dll</HintPath>
</Reference> </Reference>
<Reference Include="SimplSharpCWSHelperInterface, Version=2.0.0.0, Culture=neutral, PublicKeyToken=1099c178b3b54c3b, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\..\..\..\ProgramData\Crestron\SDK\SimplSharpCWSHelperInterface.dll</HintPath>
</Reference>
<Reference Include="SimplSharpHelperInterface, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1099c178b3b54c3b, processorArchitecture=MSIL"> <Reference Include="SimplSharpHelperInterface, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1099c178b3b54c3b, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion> <SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\..\..\..\ProgramData\Crestron\SDK\SimplSharpHelperInterface.dll</HintPath> <HintPath>..\..\..\..\..\..\..\..\ProgramData\Crestron\SDK\SimplSharpHelperInterface.dll</HintPath>
@@ -89,6 +93,9 @@
<Compile Include="Comm\TcpServerConfigObject.cs" /> <Compile Include="Comm\TcpServerConfigObject.cs" />
<Compile Include="Config\PortalConfigReader.cs" /> <Compile Include="Config\PortalConfigReader.cs" />
<Compile Include="CoreInterfaces.cs" /> <Compile Include="CoreInterfaces.cs" />
<Compile Include="Web\RequestHandlers\DefaultRequestHandler.cs" />
<Compile Include="Web\RequestHandlers\WebApiBaseRequestHandler.cs" />
<Compile Include="Web\WebApiServer.cs" />
<Compile Include="EventArgs.cs" /> <Compile Include="EventArgs.cs" />
<Compile Include="GenericRESTfulCommunications\Constants.cs" /> <Compile Include="GenericRESTfulCommunications\Constants.cs" />
<Compile Include="GenericRESTfulCommunications\GenericRESTfulClient.cs" /> <Compile Include="GenericRESTfulCommunications\GenericRESTfulClient.cs" />

View File

@@ -0,0 +1,3 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=CrestronWebServer/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=Web/@EntryIndexedValue">False</s:Boolean></wpf:ResourceDictionary>

View File

@@ -0,0 +1,17 @@
using Crestron.SimplSharp.WebScripting;
namespace PepperDash.Core.Web.RequestHandlers
{
/// <summary>
/// Web API default request handler
/// </summary>
public class DefaultRequestHandler : WebApiBaseRequestHandler
{
/// <summary>
/// Constructor
/// </summary>
public DefaultRequestHandler()
: base(true)
{ }
}
}

View File

@@ -0,0 +1,165 @@
using System;
using System.Collections.Generic;
using Crestron.SimplSharp.WebScripting;
namespace PepperDash.Core.Web.RequestHandlers
{
/// <summary>
/// CWS Base Handler, implements IHttpCwsHandler
/// </summary>
public abstract class WebApiBaseRequestHandler : IHttpCwsHandler
{
private readonly Dictionary<string, Action<HttpCwsContext>> _handlers;
protected readonly bool EnableCors;
/// <summary>
/// Constructor
/// </summary>
protected WebApiBaseRequestHandler(bool enableCors)
{
EnableCors = enableCors;
_handlers = new Dictionary<string, Action<HttpCwsContext>>
{
{"CONNECT", HandleConnect},
{"DELETE", HandleDelete},
{"GET", HandleGet},
{"HEAD", HandleHead},
{"OPTIONS", HandleOptions},
{"PATCH", HandlePatch},
{"POST", HandlePost},
{"PUT", HandlePut},
{"TRACE", HandleTrace}
};
}
/// <summary>
/// Constructor
/// </summary>
protected WebApiBaseRequestHandler()
: this(false)
{
}
/// <summary>
/// Handles CONNECT method requests
/// </summary>
/// <param name="context"></param>
protected virtual void HandleConnect(HttpCwsContext context)
{
context.Response.StatusCode = 501;
context.Response.StatusDescription = "Not Implemented";
context.Response.End();
}
/// <summary>
/// Handles DELETE method requests
/// </summary>
/// <param name="context"></param>
protected virtual void HandleDelete(HttpCwsContext context)
{
context.Response.StatusCode = 501;
context.Response.StatusDescription = "Not Implemented";
context.Response.End();
}
/// <summary>
/// Handles GET method requests
/// </summary>
/// <param name="context"></param>
protected virtual void HandleGet(HttpCwsContext context)
{
context.Response.StatusCode = 501;
context.Response.StatusDescription = "Not Implemented";
context.Response.End();
}
/// <summary>
/// Handles HEAD method requests
/// </summary>
/// <param name="context"></param>
protected virtual void HandleHead(HttpCwsContext context)
{
context.Response.StatusCode = 501;
context.Response.StatusDescription = "Not Implemented";
context.Response.End();
}
/// <summary>
/// Handles OPTIONS method requests
/// </summary>
/// <param name="context"></param>
protected virtual void HandleOptions(HttpCwsContext context)
{
context.Response.StatusCode = 501;
context.Response.StatusDescription = "Not Implemented";
context.Response.End();
}
/// <summary>
/// Handles PATCH method requests
/// </summary>
/// <param name="context"></param>
protected virtual void HandlePatch(HttpCwsContext context)
{
context.Response.StatusCode = 501;
context.Response.StatusDescription = "Not Implemented";
context.Response.End();
}
/// <summary>
/// Handles POST method requests
/// </summary>
/// <param name="context"></param>
protected virtual void HandlePost(HttpCwsContext context)
{
context.Response.StatusCode = 501;
context.Response.StatusDescription = "Not Implemented";
context.Response.End();
}
/// <summary>
/// Handles PUT method requests
/// </summary>
/// <param name="context"></param>
protected virtual void HandlePut(HttpCwsContext context)
{
context.Response.StatusCode = 501;
context.Response.StatusDescription = "Not Implemented";
context.Response.End();
}
/// <summary>
/// Handles TRACE method requests
/// </summary>
/// <param name="context"></param>
protected virtual void HandleTrace(HttpCwsContext context)
{
context.Response.StatusCode = 501;
context.Response.StatusDescription = "Not Implemented";
context.Response.End();
}
/// <summary>
/// Process request
/// </summary>
/// <param name="context"></param>
public void ProcessRequest(HttpCwsContext context)
{
Action<HttpCwsContext> handler;
if (!_handlers.TryGetValue(context.Request.HttpMethod, out handler))
{
return;
}
if (EnableCors)
{
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
context.Response.Headers.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
}
handler(context);
}
}
}

View File

@@ -0,0 +1,284 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Crestron.SimplSharp;
using Crestron.SimplSharp.WebScripting;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PepperDash.Core.Web.RequestHandlers;
namespace PepperDash.Core.Web
{
/// <summary>
/// Web API server
/// </summary>
public class WebApiServer : IKeyName
{
private const string SplusKey = "Uninitialized Web API Server";
private const string DefaultName = "Web API Server";
private const string DefaultBasePath = "/api";
private const uint DebugTrace = 0;
private const uint DebugInfo = 1;
private const uint DebugVerbose = 2;
private readonly CCriticalSection _serverLock = new CCriticalSection();
private HttpCwsServer _server;
/// <summary>
/// Web API server key
/// </summary>
public string Key { get; private set; }
/// <summary>
/// Web API server name
/// </summary>
public string Name { get; private set; }
/// <summary>
/// CWS base path, will default to "/api" if not set via initialize method
/// </summary>
public string BasePath { get; private set; }
/// <summary>
/// Indicates CWS is registered with base path
/// </summary>
public bool IsRegistered { get; private set; }
/// <summary>
/// Http request handler
/// </summary>
//public IHttpCwsHandler HttpRequestHandler
//{
// get { return _server.HttpRequestHandler; }
// set
// {
// if (_server == null) return;
// _server.HttpRequestHandler = value;
// }
//}
/// <summary>
/// Received request event handler
/// </summary>
//public event EventHandler<HttpCwsRequestEventArgs> ReceivedRequestEvent
//{
// add { _server.ReceivedRequestEvent += new HttpCwsRequestEventHandler(value); }
// remove { _server.ReceivedRequestEvent -= new HttpCwsRequestEventHandler(value); }
//}
/// <summary>
/// Constructor for S+. Make sure to set necessary properties using init method
/// </summary>
public WebApiServer()
: this(SplusKey, DefaultName, null)
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="key"></param>
/// <param name="basePath"></param>
public WebApiServer(string key, string basePath)
: this(key, DefaultName, basePath)
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="key"></param>
/// <param name="name"></param>
/// <param name="basePath"></param>
public WebApiServer(string key, string name, string basePath)
{
Key = key;
Name = string.IsNullOrEmpty(name) ? DefaultName : name;
BasePath = string.IsNullOrEmpty(basePath) ? DefaultBasePath : basePath;
if (_server == null) _server = new HttpCwsServer(BasePath);
_server.setProcessName(Key);
_server.HttpRequestHandler = new DefaultRequestHandler();
CrestronEnvironment.ProgramStatusEventHandler += CrestronEnvironment_ProgramStatusEventHandler;
CrestronEnvironment.EthernetEventHandler += CrestronEnvironment_EthernetEventHandler;
}
/// <summary>
/// Program status event handler
/// </summary>
/// <param name="programEventType"></param>
void CrestronEnvironment_ProgramStatusEventHandler(eProgramStatusEventType programEventType)
{
if (programEventType != eProgramStatusEventType.Stopping) return;
Debug.Console(DebugInfo, this, "Program stopping. stopping server");
Stop();
}
/// <summary>
/// Ethernet event handler
/// </summary>
/// <param name="ethernetEventArgs"></param>
void CrestronEnvironment_EthernetEventHandler(EthernetEventArgs ethernetEventArgs)
{
// Re-enable the server if the link comes back up and the status should be connected
if (ethernetEventArgs.EthernetEventType == eEthernetEventType.LinkUp && IsRegistered)
{
Debug.Console(DebugInfo, this, "Ethernet link up. Server is alreedy registered.");
return;
}
Debug.Console(DebugInfo, this, "Ethernet link up. Starting server");
Start();
}
/// <summary>
/// Initializes CWS class
/// </summary>
public void Initialize(string key, string basePath)
{
Key = key;
BasePath = string.IsNullOrEmpty(basePath) ? DefaultBasePath : basePath;
}
/// <summary>
/// Adds a route to CWS
/// </summary>
public void AddRoute(HttpCwsRoute route)
{
if (route == null)
{
Debug.Console(DebugInfo, this, "Failed to add route, route parameter is null");
return;
}
_server.Routes.Add(route);
}
/// <summary>
/// Removes a route from CWS
/// </summary>
/// <param name="route"></param>
public void RemoveRoute(HttpCwsRoute route)
{
if (route == null)
{
Debug.Console(DebugInfo, this, "Failed to remote route, orute parameter is null");
return;
}
_server.Routes.Remove(route);
}
/// <summary>
/// Returns a list of the current routes
/// </summary>
public HttpCwsRouteCollection GetRouteCollection()
{
return _server.Routes;
}
/// <summary>
/// Starts CWS instance
/// </summary>
public void Start()
{
try
{
_serverLock.Enter();
if (_server == null)
{
Debug.Console(DebugInfo, this, "Server is null, unable to start");
return;
}
if (IsRegistered)
{
Debug.Console(DebugInfo, this, "Server has already been started");
return;
}
IsRegistered = _server.Register();
Debug.Console(DebugInfo, this, "Starting server, registration {0}", IsRegistered ? "was successful" : "failed");
}
catch (Exception ex)
{
Debug.Console(DebugInfo, this, "Start Exception Message: {0}", ex.Message);
Debug.Console(DebugVerbose, this, "Start Exception StackTrace: {0}", ex.StackTrace);
if (ex.InnerException != null)
Debug.Console(DebugVerbose, this, "Start Exception InnerException: {0}", ex.InnerException);
}
finally
{
_serverLock.Leave();
}
}
/// <summary>
/// Stop CWS instance
/// </summary>
public void Stop()
{
try
{
_serverLock.Enter();
if (_server == null)
{
Debug.Console(DebugInfo, this, "Server is null or has already been stopped");
return;
}
IsRegistered = _server.Unregister() == false;
Debug.Console(DebugInfo, this, "Stopping server, unregistration {0}", IsRegistered ? "failed" : "was successful");
_server.Dispose();
_server = null;
}
catch (Exception ex)
{
Debug.Console(DebugInfo, this, "Server Stop Exception Message: {0}", ex.Message);
Debug.Console(DebugVerbose, this, "Server Stop Exception StackTrace: {0}", ex.StackTrace);
if (ex.InnerException != null)
Debug.Console(DebugVerbose, this, "Server Stop Exception InnerException: {0}", ex.InnerException);
}
finally
{
_serverLock.Leave();
}
}
/// <summary>
/// Received request handler
/// </summary>
/// <remarks>
/// This is here for development and testing
/// </remarks>
/// <param name="sender"></param>
/// <param name="args"></param>
public void ReceivedRequestEventHandler(object sender, HttpCwsRequestEventArgs args)
{
try
{
var j = JsonConvert.SerializeObject(args.Context, Formatting.Indented);
Debug.Console(DebugVerbose, this, "RecieveRequestEventHandler Context:\x0d\x0a{0}", j);
}
catch (Exception ex)
{
Debug.Console(DebugInfo, this, "ReceivedRequestEventHandler Exception Message: {0}", ex.Message);
Debug.Console(DebugVerbose, this, "ReceivedRequestEventHandler Exception StackTrace: {0}", ex.StackTrace);
if (ex.InnerException != null)
Debug.Console(DebugVerbose, this, "ReceivedRequestEventHandler Exception InnerException: {0}", ex.InnerException);
}
}
}
}