Changes lock to CCriticalSection

This commit is contained in:
Alex Johnson
2022-09-07 11:46:06 -04:00
parent 4139556149
commit 9326703454
2 changed files with 90 additions and 56 deletions

View File

@@ -129,7 +129,7 @@ namespace PepperDash.Core
CTimer ReconnectTimer; CTimer ReconnectTimer;
//Lock object to prevent simulatneous connect/disconnect operations //Lock object to prevent simulatneous connect/disconnect operations
private readonly object connectLock = new object(); private CCriticalSection connectLock = new CCriticalSection();
private bool DisconnectLogged = false; private bool DisconnectLogged = false;
@@ -163,7 +163,6 @@ 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;
@@ -213,8 +212,10 @@ namespace PepperDash.Core
} }
ConnectEnabled = true; ConnectEnabled = true;
lock (connectLock)
try
{ {
connectLock.Enter();
if (IsConnected) if (IsConnected)
{ {
Debug.Console(1, this, "Connection already connected. Exiting Connect()"); Debug.Console(1, this, "Connection already connected. Exiting Connect()");
@@ -296,6 +297,10 @@ namespace PepperDash.Core
} }
} }
} }
finally
{
connectLock.Leave();
}
} }
/// <summary> /// <summary>
@@ -303,11 +308,16 @@ namespace PepperDash.Core
/// </summary> /// </summary>
public void Disconnect() public void Disconnect()
{ {
lock(connectLock) try
{ {
connectLock.Enter();
// Stop trying reconnects, if we are // Stop trying reconnects, if we are
ReconnectTimer.Stop(); ReconnectTimer.Stop();
KillClient(SocketStatus.SOCKET_STATUS_BROKEN_LOCALLY); KillClient(SocketStatus.SOCKET_STATUS_BROKEN_LOCALLY);
}
finally
{
connectLock.Leave();
} }
} }
@@ -404,10 +414,15 @@ namespace PepperDash.Core
else else
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Unhandled SSH client error: {0}", e.Exception); Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Unhandled SSH client error: {0}", e.Exception);
lock (connectLock) try
{ {
connectLock.Enter();
KillClient(SocketStatus.SOCKET_STATUS_BROKEN_REMOTELY); KillClient(SocketStatus.SOCKET_STATUS_BROKEN_REMOTELY);
} }
finally
{
connectLock.Leave();
}
if (AutoReconnect && ConnectEnabled) if (AutoReconnect && ConnectEnabled)
{ {
Debug.Console(1, this, "Checking autoreconnect: {0}, {1}ms", AutoReconnect, AutoReconnectIntervalMs); Debug.Console(1, this, "Checking autoreconnect: {0}, {1}ms", AutoReconnect, AutoReconnectIntervalMs);

View File

@@ -6,7 +6,6 @@ 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
{ {
@@ -18,7 +17,7 @@ namespace PepperDash.Core
private const string SplusKey = "Uninitialized TcpIpClient"; private const string SplusKey = "Uninitialized TcpIpClient";
/// <summary> /// <summary>
/// Enables debugging to console /// Stream debugging
/// </summary> /// </summary>
public CommunicationStreamDebugging StreamDebugging { get; private set; } public CommunicationStreamDebugging StreamDebugging { get; private set; }
@@ -39,23 +38,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 +83,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 +102,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 +122,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 +138,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 +150,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,13 +166,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; }
} }
//Lock object to prevent simulatneous connect/disconnect operations //Lock object to prevent simulatneous connect/disconnect operations
private readonly object connectLock = new object(); private CCriticalSection connectLock = new CCriticalSection();
CTimer RetryTimer; // private Timer for auto reconnect
private CTimer RetryTimer;
/// <summary> /// <summary>
/// Constructor /// Constructor
@@ -186,18 +186,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;
RetryTimer = new CTimer(o => RetryTimer = new CTimer(o =>
{ {
Reconnect(); Reconnect();
}, Timeout.Infinite); }, Timeout.Infinite);
}
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
}
/// <summary> /// <summary>
/// Constructor /// Constructor
@@ -223,7 +222,6 @@ 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;
@@ -262,9 +260,9 @@ namespace PepperDash.Core
{ {
RetryTimer.Stop(); RetryTimer.Stop();
RetryTimer.Dispose(); RetryTimer.Dispose();
if (Client != null) if (_client != null)
{ {
Client.SocketStatusChange -= this.Client_SocketStatusChange; _client.SocketStatusChange -= this.Client_SocketStatusChange;
DisconnectClient(); DisconnectClient();
} }
return true; return true;
@@ -288,8 +286,9 @@ namespace PepperDash.Core
} }
} }
lock(connectLock) try
{ {
connectLock.Enter();
if (IsConnected) if (IsConnected)
{ {
Debug.Console(1, this, "Connection already connected. Exiting Connect()"); Debug.Console(1, this, "Connection already connected. Exiting Connect()");
@@ -298,25 +297,28 @@ namespace PepperDash.Core
{ {
//Stop retry timer if running //Stop retry timer if running
RetryTimer.Stop(); RetryTimer.Stop();
_client = new TCPClient(Hostname, Port, BufferSize);
Client = new TCPClient(Hostname, Port, BufferSize); _client.SocketStatusChange -= Client_SocketStatusChange;
Client.SocketStatusChange -= Client_SocketStatusChange; _client.SocketStatusChange += Client_SocketStatusChange;
Client.SocketStatusChange += Client_SocketStatusChange;
DisconnectCalledByUser = false; DisconnectCalledByUser = false;
_client.ConnectToServerAsync(ConnectToServerCallback);
Client.ConnectToServerAsync(ConnectToServerCallback);
} }
}
finally
{
connectLock.Leave();
} }
} }
private void Reconnect() private void Reconnect()
{ {
if (Client == null) if (_client == null)
{ {
return; return;
} }
lock (connectLock) try
{ {
connectLock.Enter();
if (IsConnected || DisconnectCalledByUser == true) if (IsConnected || DisconnectCalledByUser == true)
{ {
Debug.Console(1, this, "Reconnect no longer needed. Exiting Reconnect()"); Debug.Console(1, this, "Reconnect no longer needed. Exiting Reconnect()");
@@ -324,9 +326,13 @@ namespace PepperDash.Core
else else
{ {
Debug.Console(1, this, "Attempting reconnect now"); Debug.Console(1, this, "Attempting reconnect now");
Client.ConnectToServerAsync(ConnectToServerCallback); _client.ConnectToServerAsync(ConnectToServerCallback);
} }
} }
finally
{
connectLock.Leave();
}
} }
/// <summary> /// <summary>
@@ -334,13 +340,18 @@ namespace PepperDash.Core
/// </summary> /// </summary>
public void Disconnect() public void Disconnect()
{ {
lock (connectLock) try
{ {
connectLock.Enter();
DisconnectCalledByUser = true; DisconnectCalledByUser = true;
// Stop trying reconnects, if we are // Stop trying reconnects, if we are
RetryTimer.Stop(); RetryTimer.Stop();
DisconnectClient(); DisconnectClient();
}
finally
{
connectLock.Leave();
} }
} }
@@ -349,11 +360,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();
} }
} }
@@ -381,15 +392,20 @@ namespace PepperDash.Core
{ {
CrestronInvoke.BeginInvoke(o => CrestronInvoke.BeginInvoke(o =>
{ {
lock (connectLock) try
{ {
if (!IsConnected && AutoReconnect && !DisconnectCalledByUser && Client != null) connectLock.Enter();
if (!IsConnected && AutoReconnect && !DisconnectCalledByUser && _client != null)
{ {
DisconnectClient(); DisconnectClient();
Debug.Console(1, this, "Attempting reconnect, status={0}", Client.ClientStatus); Debug.Console(1, this, "Attempting reconnect, status={0}", _client.ClientStatus);
RetryTimer.Reset(AutoReconnectIntervalMs); RetryTimer.Reset(AutoReconnectIntervalMs);
} }
} }
finally
{
connectLock.Leave();
}
}); });
} }
@@ -420,7 +436,9 @@ 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));
} }
@@ -438,8 +456,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>
@@ -463,8 +481,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>
@@ -479,9 +497,10 @@ namespace PepperDash.Core
Debug.Console(0, this, "Socket status change {0} ({1})", clientSocketStatus, ClientStatusText); Debug.Console(0, this, "Socket status change {0} ({1})", clientSocketStatus, ClientStatusText);
WaitAndTryReconnect(); WaitAndTryReconnect();
} }
else
{ {
Debug.Console(1, this, "Socket status change {0} ({1})", clientSocketStatus, ClientStatusText); Debug.Console(1, this, "Socket status change {0} ({1})", clientSocketStatus, ClientStatusText);
Client.ReceiveDataAsync(Receive); _client.ReceiveDataAsync(Receive);
} }
var handler = ConnectionChange; var handler = ConnectionChange;