chore: run code cleanup

Ran code cleanup with the options set to remove unused
usings, sort usings, and adjust namespaces to match
folders.
This commit is contained in:
Andrew Welker
2023-03-23 09:26:17 -06:00
parent 046caba889
commit 2f2ea964cb
67 changed files with 4192 additions and 4693 deletions

View File

@@ -1,76 +1,70 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Crestron.SimplSharp;
using PepperDash.Core;
namespace PepperDash.Core
namespace PepperDash.Core.Comm
{
/// <summary>
/// Defines the string event handler for line events on the gather
/// </summary>
/// <param name="text"></param>
public delegate void LineReceivedHandler(string text);
/// <summary>
/// Defines the string event handler for line events on the gather
/// </summary>
/// <param name="text"></param>
public delegate void LineReceivedHandler(string text);
/// <summary>
/// Attaches to IBasicCommunication as a text gather
/// </summary>
public class CommunicationGather
{
/// <summary>
/// Event that fires when a line is received from the IBasicCommunication source.
/// The event merely contains the text, not an EventArgs type class.
/// </summary>
public event EventHandler<GenericCommMethodReceiveTextArgs> LineReceived;
/// <summary>
/// Attaches to IBasicCommunication as a text gather
/// </summary>
public class CommunicationGather
{
/// <summary>
/// Event that fires when a line is received from the IBasicCommunication source.
/// The event merely contains the text, not an EventArgs type class.
/// </summary>
public event EventHandler<GenericCommMethodReceiveTextArgs> LineReceived;
/// <summary>
/// The communication port that this gathers on
/// </summary>
/// <summary>
/// The communication port that this gathers on
/// </summary>
public ICommunicationReceiver Port { get; private set; }
/// <summary>
/// Default false. If true, the delimiter will be included in the line output
/// events
/// </summary>
public bool IncludeDelimiter { get; set; }
/// <summary>
/// Default false. If true, the delimiter will be included in the line output
/// events
/// </summary>
public bool IncludeDelimiter { get; set; }
/// <summary>
/// For receive buffer
/// </summary>
StringBuilder ReceiveBuffer = new StringBuilder();
/// <summary>
/// For receive buffer
/// </summary>
StringBuilder ReceiveBuffer = new StringBuilder();
/// <summary>
/// Delimiter, like it says!
/// </summary>
char Delimiter;
/// <summary>
/// Delimiter, like it says!
/// </summary>
char Delimiter;
string[] StringDelimiters;
string[] StringDelimiters;
/// <summary>
/// Constructor for using a char delimiter
/// </summary>
/// <param name="port"></param>
/// <param name="delimiter"></param>
public CommunicationGather(ICommunicationReceiver port, char delimiter)
{
Port = port;
Delimiter = delimiter;
port.TextReceived += new EventHandler<GenericCommMethodReceiveTextArgs>(Port_TextReceived);
}
/// <summary>
/// Constructor for using a char delimiter
/// </summary>
/// <param name="port"></param>
/// <param name="delimiter"></param>
public CommunicationGather(ICommunicationReceiver port, char delimiter)
{
Port = port;
Delimiter = delimiter;
port.TextReceived += new EventHandler<GenericCommMethodReceiveTextArgs>(Port_TextReceived);
}
/// <summary>
/// Constructor for using a single string delimiter
/// </summary>
/// <param name="port"></param>
/// <param name="delimiter"></param>
/// <summary>
/// Constructor for using a single string delimiter
/// </summary>
/// <param name="port"></param>
/// <param name="delimiter"></param>
public CommunicationGather(ICommunicationReceiver port, string delimiter)
:this(port, new string[] { delimiter} )
{
}
: this(port, new string[] { delimiter })
{
}
/// <summary>
/// Constructor for using an array of string delimiters
@@ -84,57 +78,57 @@ namespace PepperDash.Core
port.TextReceived += Port_TextReceivedStringDelimiter;
}
/// <summary>
/// Disconnects this gather from the Port's TextReceived event. This will not fire LineReceived
/// after the this call.
/// </summary>
public void Stop()
{
Port.TextReceived -= Port_TextReceived;
Port.TextReceived -= Port_TextReceivedStringDelimiter;
}
/// <summary>
/// Disconnects this gather from the Port's TextReceived event. This will not fire LineReceived
/// after the this call.
/// </summary>
public void Stop()
{
Port.TextReceived -= Port_TextReceived;
Port.TextReceived -= Port_TextReceivedStringDelimiter;
}
/// <summary>
/// Handler for raw data coming from port
/// </summary>
void Port_TextReceived(object sender, GenericCommMethodReceiveTextArgs args)
{
var handler = LineReceived;
if (handler != null)
{
ReceiveBuffer.Append(args.Text);
var str = ReceiveBuffer.ToString();
var lines = str.Split(Delimiter);
if (lines.Length > 0)
{
for (int i = 0; i < lines.Length - 1; i++)
{
string strToSend = null;
if (IncludeDelimiter)
strToSend = lines[i] + Delimiter;
else
strToSend = lines[i];
handler(this, new GenericCommMethodReceiveTextArgs(strToSend));
}
ReceiveBuffer = new StringBuilder(lines[lines.Length - 1]);
}
}
}
/// <summary>
/// Handler for raw data coming from port
/// </summary>
void Port_TextReceived(object sender, GenericCommMethodReceiveTextArgs args)
{
var handler = LineReceived;
if (handler != null)
{
ReceiveBuffer.Append(args.Text);
var str = ReceiveBuffer.ToString();
var lines = str.Split(Delimiter);
if (lines.Length > 0)
{
for (int i = 0; i < lines.Length - 1; i++)
{
string strToSend = null;
if (IncludeDelimiter)
strToSend = lines[i] + Delimiter;
else
strToSend = lines[i];
handler(this, new GenericCommMethodReceiveTextArgs(strToSend));
}
ReceiveBuffer = new StringBuilder(lines[lines.Length - 1]);
}
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
void Port_TextReceivedStringDelimiter(object sender, GenericCommMethodReceiveTextArgs args)
{
var handler = LineReceived;
if (handler != null)
{
// Receive buffer should either be empty or not contain the delimiter
// If the line does not have a delimiter, append the
ReceiveBuffer.Append(args.Text);
var str = ReceiveBuffer.ToString();
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
void Port_TextReceivedStringDelimiter(object sender, GenericCommMethodReceiveTextArgs args)
{
var handler = LineReceived;
if (handler != null)
{
// Receive buffer should either be empty or not contain the delimiter
// If the line does not have a delimiter, append the
ReceiveBuffer.Append(args.Text);
var str = ReceiveBuffer.ToString();
// Case: Receiving DEVICE get version\x0d\0x0a+OK "value":"1234"\x0d\x0a
@@ -153,7 +147,7 @@ namespace PepperDash.Core
var lines = Regex.Split(str, delimiter);
if (lines.Length == 1)
continue;
for (int i = 0; i < lines.Length - 1; i++)
{
string strToSend = null;
@@ -163,17 +157,17 @@ namespace PepperDash.Core
strToSend = lines[i];
handler(this, new GenericCommMethodReceiveTextArgs(strToSend, delimiter));
}
ReceiveBuffer = new StringBuilder(lines[lines.Length - 1]);
ReceiveBuffer = new StringBuilder(lines[lines.Length - 1]);
}
}
}
}
}
/// <summary>
/// Deconstructor. Disconnects from port TextReceived events.
/// </summary>
~CommunicationGather()
{
Stop();
}
}
/// <summary>
/// Deconstructor. Disconnects from port TextReceived events.
/// </summary>
~CommunicationGather()
{
Stop();
}
}
}

View File

@@ -1,11 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
using PepperDash.Core;
using Crestron.SimplSharp;
using PepperDash.Core.Logging;
using System;
namespace PepperDash.Core
namespace PepperDash.Core.Comm
{
/// <summary>
/// Controls the ability to disable/enable debugging of TX/RX data sent to/from a device with a built in timer to disable
@@ -37,14 +34,14 @@ namespace PepperDash.Core
{
get
{
return _DebugTimeoutInMs/60000;
return _DebugTimeoutInMs / 60000;
}
}
/// <summary>
/// Indicates that receive stream debugging is enabled
/// </summary>
public bool RxStreamDebuggingIsEnabled{ get; private set; }
public bool RxStreamDebuggingIsEnabled { get; private set; }
/// <summary>
/// Indicates that transmit stream debugging is enabled
@@ -102,7 +99,7 @@ namespace PepperDash.Core
TxStreamDebuggingIsEnabled = true;
Debug.SetDeviceDebugSettings(ParentDeviceKey, setting);
}
/// <summary>
@@ -144,7 +141,7 @@ namespace PepperDash.Core
/// <summary>
/// Debug received data
/// </summary>
Rx = 1,
Rx = 1,
/// <summary>
/// Debug transmitted data
/// </summary>

View File

@@ -1,13 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
using Newtonsoft.Json;
using System;
namespace PepperDash.Core
namespace PepperDash.Core.Comm
{
/// <summary>
/// Config properties that indicate how to communicate with a device for control

View File

@@ -8,15 +8,10 @@ and in all parts thereof, regardless of the use to which it is being put. Any u
of this material by another party without the express written permission of PepperDash Technology Corporation is prohibited.
PepperDash Technology Corporation reserves all rights under applicable laws.
------------------------------------ */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronSockets;
using System;
namespace PepperDash.Core
namespace PepperDash.Core.Comm
{
/// <summary>
/// Delegate for notifying of socket status changes
@@ -28,7 +23,7 @@ namespace PepperDash.Core
/// EventArgs class for socket status changes
/// </summary>
public class GenericSocketStatusChageEventArgs : EventArgs
{
{
/// <summary>
///
/// </summary>
@@ -39,13 +34,13 @@ namespace PepperDash.Core
/// </summary>
/// <param name="client"></param>
public GenericSocketStatusChageEventArgs(ISocketStatus client)
{
Client = client;
}
/// <summary>
/// S+ Constructor
/// </summary>
public GenericSocketStatusChageEventArgs() { }
{
Client = client;
}
/// <summary>
/// S+ Constructor
/// </summary>
public GenericSocketStatusChageEventArgs() { }
}
/// <summary>
@@ -72,10 +67,10 @@ namespace PepperDash.Core
{
State = state;
}
/// <summary>
/// S+ Constructor
/// </summary>
public GenericTcpServerStateChangedEventArgs() { }
/// <summary>
/// S+ Constructor
/// </summary>
public GenericTcpServerStateChangedEventArgs() { }
}
/// <summary>
@@ -126,10 +121,10 @@ namespace PepperDash.Core
ReceivedFromClientIndex = clientIndex;
ClientStatus = clientStatus;
}
/// <summary>
/// S+ Constructor
/// </summary>
public GenericTcpServerSocketStatusChangeEventArgs() { }
/// <summary>
/// S+ Constructor
/// </summary>
public GenericTcpServerSocketStatusChangeEventArgs() { }
}
/// <summary>
@@ -146,12 +141,12 @@ namespace PepperDash.Core
///
/// </summary>
public ushort ReceivedFromClientIndexShort
{
get
{
return (ushort)ReceivedFromClientIndex;
}
}
{
get
{
return (ushort)ReceivedFromClientIndex;
}
}
/// <summary>
///
@@ -177,10 +172,10 @@ namespace PepperDash.Core
Text = text;
ReceivedFromClientIndex = clientIndex;
}
/// <summary>
/// S+ Constructor
/// </summary>
public GenericTcpServerCommMethodReceiveTextArgs() { }
/// <summary>
/// S+ Constructor
/// </summary>
public GenericTcpServerCommMethodReceiveTextArgs() { }
}
/// <summary>
@@ -201,10 +196,10 @@ namespace PepperDash.Core
{
IsReady = isReady;
}
/// <summary>
/// S+ Constructor
/// </summary>
public GenericTcpServerClientReadyForcommunicationsEventArgs() { }
/// <summary>
/// S+ Constructor
/// </summary>
public GenericTcpServerClientReadyForcommunicationsEventArgs() { }
}
/// <summary>
@@ -246,6 +241,6 @@ namespace PepperDash.Core
}
}

View File

@@ -1,10 +1,8 @@
using System;
using Crestron.SimplSharp;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
namespace PepperDash.Core
namespace PepperDash.Core.Comm
{
/// <summary>
/// Background class that manages debug features for sockets
@@ -20,7 +18,7 @@ namespace PepperDash.Core
{
if (CrestronEnvironment.RuntimeEnvironment == eRuntimeEnvironment.SimplSharpPro)
{
CrestronConsole.AddNewConsoleCommand(SocketCommand, "socket", "socket commands: list, send, connect, disco",
CrestronConsole.AddNewConsoleCommand(SocketCommand, "socket", "socket commands: list, send, connect, disco",
ConsoleAccessLevelEnum.AccessOperator);
}
}
@@ -38,30 +36,30 @@ namespace PepperDash.Core
if (tokens.Length == 0)
return;
var command = tokens[0].ToLower();
if(command == "connect")
if (command == "connect")
{
}
else if(command == "disco")
else if (command == "disco")
{
}
else if(command =="list")
else if (command == "list")
{
CrestronConsole.ConsoleCommandResponse("{0} sockets", Sockets.Count);
if(Sockets.Count == 0)
if (Sockets.Count == 0)
return;
// get the longest key name, for formatting
var longestLength = Sockets.Aggregate("",
var longestLength = Sockets.Aggregate("",
(max, cur) => max.Length > cur.Key.Length ? max : cur.Key).Length;
for(int i = 0; i < Sockets.Count; i++)
for (int i = 0; i < Sockets.Count; i++)
{
var sock = Sockets[i];
CrestronConsole.ConsoleCommandResponse("{0} {1} {2} {3}",
i, sock.Key, GetSocketType(sock), sock.ClientStatus);
}
}
else if(command == "send")
else if (command == "send")
{
}
@@ -87,7 +85,7 @@ namespace PepperDash.Core
/// <param name="socket"></param>
public static void AddSocket(ISocketStatus socket)
{
if(!Sockets.Contains(socket))
if (!Sockets.Contains(socket))
Sockets.Add(socket);
}

View File

@@ -1,17 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronIO;
using Crestron.SimplSharp.Net.Http;
using PepperDash.Core.Logging;
using System;
using System.Text;
namespace PepperDash.Core
namespace PepperDash.Core.Comm
{
/// <summary>
/// Client for communicating with an HTTP Server Side Event pattern
/// </summary>
public class GenericHttpSseClient : ICommunicationReceiver
public class GenericHttpSseClient : ICommunicationReceiver
{
/// <summary>
/// Notifies when bytes have been received
@@ -90,11 +89,11 @@ namespace PepperDash.Core
/// <param name="url"></param>
public void InitiateConnection(string url)
{
CrestronInvoke.BeginInvoke(o =>
CrestronInvoke.BeginInvoke(o =>
{
try
{
if(string.IsNullOrEmpty(url))
if (string.IsNullOrEmpty(url))
{
Debug.Console(0, this, "Error connecting to Server. No URL specified");
return;
@@ -187,7 +186,7 @@ namespace PepperDash.Core
Crestron.SimplSharp.CrestronIO.IAsyncResult asyncResult = null;
do
{
asyncResult = streamResponse.BeginRead(asyncState.BufferRead, 0, RequestState.BUFFER_SIZE,
asyncResult = streamResponse.BeginRead(asyncState.BufferRead, 0, RequestState.BUFFER_SIZE,
new Crestron.SimplSharp.CrestronIO.AsyncCallback(ReadCallBack), asyncState);
}
while (asyncResult.CompletedSynchronously && !asyncState.Done);
@@ -226,7 +225,7 @@ namespace PepperDash.Core
var str = Encoding.GetEncoding(28591).GetString(bytes, 0, bytes.Length);
textHandler(this, new GenericCommMethodReceiveTextArgs(str));
}
//requestState.RequestData.Append(Encoding.ASCII.GetString(requestState.BufferRead, 0, read));
//CrestronConsole.PrintLine(requestState.RequestData.ToString());
@@ -241,7 +240,7 @@ namespace PepperDash.Core
Crestron.SimplSharp.CrestronIO.IAsyncResult asynchronousResult;
do
{
asynchronousResult = responseStream.BeginRead(requestState.BufferRead, 0, RequestState.BUFFER_SIZE,
asynchronousResult = responseStream.BeginRead(requestState.BufferRead, 0, RequestState.BUFFER_SIZE,
new Crestron.SimplSharp.CrestronIO.AsyncCallback(ReadCallBack), requestState);
}
while (asynchronousResult.CompletedSynchronously && !requestState.Done);

View File

@@ -1,12 +1,11 @@
using System;
using System.Collections.Generic;
using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronSockets;
using PepperDash.Core.Logging;
using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronSockets;
namespace PepperDash.Core
namespace PepperDash.Core.Comm
{
/// <summary>
/// A class to handle secure TCP/IP communications with a server
@@ -47,7 +46,7 @@ namespace PepperDash.Core
/// It is not recommended to use both the TextReceived event and the TextReceivedQueueInvoke event.
/// </summary>
public event EventHandler<GenericTcpServerCommMethodReceiveTextArgs> TextReceivedQueueInvoke;
/// <summary>
/// For a client with a pre shared key, this will fire after the communication is established and the key exchange is complete. If you require
/// a key and subscribe to the socket change event and try to send data on a connection the data sent will interfere with the key exchange and disconnect.
@@ -261,7 +260,7 @@ namespace PepperDash.Core
/// <summary>
/// Simpl+ Heartbeat Analog value in seconds
/// </summary>
public ushort HeartbeatRequiredIntervalInSeconds { set { HeartbeatInterval = (value * 1000); } }
public ushort HeartbeatRequiredIntervalInSeconds { set { HeartbeatInterval = value * 1000; } }
CTimer HeartbeatSendTimer;
CTimer HeartbeatAckTimer;
@@ -424,7 +423,7 @@ namespace PepperDash.Core
{
if (_client != null)
{
_client.SocketStatusChange -= this.Client_SocketStatusChange;
_client.SocketStatusChange -= Client_SocketStatusChange;
DisconnectClient();
}
return true;
@@ -483,7 +482,7 @@ namespace PepperDash.Core
_client = new SecureTCPClient(Hostname, Port, BufferSize);
_client.SocketStatusChange += Client_SocketStatusChange;
if (HeartbeatEnabled)
_client.SocketSendOrReceiveTimeOutInMs = (HeartbeatInterval * 5);
_client.SocketSendOrReceiveTimeOutInMs = HeartbeatInterval * 5;
_client.AddressClientConnectedTo = Hostname;
_client.PortNumber = Port;
// SecureClient = c;
@@ -608,7 +607,7 @@ namespace PepperDash.Core
ConnectFailTimer.Dispose();
ConnectFailTimer = null;
}
#region Methods
/// <summary>
@@ -744,11 +743,11 @@ namespace PepperDash.Core
if (HeartbeatSendTimer == null)
{
HeartbeatSendTimer = new CTimer(this.SendHeartbeat, null, HeartbeatInterval, HeartbeatInterval);
HeartbeatSendTimer = new CTimer(SendHeartbeat, null, HeartbeatInterval, HeartbeatInterval);
}
if (HeartbeatAckTimer == null)
{
HeartbeatAckTimer = new CTimer(HeartbeatAckTimerFail, null, (HeartbeatInterval * 2), (HeartbeatInterval * 2));
HeartbeatAckTimer = new CTimer(HeartbeatAckTimerFail, null, HeartbeatInterval * 2, HeartbeatInterval * 2);
}
}
@@ -772,7 +771,7 @@ namespace PepperDash.Core
}
void SendHeartbeat(object notused)
{
this.SendText(HeartbeatString);
SendText(HeartbeatString);
Debug.Console(2, this, "Sending Heartbeat");
}
@@ -796,7 +795,7 @@ namespace PepperDash.Core
}
else
{
HeartbeatAckTimer = new CTimer(HeartbeatAckTimerFail, null, (HeartbeatInterval * 2), (HeartbeatInterval * 2));
HeartbeatAckTimer = new CTimer(HeartbeatAckTimerFail, null, HeartbeatInterval * 2, HeartbeatInterval * 2);
}
Debug.Console(2, this, "Heartbeat Received: {0}, from Server", HeartbeatString);
return remainingText;
@@ -861,7 +860,7 @@ namespace PepperDash.Core
// HOW IN THE HELL DO WE CATCH AN EXCEPTION IN SENDING?????
if (n <= 0)
{
Debug.Console(1, Debug.ErrorLogLevel.Warning, "[{0}] Sent zero bytes. Was there an error?", this.Key);
Debug.Console(1, Debug.ErrorLogLevel.Warning, "[{0}] Sent zero bytes. Was there an error?", Key);
}
});
}
@@ -906,7 +905,7 @@ namespace PepperDash.Core
}
try
{
Debug.Console(2, this, "Socket status change: {0} ({1})", client.ClientStatus, (ushort)(client.ClientStatus));
Debug.Console(2, this, "Socket status change: {0} ({1})", client.ClientStatus, (ushort)client.ClientStatus);
OnConnectionChange();
// The client could be null or disposed by this time...
@@ -940,12 +939,12 @@ namespace PepperDash.Core
void OnClientReadyForcommunications(bool isReady)
{
IsReadyForCommunication = isReady;
if (IsReadyForCommunication)
if (IsReadyForCommunication)
HeartbeatStart();
var handler = ClientReadyForCommunications;
if (handler == null) return;
handler(this, new GenericTcpServerClientReadyForcommunicationsEventArgs(IsReadyForCommunication));
}
#endregion

View File

@@ -10,15 +10,14 @@ of this material by another party without the express written permission of Pepp
PepperDash Technology Corporation reserves all rights under applicable laws.
------------------------------------ */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronSockets;
using PepperDash.Core.Logging;
using System;
using System.Linq;
using System.Text;
namespace PepperDash.Core
namespace PepperDash.Core.Comm
{
/// <summary>
/// Generic secure TCP/IP client for server
@@ -250,7 +249,7 @@ namespace PepperDash.Core
/// <summary>
/// Simpl+ Heartbeat Analog value in seconds
/// </summary>
public ushort HeartbeatRequiredIntervalInSeconds { set { HeartbeatInterval = (value * 1000); } }
public ushort HeartbeatRequiredIntervalInSeconds { set { HeartbeatInterval = value * 1000; } }
CTimer HeartbeatSendTimer;
CTimer HeartbeatAckTimer;
@@ -360,7 +359,7 @@ namespace PepperDash.Core
SharedKey = clientConfigObject.SharedKey;
SharedKeyRequired = clientConfigObject.SharedKeyRequired;
HeartbeatEnabled = clientConfigObject.HeartbeatRequired;
HeartbeatRequiredIntervalInSeconds = clientConfigObject.HeartbeatRequiredIntervalInSeconds > 0 ?
HeartbeatRequiredIntervalInSeconds = clientConfigObject.HeartbeatRequiredIntervalInSeconds > 0 ?
clientConfigObject.HeartbeatRequiredIntervalInSeconds : (ushort)15;
HeartbeatString = string.IsNullOrEmpty(clientConfigObject.HeartbeatStringToMatch) ? "heartbeat" : clientConfigObject.HeartbeatStringToMatch;
Port = TcpSshProperties.Port;
@@ -446,7 +445,7 @@ namespace PepperDash.Core
Client = new SecureTCPClient(Hostname, Port, BufferSize);
Client.SocketStatusChange += Client_SocketStatusChange;
if (HeartbeatEnabled)
Client.SocketSendOrReceiveTimeOutInMs = (HeartbeatInterval * 5);
Client.SocketSendOrReceiveTimeOutInMs = HeartbeatInterval * 5;
Client.AddressClientConnectedTo = Hostname;
Client.PortNumber = Port;
// SecureClient = c;
@@ -590,7 +589,7 @@ namespace PepperDash.Core
RetryTimer.Stop();
RetryTimer = null;
}
if(AutoReconnectTriggered != null)
if (AutoReconnectTriggered != null)
AutoReconnectTriggered(this, new EventArgs());
RetryTimer = new CTimer(o => Connect(), rndTime);
}
@@ -702,11 +701,11 @@ namespace PepperDash.Core
if (HeartbeatSendTimer == null)
{
HeartbeatSendTimer = new CTimer(this.SendHeartbeat, null, HeartbeatInterval, HeartbeatInterval);
HeartbeatSendTimer = new CTimer(SendHeartbeat, null, HeartbeatInterval, HeartbeatInterval);
}
if (HeartbeatAckTimer == null)
{
HeartbeatAckTimer = new CTimer(HeartbeatAckTimerFail, null, (HeartbeatInterval * 2), (HeartbeatInterval * 2));
HeartbeatAckTimer = new CTimer(HeartbeatAckTimerFail, null, HeartbeatInterval * 2, HeartbeatInterval * 2);
}
}
@@ -730,7 +729,7 @@ namespace PepperDash.Core
}
void SendHeartbeat(object notused)
{
this.SendText(HeartbeatString);
SendText(HeartbeatString);
Debug.Console(2, this, "Sending Heartbeat");
}
@@ -754,7 +753,7 @@ namespace PepperDash.Core
}
else
{
HeartbeatAckTimer = new CTimer(HeartbeatAckTimerFail, null, (HeartbeatInterval * 2), (HeartbeatInterval * 2));
HeartbeatAckTimer = new CTimer(HeartbeatAckTimerFail, null, HeartbeatInterval * 2, HeartbeatInterval * 2);
}
Debug.Console(2, this, "Heartbeat Received: {0}, from Server", HeartbeatString);
return remainingText;
@@ -819,7 +818,7 @@ namespace PepperDash.Core
// HOW IN THE HELL DO WE CATCH AN EXCEPTION IN SENDING?????
if (n <= 0)
{
Debug.Console(1, Debug.ErrorLogLevel.Warning, "[{0}] Sent zero bytes. Was there an error?", this.Key);
Debug.Console(1, Debug.ErrorLogLevel.Warning, "[{0}] Sent zero bytes. Was there an error?", Key);
}
});
}
@@ -864,7 +863,7 @@ namespace PepperDash.Core
}
try
{
Debug.Console(2, this, "Socket status change: {0} ({1})", client.ClientStatus, (ushort)(client.ClientStatus));
Debug.Console(2, this, "Socket status change: {0} ({1})", client.ClientStatus, (ushort)client.ClientStatus);
OnConnectionChange();
// The client could be null or disposed by this time...
@@ -897,7 +896,7 @@ namespace PepperDash.Core
void OnClientReadyForcommunications(bool isReady)
{
IsReadyForCommunication = isReady;
if (this.IsReadyForCommunication) { HeartbeatStart(); }
if (IsReadyForCommunication) { HeartbeatStart(); }
var handler = ClientReadyForCommunications;
if (handler != null)
handler(this, new GenericTcpServerClientReadyForcommunicationsEventArgs(IsReadyForCommunication));

View File

@@ -10,16 +10,15 @@ of this material by another party without the express written permission of Pepp
PepperDash Technology Corporation reserves all rights under applicable laws.
------------------------------------ */
using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronSockets;
using PepperDash.Core.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronSockets;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace PepperDash.Core
namespace PepperDash.Core.Comm
{
/// <summary>
/// Generic secure TCP/IP server
@@ -257,7 +256,7 @@ namespace PepperDash.Core
/// <summary>
/// Simpl+ Heartbeat Analog value in seconds
/// </summary>
public ushort HeartbeatRequiredIntervalInSeconds { set { HeartbeatRequiredIntervalMs = (value * 1000); } }
public ushort HeartbeatRequiredIntervalInSeconds { set { HeartbeatRequiredIntervalMs = value * 1000; } }
/// <summary>
/// String to Match for heartbeat. If null or empty any string will reset heartbeat timer
@@ -418,34 +417,34 @@ namespace PepperDash.Core
}
if (SecureServer == null)
{
SecureServer = new SecureTCPServer(Port, MaxClients);
if (HeartbeatRequired)
SecureServer.SocketSendOrReceiveTimeOutInMs = (this.HeartbeatRequiredIntervalMs * 5);
SecureServer.HandshakeTimeout = 30;
SecureServer.SocketStatusChange += new SecureTCPServerSocketStatusChangeEventHandler(SecureServer_SocketStatusChange);
}
else
{
SecureServer.PortNumber = Port;
}
ServerStopped = false;
if (SecureServer == null)
{
SecureServer = new SecureTCPServer(Port, MaxClients);
if (HeartbeatRequired)
SecureServer.SocketSendOrReceiveTimeOutInMs = HeartbeatRequiredIntervalMs * 5;
SecureServer.HandshakeTimeout = 30;
SecureServer.SocketStatusChange += new SecureTCPServerSocketStatusChangeEventHandler(SecureServer_SocketStatusChange);
}
else
{
SecureServer.PortNumber = Port;
}
ServerStopped = false;
// Start the listner
SocketErrorCodes status = SecureServer.WaitForConnectionAsync(IPAddress.Any, SecureConnectCallback);
if (status != SocketErrorCodes.SOCKET_OPERATION_PENDING)
{
Debug.Console(0, this, Debug.ErrorLogLevel.Error, "Error starting WaitForConnectionAsync {0}", status);
}
else
{
ServerStopped = false;
}
OnServerStateChange(SecureServer.State);
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Secure Server Status: {0}, Socket Status: {1}", SecureServer.State, SecureServer.ServerSocketStatus);
ServerCCSection.Leave();
// Start the listner
SocketErrorCodes status = SecureServer.WaitForConnectionAsync(IPAddress.Any, SecureConnectCallback);
if (status != SocketErrorCodes.SOCKET_OPERATION_PENDING)
{
Debug.Console(0, this, Debug.ErrorLogLevel.Error, "Error starting WaitForConnectionAsync {0}", status);
}
else
{
ServerStopped = false;
}
OnServerStateChange(SecureServer.State);
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Secure Server Status: {0}, Socket Status: {1}", SecureServer.State, SecureServer.ServerSocketStatus);
ServerCCSection.Leave();
}
catch (Exception ex)
{
@@ -459,21 +458,21 @@ namespace PepperDash.Core
/// </summary>
public void StopListening()
{
try
{
Debug.Console(2, this, Debug.ErrorLogLevel.Notice, "Stopping Listener");
if (SecureServer != null)
{
SecureServer.Stop();
Debug.Console(2, this, Debug.ErrorLogLevel.Notice, "Server State: {0}", SecureServer.State);
OnServerStateChange(SecureServer.State);
}
ServerStopped = true;
}
catch (Exception ex)
{
Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error stopping server. Error: {0}", ex);
}
try
{
Debug.Console(2, this, Debug.ErrorLogLevel.Notice, "Stopping Listener");
if (SecureServer != null)
{
SecureServer.Stop();
Debug.Console(2, this, Debug.ErrorLogLevel.Notice, "Server State: {0}", SecureServer.State);
OnServerStateChange(SecureServer.State);
}
ServerStopped = true;
}
catch (Exception ex)
{
Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error stopping server. Error: {0}", ex);
}
}
/// <summary>
@@ -528,7 +527,7 @@ namespace PepperDash.Core
OnServerStateChange(SecureServer.State); //State shows both listening and connected
}
// var o = new { };
// var o = new { };
}
/// <summary>
@@ -546,7 +545,7 @@ namespace PepperDash.Core
byte[] b = Encoding.GetEncoding(28591).GetBytes(text);
foreach (uint i in ConnectedClientsIndexes)
{
if (!SharedKeyRequired || (SharedKeyRequired && ClientReadyAfterKeyExchange.Contains(i)))
if (!SharedKeyRequired || SharedKeyRequired && ClientReadyAfterKeyExchange.Contains(i))
{
SocketErrorCodes error = SecureServer.SendDataAsync(i, b, b.Length, (x, y, z) => { });
if (error != SocketErrorCodes.SOCKET_OK && error != SocketErrorCodes.SOCKET_OPERATION_PENDING)
@@ -575,7 +574,7 @@ namespace PepperDash.Core
byte[] b = Encoding.GetEncoding(28591).GetBytes(text);
if (SecureServer != null && SecureServer.GetServerSocketStatusForSpecificClient(clientIndex) == SocketStatus.SOCKET_STATUS_CONNECTED)
{
if (!SharedKeyRequired || (SharedKeyRequired && ClientReadyAfterKeyExchange.Contains(clientIndex)))
if (!SharedKeyRequired || SharedKeyRequired && ClientReadyAfterKeyExchange.Contains(clientIndex))
SecureServer.SendDataAsync(clientIndex, b, b.Length, (x, y, z) => { });
}
}
@@ -639,9 +638,9 @@ namespace PepperDash.Core
public string GetClientIPAddress(uint clientIndex)
{
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "GetClientIPAddress Index: {0}", clientIndex);
if (!SharedKeyRequired || (SharedKeyRequired && ClientReadyAfterKeyExchange.Contains(clientIndex)))
if (!SharedKeyRequired || SharedKeyRequired && ClientReadyAfterKeyExchange.Contains(clientIndex))
{
var ipa = this.SecureServer.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex);
var ipa = SecureServer.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex);
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "GetClientIPAddress IPAddreess: {0}", ipa);
return ipa;
@@ -666,7 +665,7 @@ namespace PepperDash.Core
address = SecureServer.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex);
Debug.Console(1, this, Debug.ErrorLogLevel.Warning, "Heartbeat not received for Client index {2} IP: {0}, DISCONNECTING BECAUSE HEARTBEAT REQUIRED IS TRUE {1}",
address, string.IsNullOrEmpty(HeartbeatStringToMatch) ? "" : ("HeartbeatStringToMatch: " + HeartbeatStringToMatch), clientIndex);
address, string.IsNullOrEmpty(HeartbeatStringToMatch) ? "" : "HeartbeatStringToMatch: " + HeartbeatStringToMatch, clientIndex);
if (SecureServer.GetServerSocketStatusForSpecificClient(clientIndex) == SocketStatus.SOCKET_STATUS_CONNECTED)
SendTextToClient("Heartbeat not received by server, closing connection", clientIndex);
@@ -700,13 +699,13 @@ namespace PepperDash.Core
{
try
{
// Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "SecureServerSocketStatusChange Index:{0} status:{1} Port:{2} IP:{3}", clientIndex, serverSocketStatus, this.SecureServer.GetPortNumberServerAcceptedConnectionFromForSpecificClient(clientIndex), this.SecureServer.GetLocalAddressServerAcceptedConnectionFromForSpecificClient(clientIndex));
// Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "SecureServerSocketStatusChange Index:{0} status:{1} Port:{2} IP:{3}", clientIndex, serverSocketStatus, this.SecureServer.GetPortNumberServerAcceptedConnectionFromForSpecificClient(clientIndex), this.SecureServer.GetLocalAddressServerAcceptedConnectionFromForSpecificClient(clientIndex));
if (serverSocketStatus != SocketStatus.SOCKET_STATUS_CONNECTED)
{
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "SecureServerSocketStatusChange ConnectedCLients: {0} ServerState: {1} Port: {2}", SecureServer.NumberOfClientsConnected, SecureServer.State, SecureServer.PortNumber);
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "SecureServerSocketStatusChange ConnectedCLients: {0} ServerState: {1} Port: {2}", SecureServer.NumberOfClientsConnected, SecureServer.State, SecureServer.PortNumber);
if (ConnectedClientsIndexes.Contains(clientIndex))
ConnectedClientsIndexes.Remove(clientIndex);
if (HeartbeatRequired && HeartbeatTimerDictionary.ContainsKey(clientIndex))
@@ -717,12 +716,12 @@ namespace PepperDash.Core
}
if (ClientReadyAfterKeyExchange.Contains(clientIndex))
ClientReadyAfterKeyExchange.Remove(clientIndex);
if (WaitingForSharedKey.Contains(clientIndex))
WaitingForSharedKey.Remove(clientIndex);
if (SecureServer.MaxNumberOfClientSupported > SecureServer.NumberOfClientsConnected)
{
Listen();
}
if (WaitingForSharedKey.Contains(clientIndex))
WaitingForSharedKey.Remove(clientIndex);
if (SecureServer.MaxNumberOfClientSupported > SecureServer.NumberOfClientsConnected)
{
Listen();
}
}
}
catch (Exception ex)
@@ -786,7 +785,7 @@ namespace PepperDash.Core
}
else
{
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Client attempt faulty.");
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Client attempt faulty.");
}
}
catch (Exception ex)
@@ -794,19 +793,19 @@ namespace PepperDash.Core
Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error in Socket Status Connect Callback. Error: {0}", ex);
}
// Rearm the listner
SocketErrorCodes status = server.WaitForConnectionAsync(IPAddress.Any, SecureConnectCallback);
if (status != SocketErrorCodes.SOCKET_OPERATION_PENDING)
{
Debug.Console(0, this, Debug.ErrorLogLevel.Error, "Socket status connect callback status {0}", status);
if (status == SocketErrorCodes.SOCKET_CONNECTION_IN_PROGRESS)
{
// There is an issue where on a failed negotiation we need to stop and start the server. This should still leave connected clients intact.
server.Stop();
Listen();
}
}
}
// Rearm the listner
SocketErrorCodes status = server.WaitForConnectionAsync(IPAddress.Any, SecureConnectCallback);
if (status != SocketErrorCodes.SOCKET_OPERATION_PENDING)
{
Debug.Console(0, this, Debug.ErrorLogLevel.Error, "Socket status connect callback status {0}", status);
if (status == SocketErrorCodes.SOCKET_CONNECTION_IN_PROGRESS)
{
// There is an issue where on a failed negotiation we need to stop and start the server. This should still leave connected clients intact.
server.Stop();
Listen();
}
}
}
#endregion
@@ -821,13 +820,13 @@ namespace PepperDash.Core
{
if (numberOfBytesReceived > 0)
{
string received = "Nothing";
var handler = TextReceivedQueueInvoke;
try
{
byte[] bytes = mySecureTCPServer.GetIncomingDataBufferForSpecificClient(clientIndex);
received = System.Text.Encoding.GetEncoding(28591).GetString(bytes, 0, numberOfBytesReceived);
received = Encoding.GetEncoding(28591).GetString(bytes, 0, numberOfBytesReceived);
if (WaitingForSharedKey.Contains(clientIndex))
{
received = received.Replace("\r", "");
@@ -838,7 +837,7 @@ namespace PepperDash.Core
Debug.Console(1, this, Debug.ErrorLogLevel.Warning, "Client at index {0} Shared key did not match the server, disconnecting client. Key: {1}", clientIndex, received);
mySecureTCPServer.SendData(clientIndex, b, b.Length);
mySecureTCPServer.Disconnect(clientIndex);
return;
}
@@ -846,7 +845,7 @@ namespace PepperDash.Core
byte[] success = Encoding.GetEncoding(28591).GetBytes("Shared Key Match");
mySecureTCPServer.SendDataAsync(clientIndex, success, success.Length, null);
OnServerClientReadyForCommunications(clientIndex);
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Client with index {0} provided the shared key and successfully connected to the server", clientIndex);
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Client with index {0} provided the shared key and successfully connected to the server", clientIndex);
}
else if (!string.IsNullOrEmpty(checkHeartbeat(clientIndex, received)))
{
@@ -861,8 +860,8 @@ namespace PepperDash.Core
{
Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error Receiving data: {0}. Error: {1}", received, ex);
}
if (mySecureTCPServer.GetServerSocketStatusForSpecificClient(clientIndex) == SocketStatus.SOCKET_STATUS_CONNECTED)
mySecureTCPServer.ReceiveDataAsync(clientIndex, SecureReceivedDataAsyncCallback);
if (mySecureTCPServer.GetServerSocketStatusForSpecificClient(clientIndex) == SocketStatus.SOCKET_STATUS_CONNECTED)
mySecureTCPServer.ReceiveDataAsync(clientIndex, SecureReceivedDataAsyncCallback);
//Check to see if there is a subscription to the TextReceivedQueueInvoke event. If there is start the dequeue thread.
if (handler != null)
@@ -872,9 +871,9 @@ namespace PepperDash.Core
CrestronInvoke.BeginInvoke((o) => DequeueEvent());
}
}
else
{
mySecureTCPServer.Disconnect(clientIndex);
else
{
mySecureTCPServer.Disconnect(clientIndex);
}
}
@@ -1011,8 +1010,8 @@ namespace PepperDash.Core
void RunMonitorClient()
{
MonitorClient = new GenericSecureTcpIpClient_ForServer(Key + "-MONITOR", "127.0.0.1", Port, 2000);
MonitorClient.SharedKeyRequired = this.SharedKeyRequired;
MonitorClient.SharedKey = this.SharedKey;
MonitorClient.SharedKeyRequired = SharedKeyRequired;
MonitorClient.SharedKey = SharedKey;
MonitorClient.ConnectionHasHungCallback = MonitorClientHasHungCallback;
//MonitorClient.ConnectionChange += MonitorClient_ConnectionChange;
MonitorClient.ClientReadyForCommunications += MonitorClient_IsReadyForComm;

View File

@@ -1,174 +1,174 @@
using System;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronSockets;
using Crestron.SimplSharp.Ssh;
using Crestron.SimplSharp.Ssh.Common;
using PepperDash.Core.Logging;
using System;
using System.Text;
namespace PepperDash.Core
namespace PepperDash.Core.Comm
{
/// <summary>
///
/// </summary>
/// <summary>
///
/// </summary>
public class GenericSshClient : Device, ISocketStatusWithStreamDebugging, IAutoReconnect
{
private const string SPlusKey = "Uninitialized SshClient";
{
private const string SPlusKey = "Uninitialized SshClient";
/// <summary>
/// Object to enable stream debugging
/// </summary>
public CommunicationStreamDebugging StreamDebugging { get; private set; }
/// <summary>
/// Event that fires when data is received. Delivers args with byte array
/// </summary>
public event EventHandler<GenericCommMethodReceiveBytesArgs> BytesReceived;
/// <summary>
/// Event that fires when data is received. Delivers args with byte array
/// </summary>
public event EventHandler<GenericCommMethodReceiveBytesArgs> BytesReceived;
/// <summary>
/// Event that fires when data is received. Delivered as text.
/// </summary>
public event EventHandler<GenericCommMethodReceiveTextArgs> TextReceived;
/// <summary>
/// Event that fires when data is received. Delivered as text.
/// </summary>
public event EventHandler<GenericCommMethodReceiveTextArgs> TextReceived;
/// <summary>
/// Event when the connection status changes.
/// </summary>
public event EventHandler<GenericSocketStatusChageEventArgs> ConnectionChange;
/// <summary>
/// Event when the connection status changes.
/// </summary>
public event EventHandler<GenericSocketStatusChageEventArgs> ConnectionChange;
///// <summary>
/////
///// </summary>
//public event GenericSocketStatusChangeEventDelegate SocketStatusChange;
/// <summary>
/// Address of server
/// </summary>
public string Hostname { get; set; }
/// <summary>
/// Address of server
/// </summary>
public string Hostname { get; set; }
/// <summary>
/// Port on server
/// </summary>
public int Port { get; set; }
/// <summary>
/// Port on server
/// </summary>
public int Port { get; set; }
/// <summary>
/// Username for server
/// </summary>
public string Username { get; set; }
/// <summary>
/// Username for server
/// </summary>
public string Username { get; set; }
/// <summary>
/// And... Password for server. That was worth documenting!
/// </summary>
public string Password { get; set; }
/// <summary>
/// And... Password for server. That was worth documenting!
/// </summary>
public string Password { get; set; }
/// <summary>
/// True when the server is connected - when status == 2.
/// </summary>
public bool IsConnected
{
// returns false if no client or not connected
/// <summary>
/// True when the server is connected - when status == 2.
/// </summary>
public bool IsConnected
{
// returns false if no client or not connected
get { return Client != null && ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED; }
}
}
/// <summary>
/// S+ helper for IsConnected
/// </summary>
public ushort UIsConnected
{
get { return (ushort)(IsConnected ? 1 : 0); }
}
/// <summary>
/// S+ helper for IsConnected
/// </summary>
public ushort UIsConnected
{
get { return (ushort)(IsConnected ? 1 : 0); }
}
/// <summary>
///
/// </summary>
public SocketStatus ClientStatus
{
get { return _ClientStatus; }
private set
{
if (_ClientStatus == value)
return;
_ClientStatus = value;
OnConnectionChange();
}
}
SocketStatus _ClientStatus;
/// <summary>
///
/// </summary>
public SocketStatus ClientStatus
{
get { return _ClientStatus; }
private set
{
if (_ClientStatus == value)
return;
_ClientStatus = value;
OnConnectionChange();
}
}
SocketStatus _ClientStatus;
/// <summary>
/// Contains the familiar Simpl analog status values. This drives the ConnectionChange event
/// and IsConnected with be true when this == 2.
/// </summary>
public ushort UStatus
{
get { return (ushort)_ClientStatus; }
}
/// <summary>
/// Contains the familiar Simpl analog status values. This drives the ConnectionChange event
/// and IsConnected with be true when this == 2.
/// </summary>
public ushort UStatus
{
get { return (ushort)_ClientStatus; }
}
/// <summary>
/// Determines whether client will attempt reconnection on failure. Default is true
/// </summary>
public bool AutoReconnect { get; set; }
/// <summary>
/// Determines whether client will attempt reconnection on failure. Default is true
/// </summary>
public bool AutoReconnect { get; set; }
/// <summary>
/// Will be set and unset by connect and disconnect only
/// </summary>
public bool ConnectEnabled { get; private set; }
/// <summary>
/// Will be set and unset by connect and disconnect only
/// </summary>
public bool ConnectEnabled { get; private set; }
/// <summary>
/// S+ helper for AutoReconnect
/// </summary>
public ushort UAutoReconnect
{
get { return (ushort)(AutoReconnect ? 1 : 0); }
set { AutoReconnect = value == 1; }
}
/// <summary>
/// S+ helper for AutoReconnect
/// </summary>
public ushort UAutoReconnect
{
get { return (ushort)(AutoReconnect ? 1 : 0); }
set { AutoReconnect = value == 1; }
}
/// <summary>
/// Millisecond value, determines the timeout period in between reconnect attempts.
/// Set to 5000 by default
/// </summary>
public int AutoReconnectIntervalMs { get; set; }
/// <summary>
/// Millisecond value, determines the timeout period in between reconnect attempts.
/// Set to 5000 by default
/// </summary>
public int AutoReconnectIntervalMs { get; set; }
SshClient Client;
SshClient Client;
ShellStream TheStream;
ShellStream TheStream;
CTimer ReconnectTimer;
CTimer ReconnectTimer;
//Lock object to prevent simulatneous connect/disconnect operations
private CCriticalSection connectLock = new CCriticalSection();
private bool DisconnectLogged = false;
/// <summary>
/// Typical constructor.
/// </summary>
public GenericSshClient(string key, string hostname, int port, string username, string password) :
base(key)
{
/// <summary>
/// Typical constructor.
/// </summary>
public GenericSshClient(string key, string hostname, int port, string username, string password) :
base(key)
{
StreamDebugging = new CommunicationStreamDebugging(key);
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
Key = key;
Hostname = hostname;
Port = port;
Username = username;
Password = password;
AutoReconnectIntervalMs = 5000;
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
Key = key;
Hostname = hostname;
Port = port;
Username = username;
Password = password;
AutoReconnectIntervalMs = 5000;
ReconnectTimer = new CTimer(o =>
{
{
if (ConnectEnabled)
{
Connect();
}
}, Timeout.Infinite);
}
}, Timeout.Infinite);
}
/// <summary>
/// S+ Constructor - Must set all properties before calling Connect
/// </summary>
public GenericSshClient()
: base(SPlusKey)
{
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
AutoReconnectIntervalMs = 5000;
/// <summary>
/// S+ Constructor - Must set all properties before calling Connect
/// </summary>
public GenericSshClient()
: base(SPlusKey)
{
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
AutoReconnectIntervalMs = 5000;
ReconnectTimer = new CTimer(o =>
{
@@ -177,35 +177,35 @@ namespace PepperDash.Core
Connect();
}
}, Timeout.Infinite);
}
}
/// <summary>
/// Just to help S+ set the key
/// </summary>
public void Initialize(string key)
{
Key = key;
}
/// <summary>
/// Just to help S+ set the key
/// </summary>
public void Initialize(string key)
{
Key = key;
}
/// <summary>
/// Handles closing this up when the program shuts down
/// </summary>
void CrestronEnvironment_ProgramStatusEventHandler(eProgramStatusEventType programEventType)
{
if (programEventType == eProgramStatusEventType.Stopping)
{
if (Client != null)
{
Debug.Console(1, this, "Program stopping. Closing connection");
/// <summary>
/// Handles closing this up when the program shuts down
/// </summary>
void CrestronEnvironment_ProgramStatusEventHandler(eProgramStatusEventType programEventType)
{
if (programEventType == eProgramStatusEventType.Stopping)
{
if (Client != null)
{
Debug.Console(1, this, "Program stopping. Closing connection");
Disconnect();
}
}
}
}
}
}
/// <summary>
/// Connect to the server, using the provided properties.
/// </summary>
public void Connect()
/// <summary>
/// Connect to the server, using the provided properties.
/// </summary>
public void Connect()
{
// Don't go unless everything is here
if (string.IsNullOrEmpty(Hostname) || Port < 1 || Port > 65535
@@ -307,21 +307,21 @@ namespace PepperDash.Core
}
}
/// <summary>
/// Disconnect the clients and put away it's resources.
/// </summary>
public void Disconnect()
{
ConnectEnabled = false;
// Stop trying reconnects, if we are
if (ReconnectTimer != null)
{
ReconnectTimer.Stop();
ReconnectTimer = null;
}
/// <summary>
/// Disconnect the clients and put away it's resources.
/// </summary>
public void Disconnect()
{
ConnectEnabled = false;
// Stop trying reconnects, if we are
if (ReconnectTimer != null)
{
ReconnectTimer.Stop();
ReconnectTimer = null;
}
KillClient(SocketStatus.SOCKET_STATUS_BROKEN_LOCALLY);
}
}
/// <summary>
/// Kills the stream, cleans up the client and sets it to null
@@ -331,7 +331,7 @@ namespace PepperDash.Core
KillStream();
if (Client != null)
{
{
Client.Disconnect();
Client = null;
ClientStatus = status;
@@ -339,96 +339,96 @@ namespace PepperDash.Core
}
}
/// <summary>
/// Anything to do with reestablishing connection on failures
/// </summary>
void HandleConnectionFailure()
{
/// <summary>
/// Anything to do with reestablishing connection on failures
/// </summary>
void HandleConnectionFailure()
{
KillClient(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
Debug.Console(1, this, "Client nulled due to connection failure. AutoReconnect: {0}, ConnectEnabled: {1}", AutoReconnect, ConnectEnabled);
if (AutoReconnect && ConnectEnabled)
{
Debug.Console(1, this, "Checking autoreconnect: {0}, {1}ms", AutoReconnect, AutoReconnectIntervalMs);
if (ReconnectTimer == null)
{
ReconnectTimer = new CTimer(o =>
{
Connect();
}, AutoReconnectIntervalMs);
Debug.Console(1, this, "Attempting connection in {0} seconds",
(float) (AutoReconnectIntervalMs/1000));
}
else
{
Debug.Console(1, this, "{0} second reconnect cycle running",
(float) (AutoReconnectIntervalMs/1000));
}
}
}
if (AutoReconnect && ConnectEnabled)
{
Debug.Console(1, this, "Checking autoreconnect: {0}, {1}ms", AutoReconnect, AutoReconnectIntervalMs);
if (ReconnectTimer == null)
{
ReconnectTimer = new CTimer(o =>
{
Connect();
}, AutoReconnectIntervalMs);
Debug.Console(1, this, "Attempting connection in {0} seconds",
(float)(AutoReconnectIntervalMs / 1000));
}
else
{
Debug.Console(1, this, "{0} second reconnect cycle running",
(float)(AutoReconnectIntervalMs / 1000));
}
}
}
/// <summary>
/// Kills the stream
/// </summary>
void KillStream()
{
if (TheStream != null)
{
TheStream.DataReceived -= Stream_DataReceived;
TheStream.Close();
TheStream.Dispose();
TheStream = null;
{
if (TheStream != null)
{
TheStream.DataReceived -= Stream_DataReceived;
TheStream.Close();
TheStream.Dispose();
TheStream = null;
Debug.Console(1, this, "Disconnected stream");
}
}
}
}
/// <summary>
/// Handles the keyboard interactive authentication, should it be required.
/// </summary>
void kauth_AuthenticationPrompt(object sender, AuthenticationPromptEventArgs e)
{
foreach (AuthenticationPrompt prompt in e.Prompts)
if (prompt.Request.IndexOf("Password:", StringComparison.InvariantCultureIgnoreCase) != -1)
prompt.Response = Password;
}
/// <summary>
/// Handler for data receive on ShellStream. Passes data across to queue for line parsing.
/// </summary>
void Stream_DataReceived(object sender, Crestron.SimplSharp.Ssh.Common.ShellDataEventArgs e)
{
var bytes = e.Data;
if (bytes.Length > 0)
{
var bytesHandler = BytesReceived;
if (bytesHandler != null)
{
if (StreamDebugging.RxStreamDebuggingIsEnabled)
{
Debug.Console(0, this, "Received {1} bytes: '{0}'", ComTextHelper.GetEscapedText(bytes), bytes.Length);
}
/// <summary>
/// Handles the keyboard interactive authentication, should it be required.
/// </summary>
void kauth_AuthenticationPrompt(object sender, AuthenticationPromptEventArgs e)
{
foreach (AuthenticationPrompt prompt in e.Prompts)
if (prompt.Request.IndexOf("Password:", StringComparison.InvariantCultureIgnoreCase) != -1)
prompt.Response = Password;
}
/// <summary>
/// Handler for data receive on ShellStream. Passes data across to queue for line parsing.
/// </summary>
void Stream_DataReceived(object sender, ShellDataEventArgs e)
{
var bytes = e.Data;
if (bytes.Length > 0)
{
var bytesHandler = BytesReceived;
if (bytesHandler != null)
{
if (StreamDebugging.RxStreamDebuggingIsEnabled)
{
Debug.Console(0, this, "Received {1} bytes: '{0}'", ComTextHelper.GetEscapedText(bytes), bytes.Length);
}
bytesHandler(this, new GenericCommMethodReceiveBytesArgs(bytes));
}
var textHandler = TextReceived;
if (textHandler != null)
{
var str = Encoding.GetEncoding(28591).GetString(bytes, 0, bytes.Length);
}
var textHandler = TextReceived;
if (textHandler != null)
{
var str = Encoding.GetEncoding(28591).GetString(bytes, 0, bytes.Length);
if (StreamDebugging.RxStreamDebuggingIsEnabled)
Debug.Console(0, this, "Received: '{0}'", ComTextHelper.GetDebugText(str));
textHandler(this, new GenericCommMethodReceiveTextArgs(str));
}
}
}
}
}
/// <summary>
/// Error event handler for client events - disconnect, etc. Will forward those events via ConnectionChange
/// event
/// </summary>
void Client_ErrorOccurred(object sender, Crestron.SimplSharp.Ssh.Common.ExceptionEventArgs e)
{
/// <summary>
/// Error event handler for client events - disconnect, etc. Will forward those events via ConnectionChange
/// event
/// </summary>
void Client_ErrorOccurred(object sender, ExceptionEventArgs e)
{
CrestronInvoke.BeginInvoke(o =>
{
if (e.Exception is SshConnectionException || e.Exception is System.Net.Sockets.SocketException)
@@ -451,27 +451,27 @@ namespace PepperDash.Core
ReconnectTimer.Reset(AutoReconnectIntervalMs);
}
});
}
}
/// <summary>
/// Helper for ConnectionChange event
/// </summary>
void OnConnectionChange()
{
if (ConnectionChange != null)
ConnectionChange(this, new GenericSocketStatusChageEventArgs(this));
}
/// <summary>
/// Helper for ConnectionChange event
/// </summary>
void OnConnectionChange()
{
if (ConnectionChange != null)
ConnectionChange(this, new GenericSocketStatusChageEventArgs(this));
}
#region IBasicCommunication Members
#region IBasicCommunication Members
/// <summary>
/// Sends text to the server
/// </summary>
/// <param name="text"></param>
public void SendText(string text)
{
try
{
/// <summary>
/// Sends text to the server
/// </summary>
/// <param name="text"></param>
public void SendText(string text)
{
try
{
if (Client != null && TheStream != null && IsConnected)
{
if (StreamDebugging.TxStreamDebuggingIsEnabled)
@@ -485,24 +485,24 @@ namespace PepperDash.Core
{
Debug.Console(1, this, "Client is null or disconnected. Cannot Send Text");
}
}
catch (Exception ex)
{
Debug.Console(0, "Exception: {0}", ex.Message);
Debug.Console(0, "Stack Trace: {0}", ex.StackTrace);
}
catch (Exception ex)
{
Debug.Console(0, "Exception: {0}", ex.Message);
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");
}
}
/// <summary>
/// Sends Bytes to the server
/// </summary>
/// <param name="bytes"></param>
public void SendBytes(byte[] bytes)
{
try
{
{
try
{
if (Client != null && TheStream != null && IsConnected)
{
if (StreamDebugging.TxStreamDebuggingIsEnabled)
@@ -515,23 +515,23 @@ namespace PepperDash.Core
{
Debug.Console(1, this, "Client is null or disconnected. Cannot Send Bytes");
}
}
catch
{
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Stream write failed. Disconnected, closing");
}
}
}
catch
{
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Stream write failed. Disconnected, closing");
}
}
#endregion
}
#endregion
}
//*****************************************************************************************************
//*****************************************************************************************************
/// <summary>
/// Fired when connection changes
/// </summary>
public class SshConnectionChangeEventArgs : EventArgs
{
//*****************************************************************************************************
//*****************************************************************************************************
/// <summary>
/// Fired when connection changes
/// </summary>
public class SshConnectionChangeEventArgs : EventArgs
{
/// <summary>
/// Connection State
/// </summary>
@@ -552,10 +552,10 @@ namespace PepperDash.Core
/// </summary>
public ushort Status { get { return Client.UStatus; } }
/// <summary>
/// <summary>
/// S+ Constructor
/// </summary>
public SshConnectionChangeEventArgs() { }
/// </summary>
public SshConnectionChangeEventArgs() { }
/// <summary>
/// EventArgs class
@@ -563,9 +563,9 @@ namespace PepperDash.Core
/// <param name="isConnected">Connection State</param>
/// <param name="client">The Client</param>
public SshConnectionChangeEventArgs(bool isConnected, GenericSshClient client)
{
IsConnected = isConnected;
Client = client;
}
}
{
IsConnected = isConnected;
Client = client;
}
}
}

View File

@@ -1,14 +1,14 @@
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 PepperDash.Core.Logging;
using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace PepperDash.Core
namespace PepperDash.Core.Comm
{
/// <summary>
/// A class to handle basic TCP/IP communications with a server
@@ -21,44 +21,44 @@ namespace PepperDash.Core
/// </summary>
public CommunicationStreamDebugging StreamDebugging { get; private set; }
/// <summary>
/// Fires when data is received from the server and returns it as a Byte array
/// </summary>
public event EventHandler<GenericCommMethodReceiveBytesArgs> BytesReceived;
/// <summary>
/// Fires when data is received from the server and returns it as a Byte array
/// </summary>
public event EventHandler<GenericCommMethodReceiveBytesArgs> BytesReceived;
/// <summary>
/// Fires when data is received from the server and returns it as text
/// </summary>
public event EventHandler<GenericCommMethodReceiveTextArgs> TextReceived;
/// <summary>
/// Fires when data is received from the server and returns it as text
/// </summary>
public event EventHandler<GenericCommMethodReceiveTextArgs> TextReceived;
/// <summary>
///
/// </summary>
//public event GenericSocketStatusChangeEventDelegate SocketStatusChange;
public event EventHandler<GenericSocketStatusChageEventArgs> ConnectionChange;
/// <summary>
///
/// </summary>
//public event GenericSocketStatusChangeEventDelegate SocketStatusChange;
public event EventHandler<GenericSocketStatusChageEventArgs> ConnectionChange;
private string _hostname;
private string _hostname;
/// <summary>
/// Address of server
/// </summary>
public string Hostname
{
get
{
return _hostname;
}
get
{
return _hostname;
}
set
{
_hostname = value;
if (_client != null)
{
_client.AddressClientConnectedTo = _hostname;
}
}
}
set
{
_hostname = value;
if (_client != null)
{
_client.AddressClientConnectedTo = _hostname;
}
}
}
/// <summary>
/// Port on server
@@ -80,19 +80,19 @@ namespace PepperDash.Core
/// </summary>
public int BufferSize { get; set; }
/// <summary>
/// The actual client class
/// </summary>
private TCPClient _client;
/// <summary>
/// The actual client class
/// </summary>
private TCPClient _client;
/// <summary>
/// Bool showing if socket is connected
/// </summary>
public bool IsConnected
{
get { return _client != null && _client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED; }
/// <summary>
/// Bool showing if socket is connected
/// </summary>
public bool IsConnected
{
get { return _client != null && _client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED; }
}
/// <summary>
/// S+ helper for IsConnected
/// </summary>
@@ -101,15 +101,15 @@ namespace PepperDash.Core
get { return (ushort)(IsConnected ? 1 : 0); }
}
/// <summary>
/// _client socket status Read only
/// </summary>
public SocketStatus ClientStatus
{
get
/// <summary>
/// _client socket status Read only
/// </summary>
public SocketStatus ClientStatus
{
get
{
return _client == null ? SocketStatus.SOCKET_STATUS_NO_CONNECT : _client.ClientStatus;
}
return _client == null ? SocketStatus.SOCKET_STATUS_NO_CONNECT : _client.ClientStatus;
}
}
/// <summary>
@@ -121,26 +121,26 @@ namespace PepperDash.Core
get { return (ushort)ClientStatus; }
}
/// <summary>
/// <summary>
/// Status text shows the message associated with socket status
/// </summary>
public string ClientStatusText { get { return ClientStatus.ToString(); } }
/// </summary>
public string ClientStatusText { get { return ClientStatus.ToString(); } }
/// <summary>
/// Ushort representation of client status
/// </summary>
/// <summary>
/// Ushort representation of client status
/// </summary>
[Obsolete]
public ushort UClientStatus { get { return (ushort)ClientStatus; } }
public ushort UClientStatus { get { return (ushort)ClientStatus; } }
/// <summary>
/// Connection failure reason
/// </summary>
public string ConnectionFailure { get { return ClientStatus.ToString(); } }
/// <summary>
/// Connection failure reason
/// </summary>
public string ConnectionFailure { get { return ClientStatus.ToString(); } }
/// <summary>
/// bool to track if auto reconnect should be set on the socket
/// </summary>
public bool AutoReconnect { get; set; }
/// <summary>
/// bool to track if auto reconnect should be set on the socket
/// </summary>
public bool AutoReconnect { get; set; }
/// <summary>
/// S+ helper for AutoReconnect
@@ -151,29 +151,29 @@ namespace PepperDash.Core
set { AutoReconnect = value == 1; }
}
/// <summary>
/// Milliseconds to wait before attempting to reconnect. Defaults to 5000
/// </summary>
public int AutoReconnectIntervalMs { get; set; }
/// <summary>
/// Milliseconds to wait before attempting to reconnect. Defaults to 5000
/// </summary>
public int AutoReconnectIntervalMs { get; set; }
/// <summary>
/// Set only when the disconnect method is called
/// </summary>
bool DisconnectCalledByUser;
/// <summary>
/// Set only when the disconnect method is called
/// </summary>
bool DisconnectCalledByUser;
/// <summary>
///
/// </summary>
public bool Connected
{
get { return _client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED; }
}
/// <summary>
///
/// </summary>
public bool Connected
{
get { return _client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED; }
}
//Lock object to prevent simulatneous connect/disconnect operations
private CCriticalSection connectLock = new CCriticalSection();
// private Timer for auto reconnect
private CTimer RetryTimer;
private CTimer RetryTimer;
/// <summary>
/// Constructor
@@ -183,8 +183,8 @@ namespace PepperDash.Core
/// <param name="port"></param>
/// <param name="bufferSize"></param>
public GenericTcpIpClient(string key, string address, int port, int bufferSize)
: base(key)
{
: base(key)
{
StreamDebugging = new CommunicationStreamDebugging(key);
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
AutoReconnectIntervalMs = 5000;
@@ -220,17 +220,17 @@ namespace PepperDash.Core
/// Default constructor for S+
/// </summary>
public GenericTcpIpClient()
: base(SplusKey)
{
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
AutoReconnectIntervalMs = 5000;
: base(SplusKey)
{
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
AutoReconnectIntervalMs = 5000;
BufferSize = 2000;
RetryTimer = new CTimer(o =>
{
Reconnect();
}, Timeout.Infinite);
}
}
/// <summary>
/// Just to help S+ set the key
@@ -257,22 +257,22 @@ namespace PepperDash.Core
/// </summary>
/// <returns></returns>
public override bool Deactivate()
{
{
RetryTimer.Stop();
RetryTimer.Dispose();
if (_client != null)
{
_client.SocketStatusChange -= this.Client_SocketStatusChange;
_client.SocketStatusChange -= Client_SocketStatusChange;
DisconnectClient();
}
return true;
}
return true;
}
/// <summary>
/// Attempts to connect to the server
/// </summary>
public void Connect()
{
{
if (string.IsNullOrEmpty(Hostname))
{
Debug.Console(1, Debug.ErrorLogLevel.Warning, "GenericTcpIpClient '{0}': No address set", Key);
@@ -308,7 +308,7 @@ namespace PepperDash.Core
{
connectLock.Leave();
}
}
}
private void Reconnect()
{
@@ -339,7 +339,7 @@ namespace PepperDash.Core
/// Attempts to disconnect the client
/// </summary>
public void Disconnect()
{
{
try
{
connectLock.Enter();
@@ -353,7 +353,7 @@ namespace PepperDash.Core
{
connectLock.Leave();
}
}
}
/// <summary>
/// Does the actual disconnect business
@@ -373,7 +373,7 @@ namespace PepperDash.Core
/// </summary>
/// <param name="c"></param>
void ConnectToServerCallback(TCPClient c)
{
{
if (c.ClientStatus != SocketStatus.SOCKET_STATUS_CONNECTED)
{
Debug.Console(0, this, "Server connection result: {0}", c.ClientStatus);
@@ -383,13 +383,13 @@ namespace PepperDash.Core
{
Debug.Console(1, this, "Server connection result: {0}", c.ClientStatus);
}
}
}
/// <summary>
/// Disconnects, waits and attemtps to connect again
/// </summary>
void WaitAndTryReconnect()
{
{
CrestronInvoke.BeginInvoke(o =>
{
try
@@ -407,7 +407,7 @@ namespace PepperDash.Core
connectLock.Leave();
}
});
}
}
/// <summary>
/// Recieves incoming data
@@ -415,7 +415,7 @@ namespace PepperDash.Core
/// <param name="client"></param>
/// <param name="numBytes"></param>
void Receive(TCPClient client, int numBytes)
{
{
if (client != null)
{
if (numBytes > 0)
@@ -441,49 +441,49 @@ namespace PepperDash.Core
}
textHandler(this, new GenericCommMethodReceiveTextArgs(str));
}
}
}
client.ReceiveDataAsync(Receive);
}
}
}
/// <summary>
/// General send method
/// </summary>
public void SendText(string text)
{
var bytes = Encoding.GetEncoding(28591).GetBytes(text);
// Check debug level before processing byte array
/// <summary>
/// General send method
/// </summary>
public void SendText(string text)
{
var bytes = Encoding.GetEncoding(28591).GetBytes(text);
// Check debug level before processing byte array
if (StreamDebugging.TxStreamDebuggingIsEnabled)
Debug.Console(0, this, "Sending {0} characters of text: '{1}'", text.Length, ComTextHelper.GetDebugText(text));
if (_client != null)
_client.SendData(bytes, bytes.Length);
}
_client.SendData(bytes, bytes.Length);
}
/// <summary>
/// This is useful from console and...?
/// </summary>
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);
}
/// <summary>
/// This is useful from console and...?
/// </summary>
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);
}
/// <summary>
/// Sends Bytes to the server
/// </summary>
/// <param name="bytes"></param>
public void SendBytes(byte[] bytes)
{
{
if (StreamDebugging.TxStreamDebuggingIsEnabled)
Debug.Console(0, this, "Sending {0} bytes: '{1}'", bytes.Length, ComTextHelper.GetEscapedText(bytes));
if (_client != null)
_client.SendData(bytes, bytes.Length);
}
_client.SendData(bytes, bytes.Length);
}
/// <summary>
/// Socket Status Change Handler
@@ -491,7 +491,7 @@ namespace PepperDash.Core
/// <param name="client"></param>
/// <param name="clientSocketStatus"></param>
void Client_SocketStatusChange(TCPClient client, SocketStatus clientSocketStatus)
{
{
if (clientSocketStatus != SocketStatus.SOCKET_STATUS_CONNECTED)
{
Debug.Console(0, this, "Socket status change {0} ({1})", clientSocketStatus, ClientStatusText);
@@ -500,68 +500,68 @@ namespace PepperDash.Core
else
{
Debug.Console(1, this, "Socket status change {0} ({1})", clientSocketStatus, ClientStatusText);
_client.ReceiveDataAsync(Receive);
_client.ReceiveDataAsync(Receive);
}
var handler = ConnectionChange;
if (handler != null)
ConnectionChange(this, new GenericSocketStatusChageEventArgs(this));
}
}
var handler = ConnectionChange;
if (handler != null)
ConnectionChange(this, new GenericSocketStatusChageEventArgs(this));
}
}
/// <summary>
/// Configuration properties for TCP/SSH Connections
/// </summary>
public class TcpSshPropertiesConfig
{
{
/// <summary>
/// Address to connect to
/// </summary>
[JsonProperty(Required = Required.Always)]
public string Address { get; set; }
public string Address { get; set; }
/// <summary>
/// Port to connect to
/// </summary>
[JsonProperty(Required = Required.Always)]
public int Port { get; set; }
[JsonProperty(Required = Required.Always)]
public int Port { get; set; }
/// <summary>
/// Username credential
/// </summary>
public string Username { get; set; }
public string Username { get; set; }
/// <summary>
/// Passord credential
/// </summary>
public string Password { get; set; }
/// <summary>
/// Defaults to 32768
/// </summary>
public int BufferSize { get; set; }
/// <summary>
/// Defaults to 32768
/// </summary>
public int BufferSize { get; set; }
/// <summary>
/// Defaults to true
/// </summary>
public bool AutoReconnect { get; set; }
/// <summary>
/// Defaults to true
/// </summary>
public bool AutoReconnect { get; set; }
/// <summary>
/// Defaults to 5000ms
/// </summary>
public int AutoReconnectIntervalMs { get; set; }
/// <summary>
/// Defaults to 5000ms
/// </summary>
public int AutoReconnectIntervalMs { get; set; }
/// <summary>
/// Default constructor
/// </summary>
public TcpSshPropertiesConfig()
{
BufferSize = 32768;
AutoReconnect = true;
AutoReconnectIntervalMs = 5000;
{
BufferSize = 32768;
AutoReconnect = true;
AutoReconnectIntervalMs = 5000;
Username = "";
Password = "";
}
}
}
}
}

View File

@@ -10,15 +10,14 @@ of this material by another party without the express written permission of Pepp
PepperDash Technology Corporation reserves all rights under applicable laws.
------------------------------------ */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronSockets;
using PepperDash.Core.Logging;
using System;
using System.Linq;
using System.Text;
namespace PepperDash.Core
namespace PepperDash.Core.Comm
{
/// <summary>
/// Generic TCP/IP client for server
@@ -361,8 +360,8 @@ namespace PepperDash.Core
Client = new TCPClient(Hostname, Port, BufferSize);
Client.SocketStatusChange += Client_SocketStatusChange;
if(HeartbeatEnabled)
Client.SocketSendOrReceiveTimeOutInMs = (HeartbeatInterval * 5);
if (HeartbeatEnabled)
Client.SocketSendOrReceiveTimeOutInMs = HeartbeatInterval * 5;
Client.AddressClientConnectedTo = Hostname;
Client.PortNumber = Port;
// SecureClient = c;
@@ -385,7 +384,7 @@ namespace PepperDash.Core
}
}, 30000);
Debug.Console(2, this, "Making Connection Count:{0}", ConnectionCount);
Debug.Console(2, this, "Making Connection Count:{0}", ConnectionCount);
Client.ConnectToServerAsync(o =>
{
Debug.Console(2, this, "ConnectToServerAsync Count:{0} Ran!", ConnectionCount);
@@ -563,15 +562,15 @@ namespace PepperDash.Core
{
if (HeartbeatEnabled)
{
Debug.Console(2, this, "Starting Heartbeat");
Debug.Console(2, this, "Starting Heartbeat");
if (HeartbeatSendTimer == null)
{
HeartbeatSendTimer = new CTimer(this.SendHeartbeat, null, HeartbeatInterval, HeartbeatInterval);
HeartbeatSendTimer = new CTimer(SendHeartbeat, null, HeartbeatInterval, HeartbeatInterval);
}
if (HeartbeatAckTimer == null)
{
HeartbeatAckTimer = new CTimer(HeartbeatAckTimerFail, null, (HeartbeatInterval * 2), (HeartbeatInterval * 2));
HeartbeatAckTimer = new CTimer(HeartbeatAckTimerFail, null, HeartbeatInterval * 2, HeartbeatInterval * 2);
}
}
@@ -581,7 +580,7 @@ namespace PepperDash.Core
if (HeartbeatSendTimer != null)
{
Debug.Console(2, this, "Stoping Heartbeat Send");
Debug.Console(2, this, "Stoping Heartbeat Send");
HeartbeatSendTimer.Stop();
HeartbeatSendTimer = null;
}
@@ -595,7 +594,7 @@ namespace PepperDash.Core
}
void SendHeartbeat(object notused)
{
this.SendText(HeartbeatString);
SendText(HeartbeatString);
Debug.Console(2, this, "Sending Heartbeat");
}
@@ -619,12 +618,12 @@ namespace PepperDash.Core
}
else
{
HeartbeatAckTimer = new CTimer(HeartbeatAckTimerFail, null, (HeartbeatInterval * 2), (HeartbeatInterval * 2));
HeartbeatAckTimer = new CTimer(HeartbeatAckTimerFail, null, HeartbeatInterval * 2, HeartbeatInterval * 2);
}
Debug.Console(2, this, "Heartbeat Received: {0}, from Server", HeartbeatString);
return remainingText;
}
}
}
}
}
catch (Exception ex)
@@ -684,7 +683,7 @@ namespace PepperDash.Core
// HOW IN THE HELL DO WE CATCH AN EXCEPTION IN SENDING?????
if (n <= 0)
{
Debug.Console(1, Debug.ErrorLogLevel.Warning, "[{0}] Sent zero bytes. Was there an error?", this.Key);
Debug.Console(1, Debug.ErrorLogLevel.Warning, "[{0}] Sent zero bytes. Was there an error?", Key);
}
});
}
@@ -729,10 +728,10 @@ namespace PepperDash.Core
}
try
{
Debug.Console(2, this, "Socket status change: {0} ({1})", client.ClientStatus, (ushort)(client.ClientStatus));
Debug.Console(2, this, "Socket status change: {0} ({1})", client.ClientStatus, (ushort)client.ClientStatus);
OnConnectionChange();
// The client could be null or disposed by this time...
if (Client == null || Client.ClientStatus != SocketStatus.SOCKET_STATUS_CONNECTED)
{
@@ -763,12 +762,12 @@ namespace PepperDash.Core
void OnClientReadyForcommunications(bool isReady)
{
IsReadyForCommunication = isReady;
if (this.IsReadyForCommunication) { HeartbeatStart(); }
if (IsReadyForCommunication) { HeartbeatStart(); }
var handler = ClientReadyForCommunications;
if (handler != null)
handler(this, new GenericTcpServerClientReadyForcommunicationsEventArgs(IsReadyForCommunication));
}
#endregion
}
}

View File

@@ -10,16 +10,15 @@ of this material by another party without the express written permission of Pepp
PepperDash Technology Corporation reserves all rights under applicable laws.
------------------------------------ */
using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronSockets;
using PepperDash.Core.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronSockets;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace PepperDash.Core
namespace PepperDash.Core.Comm
{
/// <summary>
/// Generic TCP/IP server device
@@ -238,7 +237,7 @@ namespace PepperDash.Core
/// <summary>
/// Simpl+ Heartbeat Analog value in seconds
/// </summary>
public ushort HeartbeatRequiredIntervalInSeconds { set { HeartbeatRequiredIntervalMs = (value * 1000); } }
public ushort HeartbeatRequiredIntervalInSeconds { set { HeartbeatRequiredIntervalMs = value * 1000; } }
/// <summary>
/// String to Match for heartbeat. If null or empty any string will reset heartbeat timer
@@ -402,10 +401,10 @@ namespace PepperDash.Core
if (myTcpServer == null)
{
myTcpServer = new TCPServer(Port, MaxClients);
if(HeartbeatRequired)
myTcpServer.SocketSendOrReceiveTimeOutInMs = (this.HeartbeatRequiredIntervalMs * 5);
// myTcpServer.HandshakeTimeout = 30;
if (HeartbeatRequired)
myTcpServer.SocketSendOrReceiveTimeOutInMs = HeartbeatRequiredIntervalMs * 5;
// myTcpServer.HandshakeTimeout = 30;
}
else
{
@@ -445,9 +444,9 @@ namespace PepperDash.Core
{
myTcpServer.Stop();
Debug.Console(2, this, Debug.ErrorLogLevel.Notice, "Server State: {0}", myTcpServer.State);
OnServerStateChange(myTcpServer.State);
OnServerStateChange(myTcpServer.State);
}
ServerStopped = true;
ServerStopped = true;
}
catch (Exception ex)
{
@@ -525,7 +524,7 @@ namespace PepperDash.Core
byte[] b = Encoding.GetEncoding(28591).GetBytes(text);
foreach (uint i in ConnectedClientsIndexes)
{
if (!SharedKeyRequired || (SharedKeyRequired && ClientReadyAfterKeyExchange.Contains(i)))
if (!SharedKeyRequired || SharedKeyRequired && ClientReadyAfterKeyExchange.Contains(i))
{
SocketErrorCodes error = myTcpServer.SendDataAsync(i, b, b.Length, (x, y, z) => { });
if (error != SocketErrorCodes.SOCKET_OK && error != SocketErrorCodes.SOCKET_OPERATION_PENDING)
@@ -554,7 +553,7 @@ namespace PepperDash.Core
byte[] b = Encoding.GetEncoding(28591).GetBytes(text);
if (myTcpServer != null && myTcpServer.GetServerSocketStatusForSpecificClient(clientIndex) == SocketStatus.SOCKET_STATUS_CONNECTED)
{
if (!SharedKeyRequired || (SharedKeyRequired && ClientReadyAfterKeyExchange.Contains(clientIndex)))
if (!SharedKeyRequired || SharedKeyRequired && ClientReadyAfterKeyExchange.Contains(clientIndex))
myTcpServer.SendDataAsync(clientIndex, b, b.Length, (x, y, z) => { });
}
}
@@ -618,9 +617,9 @@ namespace PepperDash.Core
public string GetClientIPAddress(uint clientIndex)
{
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "GetClientIPAddress Index: {0}", clientIndex);
if (!SharedKeyRequired || (SharedKeyRequired && ClientReadyAfterKeyExchange.Contains(clientIndex)))
if (!SharedKeyRequired || SharedKeyRequired && ClientReadyAfterKeyExchange.Contains(clientIndex))
{
var ipa = this.myTcpServer.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex);
var ipa = myTcpServer.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex);
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "GetClientIPAddress IPAddreess: {0}", ipa);
return ipa;
@@ -645,7 +644,7 @@ namespace PepperDash.Core
address = myTcpServer.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex);
Debug.Console(1, this, Debug.ErrorLogLevel.Warning, "Heartbeat not received for Client index {2} IP: {0}, DISCONNECTING BECAUSE HEARTBEAT REQUIRED IS TRUE {1}",
address, string.IsNullOrEmpty(HeartbeatStringToMatch) ? "" : ("HeartbeatStringToMatch: " + HeartbeatStringToMatch), clientIndex);
address, string.IsNullOrEmpty(HeartbeatStringToMatch) ? "" : "HeartbeatStringToMatch: " + HeartbeatStringToMatch, clientIndex);
if (myTcpServer.GetServerSocketStatusForSpecificClient(clientIndex) == SocketStatus.SOCKET_STATUS_CONNECTED)
SendTextToClient("Heartbeat not received by server, closing connection", clientIndex);
@@ -680,7 +679,7 @@ namespace PepperDash.Core
try
{
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "SecureServerSocketStatusChange Index:{0} status:{1} Port:{2} IP:{3}", clientIndex, serverSocketStatus, this.myTcpServer.GetPortNumberServerAcceptedConnectionFromForSpecificClient(clientIndex), this.myTcpServer.GetLocalAddressServerAcceptedConnectionFromForSpecificClient(clientIndex));
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "SecureServerSocketStatusChange Index:{0} status:{1} Port:{2} IP:{3}", clientIndex, serverSocketStatus, myTcpServer.GetPortNumberServerAcceptedConnectionFromForSpecificClient(clientIndex), myTcpServer.GetLocalAddressServerAcceptedConnectionFromForSpecificClient(clientIndex));
if (serverSocketStatus != SocketStatus.SOCKET_STATUS_CONNECTED)
{
if (ConnectedClientsIndexes.Contains(clientIndex))
@@ -693,8 +692,8 @@ namespace PepperDash.Core
}
if (ClientReadyAfterKeyExchange.Contains(clientIndex))
ClientReadyAfterKeyExchange.Remove(clientIndex);
if (WaitingForSharedKey.Contains(clientIndex))
WaitingForSharedKey.Remove(clientIndex);
if (WaitingForSharedKey.Contains(clientIndex))
WaitingForSharedKey.Remove(clientIndex);
}
}
catch (Exception ex)
@@ -790,48 +789,48 @@ namespace PepperDash.Core
/// <param name="numberOfBytesReceived"></param>
void TcpServerReceivedDataAsyncCallback(TCPServer myTCPServer, uint clientIndex, int numberOfBytesReceived)
{
if (numberOfBytesReceived > 0)
{
string received = "Nothing";
try
{
byte[] bytes = myTCPServer.GetIncomingDataBufferForSpecificClient(clientIndex);
received = System.Text.Encoding.GetEncoding(28591).GetString(bytes, 0, numberOfBytesReceived);
if (WaitingForSharedKey.Contains(clientIndex))
{
received = received.Replace("\r", "");
received = received.Replace("\n", "");
if (received != SharedKey)
{
byte[] b = Encoding.GetEncoding(28591).GetBytes("Shared key did not match server. Disconnecting");
Debug.Console(1, this, Debug.ErrorLogLevel.Warning, "Client at index {0} Shared key did not match the server, disconnecting client. Key: {1}", clientIndex, received);
myTCPServer.SendData(clientIndex, b, b.Length);
myTCPServer.Disconnect(clientIndex);
return;
}
if (numberOfBytesReceived > 0)
{
string received = "Nothing";
try
{
byte[] bytes = myTCPServer.GetIncomingDataBufferForSpecificClient(clientIndex);
received = Encoding.GetEncoding(28591).GetString(bytes, 0, numberOfBytesReceived);
if (WaitingForSharedKey.Contains(clientIndex))
{
received = received.Replace("\r", "");
received = received.Replace("\n", "");
if (received != SharedKey)
{
byte[] b = Encoding.GetEncoding(28591).GetBytes("Shared key did not match server. Disconnecting");
Debug.Console(1, this, Debug.ErrorLogLevel.Warning, "Client at index {0} Shared key did not match the server, disconnecting client. Key: {1}", clientIndex, received);
myTCPServer.SendData(clientIndex, b, b.Length);
myTCPServer.Disconnect(clientIndex);
return;
}
WaitingForSharedKey.Remove(clientIndex);
byte[] success = Encoding.GetEncoding(28591).GetBytes("Shared Key Match");
myTCPServer.SendDataAsync(clientIndex, success, success.Length, null);
OnServerClientReadyForCommunications(clientIndex);
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Client with index {0} provided the shared key and successfully connected to the server", clientIndex);
}
WaitingForSharedKey.Remove(clientIndex);
byte[] success = Encoding.GetEncoding(28591).GetBytes("Shared Key Match");
myTCPServer.SendDataAsync(clientIndex, success, success.Length, null);
OnServerClientReadyForCommunications(clientIndex);
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Client with index {0} provided the shared key and successfully connected to the server", clientIndex);
}
else if (!string.IsNullOrEmpty(checkHeartbeat(clientIndex, received)))
onTextReceived(received, clientIndex);
}
catch (Exception ex)
{
Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error Receiving data: {0}. Error: {1}", received, ex);
}
if (myTCPServer.GetServerSocketStatusForSpecificClient(clientIndex) == SocketStatus.SOCKET_STATUS_CONNECTED)
myTCPServer.ReceiveDataAsync(clientIndex, TcpServerReceivedDataAsyncCallback);
}
else
{
// If numberOfBytesReceived <= 0
myTCPServer.Disconnect();
}
else if (!string.IsNullOrEmpty(checkHeartbeat(clientIndex, received)))
onTextReceived(received, clientIndex);
}
catch (Exception ex)
{
Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error Receiving data: {0}. Error: {1}", received, ex);
}
if (myTCPServer.GetServerSocketStatusForSpecificClient(clientIndex) == SocketStatus.SOCKET_STATUS_CONNECTED)
myTCPServer.ReceiveDataAsync(clientIndex, TcpServerReceivedDataAsyncCallback);
}
else
{
// If numberOfBytesReceived <= 0
myTCPServer.Disconnect();
}
}
@@ -938,8 +937,8 @@ namespace PepperDash.Core
void RunMonitorClient()
{
MonitorClient = new GenericTcpIpClient_ForServer(Key + "-MONITOR", "127.0.0.1", Port, 2000);
MonitorClient.SharedKeyRequired = this.SharedKeyRequired;
MonitorClient.SharedKey = this.SharedKey;
MonitorClient.SharedKeyRequired = SharedKeyRequired;
MonitorClient.SharedKey = SharedKey;
MonitorClient.ConnectionHasHungCallback = MonitorClientHasHungCallback;
//MonitorClient.ConnectionChange += MonitorClient_ConnectionChange;
MonitorClient.ClientReadyForCommunications += MonitorClient_IsReadyForComm;

View File

@@ -1,21 +1,13 @@
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;
using PepperDash.Core.Logging;
using System;
using System.Linq;
using System.Text;
namespace PepperDash.Core
namespace PepperDash.Core.Comm
{
/// <summary>
/// Generic UDP Server device
@@ -131,7 +123,7 @@ namespace PepperDash.Core
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
CrestronEnvironment.EthernetEventHandler += new EthernetEventHandler(CrestronEnvironment_EthernetEventHandler);
}
/// <summary>
///
/// </summary>
@@ -142,7 +134,7 @@ namespace PepperDash.Core
public GenericUdpServer(string key, string address, int port, int buffefSize)
: base(key)
{
StreamDebugging = new CommunicationStreamDebugging(key);
StreamDebugging = new CommunicationStreamDebugging(key);
Hostname = address;
Port = port;
BufferSize = buffefSize;
@@ -184,7 +176,7 @@ namespace PepperDash.Core
/// <param name="programEventType"></param>
void CrestronEnvironment_ProgramStatusEventHandler(eProgramStatusEventType programEventType)
{
if (programEventType != eProgramStatusEventType.Stopping)
if (programEventType != eProgramStatusEventType.Stopping)
return;
Debug.Console(1, this, "Program stopping. Disabling Server");
@@ -233,7 +225,7 @@ namespace PepperDash.Core
/// </summary>
public void Disconnect()
{
if(Server != null)
if (Server != null)
Server.DisableUDPServer();
IsConnected = false;
@@ -255,7 +247,7 @@ namespace PepperDash.Core
try
{
if (numBytes <= 0)
if (numBytes <= 0)
return;
var sourceIp = Server.IPAddressLastMessageReceivedFrom;
@@ -331,7 +323,7 @@ namespace PepperDash.Core
///
/// </summary>
public class GenericUdpReceiveTextExtraArgs : EventArgs
{
{
/// <summary>
///
/// </summary>
@@ -343,7 +335,7 @@ namespace PepperDash.Core
/// <summary>
///
/// </summary>
public int Port { get; private set; }
public int Port { get; private set; }
/// <summary>
///
/// </summary>
@@ -357,18 +349,18 @@ namespace PepperDash.Core
/// <param name="port"></param>
/// <param name="bytes"></param>
public GenericUdpReceiveTextExtraArgs(string text, string ipAddress, int port, byte[] bytes)
{
Text = text;
IpAddress = ipAddress;
Port = port;
Bytes = bytes;
}
{
Text = text;
IpAddress = ipAddress;
Port = port;
Bytes = bytes;
}
/// <summary>
/// Stupid S+ Constructor
/// </summary>
public GenericUdpReceiveTextExtraArgs() { }
}
/// <summary>
/// Stupid S+ Constructor
/// </summary>
public GenericUdpReceiveTextExtraArgs() { }
}
/// <summary>
///

View File

@@ -1,10 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
using Crestron.SimplSharp;
using PepperDash.Core.Interfaces;
using PepperDash.Core.Logging;
using System;
namespace PepperDash.Core
namespace PepperDash.Core.Comm
{
/// <summary>
/// Allows for two simultaneous TCP clients to connect to a redundant pair of QSC Core DSPs and manages

View File

@@ -2,7 +2,7 @@
using Newtonsoft.Json;
namespace PepperDash.Core
namespace PepperDash.Core.Comm
{
/// <summary>
/// Client config object for TCP client with server that inherits from TcpSshPropertiesConfig and adds properties for shared key and heartbeat

View File

@@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
namespace PepperDash.Core
namespace PepperDash.Core.Comm
{
/// <summary>
/// Tcp Server Config object with properties for a tcp server with shared key and heartbeat capabilities

View File

@@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
namespace PepperDash.Core
namespace PepperDash.Core.Comm
{
/// <summary>
/// Crestron Control Methods for a comm object

View File

@@ -1,243 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronSockets;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace PepperDash.Core
{
/// <summary>
/// An incoming communication stream
/// </summary>
public interface ICommunicationReceiver : IKeyed
{
/// <summary>
/// Notifies of bytes received
/// </summary>
event EventHandler<GenericCommMethodReceiveBytesArgs> BytesReceived;
/// <summary>
/// Notifies of text received
/// </summary>
event EventHandler<GenericCommMethodReceiveTextArgs> TextReceived;
/// <summary>
/// Indicates connection status
/// </summary>
bool IsConnected { get; }
/// <summary>
/// Connect to the device
/// </summary>
void Connect();
/// <summary>
/// Disconnect from the device
/// </summary>
void Disconnect();
}
/// <summary>
/// Represents a device that uses basic connection
/// </summary>
public interface IBasicCommunication : ICommunicationReceiver
{
/// <summary>
/// Send text to the device
/// </summary>
/// <param name="text"></param>
void SendText(string text);
/// <summary>
/// Send bytes to the device
/// </summary>
/// <param name="bytes"></param>
void SendBytes(byte[] bytes);
}
/// <summary>
/// Represents a device that implements IBasicCommunication and IStreamDebugging
/// </summary>
public interface IBasicCommunicationWithStreamDebugging : IBasicCommunication, IStreamDebugging
{
}
/// <summary>
/// Represents a device with stream debugging capablities
/// </summary>
public interface IStreamDebugging
{
/// <summary>
/// Object to enable stream debugging
/// </summary>
CommunicationStreamDebugging StreamDebugging { get; }
}
/// <summary>
/// For IBasicCommunication classes that have SocketStatus. GenericSshClient,
/// GenericTcpIpClient
/// </summary>
public interface ISocketStatus : IBasicCommunication
{
/// <summary>
/// Notifies of socket status changes
/// </summary>
event EventHandler<GenericSocketStatusChageEventArgs> ConnectionChange;
/// <summary>
/// The current socket status of the client
/// </summary>
SocketStatus ClientStatus { get; }
}
/// <summary>
/// Describes a device that implements ISocketStatus and IStreamDebugging
/// </summary>
public interface ISocketStatusWithStreamDebugging : ISocketStatus, IStreamDebugging
{
}
/// <summary>
/// Describes a device that can automatically attempt to reconnect
/// </summary>
public interface IAutoReconnect
{
/// <summary>
/// Enable automatic recconnect
/// </summary>
bool AutoReconnect { get; set; }
/// <summary>
/// Interval in ms to attempt automatic recconnections
/// </summary>
int AutoReconnectIntervalMs { get; set; }
}
/// <summary>
///
/// </summary>
public enum eGenericCommMethodStatusChangeType
{
/// <summary>
/// Connected
/// </summary>
Connected,
/// <summary>
/// Disconnected
/// </summary>
Disconnected
}
/// <summary>
/// This delegate defines handler for IBasicCommunication status changes
/// </summary>
/// <param name="comm">Device firing the status change</param>
/// <param name="status"></param>
public delegate void GenericCommMethodStatusHandler(IBasicCommunication comm, eGenericCommMethodStatusChangeType status);
/// <summary>
///
/// </summary>
public class GenericCommMethodReceiveBytesArgs : EventArgs
{
/// <summary>
///
/// </summary>
public byte[] Bytes { get; private set; }
/// <summary>
///
/// </summary>
/// <param name="bytes"></param>
public GenericCommMethodReceiveBytesArgs(byte[] bytes)
{
Bytes = bytes;
}
/// <summary>
/// S+ Constructor
/// </summary>
public GenericCommMethodReceiveBytesArgs() { }
}
/// <summary>
///
/// </summary>
public class GenericCommMethodReceiveTextArgs : EventArgs
{
/// <summary>
///
/// </summary>
public string Text { get; private set; }
/// <summary>
///
/// </summary>
public string Delimiter { get; private set; }
/// <summary>
///
/// </summary>
/// <param name="text"></param>
public GenericCommMethodReceiveTextArgs(string text)
{
Text = text;
}
/// <summary>
///
/// </summary>
/// <param name="text"></param>
/// <param name="delimiter"></param>
public GenericCommMethodReceiveTextArgs(string text, string delimiter)
:this(text)
{
Delimiter = delimiter;
}
/// <summary>
/// S+ Constructor
/// </summary>
public GenericCommMethodReceiveTextArgs() { }
}
/// <summary>
///
/// </summary>
public class ComTextHelper
{
/// <summary>
/// Gets escaped text for a byte array
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static string GetEscapedText(byte[] bytes)
{
return String.Concat(bytes.Select(b => string.Format(@"[{0:X2}]", (int)b)).ToArray());
}
/// <summary>
/// Gets escaped text for a string
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string GetEscapedText(string text)
{
var bytes = Encoding.GetEncoding(28591).GetBytes(text);
return String.Concat(bytes.Select(b => string.Format(@"[{0:X2}]", (int)b)).ToArray());
}
/// <summary>
/// Gets debug text for a string
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string GetDebugText(string text)
{
return Regex.Replace(text, @"[^\u0020-\u007E]", a => GetEscapedText(a.Value));
}
}
}

View File

@@ -1,16 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp.CrestronIO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronIO;
using PepperDash.Core;
using PepperDash.Core.Logging;
using System;
using System.Linq;
namespace PepperDash.Core.Config
{
@@ -18,127 +13,127 @@ namespace PepperDash.Core.Config
/// Reads a Portal formatted config file
/// </summary>
public class PortalConfigReader
{
/// <summary>
/// Reads the config file, checks if it needs a merge, merges and saves, then returns the merged Object.
/// </summary>
/// <returns>JObject of config file</returns>
public static void ReadAndMergeFileIfNecessary(string filePath, string savePath)
{
try
{
if (!File.Exists(filePath))
{
Debug.Console(1, Debug.ErrorLogLevel.Error,
"ERROR: Configuration file not present. Please load file to {0} and reset program", filePath);
}
{
/// <summary>
/// Reads the config file, checks if it needs a merge, merges and saves, then returns the merged Object.
/// </summary>
/// <returns>JObject of config file</returns>
public static void ReadAndMergeFileIfNecessary(string filePath, string savePath)
{
try
{
if (!File.Exists(filePath))
{
Debug.Console(1, Debug.ErrorLogLevel.Error,
"ERROR: Configuration file not present. Please load file to {0} and reset program", filePath);
}
using (StreamReader fs = new StreamReader(filePath))
{
var jsonObj = JObject.Parse(fs.ReadToEnd());
if(jsonObj["template"] != null && jsonObj["system"] != null)
{
// it's a double-config, merge it.
var merged = MergeConfigs(jsonObj);
if (jsonObj["system_url"] != null)
{
merged["systemUrl"] = jsonObj["system_url"].Value<string>();
}
using (StreamReader fs = new StreamReader(filePath))
{
var jsonObj = JObject.Parse(fs.ReadToEnd());
if (jsonObj["template"] != null && jsonObj["system"] != null)
{
// it's a double-config, merge it.
var merged = MergeConfigs(jsonObj);
if (jsonObj["system_url"] != null)
{
merged["systemUrl"] = jsonObj["system_url"].Value<string>();
}
if (jsonObj["template_url"] != null)
{
merged["templateUrl"] = jsonObj["template_url"].Value<string>();
}
if (jsonObj["template_url"] != null)
{
merged["templateUrl"] = jsonObj["template_url"].Value<string>();
}
jsonObj = merged;
}
jsonObj = merged;
}
using (StreamWriter fw = new StreamWriter(savePath))
{
fw.Write(jsonObj.ToString(Formatting.Indented));
Debug.Console(1, "JSON config merged and saved to {0}", savePath);
}
using (StreamWriter fw = new StreamWriter(savePath))
{
fw.Write(jsonObj.ToString(Formatting.Indented));
Debug.Console(1, "JSON config merged and saved to {0}", savePath);
}
}
}
catch (Exception e)
{
Debug.Console(1, Debug.ErrorLogLevel.Error, "ERROR: Config load failed: \r{0}", e);
}
}
}
}
catch (Exception e)
{
Debug.Console(1, Debug.ErrorLogLevel.Error, "ERROR: Config load failed: \r{0}", e);
}
}
/// <summary>
///
/// </summary>
/// <param name="doubleConfig"></param>
/// <returns></returns>
public static JObject MergeConfigs(JObject doubleConfig)
{
var system = JObject.FromObject(doubleConfig["system"]);
var template = JObject.FromObject(doubleConfig["template"]);
var merged = new JObject();
/// <summary>
///
/// </summary>
/// <param name="doubleConfig"></param>
/// <returns></returns>
public static JObject MergeConfigs(JObject doubleConfig)
{
var system = JObject.FromObject(doubleConfig["system"]);
var template = JObject.FromObject(doubleConfig["template"]);
var merged = new JObject();
// Put together top-level objects
if (system["info"] != null)
merged.Add("info", Merge(template["info"], system["info"], "infO"));
else
merged.Add("info", template["info"]);
// Put together top-level objects
if (system["info"] != null)
merged.Add("info", Merge(template["info"], system["info"], "infO"));
else
merged.Add("info", template["info"]);
merged.Add("devices", MergeArraysOnTopLevelProperty(template["devices"] as JArray,
system["devices"] as JArray, "uid", "devices"));
merged.Add("devices", MergeArraysOnTopLevelProperty(template["devices"] as JArray,
system["devices"] as JArray, "uid", "devices"));
if (system["rooms"] == null)
merged.Add("rooms", template["rooms"]);
else
merged.Add("rooms", MergeArraysOnTopLevelProperty(template["rooms"] as JArray,
system["rooms"] as JArray, "key", "rooms"));
if (system["rooms"] == null)
merged.Add("rooms", template["rooms"]);
else
merged.Add("rooms", MergeArraysOnTopLevelProperty(template["rooms"] as JArray,
system["rooms"] as JArray, "key", "rooms"));
if (system["sourceLists"] == null)
merged.Add("sourceLists", template["sourceLists"]);
else
merged.Add("sourceLists", Merge(template["sourceLists"], system["sourceLists"], "sourceLists"));
if (system["sourceLists"] == null)
merged.Add("sourceLists", template["sourceLists"]);
else
merged.Add("sourceLists", Merge(template["sourceLists"], system["sourceLists"], "sourceLists"));
if (system["destinationLists"] == null)
merged.Add("destinationLists", template["destinationLists"]);
else
merged.Add("destinationLists",
Merge(template["destinationLists"], system["destinationLists"], "destinationLists"));
if (system["destinationLists"] == null)
merged.Add("destinationLists", template["destinationLists"]);
else
merged.Add("destinationLists",
Merge(template["destinationLists"], system["destinationLists"], "destinationLists"));
// Template tie lines take precedence. Config tool doesn't do them at system
// level anyway...
if (template["tieLines"] != null)
merged.Add("tieLines", template["tieLines"]);
else if (system["tieLines"] != null)
merged.Add("tieLines", system["tieLines"]);
else
merged.Add("tieLines", new JArray());
// Template tie lines take precedence. Config tool doesn't do them at system
// level anyway...
if (template["tieLines"] != null)
merged.Add("tieLines", template["tieLines"]);
else if (system["tieLines"] != null)
merged.Add("tieLines", system["tieLines"]);
else
merged.Add("tieLines", new JArray());
if (template["joinMaps"] != null)
merged.Add("joinMaps", template["joinMaps"]);
else
merged.Add("joinMaps", new JObject());
if (system["global"] != null)
merged.Add("global", Merge(template["global"], system["global"], "global"));
else
merged.Add("global", template["global"]);
if (system["global"] != null)
merged.Add("global", Merge(template["global"], system["global"], "global"));
else
merged.Add("global", template["global"]);
Debug.Console(2, "MERGED CONFIG RESULT: \x0d\x0a{0}", merged);
return merged;
}
Debug.Console(2, "MERGED CONFIG RESULT: \x0d\x0a{0}", merged);
return merged;
}
/// <summary>
/// Merges the contents of a base and a delta array, matching the entries on a top-level property
/// given by propertyName. Returns a merge of them. Items in the delta array that do not have
/// a matched item in base array will not be merged. Non keyed system items will replace the template items.
/// </summary>
static JArray MergeArraysOnTopLevelProperty(JArray a1, JArray a2, string propertyName, string path)
{
var result = new JArray();
if (a2 == null || a2.Count == 0) // If the system array is null or empty, return the template array
return a1;
else if (a1 != null)
{
/// <summary>
/// Merges the contents of a base and a delta array, matching the entries on a top-level property
/// given by propertyName. Returns a merge of them. Items in the delta array that do not have
/// a matched item in base array will not be merged. Non keyed system items will replace the template items.
/// </summary>
static JArray MergeArraysOnTopLevelProperty(JArray a1, JArray a2, string propertyName, string path)
{
var result = new JArray();
if (a2 == null || a2.Count == 0) // If the system array is null or empty, return the template array
return a1;
else if (a1 != null)
{
if (a2[0]["key"] == null) // If the first item in the system array has no key, overwrite the template array
{ // with the system array
return a2;
@@ -159,69 +154,69 @@ namespace PepperDash.Core.Config
result.Add(a1Dev);
}
}
}
return result;
}
}
return result;
}
/// <summary>
/// Helper for using with JTokens. Converts to JObject
/// </summary>
static JObject Merge(JToken t1, JToken t2, string path)
{
return Merge(JObject.FromObject(t1), JObject.FromObject(t2), path);
}
/// <summary>
/// Helper for using with JTokens. Converts to JObject
/// </summary>
static JObject Merge(JToken t1, JToken t2, string path)
{
return Merge(JObject.FromObject(t1), JObject.FromObject(t2), path);
}
/// <summary>
/// Merge o2 onto o1
/// </summary>
/// <summary>
/// Merge o2 onto o1
/// </summary>
/// <param name="o1"></param>
/// <param name="o2"></param>
/// <param name="path"></param>
static JObject Merge(JObject o1, JObject o2, string path)
{
foreach (var o2Prop in o2)
{
var propKey = o2Prop.Key;
var o1Value = o1[propKey];
var o2Value = o2[propKey];
static JObject Merge(JObject o1, JObject o2, string path)
{
foreach (var o2Prop in o2)
{
var propKey = o2Prop.Key;
var o1Value = o1[propKey];
var o2Value = o2[propKey];
// if the property doesn't exist on o1, then add it.
if (o1Value == null)
{
o1.Add(propKey, o2Value);
}
// otherwise merge them
else
{
// Drill down
var propPath = String.Format("{0}.{1}", path, propKey);
try
{
// if the property doesn't exist on o1, then add it.
if (o1Value == null)
{
o1.Add(propKey, o2Value);
}
// otherwise merge them
else
{
// Drill down
var propPath = String.Format("{0}.{1}", path, propKey);
try
{
if (o1Value is JArray)
{
if (o2Value is JArray)
{
o1Value.Replace(MergeArraysOnTopLevelProperty(o1Value as JArray, o2Value as JArray, "key", propPath));
}
}
else if (o2Prop.Value.HasValues && o1Value.HasValues)
{
o1Value.Replace(Merge(JObject.FromObject(o1Value), JObject.FromObject(o2Value), propPath));
}
else
{
o1Value.Replace(o2Prop.Value);
}
}
catch (Exception e)
{
Debug.Console(1, Debug.ErrorLogLevel.Warning, "Cannot merge items at path {0}: \r{1}", propPath, e);
}
}
}
return o1;
}
}
if (o1Value is JArray)
{
if (o2Value is JArray)
{
o1Value.Replace(MergeArraysOnTopLevelProperty(o1Value as JArray, o2Value as JArray, "key", propPath));
}
}
else if (o2Prop.Value.HasValues && o1Value.HasValues)
{
o1Value.Replace(Merge(JObject.FromObject(o1Value), JObject.FromObject(o2Value), propPath));
}
else
{
o1Value.Replace(o2Prop.Value);
}
}
catch (Exception e)
{
Debug.Console(1, Debug.ErrorLogLevel.Warning, "Cannot merge items at path {0}: \r{1}", propPath, e);
}
}
}
return o1;
}
}
}

View File

@@ -1,10 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
using System.Text;
namespace PepperDash.Core
namespace PepperDash.Core.Conversion
{
public class EncodingHelper
{

View File

@@ -1,30 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
namespace PepperDash.Core
{
/// <summary>
/// Unique key interface to require a unique key for the class
/// </summary>
public interface IKeyed
{
/// <summary>
/// Unique Key
/// </summary>
string Key { get; }
}
/// <summary>
/// Named Keyed device interface. Forces the devie to have a Unique Key and a name.
/// </summary>
public interface IKeyName : IKeyed
{
/// <summary>
/// Isn't it obvious :)
/// </summary>
string Name { get; }
}
}

View File

@@ -1,22 +1,24 @@
using System;
using PepperDash.Core.Interfaces;
using PepperDash.Core.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
namespace PepperDash.Core
{
//*********************************************************************************************************
/// <summary>
/// The core event and status-bearing class that most if not all device and connectors can derive from.
/// </summary>
public class Device : IKeyName
{
//*********************************************************************************************************
/// <summary>
/// The core event and status-bearing class that most if not all device and connectors can derive from.
/// </summary>
public class Device : IKeyName
{
/// <summary>
/// Unique Key
/// </summary>
public string Key { get; protected set; }
/// <summary>
/// Name of the devie
/// </summary>
/// <summary>
/// Name of the devie
/// </summary>
public string Name { get; protected set; }
/// <summary>
///
@@ -33,26 +35,26 @@ namespace PepperDash.Core
///// </summary>
//public bool HasConfig { get { return Config != null; } }
List<Action> _PreActivationActions;
List<Action> _PostActivationActions;
List<Action> _PreActivationActions;
List<Action> _PostActivationActions;
/// <summary>
///
/// </summary>
public static Device DefaultDevice { get { return _DefaultDevice; } }
static Device _DefaultDevice = new Device("Default", "Default");
static Device _DefaultDevice = new Device("Default", "Default");
/// <summary>
/// Base constructor for all Devices.
/// </summary>
/// <param name="key"></param>
public Device(string key)
{
Key = key;
if (key.Contains('.')) Debug.Console(0, this, "WARNING: Device name's should not include '.'");
Name = "";
/// <summary>
/// Base constructor for all Devices.
/// </summary>
/// <param name="key"></param>
public Device(string key)
{
Key = key;
if (key.Contains('.')) Debug.Console(0, this, "WARNING: Device name's should not include '.'");
Name = "";
}
}
/// <summary>
/// Constructor with key and name
@@ -60,10 +62,10 @@ namespace PepperDash.Core
/// <param name="key"></param>
/// <param name="name"></param>
public Device(string key, string name) : this(key)
{
Name = name;
{
Name = name;
}
}
//public Device(DeviceConfig config)
// : this(config.Key, config.Name)
@@ -76,22 +78,22 @@ namespace PepperDash.Core
/// </summary>
/// <param name="act"></param>
public void AddPreActivationAction(Action act)
{
if (_PreActivationActions == null)
_PreActivationActions = new List<Action>();
_PreActivationActions.Add(act);
}
{
if (_PreActivationActions == null)
_PreActivationActions = new List<Action>();
_PreActivationActions.Add(act);
}
/// <summary>
/// Adds a post activation action
/// </summary>
/// <param name="act"></param>
public void AddPostActivationAction(Action act)
{
if (_PostActivationActions == null)
_PostActivationActions = new List<Action>();
_PostActivationActions.Add(act);
}
{
if (_PostActivationActions == null)
_PostActivationActions = new List<Action>();
_PostActivationActions.Add(act);
}
/// <summary>
/// Executes the preactivation actions
@@ -102,20 +104,20 @@ namespace PepperDash.Core
_PreActivationActions.ForEach(a => a.Invoke());
}
/// <summary>
/// Gets this device ready to be used in the system. Runs any added pre-activation items, and
/// all post-activation at end. Classes needing additional logic to
/// run should override CustomActivate()
/// </summary>
public bool Activate()
{
/// <summary>
/// Gets this device ready to be used in the system. Runs any added pre-activation items, and
/// all post-activation at end. Classes needing additional logic to
/// run should override CustomActivate()
/// </summary>
public bool Activate()
{
//if (_PreActivationActions != null)
// _PreActivationActions.ForEach(a => a.Invoke());
var result = CustomActivate();
var result = CustomActivate();
//if(result && _PostActivationActions != null)
// _PostActivationActions.ForEach(a => a.Invoke());
return result;
}
return result;
}
/// <summary>
/// Executes the postactivation actions
@@ -126,37 +128,37 @@ namespace PepperDash.Core
_PostActivationActions.ForEach(a => a.Invoke());
}
/// <summary>
/// Called in between Pre and PostActivationActions when Activate() is called.
/// Override to provide addtitional setup when calling activation. Overriding classes
/// do not need to call base.CustomActivate()
/// </summary>
/// <returns>true if device activated successfully.</returns>
public virtual bool CustomActivate() { return true; }
/// <summary>
/// Called in between Pre and PostActivationActions when Activate() is called.
/// Override to provide addtitional setup when calling activation. Overriding classes
/// do not need to call base.CustomActivate()
/// </summary>
/// <returns>true if device activated successfully.</returns>
public virtual bool CustomActivate() { return true; }
/// <summary>
/// Call to deactivate device - unlink events, etc. Overriding classes do not
/// need to call base.Deactivate()
/// </summary>
/// <returns></returns>
public virtual bool Deactivate() { return true; }
/// <summary>
/// Call to deactivate device - unlink events, etc. Overriding classes do not
/// need to call base.Deactivate()
/// </summary>
/// <returns></returns>
public virtual bool Deactivate() { return true; }
/// <summary>
/// Call this method to start communications with a device. Overriding classes do not need to call base.Initialize()
/// </summary>
public virtual void Initialize()
{
}
{
}
/// <summary>
/// Helper method to check object for bool value false and fire an Action method
/// </summary>
/// <param name="o">Should be of type bool, others will be ignored</param>
/// <param name="a">Action to be run when o is false</param>
public void OnFalse(object o, Action a)
{
if (o is bool && !(bool)o) a();
}
/// <summary>
/// Helper method to check object for bool value false and fire an Action method
/// </summary>
/// <param name="o">Should be of type bool, others will be ignored</param>
/// <param name="a">Action to be run when o is false</param>
public void OnFalse(object o, Action a)
{
if (o is bool && !(bool)o) a();
}
}
}
}

View File

@@ -1,11 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
using Crestron.SimplSharp;
using Newtonsoft.Json;
using PepperDash.Core.Logging;
namespace PepperDash.Core
{
@@ -13,110 +9,110 @@ namespace PepperDash.Core
/// Class to help with accessing values from the CrestronEthernetHelper class
/// </summary>
public class EthernetHelper
{
/// <summary>
///
/// </summary>
public static EthernetHelper LanHelper
{
get
{
if (_LanHelper == null) _LanHelper = new EthernetHelper(0);
return _LanHelper;
}
}
static EthernetHelper _LanHelper;
{
/// <summary>
///
/// </summary>
public static EthernetHelper LanHelper
{
get
{
if (_LanHelper == null) _LanHelper = new EthernetHelper(0);
return _LanHelper;
}
}
static EthernetHelper _LanHelper;
// ADD OTHER HELPERS HERE
// ADD OTHER HELPERS HERE
/// <summary>
///
/// </summary>
public int PortNumber { get; private set; }
/// <summary>
///
/// </summary>
public int PortNumber { get; private set; }
private EthernetHelper(int portNumber)
{
PortNumber = portNumber;
}
private EthernetHelper(int portNumber)
{
PortNumber = portNumber;
}
/// <summary>
///
/// </summary>
[JsonProperty("linkActive")]
public bool LinkActive
{
get
{
var status = CrestronEthernetHelper.GetEthernetParameter(
CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_LINK_STATUS, 0);
Debug.Console(0, "LinkActive = {0}", status);
return status == "";
}
}
/// <summary>
///
/// </summary>
[JsonProperty("linkActive")]
public bool LinkActive
{
get
{
var status = CrestronEthernetHelper.GetEthernetParameter(
CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_LINK_STATUS, 0);
Debug.Console(0, "LinkActive = {0}", status);
return status == "";
}
}
/// <summary>
///
/// </summary>
[JsonProperty("dchpActive")]
public bool DhcpActive
{
get
{
return CrestronEthernetHelper.GetEthernetParameter(
CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_DHCP_STATE, 0) == "ON";
}
}
/// <summary>
///
/// </summary>
[JsonProperty("dchpActive")]
public bool DhcpActive
{
get
{
return CrestronEthernetHelper.GetEthernetParameter(
CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_DHCP_STATE, 0) == "ON";
}
}
/// <summary>
///
/// </summary>
[JsonProperty("hostname")]
public string Hostname
{
get
{
return CrestronEthernetHelper.GetEthernetParameter(
CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_HOSTNAME, 0);
}
}
/// <summary>
///
/// </summary>
[JsonProperty("hostname")]
public string Hostname
{
get
{
return CrestronEthernetHelper.GetEthernetParameter(
CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_HOSTNAME, 0);
}
}
/// <summary>
///
/// </summary>
[JsonProperty("ipAddress")]
public string IPAddress
{
get
{
return CrestronEthernetHelper.GetEthernetParameter(
CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS, 0);
}
}
/// <summary>
///
/// </summary>
[JsonProperty("ipAddress")]
public string IPAddress
{
get
{
return CrestronEthernetHelper.GetEthernetParameter(
CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS, 0);
}
}
/// <summary>
///
/// </summary>
[JsonProperty("subnetMask")]
public string SubnetMask
{
get
{
return CrestronEthernetHelper.GetEthernetParameter(
CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_MASK, 0);
}
}
/// <summary>
///
/// </summary>
[JsonProperty("subnetMask")]
public string SubnetMask
{
get
{
return CrestronEthernetHelper.GetEthernetParameter(
CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_MASK, 0);
}
}
/// <summary>
///
/// </summary>
[JsonProperty("defaultGateway")]
public string DefaultGateway
{
get
{
return CrestronEthernetHelper.GetEthernetParameter(
CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_ROUTER, 0);
}
}
}
/// <summary>
///
/// </summary>
[JsonProperty("defaultGateway")]
public string DefaultGateway
{
get
{
return CrestronEthernetHelper.GetEthernetParameter(
CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_ROUTER, 0);
}
}
}
}

View File

@@ -1,172 +1,168 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
namespace PepperDash.Core
{
/// <summary>
/// Bool change event args
/// </summary>
public class BoolChangeEventArgs : EventArgs
{
/// <summary>
/// Boolean state property
/// </summary>
public bool State { get; set; }
/// <summary>
/// Boolean ushort value property
/// </summary>
public ushort IntValue { get { return (ushort)(State ? 1 : 0); } }
/// <summary>
/// Boolean change event args type
/// </summary>
public ushort Type { get; set; }
/// <summary>
/// Boolean change event args index
/// </summary>
public ushort Index { get; set; }
/// <summary>
/// Constructor
/// </summary>
public BoolChangeEventArgs()
{
/// <summary>
/// Bool change event args
/// </summary>
public class BoolChangeEventArgs : EventArgs
{
/// <summary>
/// Boolean state property
/// </summary>
public bool State { get; set; }
}
/// <summary>
/// Constructor overload
/// </summary>
/// <param name="state"></param>
/// <param name="type"></param>
public BoolChangeEventArgs(bool state, ushort type)
{
State = state;
Type = type;
}
/// <summary>
/// Constructor overload
/// </summary>
/// <param name="state"></param>
/// <param name="type"></param>
/// <param name="index"></param>
public BoolChangeEventArgs(bool state, ushort type, ushort index)
{
State = state;
Type = type;
Index = index;
}
}
/// <summary>
/// Boolean ushort value property
/// </summary>
public ushort IntValue { get { return (ushort)(State ? 1 : 0); } }
/// <summary>
/// Ushort change event args
/// </summary>
public class UshrtChangeEventArgs : EventArgs
{
/// <summary>
/// Ushort change event args integer value
/// </summary>
public ushort IntValue { get; set; }
/// <summary>
/// Ushort change event args type
/// </summary>
public ushort Type { get; set; }
/// <summary>
/// Ushort change event args index
/// </summary>
public ushort Index { get; set; }
/// <summary>
/// Constructor
/// </summary>
public UshrtChangeEventArgs()
{
/// <summary>
/// Boolean change event args type
/// </summary>
public ushort Type { get; set; }
}
/// <summary>
/// Boolean change event args index
/// </summary>
public ushort Index { get; set; }
/// <summary>
/// Constructor overload
/// </summary>
/// <param name="intValue"></param>
/// <param name="type"></param>
public UshrtChangeEventArgs(ushort intValue, ushort type)
{
IntValue = intValue;
Type = type;
}
/// <summary>
/// Constructor
/// </summary>
public BoolChangeEventArgs()
{
/// <summary>
/// Constructor overload
/// </summary>
/// <param name="intValue"></param>
/// <param name="type"></param>
/// <param name="index"></param>
public UshrtChangeEventArgs(ushort intValue, ushort type, ushort index)
{
IntValue = intValue;
Type = type;
Index = index;
}
}
}
/// <summary>
/// String change event args
/// </summary>
public class StringChangeEventArgs : EventArgs
{
/// <summary>
/// String change event args value
/// </summary>
public string StringValue { get; set; }
/// <summary>
/// Constructor overload
/// </summary>
/// <param name="state"></param>
/// <param name="type"></param>
public BoolChangeEventArgs(bool state, ushort type)
{
State = state;
Type = type;
}
/// <summary>
/// String change event args type
/// </summary>
public ushort Type { get; set; }
/// <summary>
/// Constructor overload
/// </summary>
/// <param name="state"></param>
/// <param name="type"></param>
/// <param name="index"></param>
public BoolChangeEventArgs(bool state, ushort type, ushort index)
{
State = state;
Type = type;
Index = index;
}
}
/// <summary>
/// string change event args index
/// </summary>
public ushort Index { get; set; }
/// <summary>
/// Ushort change event args
/// </summary>
public class UshrtChangeEventArgs : EventArgs
{
/// <summary>
/// Ushort change event args integer value
/// </summary>
public ushort IntValue { get; set; }
/// <summary>
/// Constructor
/// </summary>
public StringChangeEventArgs()
{
/// <summary>
/// Ushort change event args type
/// </summary>
public ushort Type { get; set; }
}
/// <summary>
/// Ushort change event args index
/// </summary>
public ushort Index { get; set; }
/// <summary>
/// Constructor overload
/// </summary>
/// <param name="stringValue"></param>
/// <param name="type"></param>
public StringChangeEventArgs(string stringValue, ushort type)
{
StringValue = stringValue;
Type = type;
}
/// <summary>
/// Constructor
/// </summary>
public UshrtChangeEventArgs()
{
/// <summary>
/// Constructor overload
/// </summary>
/// <param name="stringValue"></param>
/// <param name="type"></param>
/// <param name="index"></param>
public StringChangeEventArgs(string stringValue, ushort type, ushort index)
{
StringValue = stringValue;
Type = type;
Index = index;
}
}
}
/// <summary>
/// Constructor overload
/// </summary>
/// <param name="intValue"></param>
/// <param name="type"></param>
public UshrtChangeEventArgs(ushort intValue, ushort type)
{
IntValue = intValue;
Type = type;
}
/// <summary>
/// Constructor overload
/// </summary>
/// <param name="intValue"></param>
/// <param name="type"></param>
/// <param name="index"></param>
public UshrtChangeEventArgs(ushort intValue, ushort type, ushort index)
{
IntValue = intValue;
Type = type;
Index = index;
}
}
/// <summary>
/// String change event args
/// </summary>
public class StringChangeEventArgs : EventArgs
{
/// <summary>
/// String change event args value
/// </summary>
public string StringValue { get; set; }
/// <summary>
/// String change event args type
/// </summary>
public ushort Type { get; set; }
/// <summary>
/// string change event args index
/// </summary>
public ushort Index { get; set; }
/// <summary>
/// Constructor
/// </summary>
public StringChangeEventArgs()
{
}
/// <summary>
/// Constructor overload
/// </summary>
/// <param name="stringValue"></param>
/// <param name="type"></param>
public StringChangeEventArgs(string stringValue, ushort type)
{
StringValue = stringValue;
Type = type;
}
/// <summary>
/// Constructor overload
/// </summary>
/// <param name="stringValue"></param>
/// <param name="type"></param>
/// <param name="index"></param>
public StringChangeEventArgs(string stringValue, ushort type, ushort index)
{
StringValue = stringValue;
Type = type;
Index = index;
}
}
}

View File

@@ -1,39 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
namespace PepperDash.Core.GenericRESTfulCommunications
namespace PepperDash.Core.GenericRESTfulCommunications
{
/// <summary>
/// Constants
/// </summary>
/// <summary>
/// Constants
/// </summary>
public class GenericRESTfulConstants
{
/// <summary>
/// Generic boolean change
/// </summary>
public const ushort BoolValueChange = 1;
/// <summary>
/// Generic Ushort change
/// </summary>
public const ushort UshrtValueChange = 101;
/// <summary>
/// Response Code Ushort change
/// </summary>
public const ushort ResponseCodeChange = 102;
/// <summary>
/// Generic String chagne
/// </summary>
public const ushort StringValueChange = 201;
/// <summary>
/// Response string change
/// </summary>
public const ushort ResponseStringChange = 202;
/// <summary>
/// Error string change
/// </summary>
public const ushort ErrorStringChange = 203;
/// <summary>
/// Generic boolean change
/// </summary>
public const ushort BoolValueChange = 1;
/// <summary>
/// Generic Ushort change
/// </summary>
public const ushort UshrtValueChange = 101;
/// <summary>
/// Response Code Ushort change
/// </summary>
public const ushort ResponseCodeChange = 102;
/// <summary>
/// Generic String chagne
/// </summary>
public const ushort StringValueChange = 201;
/// <summary>
/// Response string change
/// </summary>
public const ushort ResponseStringChange = 202;
/// <summary>
/// Error string change
/// </summary>
public const ushort ErrorStringChange = 203;
}
}

View File

@@ -1,256 +1,253 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
using Crestron.SimplSharp;
using Crestron.SimplSharp.Net.Http;
using Crestron.SimplSharp.Net.Https;
using System;
namespace PepperDash.Core.GenericRESTfulCommunications
{
/// <summary>
/// Generic RESTful communication class
/// </summary>
public class GenericRESTfulClient
{
/// <summary>
/// Boolean event handler
/// </summary>
public event EventHandler<BoolChangeEventArgs> BoolChange;
/// <summary>
/// Ushort event handler
/// </summary>
public event EventHandler<UshrtChangeEventArgs> UshrtChange;
/// <summary>
/// String event handler
/// </summary>
public event EventHandler<StringChangeEventArgs> StringChange;
/// <summary>
/// Generic RESTful communication class
/// </summary>
public class GenericRESTfulClient
{
/// <summary>
/// Boolean event handler
/// </summary>
public event EventHandler<BoolChangeEventArgs> BoolChange;
/// <summary>
/// Ushort event handler
/// </summary>
public event EventHandler<UshrtChangeEventArgs> UshrtChange;
/// <summary>
/// String event handler
/// </summary>
public event EventHandler<StringChangeEventArgs> StringChange;
/// <summary>
/// Constructor
/// </summary>
public GenericRESTfulClient()
{
/// <summary>
/// Constructor
/// </summary>
public GenericRESTfulClient()
{
}
}
/// <summary>
/// Generic RESTful submit request
/// </summary>
/// <param name="url"></param>
/// <param name="port"></param>
/// <param name="requestType"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <summary>
/// Generic RESTful submit request
/// </summary>
/// <param name="url"></param>
/// <param name="port"></param>
/// <param name="requestType"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="contentType"></param>
public void SubmitRequest(string url, ushort port, ushort requestType, string contentType, string username, string password)
{
if (url.StartsWith("https:", StringComparison.OrdinalIgnoreCase))
{
SubmitRequestHttps(url, port, requestType, contentType, username, password);
}
else if (url.StartsWith("http:", StringComparison.OrdinalIgnoreCase))
{
SubmitRequestHttp(url, port, requestType, contentType, username, password);
}
else
{
OnStringChange(string.Format("Invalid URL {0}", url), 0, GenericRESTfulConstants.ErrorStringChange);
}
}
public void SubmitRequest(string url, ushort port, ushort requestType, string contentType, string username, string password)
{
if (url.StartsWith("https:", StringComparison.OrdinalIgnoreCase))
{
SubmitRequestHttps(url, port, requestType, contentType, username, password);
}
else if (url.StartsWith("http:", StringComparison.OrdinalIgnoreCase))
{
SubmitRequestHttp(url, port, requestType, contentType, username, password);
}
else
{
OnStringChange(string.Format("Invalid URL {0}", url), 0, GenericRESTfulConstants.ErrorStringChange);
}
}
/// <summary>
/// Private HTTP submit request
/// </summary>
/// <param name="url"></param>
/// <param name="port"></param>
/// <param name="requestType"></param>
/// <summary>
/// Private HTTP submit request
/// </summary>
/// <param name="url"></param>
/// <param name="port"></param>
/// <param name="requestType"></param>
/// <param name="contentType"></param>
/// <param name="username"></param>
/// <param name="password"></param>
private void SubmitRequestHttp(string url, ushort port, ushort requestType, string contentType, string username, string password)
{
try
{
HttpClient client = new HttpClient();
HttpClientRequest request = new HttpClientRequest();
HttpClientResponse response;
/// <param name="username"></param>
/// <param name="password"></param>
private void SubmitRequestHttp(string url, ushort port, ushort requestType, string contentType, string username, string password)
{
try
{
HttpClient client = new HttpClient();
HttpClientRequest request = new HttpClientRequest();
HttpClientResponse response;
client.KeepAlive = false;
if(port >= 1 || port <= 65535)
client.Port = port;
else
client.Port = 80;
client.KeepAlive = false;
var authorization = "";
if (!string.IsNullOrEmpty(username))
authorization = EncodeBase64(username, password);
if (port >= 1 || port <= 65535)
client.Port = port;
else
client.Port = 80;
if (!string.IsNullOrEmpty(authorization))
request.Header.SetHeaderValue("Authorization", authorization);
var authorization = "";
if (!string.IsNullOrEmpty(username))
authorization = EncodeBase64(username, password);
if (!string.IsNullOrEmpty(contentType))
request.Header.ContentType = contentType;
if (!string.IsNullOrEmpty(authorization))
request.Header.SetHeaderValue("Authorization", authorization);
request.Url.Parse(url);
request.RequestType = (Crestron.SimplSharp.Net.Http.RequestType)requestType;
response = client.Dispatch(request);
if (!string.IsNullOrEmpty(contentType))
request.Header.ContentType = contentType;
CrestronConsole.PrintLine(string.Format("SubmitRequestHttp Response[{0}]: {1}", response.Code, response.ContentString.ToString()));
request.Url.Parse(url);
request.RequestType = (Crestron.SimplSharp.Net.Http.RequestType)requestType;
if (!string.IsNullOrEmpty(response.ContentString.ToString()))
OnStringChange(response.ContentString.ToString(), 0, GenericRESTfulConstants.ResponseStringChange);
response = client.Dispatch(request);
if (response.Code > 0)
OnUshrtChange((ushort)response.Code, 0, GenericRESTfulConstants.ResponseCodeChange);
}
catch (Exception e)
{
//var msg = string.Format("SubmitRequestHttp({0}, {1}, {2}) failed:{3}", url, port, requestType, e.Message);
//CrestronConsole.PrintLine(msg);
//ErrorLog.Error(msg);
CrestronConsole.PrintLine(string.Format("SubmitRequestHttp Response[{0}]: {1}", response.Code, response.ContentString.ToString()));
CrestronConsole.PrintLine(e.Message);
OnStringChange(e.Message, 0, GenericRESTfulConstants.ErrorStringChange);
}
}
if (!string.IsNullOrEmpty(response.ContentString.ToString()))
OnStringChange(response.ContentString.ToString(), 0, GenericRESTfulConstants.ResponseStringChange);
/// <summary>
/// Private HTTPS submit request
/// </summary>
/// <param name="url"></param>
/// <param name="port"></param>
/// <param name="requestType"></param>
if (response.Code > 0)
OnUshrtChange((ushort)response.Code, 0, GenericRESTfulConstants.ResponseCodeChange);
}
catch (Exception e)
{
//var msg = string.Format("SubmitRequestHttp({0}, {1}, {2}) failed:{3}", url, port, requestType, e.Message);
//CrestronConsole.PrintLine(msg);
//ErrorLog.Error(msg);
CrestronConsole.PrintLine(e.Message);
OnStringChange(e.Message, 0, GenericRESTfulConstants.ErrorStringChange);
}
}
/// <summary>
/// Private HTTPS submit request
/// </summary>
/// <param name="url"></param>
/// <param name="port"></param>
/// <param name="requestType"></param>
/// <param name="contentType"></param>
/// <param name="username"></param>
/// <param name="password"></param>
private void SubmitRequestHttps(string url, ushort port, ushort requestType, string contentType, string username, string password)
{
try
{
HttpsClient client = new HttpsClient();
HttpsClientRequest request = new HttpsClientRequest();
HttpsClientResponse response;
/// <param name="username"></param>
/// <param name="password"></param>
private void SubmitRequestHttps(string url, ushort port, ushort requestType, string contentType, string username, string password)
{
try
{
HttpsClient client = new HttpsClient();
HttpsClientRequest request = new HttpsClientRequest();
HttpsClientResponse response;
client.KeepAlive = false;
client.HostVerification = false;
client.PeerVerification = false;
client.KeepAlive = false;
client.HostVerification = false;
client.PeerVerification = false;
var authorization = "";
if (!string.IsNullOrEmpty(username))
authorization = EncodeBase64(username, password);
var authorization = "";
if (!string.IsNullOrEmpty(username))
authorization = EncodeBase64(username, password);
if (!string.IsNullOrEmpty(authorization))
request.Header.SetHeaderValue("Authorization", authorization);
if (!string.IsNullOrEmpty(authorization))
request.Header.SetHeaderValue("Authorization", authorization);
if (!string.IsNullOrEmpty(contentType))
request.Header.ContentType = contentType;
if (!string.IsNullOrEmpty(contentType))
request.Header.ContentType = contentType;
request.Url.Parse(url);
request.RequestType = (Crestron.SimplSharp.Net.Https.RequestType)requestType;
response = client.Dispatch(request);
request.Url.Parse(url);
request.RequestType = (Crestron.SimplSharp.Net.Https.RequestType)requestType;
CrestronConsole.PrintLine(string.Format("SubmitRequestHttp Response[{0}]: {1}", response.Code, response.ContentString.ToString()));
response = client.Dispatch(request);
if(!string.IsNullOrEmpty(response.ContentString.ToString()))
OnStringChange(response.ContentString.ToString(), 0, GenericRESTfulConstants.ResponseStringChange);
CrestronConsole.PrintLine(string.Format("SubmitRequestHttp Response[{0}]: {1}", response.Code, response.ContentString.ToString()));
if(response.Code > 0)
OnUshrtChange((ushort)response.Code, 0, GenericRESTfulConstants.ResponseCodeChange);
}
catch (Exception e)
{
//var msg = string.Format("SubmitRequestHttps({0}, {1}, {2}, {3}, {4}) failed:{5}", url, port, requestType, username, password, e.Message);
//CrestronConsole.PrintLine(msg);
//ErrorLog.Error(msg);
if (!string.IsNullOrEmpty(response.ContentString.ToString()))
OnStringChange(response.ContentString.ToString(), 0, GenericRESTfulConstants.ResponseStringChange);
CrestronConsole.PrintLine(e.Message);
OnStringChange(e.Message, 0, GenericRESTfulConstants.ErrorStringChange);
}
}
if (response.Code > 0)
OnUshrtChange((ushort)response.Code, 0, GenericRESTfulConstants.ResponseCodeChange);
/// <summary>
/// Private method to encode username and password to Base64 string
/// </summary>
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns>authorization</returns>
private string EncodeBase64(string username, string password)
{
var authorization = "";
}
catch (Exception e)
{
//var msg = string.Format("SubmitRequestHttps({0}, {1}, {2}, {3}, {4}) failed:{5}", url, port, requestType, username, password, e.Message);
//CrestronConsole.PrintLine(msg);
//ErrorLog.Error(msg);
try
{
if (!string.IsNullOrEmpty(username))
{
string base64String = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(string.Format("{0}:{1}", username, password)));
authorization = string.Format("Basic {0}", base64String);
}
}
catch (Exception e)
{
var msg = string.Format("EncodeBase64({0}, {1}) failed:\r{2}", username, password, e);
CrestronConsole.PrintLine(msg);
ErrorLog.Error(msg);
return "" ;
}
CrestronConsole.PrintLine(e.Message);
OnStringChange(e.Message, 0, GenericRESTfulConstants.ErrorStringChange);
}
}
return authorization;
}
/// <summary>
/// Private method to encode username and password to Base64 string
/// </summary>
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns>authorization</returns>
private string EncodeBase64(string username, string password)
{
var authorization = "";
/// <summary>
/// Protected method to handle boolean change events
/// </summary>
/// <param name="state"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnBoolChange(bool state, ushort index, ushort type)
{
var handler = BoolChange;
if (handler != null)
{
var args = new BoolChangeEventArgs(state, type);
args.Index = index;
BoolChange(this, args);
}
}
try
{
if (!string.IsNullOrEmpty(username))
{
string base64String = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(string.Format("{0}:{1}", username, password)));
authorization = string.Format("Basic {0}", base64String);
}
}
catch (Exception e)
{
var msg = string.Format("EncodeBase64({0}, {1}) failed:\r{2}", username, password, e);
CrestronConsole.PrintLine(msg);
ErrorLog.Error(msg);
return "";
}
/// <summary>
/// Protected mehtod to handle ushort change events
/// </summary>
/// <param name="value"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnUshrtChange(ushort value, ushort index, ushort type)
{
var handler = UshrtChange;
if (handler != null)
{
var args = new UshrtChangeEventArgs(value, type);
args.Index = index;
UshrtChange(this, args);
}
}
return authorization;
}
/// <summary>
/// Protected method to handle string change events
/// </summary>
/// <param name="value"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnStringChange(string value, ushort index, ushort type)
{
var handler = StringChange;
if (handler != null)
{
var args = new StringChangeEventArgs(value, type);
args.Index = index;
StringChange(this, args);
}
}
}
/// <summary>
/// Protected method to handle boolean change events
/// </summary>
/// <param name="state"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnBoolChange(bool state, ushort index, ushort type)
{
var handler = BoolChange;
if (handler != null)
{
var args = new BoolChangeEventArgs(state, type);
args.Index = index;
BoolChange(this, args);
}
}
/// <summary>
/// Protected mehtod to handle ushort change events
/// </summary>
/// <param name="value"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnUshrtChange(ushort value, ushort index, ushort type)
{
var handler = UshrtChange;
if (handler != null)
{
var args = new UshrtChangeEventArgs(value, type);
args.Index = index;
UshrtChange(this, args);
}
}
/// <summary>
/// Protected method to handle string change events
/// </summary>
/// <param name="value"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnStringChange(string value, ushort index, ushort type)
{
var handler = StringChange;
if (handler != null)
{
var args = new StringChangeEventArgs(value, type);
args.Index = index;
StringChange(this, args);
}
}
}
}

View File

@@ -1,77 +1,73 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
namespace PepperDash.Core.JsonStandardObjects
{
/// <summary>
/// Constants for simpl modules
/// </summary>
public class JsonStandardDeviceConstants
{
/// <summary>
/// Json object evaluated constant
/// </summary>
public const ushort JsonObjectEvaluated = 2;
/// <summary>
/// Constants for simpl modules
/// </summary>
public class JsonStandardDeviceConstants
{
/// <summary>
/// Json object evaluated constant
/// </summary>
public const ushort JsonObjectEvaluated = 2;
/// <summary>
/// Json object changed constant
/// </summary>
public const ushort JsonObjectChanged = 104;
}
/// <summary>
/// Json object changed constant
/// </summary>
public const ushort JsonObjectChanged = 104;
}
/// <summary>
///
/// </summary>
public class DeviceChangeEventArgs : EventArgs
{
/// <summary>
/// Device change event args object
/// </summary>
public DeviceConfig Device { get; set; }
/// <summary>
///
/// </summary>
public class DeviceChangeEventArgs : EventArgs
{
/// <summary>
/// Device change event args object
/// </summary>
public DeviceConfig Device { get; set; }
/// <summary>
/// Device change event args type
/// </summary>
public ushort Type { get; set; }
/// <summary>
/// Device change event args type
/// </summary>
public ushort Type { get; set; }
/// <summary>
/// Device change event args index
/// </summary>
public ushort Index { get; set; }
/// <summary>
/// Device change event args index
/// </summary>
public ushort Index { get; set; }
/// <summary>
/// Default constructor
/// </summary>
public DeviceChangeEventArgs()
{
/// <summary>
/// Default constructor
/// </summary>
public DeviceChangeEventArgs()
{
}
}
/// <summary>
/// Constructor overload
/// </summary>
/// <param name="device"></param>
/// <param name="type"></param>
public DeviceChangeEventArgs(DeviceConfig device, ushort type)
{
Device = device;
Type = type;
}
/// <summary>
/// Constructor overload
/// </summary>
/// <param name="device"></param>
/// <param name="type"></param>
public DeviceChangeEventArgs(DeviceConfig device, ushort type)
{
Device = device;
Type = type;
}
/// <summary>
/// Constructor overload
/// </summary>
/// <param name="device"></param>
/// <param name="type"></param>
/// <param name="index"></param>
public DeviceChangeEventArgs(DeviceConfig device, ushort type, ushort index)
{
Device = device;
Type = type;
Index = index;
}
}
/// <summary>
/// Constructor overload
/// </summary>
/// <param name="device"></param>
/// <param name="type"></param>
/// <param name="index"></param>
public DeviceChangeEventArgs(DeviceConfig device, ushort type, ushort index)
{
Device = device;
Type = type;
Index = index;
}
}
}

View File

@@ -1,187 +1,184 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PepperDash.Core.JsonToSimpl;
using PepperDash.Core.Logging;
using System;
using System.Linq;
namespace PepperDash.Core.JsonStandardObjects
{
/// <summary>
/// Device class
/// </summary>
public class DeviceConfig
{
/// <summary>
/// JSON config key property
/// </summary>
public string key { get; set; }
/// <summary>
/// JSON config name property
/// </summary>
public string name { get; set; }
/// <summary>
/// JSON config type property
/// </summary>
public string type { get; set; }
/// <summary>
/// JSON config properties
/// </summary>
public PropertiesConfig properties { get; set; }
/// <summary>
/// Device class
/// </summary>
public class DeviceConfig
{
/// <summary>
/// JSON config key property
/// </summary>
public string key { get; set; }
/// <summary>
/// JSON config name property
/// </summary>
public string name { get; set; }
/// <summary>
/// JSON config type property
/// </summary>
public string type { get; set; }
/// <summary>
/// JSON config properties
/// </summary>
public PropertiesConfig properties { get; set; }
/// <summary>
/// Bool change event handler
/// </summary>
public event EventHandler<BoolChangeEventArgs> BoolChange;
/// <summary>
/// Ushort change event handler
/// </summary>
public event EventHandler<UshrtChangeEventArgs> UshrtChange;
/// <summary>
/// String change event handler
/// </summary>
public event EventHandler<StringChangeEventArgs> StringChange;
/// <summary>
/// Object change event handler
/// </summary>
public event EventHandler<DeviceChangeEventArgs> DeviceChange;
/// <summary>
/// Bool change event handler
/// </summary>
public event EventHandler<BoolChangeEventArgs> BoolChange;
/// <summary>
/// Ushort change event handler
/// </summary>
public event EventHandler<UshrtChangeEventArgs> UshrtChange;
/// <summary>
/// String change event handler
/// </summary>
public event EventHandler<StringChangeEventArgs> StringChange;
/// <summary>
/// Object change event handler
/// </summary>
public event EventHandler<DeviceChangeEventArgs> DeviceChange;
/// <summary>
/// Constructor
/// </summary>
public DeviceConfig()
{
properties = new PropertiesConfig();
}
/// <summary>
/// Constructor
/// </summary>
public DeviceConfig()
{
properties = new PropertiesConfig();
}
/// <summary>
/// Initialize method
/// </summary>
/// <param name="uniqueID"></param>
/// <param name="deviceKey"></param>
public void Initialize(string uniqueID, string deviceKey)
{
// S+ set EvaluateFb low
OnBoolChange(false, 0, JsonStandardDeviceConstants.JsonObjectEvaluated);
// validate parameters
if (string.IsNullOrEmpty(uniqueID) || string.IsNullOrEmpty(deviceKey))
{
Debug.Console(1, "UniqueID ({0} or key ({1} is null or empty", uniqueID, deviceKey);
// S+ set EvaluteFb high
OnBoolChange(true, 0, JsonStandardDeviceConstants.JsonObjectEvaluated);
return;
}
/// <summary>
/// Initialize method
/// </summary>
/// <param name="uniqueID"></param>
/// <param name="deviceKey"></param>
public void Initialize(string uniqueID, string deviceKey)
{
// S+ set EvaluateFb low
OnBoolChange(false, 0, JsonStandardDeviceConstants.JsonObjectEvaluated);
// validate parameters
if (string.IsNullOrEmpty(uniqueID) || string.IsNullOrEmpty(deviceKey))
{
Debug.Console(1, "UniqueID ({0} or key ({1} is null or empty", uniqueID, deviceKey);
// S+ set EvaluteFb high
OnBoolChange(true, 0, JsonStandardDeviceConstants.JsonObjectEvaluated);
return;
}
key = deviceKey;
key = deviceKey;
try
{
// get the file using the unique ID
JsonToSimplMaster jsonMaster = J2SGlobal.GetMasterByFile(uniqueID);
if (jsonMaster == null)
{
Debug.Console(1, "Could not find JSON file with uniqueID {0}", uniqueID);
return;
}
try
{
// get the file using the unique ID
JsonToSimplMaster jsonMaster = J2SGlobal.GetMasterByFile(uniqueID);
if (jsonMaster == null)
{
Debug.Console(1, "Could not find JSON file with uniqueID {0}", uniqueID);
return;
}
// get the device configuration using the key
var devices = jsonMaster.JsonObject.ToObject<RootObject>().devices;
var device = devices.FirstOrDefault(d => d.key.Equals(key));
if (device == null)
{
Debug.Console(1, "Could not find device with key {0}", key);
return;
}
OnObjectChange(device, 0, JsonStandardDeviceConstants.JsonObjectChanged);
// get the device configuration using the key
var devices = jsonMaster.JsonObject.ToObject<RootObject>().devices;
var device = devices.FirstOrDefault(d => d.key.Equals(key));
if (device == null)
{
Debug.Console(1, "Could not find device with key {0}", key);
return;
}
OnObjectChange(device, 0, JsonStandardDeviceConstants.JsonObjectChanged);
var index = devices.IndexOf(device);
OnStringChange(string.Format("devices[{0}]", index), 0, JsonToSimplConstants.FullPathToArrayChange);
}
catch (Exception e)
{
var msg = string.Format("Device {0} lookup failed:\r{1}", key, e);
CrestronConsole.PrintLine(msg);
ErrorLog.Error(msg);
}
finally
{
// S+ set EvaluteFb high
OnBoolChange(true, 0, JsonStandardDeviceConstants.JsonObjectEvaluated);
}
}
var index = devices.IndexOf(device);
OnStringChange(string.Format("devices[{0}]", index), 0, JsonToSimplConstants.FullPathToArrayChange);
}
catch (Exception e)
{
var msg = string.Format("Device {0} lookup failed:\r{1}", key, e);
CrestronConsole.PrintLine(msg);
ErrorLog.Error(msg);
}
finally
{
// S+ set EvaluteFb high
OnBoolChange(true, 0, JsonStandardDeviceConstants.JsonObjectEvaluated);
}
}
#region EventHandler Helpers
#region EventHandler Helpers
/// <summary>
/// BoolChange event handler helper
/// </summary>
/// <param name="state"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnBoolChange(bool state, ushort index, ushort type)
{
var handler = BoolChange;
if (handler != null)
{
var args = new BoolChangeEventArgs(state, type);
args.Index = index;
BoolChange(this, args);
}
}
/// <summary>
/// BoolChange event handler helper
/// </summary>
/// <param name="state"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnBoolChange(bool state, ushort index, ushort type)
{
var handler = BoolChange;
if (handler != null)
{
var args = new BoolChangeEventArgs(state, type);
args.Index = index;
BoolChange(this, args);
}
}
/// <summary>
/// UshrtChange event handler helper
/// </summary>
/// <param name="state"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnUshrtChange(ushort state, ushort index, ushort type)
{
var handler = UshrtChange;
if (handler != null)
{
var args = new UshrtChangeEventArgs(state, type);
args.Index = index;
UshrtChange(this, args);
}
}
/// <summary>
/// UshrtChange event handler helper
/// </summary>
/// <param name="state"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnUshrtChange(ushort state, ushort index, ushort type)
{
var handler = UshrtChange;
if (handler != null)
{
var args = new UshrtChangeEventArgs(state, type);
args.Index = index;
UshrtChange(this, args);
}
}
/// <summary>
/// StringChange event handler helper
/// </summary>
/// <param name="value"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnStringChange(string value, ushort index, ushort type)
{
var handler = StringChange;
if (handler != null)
{
var args = new StringChangeEventArgs(value, type);
args.Index = index;
StringChange(this, args);
}
}
/// <summary>
/// StringChange event handler helper
/// </summary>
/// <param name="value"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnStringChange(string value, ushort index, ushort type)
{
var handler = StringChange;
if (handler != null)
{
var args = new StringChangeEventArgs(value, type);
args.Index = index;
StringChange(this, args);
}
}
/// <summary>
/// ObjectChange event handler helper
/// </summary>
/// <param name="device"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnObjectChange(DeviceConfig device, ushort index, ushort type)
{
if (DeviceChange != null)
{
var args = new DeviceChangeEventArgs(device, type);
args.Index = index;
DeviceChange(this, args);
}
}
/// <summary>
/// ObjectChange event handler helper
/// </summary>
/// <param name="device"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnObjectChange(DeviceConfig device, ushort index, ushort type)
{
if (DeviceChange != null)
{
var args = new DeviceChangeEventArgs(device, type);
args.Index = index;
DeviceChange(this, args);
}
}
#endregion EventHandler Helpers
}
#endregion EventHandler Helpers
}
}

View File

@@ -1,12 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
namespace PepperDash.Core.JsonStandardObjects
{
/*
/*
Convert JSON snippt to C#: http://json2csharp.com/#
JSON Snippet:
@@ -47,11 +44,11 @@ namespace PepperDash.Core.JsonStandardObjects
]
}
*/
/// <summary>
/// Device communication parameter class
/// </summary>
public class ComParamsConfig
{
/// <summary>
/// Device communication parameter class
/// </summary>
public class ComParamsConfig
{
/// <summary>
///
/// </summary>
@@ -85,11 +82,11 @@ namespace PepperDash.Core.JsonStandardObjects
/// </summary>
public int pacing { get; set; }
// convert properties for simpl
// convert properties for simpl
/// <summary>
///
/// </summary>
public ushort simplBaudRate { get { return Convert.ToUInt16(baudRate); } }
public ushort simplBaudRate { get { return Convert.ToUInt16(baudRate); } }
/// <summary>
///
/// </summary>
@@ -103,20 +100,20 @@ namespace PepperDash.Core.JsonStandardObjects
/// </summary>
public ushort simplPacing { get { return Convert.ToUInt16(pacing); } }
/// <summary>
/// Constructor
/// </summary>
public ComParamsConfig()
{
/// <summary>
/// Constructor
/// </summary>
public ComParamsConfig()
{
}
}
}
}
/// <summary>
/// Device TCP/SSH properties class
/// </summary>
public class TcpSshPropertiesConfig
{
/// <summary>
/// Device TCP/SSH properties class
/// </summary>
public class TcpSshPropertiesConfig
{
/// <summary>
///
/// </summary>
@@ -142,11 +139,11 @@ namespace PepperDash.Core.JsonStandardObjects
/// </summary>
public int autoReconnectIntervalMs { get; set; }
// convert properties for simpl
// convert properties for simpl
/// <summary>
///
/// </summary>
public ushort simplPort { get { return Convert.ToUInt16(port); } }
public ushort simplPort { get { return Convert.ToUInt16(port); } }
/// <summary>
///
/// </summary>
@@ -156,20 +153,20 @@ namespace PepperDash.Core.JsonStandardObjects
/// </summary>
public ushort simplAutoReconnectIntervalMs { get { return Convert.ToUInt16(autoReconnectIntervalMs); } }
/// <summary>
/// Constructor
/// </summary>
public TcpSshPropertiesConfig()
{
/// <summary>
/// Constructor
/// </summary>
public TcpSshPropertiesConfig()
{
}
}
}
}
/// <summary>
/// Device control class
/// </summary>
public class ControlConfig
{
/// <summary>
/// Device control class
/// </summary>
public class ControlConfig
{
/// <summary>
///
/// </summary>
@@ -191,27 +188,27 @@ namespace PepperDash.Core.JsonStandardObjects
/// </summary>
public TcpSshPropertiesConfig tcpSshProperties { get; set; }
// convert properties for simpl
// convert properties for simpl
/// <summary>
///
/// </summary>
public ushort simplControlPortNumber { get { return Convert.ToUInt16(controlPortNumber); } }
public ushort simplControlPortNumber { get { return Convert.ToUInt16(controlPortNumber); } }
/// <summary>
/// Constructor
/// </summary>
public ControlConfig()
{
comParams = new ComParamsConfig();
tcpSshProperties = new TcpSshPropertiesConfig();
}
}
/// <summary>
/// Constructor
/// </summary>
public ControlConfig()
{
comParams = new ComParamsConfig();
tcpSshProperties = new TcpSshPropertiesConfig();
}
}
/// <summary>
/// Device properties class
/// </summary>
public class PropertiesConfig
{
/// <summary>
/// Device properties class
/// </summary>
public class PropertiesConfig
{
/// <summary>
///
/// </summary>
@@ -225,33 +222,33 @@ namespace PepperDash.Core.JsonStandardObjects
/// </summary>
public ControlConfig control { get; set; }
// convert properties for simpl
// convert properties for simpl
/// <summary>
///
/// </summary>
public ushort simplDeviceId { get { return Convert.ToUInt16(deviceId); } }
public ushort simplDeviceId { get { return Convert.ToUInt16(deviceId); } }
/// <summary>
///
/// </summary>
public ushort simplEnabled { get { return (ushort)(enabled ? 1 : 0); } }
/// <summary>
/// Constructor
/// </summary>
public PropertiesConfig()
{
control = new ControlConfig();
}
}
/// <summary>
/// Constructor
/// </summary>
public PropertiesConfig()
{
control = new ControlConfig();
}
}
/// <summary>
/// Root device class
/// </summary>
public class RootObject
{
/// <summary>
/// Root device class
/// </summary>
public class RootObject
{
/// <summary>
/// The collection of devices
/// </summary>
public List<DeviceConfig> devices { get; set; }
}
}
}

View File

@@ -1,16 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
namespace PepperDash.Core.JsonToSimpl
namespace PepperDash.Core.JsonToSimpl
{
/// <summary>
/// Constants for Simpl modules
/// </summary>
public class JsonToSimplConstants
{
/// <summary>
/// Constants for Simpl modules
/// </summary>
public class JsonToSimplConstants
{
/// <summary>
///
/// </summary>
@@ -38,12 +32,12 @@ namespace PepperDash.Core.JsonToSimpl
/// <summary>
///
/// </summary>
public const ushort UshortValueChange = 101;
public const ushort UshortValueChange = 101;
/// <summary>
///
/// </summary>
public const ushort StringValueChange = 201;
public const ushort StringValueChange = 201;
/// <summary>
///
/// </summary>
@@ -76,18 +70,18 @@ namespace PepperDash.Core.JsonToSimpl
/// Reports the room name change
/// </summary>
public const ushort RoomNameChange = 208;
}
}
/// <summary>
/// S+ values delegate
/// </summary>
public delegate void SPlusValuesDelegate();
/// <summary>
/// S+ values delegate
/// </summary>
public delegate void SPlusValuesDelegate();
/// <summary>
/// S+ values wrapper
/// </summary>
public class SPlusValueWrapper
{
/// <summary>
/// S+ values wrapper
/// </summary>
public class SPlusValueWrapper
{
/// <summary>
///
/// </summary>
@@ -108,7 +102,7 @@ namespace PepperDash.Core.JsonToSimpl
/// <summary>
///
/// </summary>
public SPlusValueWrapper() {}
public SPlusValueWrapper() { }
/// <summary>
///
@@ -116,28 +110,28 @@ namespace PepperDash.Core.JsonToSimpl
/// <param name="type"></param>
/// <param name="index"></param>
public SPlusValueWrapper(SPlusType type, ushort index)
{
ValueType = type;
Index = index;
}
}
{
ValueType = type;
Index = index;
}
}
/// <summary>
/// S+ types enum
/// </summary>
public enum SPlusType
{
/// <summary>
/// S+ types enum
/// </summary>
public enum SPlusType
{
/// <summary>
/// Digital
/// </summary>
Digital,
Digital,
/// <summary>
/// Analog
/// </summary>
Analog,
Analog,
/// <summary>
/// String
/// </summary>
String
}
}
}

View File

@@ -1,8 +1,8 @@
using System;
using Crestron.SimplSharp;
using PepperDash.Core.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
//using PepperDash.Core;
@@ -12,48 +12,48 @@ namespace PepperDash.Core.JsonToSimpl
/// The global class to manage all the instances of JsonToSimplMaster
/// </summary>
public class J2SGlobal
{
static List<JsonToSimplMaster> Masters = new List<JsonToSimplMaster>();
{
static List<JsonToSimplMaster> Masters = new List<JsonToSimplMaster>();
/// <summary>
/// Adds a file master. If the master's key or filename is equivalent to any existing
/// master, this will fail
/// </summary>
/// <param name="master">New master to add</param>
/// <summary>
/// Adds a file master. If the master's key or filename is equivalent to any existing
/// master, this will fail
/// </summary>
/// <param name="master">New master to add</param>
///
public static void AddMaster(JsonToSimplMaster master)
{
if (master == null)
throw new ArgumentNullException("master");
public static void AddMaster(JsonToSimplMaster master)
{
if (master == null)
throw new ArgumentNullException("master");
if (string.IsNullOrEmpty(master.UniqueID))
throw new InvalidOperationException("JSON Master cannot be added with a null UniqueId");
Debug.Console(1, "JSON Global adding master {0}", master.UniqueID);
if (string.IsNullOrEmpty(master.UniqueID))
throw new InvalidOperationException("JSON Master cannot be added with a null UniqueId");
if (Masters.Contains(master)) return;
Debug.Console(1, "JSON Global adding master {0}", master.UniqueID);
var existing = Masters.FirstOrDefault(m =>
m.UniqueID.Equals(master.UniqueID, StringComparison.OrdinalIgnoreCase));
if (existing == null)
{
Masters.Add(master);
}
else
{
var msg = string.Format("Cannot add JSON Master with unique ID '{0}'.\rID is already in use on another master.", master.UniqueID);
CrestronConsole.PrintLine(msg);
ErrorLog.Warn(msg);
}
}
if (Masters.Contains(master)) return;
/// <summary>
/// Gets a master by its key. Case-insensitive
/// </summary>
public static JsonToSimplMaster GetMasterByFile(string file)
{
return Masters.FirstOrDefault(m => m.UniqueID.Equals(file, StringComparison.OrdinalIgnoreCase));
}
}
var existing = Masters.FirstOrDefault(m =>
m.UniqueID.Equals(master.UniqueID, StringComparison.OrdinalIgnoreCase));
if (existing == null)
{
Masters.Add(master);
}
else
{
var msg = string.Format("Cannot add JSON Master with unique ID '{0}'.\rID is already in use on another master.", master.UniqueID);
CrestronConsole.PrintLine(msg);
ErrorLog.Warn(msg);
}
}
/// <summary>
/// Gets a master by its key. Case-insensitive
/// </summary>
public static JsonToSimplMaster GetMasterByFile(string file)
{
return Masters.FirstOrDefault(m => m.UniqueID.Equals(file, StringComparison.OrdinalIgnoreCase));
}
}
}

View File

@@ -1,11 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PepperDash.Core.Logging;
using System;
using System.Linq;
namespace PepperDash.Core.JsonToSimpl
{
@@ -13,7 +10,7 @@ namespace PepperDash.Core.JsonToSimpl
/// Used to interact with an array of values with the S+ modules
/// </summary>
public class JsonToSimplArrayLookupChild : JsonToSimplChildObjectBase
{
{
/// <summary>
///
/// </summary>
@@ -23,144 +20,144 @@ namespace PepperDash.Core.JsonToSimpl
/// </summary>
public string SearchPropertyValue { get; set; }
int ArrayIndex;
int ArrayIndex;
/// <summary>
/// For gt2.4.1 array lookups
/// </summary>
/// <param name="file"></param>
/// <param name="key"></param>
/// <param name="pathPrefix"></param>
/// <param name="pathSuffix"></param>
/// <param name="searchPropertyName"></param>
/// <param name="searchPropertyValue"></param>
public void Initialize(string file, string key, string pathPrefix, string pathSuffix,
string searchPropertyName, string searchPropertyValue)
{
base.Initialize(file, key, pathPrefix, pathSuffix);
SearchPropertyName = searchPropertyName;
SearchPropertyValue = searchPropertyValue;
}
/// <summary>
/// For gt2.4.1 array lookups
/// </summary>
/// <param name="file"></param>
/// <param name="key"></param>
/// <param name="pathPrefix"></param>
/// <param name="pathSuffix"></param>
/// <param name="searchPropertyName"></param>
/// <param name="searchPropertyValue"></param>
public void Initialize(string file, string key, string pathPrefix, string pathSuffix,
string searchPropertyName, string searchPropertyValue)
{
base.Initialize(file, key, pathPrefix, pathSuffix);
SearchPropertyName = searchPropertyName;
SearchPropertyValue = searchPropertyValue;
}
/// <summary>
/// For newer >=2.4.1 array lookups.
/// </summary>
/// <param name="file"></param>
/// <param name="key"></param>
/// <param name="pathPrefix"></param>
/// <param name="pathAppend"></param>
/// <param name="pathSuffix"></param>
/// <param name="searchPropertyName"></param>
/// <param name="searchPropertyValue"></param>
public void InitializeWithAppend(string file, string key, string pathPrefix, string pathAppend,
string pathSuffix, string searchPropertyName, string searchPropertyValue)
{
string pathPrefixWithAppend = (pathPrefix != null ? pathPrefix : "") + GetPathAppend(pathAppend);
base.Initialize(file, key, pathPrefixWithAppend, pathSuffix);
/// <summary>
/// For newer >=2.4.1 array lookups.
/// </summary>
/// <param name="file"></param>
/// <param name="key"></param>
/// <param name="pathPrefix"></param>
/// <param name="pathAppend"></param>
/// <param name="pathSuffix"></param>
/// <param name="searchPropertyName"></param>
/// <param name="searchPropertyValue"></param>
public void InitializeWithAppend(string file, string key, string pathPrefix, string pathAppend,
string pathSuffix, string searchPropertyName, string searchPropertyValue)
{
string pathPrefixWithAppend = (pathPrefix != null ? pathPrefix : "") + GetPathAppend(pathAppend);
base.Initialize(file, key, pathPrefixWithAppend, pathSuffix);
SearchPropertyName = searchPropertyName;
SearchPropertyValue = searchPropertyValue;
}
SearchPropertyName = searchPropertyName;
SearchPropertyValue = searchPropertyValue;
}
//PathPrefix+ArrayName+[x]+path+PathSuffix
/// <summary>
///
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
protected override string GetFullPath(string path)
{
return string.Format("{0}[{1}].{2}{3}",
PathPrefix == null ? "" : PathPrefix,
ArrayIndex,
path,
PathSuffix == null ? "" : PathSuffix);
}
//PathPrefix+ArrayName+[x]+path+PathSuffix
/// <summary>
///
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
protected override string GetFullPath(string path)
{
return string.Format("{0}[{1}].{2}{3}",
PathPrefix == null ? "" : PathPrefix,
ArrayIndex,
path,
PathSuffix == null ? "" : PathSuffix);
}
/// <summary>
/// Process all values
/// </summary>
public override void ProcessAll()
{
if (FindInArray())
base.ProcessAll();
}
{
if (FindInArray())
base.ProcessAll();
}
/// <summary>
/// Provides the path append for GetFullPath
/// </summary>
/// <returns></returns>
string GetPathAppend(string a)
{
if (string.IsNullOrEmpty(a))
{
return "";
}
if (a.StartsWith("."))
{
return a;
}
else
{
return "." + a;
}
}
/// <summary>
/// Provides the path append for GetFullPath
/// </summary>
/// <returns></returns>
string GetPathAppend(string a)
{
if (string.IsNullOrEmpty(a))
{
return "";
}
if (a.StartsWith("."))
{
return a;
}
else
{
return "." + a;
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
bool FindInArray()
{
if (Master == null)
throw new InvalidOperationException("Cannot do operations before master is linked");
if (Master.JsonObject == null)
throw new InvalidOperationException("Cannot do operations before master JSON has read");
if (PathPrefix == null)
throw new InvalidOperationException("Cannot do operations before PathPrefix is set");
/// <summary>
///
/// </summary>
/// <returns></returns>
bool FindInArray()
{
if (Master == null)
throw new InvalidOperationException("Cannot do operations before master is linked");
if (Master.JsonObject == null)
throw new InvalidOperationException("Cannot do operations before master JSON has read");
if (PathPrefix == null)
throw new InvalidOperationException("Cannot do operations before PathPrefix is set");
var token = Master.JsonObject.SelectToken(PathPrefix);
if (token is JArray)
{
var array = token as JArray;
try
{
var item = array.FirstOrDefault(o =>
{
var prop = o[SearchPropertyName];
return prop != null && prop.Value<string>()
.Equals(SearchPropertyValue, StringComparison.OrdinalIgnoreCase);
});
if (item == null)
{
Debug.Console(1, "JSON Child[{0}] Array '{1}' '{2}={3}' not found: ", Key,
PathPrefix, SearchPropertyName, SearchPropertyValue);
this.LinkedToObject = false;
return false;
}
var token = Master.JsonObject.SelectToken(PathPrefix);
if (token is JArray)
{
var array = token as JArray;
try
{
var item = array.FirstOrDefault(o =>
{
var prop = o[SearchPropertyName];
return prop != null && prop.Value<string>()
.Equals(SearchPropertyValue, StringComparison.OrdinalIgnoreCase);
});
if (item == null)
{
Debug.Console(1, "JSON Child[{0}] Array '{1}' '{2}={3}' not found: ", Key,
PathPrefix, SearchPropertyName, SearchPropertyValue);
this.LinkedToObject = false;
return false;
}
this.LinkedToObject = true;
ArrayIndex = array.IndexOf(item);
OnStringChange(string.Format("{0}[{1}]", PathPrefix, ArrayIndex), 0, JsonToSimplConstants.FullPathToArrayChange);
Debug.Console(1, "JSON Child[{0}] Found array match at index {1}", Key, ArrayIndex);
return true;
}
catch (Exception e)
{
Debug.Console(1, "JSON Child[{0}] Array '{1}' lookup error: '{2}={3}'\r{4}", Key,
PathPrefix, SearchPropertyName, SearchPropertyValue, e);
}
}
else
{
Debug.Console(1, "JSON Child[{0}] Path '{1}' is not an array", Key, PathPrefix);
}
this.LinkedToObject = true;
ArrayIndex = array.IndexOf(item);
OnStringChange(string.Format("{0}[{1}]", PathPrefix, ArrayIndex), 0, JsonToSimplConstants.FullPathToArrayChange);
Debug.Console(1, "JSON Child[{0}] Found array match at index {1}", Key, ArrayIndex);
return true;
}
catch (Exception e)
{
Debug.Console(1, "JSON Child[{0}] Array '{1}' lookup error: '{2}={3}'\r{4}", Key,
PathPrefix, SearchPropertyName, SearchPropertyValue, e);
}
}
else
{
Debug.Console(1, "JSON Child[{0}] Path '{1}' is not an array", Key, PathPrefix);
}
return false;
}
}
return false;
}
}
}

View File

@@ -1,11 +1,10 @@
using Newtonsoft.Json.Linq;
using PepperDash.Core.Interfaces;
using PepperDash.Core.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace PepperDash.Core.JsonToSimpl
{
@@ -13,7 +12,7 @@ namespace PepperDash.Core.JsonToSimpl
/// Base class for JSON objects
/// </summary>
public abstract class JsonToSimplChildObjectBase : IKeyed
{
{
/// <summary>
/// Notifies of bool change
/// </summary>
@@ -32,26 +31,26 @@ namespace PepperDash.Core.JsonToSimpl
/// </summary>
public SPlusValuesDelegate GetAllValuesDelegate { get; set; }
/// <summary>
/// Use a callback to reduce task switch/threading
/// </summary>
public SPlusValuesDelegate SetAllPathsDelegate { get; set; }
/// <summary>
/// Use a callback to reduce task switch/threading
/// </summary>
public SPlusValuesDelegate SetAllPathsDelegate { get; set; }
/// <summary>
/// Unique identifier for instance
/// </summary>
public string Key { get; protected set; }
/// <summary>
/// This will be prepended to all paths to allow path swapping or for more organized
/// sub-paths
/// </summary>
public string PathPrefix { get; protected set; }
/// <summary>
/// This will be prepended to all paths to allow path swapping or for more organized
/// sub-paths
/// </summary>
public string PathPrefix { get; protected set; }
/// <summary>
/// This is added to the end of all paths
/// </summary>
public string PathSuffix { get; protected set; }
/// <summary>
/// This is added to the end of all paths
/// </summary>
public string PathSuffix { get; protected set; }
/// <summary>
/// Indicates if the instance is linked to an object
@@ -76,107 +75,109 @@ namespace PepperDash.Core.JsonToSimpl
/// </summary>
protected Dictionary<ushort, string> StringPaths = new Dictionary<ushort, string>();
/// <summary>
/// Call this before doing anything else
/// </summary>
/// <summary>
/// Call this before doing anything else
/// </summary>
/// <param name="masterUniqueId"></param>
/// <param name="key"></param>
/// <param name="pathPrefix"></param>
/// <param name="pathSuffix"></param>
public void Initialize(string masterUniqueId, string key, string pathPrefix, string pathSuffix)
{
Key = key;
PathPrefix = pathPrefix;
PathSuffix = pathSuffix;
/// <param name="key"></param>
/// <param name="pathPrefix"></param>
/// <param name="pathSuffix"></param>
public void Initialize(string masterUniqueId, string key, string pathPrefix, string pathSuffix)
{
Key = key;
PathPrefix = pathPrefix;
PathSuffix = pathSuffix;
Master = J2SGlobal.GetMasterByFile(masterUniqueId);
if (Master != null)
Master.AddChild(this);
else
Debug.Console(1, "JSON Child [{0}] cannot link to master {1}", key, masterUniqueId);
}
Master = J2SGlobal.GetMasterByFile(masterUniqueId);
if (Master != null)
Master.AddChild(this);
else
Debug.Console(1, "JSON Child [{0}] cannot link to master {1}", key, masterUniqueId);
}
/// <summary>
/// Sets the path prefix for the object
/// </summary>
/// <param name="pathPrefix"></param>
public void SetPathPrefix(string pathPrefix)
{
PathPrefix = pathPrefix;
}
/// <summary>
/// Set the JPath to evaluate for a given bool out index.
/// </summary>
public void SetBoolPath(ushort index, string path)
{
Debug.Console(1, "JSON Child[{0}] SetBoolPath {1}={2}", Key, index, path);
if (path == null || path.Trim() == string.Empty) return;
BoolPaths[index] = path;
}
{
PathPrefix = pathPrefix;
}
/// <summary>
/// Set the JPath to evaluate for a given bool out index.
/// </summary>
public void SetBoolPath(ushort index, string path)
{
Debug.Console(1, "JSON Child[{0}] SetBoolPath {1}={2}", Key, index, path);
if (path == null || path.Trim() == string.Empty) return;
BoolPaths[index] = path;
}
/// <summary>
/// Set the JPath for a ushort out index.
/// </summary>
public void SetUshortPath(ushort index, string path)
{
Debug.Console(1, "JSON Child[{0}] SetUshortPath {1}={2}", Key, index, path);
if (path == null || path.Trim() == string.Empty) return;
UshortPaths[index] = path;
}
/// <summary>
/// Set the JPath for a ushort out index.
/// </summary>
public void SetUshortPath(ushort index, string path)
{
Debug.Console(1, "JSON Child[{0}] SetUshortPath {1}={2}", Key, index, path);
if (path == null || path.Trim() == string.Empty) return;
UshortPaths[index] = path;
}
/// <summary>
/// Set the JPath for a string output index.
/// </summary>
public void SetStringPath(ushort index, string path)
{
Debug.Console(1, "JSON Child[{0}] SetStringPath {1}={2}", Key, index, path);
if (path == null || path.Trim() == string.Empty) return;
StringPaths[index] = path;
}
/// <summary>
/// Set the JPath for a string output index.
/// </summary>
public void SetStringPath(ushort index, string path)
{
Debug.Console(1, "JSON Child[{0}] SetStringPath {1}={2}", Key, index, path);
if (path == null || path.Trim() == string.Empty) return;
StringPaths[index] = path;
}
/// <summary>
/// Evalutates all outputs with defined paths. called by S+ when paths are ready to process
/// and by Master when file is read.
/// </summary>
public virtual void ProcessAll()
{
if (!LinkedToObject)
{
Debug.Console(1, this, "Not linked to object in file. Skipping");
return;
}
/// <summary>
/// Evalutates all outputs with defined paths. called by S+ when paths are ready to process
/// and by Master when file is read.
/// </summary>
public virtual void ProcessAll()
{
if (!LinkedToObject)
{
Debug.Console(1, this, "Not linked to object in file. Skipping");
return;
}
if (SetAllPathsDelegate == null)
{
Debug.Console(1, this, "No SetAllPathsDelegate set. Ignoring ProcessAll");
return;
}
SetAllPathsDelegate();
foreach (var kvp in BoolPaths)
ProcessBoolPath(kvp.Key);
foreach (var kvp in UshortPaths)
ProcessUshortPath(kvp.Key);
foreach (var kvp in StringPaths)
ProcessStringPath(kvp.Key);
}
if (SetAllPathsDelegate == null)
{
Debug.Console(1, this, "No SetAllPathsDelegate set. Ignoring ProcessAll");
return;
}
SetAllPathsDelegate();
foreach (var kvp in BoolPaths)
ProcessBoolPath(kvp.Key);
foreach (var kvp in UshortPaths)
ProcessUshortPath(kvp.Key);
foreach (var kvp in StringPaths)
ProcessStringPath(kvp.Key);
}
/// <summary>
/// Processes a bool property, converting to bool, firing off a BoolChange event
/// </summary>
void ProcessBoolPath(ushort index)
{
string response;
if (Process(BoolPaths[index], out response))
OnBoolChange(response.Equals("true", StringComparison.OrdinalIgnoreCase),
index, JsonToSimplConstants.BoolValueChange);
else { }
// OnBoolChange(false, index, JsonToSimplConstants.BoolValueChange);
}
// Processes the path to a ushort, converting to ushort if able, twos complement if necessary, firing off UshrtChange event
void ProcessUshortPath(ushort index) {
/// <summary>
/// Processes a bool property, converting to bool, firing off a BoolChange event
/// </summary>
void ProcessBoolPath(ushort index)
{
string response;
if (Process(UshortPaths[index], out response)) {
if (Process(BoolPaths[index], out response))
OnBoolChange(response.Equals("true", StringComparison.OrdinalIgnoreCase),
index, JsonToSimplConstants.BoolValueChange);
else { }
// OnBoolChange(false, index, JsonToSimplConstants.BoolValueChange);
}
// Processes the path to a ushort, converting to ushort if able, twos complement if necessary, firing off UshrtChange event
void ProcessUshortPath(ushort index)
{
string response;
if (Process(UshortPaths[index], out response))
{
ushort val;
try { val = Convert.ToInt32(response) < 0 ? (ushort)(Convert.ToInt16(response) + 65536) : Convert.ToUInt16(response); }
catch { val = 0; }
@@ -187,94 +188,94 @@ namespace PepperDash.Core.JsonToSimpl
// OnUShortChange(0, index, JsonToSimplConstants.UshortValueChange);
}
// Processes the path to a string property and fires of a StringChange event.
void ProcessStringPath(ushort index)
{
string response;
if (Process(StringPaths[index], out response))
OnStringChange(response, index, JsonToSimplConstants.StringValueChange);
else { }
// OnStringChange("", index, JsonToSimplConstants.StringValueChange);
}
// Processes the path to a string property and fires of a StringChange event.
void ProcessStringPath(ushort index)
{
string response;
if (Process(StringPaths[index], out response))
OnStringChange(response, index, JsonToSimplConstants.StringValueChange);
else { }
// OnStringChange("", index, JsonToSimplConstants.StringValueChange);
}
/// <summary>
/// Processes the given path.
/// </summary>
/// <param name="path">JPath formatted path to the desired property</param>
/// <param name="response">The string value of the property, or a default value if it
/// doesn't exist</param>
/// <returns> This will return false in the case that EvaulateAllOnJsonChange
/// is false and the path does not evaluate to a property in the incoming JSON. </returns>
bool Process(string path, out string response)
{
path = GetFullPath(path);
Debug.Console(1, "JSON Child[{0}] Processing {1}", Key, path);
response = "";
if (Master == null)
{
Debug.Console(1, "JSONChild[{0}] cannot process without Master attached", Key);
return false;
}
/// <summary>
/// Processes the given path.
/// </summary>
/// <param name="path">JPath formatted path to the desired property</param>
/// <param name="response">The string value of the property, or a default value if it
/// doesn't exist</param>
/// <returns> This will return false in the case that EvaulateAllOnJsonChange
/// is false and the path does not evaluate to a property in the incoming JSON. </returns>
bool Process(string path, out string response)
{
path = GetFullPath(path);
Debug.Console(1, "JSON Child[{0}] Processing {1}", Key, path);
response = "";
if (Master == null)
{
Debug.Console(1, "JSONChild[{0}] cannot process without Master attached", Key);
return false;
}
if (Master.JsonObject != null && path != string.Empty)
{
bool isCount = false;
path = path.Trim();
if (path.EndsWith(".Count"))
{
path = path.Remove(path.Length - 6, 6);
isCount = true;
}
try // Catch a strange cast error on a bad path
{
var t = Master.JsonObject.SelectToken(path);
if (t != null)
{
// return the count of children objects - if any
if (isCount)
response = (t.HasValues ? t.Children().Count() : 0).ToString();
else
response = t.Value<string>();
Debug.Console(1, " ='{0}'", response);
return true;
}
}
catch
{
response = "";
}
}
// If the path isn't found, return this to determine whether to pass out the non-value or not.
return false;
}
if (Master.JsonObject != null && path != string.Empty)
{
bool isCount = false;
path = path.Trim();
if (path.EndsWith(".Count"))
{
path = path.Remove(path.Length - 6, 6);
isCount = true;
}
try // Catch a strange cast error on a bad path
{
var t = Master.JsonObject.SelectToken(path);
if (t != null)
{
// return the count of children objects - if any
if (isCount)
response = (t.HasValues ? t.Children().Count() : 0).ToString();
else
response = t.Value<string>();
Debug.Console(1, " ='{0}'", response);
return true;
}
}
catch
{
response = "";
}
}
// If the path isn't found, return this to determine whether to pass out the non-value or not.
return false;
}
//************************************************************************************************
// Save-related functions
//************************************************************************************************
// Save-related functions
/// <summary>
/// Called from Master to read inputs and update their values in master JObject
/// Callback should hit one of the following four methods
/// </summary>
public void UpdateInputsForMaster()
{
if (!LinkedToObject)
{
Debug.Console(1, this, "Not linked to object in file. Skipping");
return;
}
/// <summary>
/// Called from Master to read inputs and update their values in master JObject
/// Callback should hit one of the following four methods
/// </summary>
public void UpdateInputsForMaster()
{
if (!LinkedToObject)
{
Debug.Console(1, this, "Not linked to object in file. Skipping");
return;
}
if (SetAllPathsDelegate == null)
{
Debug.Console(1, this, "No SetAllPathsDelegate set. Ignoring UpdateInputsForMaster");
return;
}
SetAllPathsDelegate();
var del = GetAllValuesDelegate;
if (del != null)
GetAllValuesDelegate();
}
if (SetAllPathsDelegate == null)
{
Debug.Console(1, this, "No SetAllPathsDelegate set. Ignoring UpdateInputsForMaster");
return;
}
SetAllPathsDelegate();
var del = GetAllValuesDelegate;
if (del != null)
GetAllValuesDelegate();
}
/// <summary>
///
@@ -282,9 +283,9 @@ namespace PepperDash.Core.JsonToSimpl
/// <param name="key"></param>
/// <param name="theValue"></param>
public void USetBoolValue(ushort key, ushort theValue)
{
SetBoolValue(key, theValue == 1);
}
{
SetBoolValue(key, theValue == 1);
}
/// <summary>
///
@@ -292,10 +293,10 @@ namespace PepperDash.Core.JsonToSimpl
/// <param name="key"></param>
/// <param name="theValue"></param>
public void SetBoolValue(ushort key, bool theValue)
{
if (BoolPaths.ContainsKey(key))
SetValueOnMaster(BoolPaths[key], new JValue(theValue));
}
{
if (BoolPaths.ContainsKey(key))
SetValueOnMaster(BoolPaths[key], new JValue(theValue));
}
/// <summary>
///
@@ -303,10 +304,10 @@ namespace PepperDash.Core.JsonToSimpl
/// <param name="key"></param>
/// <param name="theValue"></param>
public void SetUShortValue(ushort key, ushort theValue)
{
if (UshortPaths.ContainsKey(key))
SetValueOnMaster(UshortPaths[key], new JValue(theValue));
}
{
if (UshortPaths.ContainsKey(key))
SetValueOnMaster(UshortPaths[key], new JValue(theValue));
}
/// <summary>
///
@@ -314,10 +315,10 @@ namespace PepperDash.Core.JsonToSimpl
/// <param name="key"></param>
/// <param name="theValue"></param>
public void SetStringValue(ushort key, string theValue)
{
if (StringPaths.ContainsKey(key))
SetValueOnMaster(StringPaths[key], new JValue(theValue));
}
{
if (StringPaths.ContainsKey(key))
SetValueOnMaster(StringPaths[key], new JValue(theValue));
}
/// <summary>
///
@@ -325,68 +326,68 @@ namespace PepperDash.Core.JsonToSimpl
/// <param name="keyPath"></param>
/// <param name="valueToSave"></param>
public void SetValueOnMaster(string keyPath, JValue valueToSave)
{
var path = GetFullPath(keyPath);
try
{
Debug.Console(1, "JSON Child[{0}] Queueing value on master {1}='{2}'", Key, path, valueToSave);
{
var path = GetFullPath(keyPath);
try
{
Debug.Console(1, "JSON Child[{0}] Queueing value on master {1}='{2}'", Key, path, valueToSave);
//var token = Master.JsonObject.SelectToken(path);
//if (token != null) // The path exists in the file
Master.AddUnsavedValue(path, valueToSave);
}
catch (Exception e)
{
Debug.Console(1, "JSON Child[{0}] Failed setting value for path '{1}'\r{2}", Key, path, e);
}
}
//var token = Master.JsonObject.SelectToken(path);
//if (token != null) // The path exists in the file
Master.AddUnsavedValue(path, valueToSave);
}
catch (Exception e)
{
Debug.Console(1, "JSON Child[{0}] Failed setting value for path '{1}'\r{2}", Key, path, e);
}
}
/// <summary>
/// Called during Process(...) to get the path to a given property. By default,
/// returns PathPrefix+path+PathSuffix. Override to change the way path is built.
/// </summary>
protected virtual string GetFullPath(string path)
{
return (PathPrefix != null ? PathPrefix : "") +
path + (PathSuffix != null ? PathSuffix : "");
}
/// <summary>
/// Called during Process(...) to get the path to a given property. By default,
/// returns PathPrefix+path+PathSuffix. Override to change the way path is built.
/// </summary>
protected virtual string GetFullPath(string path)
{
return (PathPrefix != null ? PathPrefix : "") +
path + (PathSuffix != null ? PathSuffix : "");
}
// Helpers for events
//******************************************************************************************
// Helpers for events
//******************************************************************************************
/// <summary>
/// Event helper
/// </summary>
/// <param name="state"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnBoolChange(bool state, ushort index, ushort type)
{
var handler = BoolChange;
if (handler != null)
{
var args = new BoolChangeEventArgs(state, type);
args.Index = index;
BoolChange(this, args);
}
}
protected void OnBoolChange(bool state, ushort index, ushort type)
{
var handler = BoolChange;
if (handler != null)
{
var args = new BoolChangeEventArgs(state, type);
args.Index = index;
BoolChange(this, args);
}
}
//******************************************************************************************
//******************************************************************************************
/// <summary>
/// Event helper
/// </summary>
/// <param name="state"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnUShortChange(ushort state, ushort index, ushort type)
{
var handler = UShortChange;
if (handler != null)
{
var args = new UshrtChangeEventArgs(state, type);
args.Index = index;
UShortChange(this, args);
}
}
protected void OnUShortChange(ushort state, ushort index, ushort type)
{
var handler = UShortChange;
if (handler != null)
{
var args = new UshrtChangeEventArgs(state, type);
args.Index = index;
UShortChange(this, args);
}
}
/// <summary>
/// Event helper
@@ -395,14 +396,14 @@ namespace PepperDash.Core.JsonToSimpl
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnStringChange(string value, ushort index, ushort type)
{
var handler = StringChange;
if (handler != null)
{
var args = new StringChangeEventArgs(value, type);
args.Index = index;
StringChange(this, args);
}
}
}
{
var handler = StringChange;
if (handler != null)
{
var args = new StringChangeEventArgs(value, type);
args.Index = index;
StringChange(this, args);
}
}
}
}

View File

@@ -1,14 +1,13 @@
using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronIO;
using Newtonsoft.Json.Linq;
using PepperDash.Core.Logging;
using System;
//using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronIO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace PepperDash.Core.JsonToSimpl
{
@@ -82,7 +81,7 @@ namespace PepperDash.Core.JsonToSimpl
JsonToSimplConstants.DevicePlatformValueChange);
// get the roomID
var roomId = Crestron.SimplSharp.InitialParametersClass.RoomId;
var roomId = Crestron.SimplSharp.InitialParametersClass.RoomId;
if (!string.IsNullOrEmpty(roomId))
{
OnStringChange(roomId, 0, JsonToSimplConstants.RoomIdChange);
@@ -96,12 +95,12 @@ namespace PepperDash.Core.JsonToSimpl
}
var rootDirectory = Directory.GetApplicationRootDirectory();
OnStringChange(rootDirectory, 0, JsonToSimplConstants.RootDirectoryChange);
OnStringChange(rootDirectory, 0, JsonToSimplConstants.RootDirectoryChange);
var splusPath = string.Empty;
if (Regex.IsMatch(filepath, @"user", RegexOptions.IgnoreCase))
{
if (is4Series)
if (is4Series)
splusPath = Regex.Replace(filepath, "user", "user", RegexOptions.IgnoreCase);
else if (isServer)
splusPath = Regex.Replace(filepath, "user", "User", RegexOptions.IgnoreCase);
@@ -110,10 +109,10 @@ namespace PepperDash.Core.JsonToSimpl
}
filepath = splusPath.Replace(dirSeparatorAlt, dirSeparator);
Filepath = string.Format("{1}{0}{2}", dirSeparator, rootDirectory,
filepath.TrimStart(dirSeparator, dirSeparatorAlt));
OnStringChange(string.Format("Attempting to evaluate {0}", Filepath), 0, JsonToSimplConstants.StringValueChange);
if (string.IsNullOrEmpty(Filepath))
@@ -133,10 +132,10 @@ namespace PepperDash.Core.JsonToSimpl
if (Directory.Exists(fileDirectory))
{
// get the directory info
var directoryInfo = new DirectoryInfo(fileDirectory);
var directoryInfo = new DirectoryInfo(fileDirectory);
// get the file to be read
var actualFile = directoryInfo.GetFiles(fileName).FirstOrDefault();
var actualFile = directoryInfo.GetFiles(fileName).FirstOrDefault();
if (actualFile == null)
{
var msg = string.Format("JSON file not found: {0}", Filepath);
@@ -148,7 +147,7 @@ namespace PepperDash.Core.JsonToSimpl
// \xSE\xR\PDT000-Template_Main_Config-Combined_DSP_v00.02.json
// \USER\PDT000-Template_Main_Config-Combined_DSP_v00.02.json
ActualFilePath = actualFile.FullName;
ActualFilePath = actualFile.FullName;
OnStringChange(ActualFilePath, 0, JsonToSimplConstants.ActualFilePathChange);
OnStringChange(string.Format("Actual JSON file is {0}", ActualFilePath), 0, JsonToSimplConstants.StringValueChange);
Debug.Console(1, "Actual JSON file is {0}", ActualFilePath);
@@ -162,7 +161,7 @@ namespace PepperDash.Core.JsonToSimpl
FilePathName = string.Format(@"{0}{1}", actualFile.DirectoryName, dirSeparator);
OnStringChange(string.Format(@"{0}", actualFile.DirectoryName), 0, JsonToSimplConstants.FilePathResolvedChange);
OnStringChange(string.Format(@"JSON File Path is {0}", actualFile.DirectoryName), 0, JsonToSimplConstants.StringValueChange);
Debug.Console(1, "JSON File Path is {0}", FilePathName);
Debug.Console(1, "JSON File Path is {0}", FilePathName);
var json = File.ReadToEnd(ActualFilePath, System.Text.Encoding.ASCII);

View File

@@ -1,14 +1,4 @@
using System;
//using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronIO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
//using System.IO;
namespace PepperDash.Core.JsonToSimpl
{
@@ -16,13 +6,13 @@ namespace PepperDash.Core.JsonToSimpl
///
/// </summary>
public class JsonToSimplFixedPathObject : JsonToSimplChildObjectBase
{
{
/// <summary>
/// Constructor
/// </summary>
public JsonToSimplFixedPathObject()
{
this.LinkedToObject = true;
}
}
{
this.LinkedToObject = true;
}
}
}

View File

@@ -1,9 +1,10 @@
using System;
using System.Collections.Generic;
using Crestron.SimplSharp;
using Newtonsoft.Json.Linq;
using PepperDash.Core.Logging;
using System;
using System.Collections.Generic;
namespace PepperDash.Core.JsonToSimpl
{
@@ -12,109 +13,109 @@ namespace PepperDash.Core.JsonToSimpl
/// </summary>
public class JsonToSimplGenericMaster : JsonToSimplMaster
{
/*****************************************************************************************/
/** Privates **/
/*****************************************************************************************/
/** Privates **/
// The JSON file in JObject form
// For gathering the incoming data
object StringBuilderLock = new object();
// To prevent multiple same-file access
static object WriteLock = new object();
// The JSON file in JObject form
// For gathering the incoming data
object StringBuilderLock = new object();
// To prevent multiple same-file access
static object WriteLock = new object();
/// <summary>
/// Callback action for saving
/// </summary>
public Action<string> SaveCallback { get; set; }
/*****************************************************************************************/
/*****************************************************************************************/
/// <summary>
/// <summary>
/// SIMPL+ default constructor.
/// </summary>
public JsonToSimplGenericMaster()
public JsonToSimplGenericMaster()
{
}
}
/// <summary>
/// Loads in JSON and triggers evaluation on all children
/// </summary>
/// <param name="json"></param>
public void LoadWithJson(string json)
{
OnBoolChange(false, 0, JsonToSimplConstants.JsonIsValidBoolChange);
try
{
JsonObject = JObject.Parse(json);
foreach (var child in Children)
child.ProcessAll();
OnBoolChange(true, 0, JsonToSimplConstants.JsonIsValidBoolChange);
}
catch (Exception e)
{
var msg = string.Format("JSON parsing failed:\r{0}", e);
CrestronConsole.PrintLine(msg);
ErrorLog.Error(msg);
}
}
/// <summary>
/// Loads in JSON and triggers evaluation on all children
/// </summary>
/// <param name="json"></param>
public void LoadWithJson(string json)
{
OnBoolChange(false, 0, JsonToSimplConstants.JsonIsValidBoolChange);
try
{
JsonObject = JObject.Parse(json);
foreach (var child in Children)
child.ProcessAll();
OnBoolChange(true, 0, JsonToSimplConstants.JsonIsValidBoolChange);
}
catch (Exception e)
{
var msg = string.Format("JSON parsing failed:\r{0}", e);
CrestronConsole.PrintLine(msg);
ErrorLog.Error(msg);
}
}
/// <summary>
/// Loads JSON into JsonObject, but does not trigger evaluation by children
/// </summary>
/// <param name="json"></param>
public void SetJsonWithoutEvaluating(string json)
{
try
{
JsonObject = JObject.Parse(json);
}
catch (Exception e)
{
Debug.Console(0, this, "JSON parsing failed:\r{0}", e);
}
}
/// <summary>
/// Loads JSON into JsonObject, but does not trigger evaluation by children
/// </summary>
/// <param name="json"></param>
public void SetJsonWithoutEvaluating(string json)
{
try
{
JsonObject = JObject.Parse(json);
}
catch (Exception e)
{
Debug.Console(0, this, "JSON parsing failed:\r{0}", e);
}
}
/// <summary>
///
/// </summary>
public override void Save()
{
// this code is duplicated in the other masters!!!!!!!!!!!!!
UnsavedValues = new Dictionary<string, JValue>();
// Make each child update their values into master object
foreach (var child in Children)
{
Debug.Console(1, this, "Master. checking child [{0}] for updates to save", child.Key);
child.UpdateInputsForMaster();
}
/// <summary>
///
/// </summary>
public override void Save()
{
// this code is duplicated in the other masters!!!!!!!!!!!!!
UnsavedValues = new Dictionary<string, JValue>();
// Make each child update their values into master object
foreach (var child in Children)
{
Debug.Console(1, this, "Master. checking child [{0}] for updates to save", child.Key);
child.UpdateInputsForMaster();
}
if (UnsavedValues == null || UnsavedValues.Count == 0)
{
Debug.Console(1, this, "Master. No updated values to save. Skipping");
return;
}
if (UnsavedValues == null || UnsavedValues.Count == 0)
{
Debug.Console(1, this, "Master. No updated values to save. Skipping");
return;
}
lock (WriteLock)
{
Debug.Console(1, this, "Saving");
foreach (var path in UnsavedValues.Keys)
{
var tokenToReplace = JsonObject.SelectToken(path);
if (tokenToReplace != null)
{// It's found
tokenToReplace.Replace(UnsavedValues[path]);
Debug.Console(1, this, "Master Updating '{0}'", path);
}
else // No token. Let's make one
{
Debug.Console(1, "Master Cannot write value onto missing property: '{0}'", path);
}
}
}
if (SaveCallback != null)
SaveCallback(JsonObject.ToString());
else
Debug.Console(0, this, "WARNING: No save callback defined.");
}
}
lock (WriteLock)
{
Debug.Console(1, this, "Saving");
foreach (var path in UnsavedValues.Keys)
{
var tokenToReplace = JsonObject.SelectToken(path);
if (tokenToReplace != null)
{// It's found
tokenToReplace.Replace(UnsavedValues[path]);
Debug.Console(1, this, "Master Updating '{0}'", path);
}
else // No token. Let's make one
{
Debug.Console(1, "Master Cannot write value onto missing property: '{0}'", path);
}
}
}
if (SaveCallback != null)
SaveCallback(JsonObject.ToString());
else
Debug.Console(0, this, "WARNING: No save callback defined.");
}
}
}

View File

@@ -1,14 +1,13 @@
using Crestron.SimplSharp;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PepperDash.Core.Interfaces;
using PepperDash.Core.Logging;
using System;
//using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronIO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace PepperDash.Core.JsonToSimpl
{
@@ -16,7 +15,7 @@ namespace PepperDash.Core.JsonToSimpl
/// Abstract base class for JsonToSimpl interactions
/// </summary>
public abstract class JsonToSimplMaster : IKeyed
{
{
/// <summary>
/// Notifies of bool change
/// </summary>
@@ -35,116 +34,116 @@ namespace PepperDash.Core.JsonToSimpl
/// </summary>
protected List<JsonToSimplChildObjectBase> Children = new List<JsonToSimplChildObjectBase>();
/*****************************************************************************************/
/*****************************************************************************************/
/// <summary>
/// Mirrors the Unique ID for now.
/// </summary>
public string Key { get { return UniqueID; } }
/// <summary>
/// Mirrors the Unique ID for now.
/// </summary>
public string Key { get { return UniqueID; } }
/// <summary>
/// A unique ID
/// </summary>
public string UniqueID { get; protected set; }
/// <summary>
/// Merely for use in debug messages
/// </summary>
public string DebugName
{
get { return _DebugName; }
set { if (DebugName == null) _DebugName = ""; else _DebugName = value; }
}
string _DebugName = "";
/// <summary>
/// Merely for use in debug messages
/// </summary>
public string DebugName
{
get { return _DebugName; }
set { if (DebugName == null) _DebugName = ""; else _DebugName = value; }
}
string _DebugName = "";
/// <summary>
/// This will be prepended to all paths to allow path swapping or for more organized
/// sub-paths
/// </summary>
public string PathPrefix { get; set; }
/// <summary>
/// This will be prepended to all paths to allow path swapping or for more organized
/// sub-paths
/// </summary>
public string PathPrefix { get; set; }
/// <summary>
/// This is added to the end of all paths
/// </summary>
public string PathSuffix { get; set; }
/// <summary>
/// This is added to the end of all paths
/// </summary>
public string PathSuffix { get; set; }
/// <summary>
/// Enables debugging output to the console. Certain error messages will be logged to the
/// system's error log regardless of this setting
/// </summary>
public bool DebugOn { get; set; }
/// <summary>
/// Enables debugging output to the console. Certain error messages will be logged to the
/// system's error log regardless of this setting
/// </summary>
public bool DebugOn { get; set; }
/// <summary>
/// Ushort helper for Debug property
/// </summary>
public ushort UDebug
{
get { return (ushort)(DebugOn ? 1 : 0); }
set
{
DebugOn = (value == 1);
CrestronConsole.PrintLine("JsonToSimpl debug={0}", DebugOn);
}
}
/// <summary>
/// Ushort helper for Debug property
/// </summary>
public ushort UDebug
{
get { return (ushort)(DebugOn ? 1 : 0); }
set
{
DebugOn = (value == 1);
CrestronConsole.PrintLine("JsonToSimpl debug={0}", DebugOn);
}
}
/// <summary>
///
/// </summary>
public JObject JsonObject { get; protected set; }
/*****************************************************************************************/
/** Privates **/
/*****************************************************************************************/
/** Privates **/
// The JSON file in JObject form
// For gathering the incoming data
protected Dictionary<string, JValue> UnsavedValues = new Dictionary<string, JValue>();
// The JSON file in JObject form
// For gathering the incoming data
protected Dictionary<string, JValue> UnsavedValues = new Dictionary<string, JValue>();
/*****************************************************************************************/
/*****************************************************************************************/
/// <summary>
/// SIMPL+ default constructor.
/// </summary>
public JsonToSimplMaster()
{
}
/// <summary>
/// SIMPL+ default constructor.
/// </summary>
public JsonToSimplMaster()
{
}
/// <summary>
/// Sets up class - overriding methods should always call this.
/// </summary>
/// <param name="uniqueId"></param>
public virtual void Initialize(string uniqueId)
{
UniqueID = uniqueId;
J2SGlobal.AddMaster(this); // Should not re-add
}
/// <summary>
/// Sets up class - overriding methods should always call this.
/// </summary>
/// <param name="uniqueId"></param>
public virtual void Initialize(string uniqueId)
{
UniqueID = uniqueId;
J2SGlobal.AddMaster(this); // Should not re-add
}
/// <summary>
/// Adds a child "module" to this master
/// </summary>
/// <param name="child"></param>
public void AddChild(JsonToSimplChildObjectBase child)
{
if (!Children.Contains(child))
{
Children.Add(child);
}
}
/// <summary>
/// Adds a child "module" to this master
/// </summary>
/// <param name="child"></param>
public void AddChild(JsonToSimplChildObjectBase child)
{
if (!Children.Contains(child))
{
Children.Add(child);
}
}
/// <summary>
/// Called from the child to add changed or new values for saving
/// </summary>
public void AddUnsavedValue(string path, JValue value)
{
if (UnsavedValues.ContainsKey(path))
{
Debug.Console(0, "Master[{0}] WARNING - Attempt to add duplicate value for path '{1}'.\r Ingoring. Please ensure that path does not exist on multiple modules.", UniqueID, path);
}
else
UnsavedValues.Add(path, value);
//Debug.Console(0, "Master[{0}] Unsaved size={1}", UniqueID, UnsavedValues.Count);
}
/// <summary>
/// Called from the child to add changed or new values for saving
/// </summary>
public void AddUnsavedValue(string path, JValue value)
{
if (UnsavedValues.ContainsKey(path))
{
Debug.Console(0, "Master[{0}] WARNING - Attempt to add duplicate value for path '{1}'.\r Ingoring. Please ensure that path does not exist on multiple modules.", UniqueID, path);
}
else
UnsavedValues.Add(path, value);
//Debug.Console(0, "Master[{0}] Unsaved size={1}", UniqueID, UnsavedValues.Count);
}
/// <summary>
/// Saves the file
@@ -152,27 +151,27 @@ namespace PepperDash.Core.JsonToSimpl
public abstract void Save();
/// <summary>
///
/// </summary>
public static class JsonFixes
{
/// <summary>
///
/// </summary>
public static class JsonFixes
{
/// <summary>
/// Deserializes a string into a JObject
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public static JObject ParseObject(string json)
{
using (var reader = new JsonTextReader(new System.IO.StringReader(json)))
{
var startDepth = reader.Depth;
var obj = JObject.Load(reader);
if (startDepth != reader.Depth)
throw new JsonSerializationException("Unenclosed json found");
return obj;
}
}
{
using (var reader = new JsonTextReader(new System.IO.StringReader(json)))
{
var startDepth = reader.Depth;
var obj = JObject.Load(reader);
if (startDepth != reader.Depth)
throw new JsonSerializationException("Unenclosed json found");
return obj;
}
}
/// <summary>
/// Deserializes a string into a JArray
@@ -180,49 +179,49 @@ namespace PepperDash.Core.JsonToSimpl
/// <param name="json"></param>
/// <returns></returns>
public static JArray ParseArray(string json)
{
using (var reader = new JsonTextReader(new System.IO.StringReader(json)))
{
var startDepth = reader.Depth;
var obj = JArray.Load(reader);
if (startDepth != reader.Depth)
throw new JsonSerializationException("Unenclosed json found");
return obj;
}
}
}
{
using (var reader = new JsonTextReader(new System.IO.StringReader(json)))
{
var startDepth = reader.Depth;
var obj = JArray.Load(reader);
if (startDepth != reader.Depth)
throw new JsonSerializationException("Unenclosed json found");
return obj;
}
}
}
/// <summary>
/// Helper event
/// </summary>
/// <param name="state"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnBoolChange(bool state, ushort index, ushort type)
{
if (BoolChange != null)
{
var args = new BoolChangeEventArgs(state, type);
args.Index = index;
BoolChange(this, args);
}
}
/// <summary>
/// Helper event
/// </summary>
/// <param name="state"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnBoolChange(bool state, ushort index, ushort type)
{
if (BoolChange != null)
{
var args = new BoolChangeEventArgs(state, type);
args.Index = index;
BoolChange(this, args);
}
}
/// <summary>
/// Helper event
/// </summary>
/// <param name="state"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnUshrtChange(ushort state, ushort index, ushort type)
{
if (UshrtChange != null)
{
var args = new UshrtChangeEventArgs(state, type);
args.Index = index;
UshrtChange(this, args);
}
}
/// <summary>
/// Helper event
/// </summary>
/// <param name="state"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnUshrtChange(ushort state, ushort index, ushort type)
{
if (UshrtChange != null)
{
var args = new UshrtChangeEventArgs(state, type);
args.Index = index;
UshrtChange(this, args);
}
}
/// <summary>
/// Helper event
@@ -231,13 +230,13 @@ namespace PepperDash.Core.JsonToSimpl
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnStringChange(string value, ushort index, ushort type)
{
if (StringChange != null)
{
var args = new StringChangeEventArgs(value, type);
args.Index = index;
StringChange(this, args);
}
}
}
{
if (StringChange != null)
{
var args = new StringChangeEventArgs(value, type);
args.Index = index;
StringChange(this, args);
}
}
}
}

View File

@@ -1,16 +1,14 @@
using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronIO;
using Newtonsoft.Json.Linq;
using PepperDash.Core.Config;
using PepperDash.Core.Logging;
using System;
//using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronIO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PepperDash.Core.Config;
namespace PepperDash.Core.JsonToSimpl
{
@@ -19,179 +17,179 @@ namespace PepperDash.Core.JsonToSimpl
/// </summary>
public class JsonToSimplPortalFileMaster : JsonToSimplMaster
{
/// <summary>
/// Sets the filepath as well as registers this with the Global.Masters list
/// </summary>
public string PortalFilepath { get; private set; }
/// <summary>
/// Sets the filepath as well as registers this with the Global.Masters list
/// </summary>
public string PortalFilepath { get; private set; }
/// <summary>
/// File path of the actual file being read (Portal or local)
/// </summary>
public string ActualFilePath { get; private set; }
/*****************************************************************************************/
/** Privates **/
/*****************************************************************************************/
/** Privates **/
// To prevent multiple same-file access
object StringBuilderLock = new object();
static object FileLock = new object();
// To prevent multiple same-file access
object StringBuilderLock = new object();
static object FileLock = new object();
/*****************************************************************************************/
/*****************************************************************************************/
/// <summary>
/// <summary>
/// SIMPL+ default constructor.
/// </summary>
public JsonToSimplPortalFileMaster()
public JsonToSimplPortalFileMaster()
{
}
}
/// <summary>
/// Read, evaluate and udpate status
/// </summary>
public void EvaluateFile(string portalFilepath)
{
PortalFilepath = portalFilepath;
/// <summary>
/// Read, evaluate and udpate status
/// </summary>
public void EvaluateFile(string portalFilepath)
{
PortalFilepath = portalFilepath;
OnBoolChange(false, 0, JsonToSimplConstants.JsonIsValidBoolChange);
if (string.IsNullOrEmpty(PortalFilepath))
{
CrestronConsole.PrintLine("Cannot evaluate file. JSON file path not set");
return;
}
OnBoolChange(false, 0, JsonToSimplConstants.JsonIsValidBoolChange);
if (string.IsNullOrEmpty(PortalFilepath))
{
CrestronConsole.PrintLine("Cannot evaluate file. JSON file path not set");
return;
}
// Resolve possible wildcarded filename
// Resolve possible wildcarded filename
// If the portal file is xyz.json, then
// the file we want to check for first will be called xyz.local.json
var localFilepath = Path.ChangeExtension(PortalFilepath, "local.json");
Debug.Console(0, this, "Checking for local file {0}", localFilepath);
var actualLocalFile = GetActualFileInfoFromPath(localFilepath);
// If the portal file is xyz.json, then
// the file we want to check for first will be called xyz.local.json
var localFilepath = Path.ChangeExtension(PortalFilepath, "local.json");
Debug.Console(0, this, "Checking for local file {0}", localFilepath);
var actualLocalFile = GetActualFileInfoFromPath(localFilepath);
if (actualLocalFile != null)
{
ActualFilePath = actualLocalFile.FullName;
if (actualLocalFile != null)
{
ActualFilePath = actualLocalFile.FullName;
OnStringChange(ActualFilePath, 0, JsonToSimplConstants.ActualFilePathChange);
}
// If the local file does not exist, then read the portal file xyz.json
// and create the local.
else
{
Debug.Console(1, this, "Local JSON file not found {0}\rLoading portal JSON file", localFilepath);
var actualPortalFile = GetActualFileInfoFromPath(portalFilepath);
if (actualPortalFile != null)
{
var newLocalPath = Path.ChangeExtension(actualPortalFile.FullName, "local.json");
// got the portal file, hand off to the merge / save method
PortalConfigReader.ReadAndMergeFileIfNecessary(actualPortalFile.FullName, newLocalPath);
ActualFilePath = newLocalPath;
}
// If the local file does not exist, then read the portal file xyz.json
// and create the local.
else
{
Debug.Console(1, this, "Local JSON file not found {0}\rLoading portal JSON file", localFilepath);
var actualPortalFile = GetActualFileInfoFromPath(portalFilepath);
if (actualPortalFile != null)
{
var newLocalPath = Path.ChangeExtension(actualPortalFile.FullName, "local.json");
// got the portal file, hand off to the merge / save method
PortalConfigReader.ReadAndMergeFileIfNecessary(actualPortalFile.FullName, newLocalPath);
ActualFilePath = newLocalPath;
OnStringChange(ActualFilePath, 0, JsonToSimplConstants.ActualFilePathChange);
}
else
{
var msg = string.Format("Portal JSON file not found: {0}", PortalFilepath);
Debug.Console(1, this, msg);
ErrorLog.Error(msg);
return;
}
}
}
else
{
var msg = string.Format("Portal JSON file not found: {0}", PortalFilepath);
Debug.Console(1, this, msg);
ErrorLog.Error(msg);
return;
}
}
// At this point we should have a local file. Do it.
Debug.Console(1, "Reading local JSON file {0}", ActualFilePath);
// At this point we should have a local file. Do it.
Debug.Console(1, "Reading local JSON file {0}", ActualFilePath);
string json = File.ReadToEnd(ActualFilePath, System.Text.Encoding.ASCII);
string json = File.ReadToEnd(ActualFilePath, System.Text.Encoding.ASCII);
try
{
JsonObject = JObject.Parse(json);
foreach (var child in Children)
child.ProcessAll();
OnBoolChange(true, 0, JsonToSimplConstants.JsonIsValidBoolChange);
}
catch (Exception e)
{
var msg = string.Format("JSON parsing failed:\r{0}", e);
CrestronConsole.PrintLine(msg);
ErrorLog.Error(msg);
return;
}
}
try
{
JsonObject = JObject.Parse(json);
foreach (var child in Children)
child.ProcessAll();
OnBoolChange(true, 0, JsonToSimplConstants.JsonIsValidBoolChange);
}
catch (Exception e)
{
var msg = string.Format("JSON parsing failed:\r{0}", e);
CrestronConsole.PrintLine(msg);
ErrorLog.Error(msg);
return;
}
}
/// <summary>
/// Returns the FileInfo object for a given path, with possible wildcards
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
FileInfo GetActualFileInfoFromPath(string path)
{
var dir = Path.GetDirectoryName(path);
var localFilename = Path.GetFileName(path);
var directory = new DirectoryInfo(dir);
// search the directory for the file w/ wildcards
return directory.GetFiles(localFilename).FirstOrDefault();
}
/// <summary>
/// Returns the FileInfo object for a given path, with possible wildcards
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
FileInfo GetActualFileInfoFromPath(string path)
{
var dir = Path.GetDirectoryName(path);
var localFilename = Path.GetFileName(path);
var directory = new DirectoryInfo(dir);
// search the directory for the file w/ wildcards
return directory.GetFiles(localFilename).FirstOrDefault();
}
/// <summary>
///
/// </summary>
/// <param name="level"></param>
public void setDebugLevel(int level)
{
Debug.SetDebugLevel(level);
}
/// <summary>
///
/// </summary>
/// <param name="level"></param>
public void setDebugLevel(int level)
{
Debug.SetDebugLevel(level);
}
/// <summary>
///
/// </summary>
public override void Save()
{
// this code is duplicated in the other masters!!!!!!!!!!!!!
UnsavedValues = new Dictionary<string, JValue>();
// Make each child update their values into master object
foreach (var child in Children)
{
Debug.Console(1, "Master [{0}] checking child [{1}] for updates to save", UniqueID, child.Key);
child.UpdateInputsForMaster();
}
/// <summary>
///
/// </summary>
public override void Save()
{
// this code is duplicated in the other masters!!!!!!!!!!!!!
UnsavedValues = new Dictionary<string, JValue>();
// Make each child update their values into master object
foreach (var child in Children)
{
Debug.Console(1, "Master [{0}] checking child [{1}] for updates to save", UniqueID, child.Key);
child.UpdateInputsForMaster();
}
if (UnsavedValues == null || UnsavedValues.Count == 0)
{
Debug.Console(1, "Master [{0}] No updated values to save. Skipping", UniqueID);
return;
}
lock (FileLock)
{
Debug.Console(1, "Saving");
foreach (var path in UnsavedValues.Keys)
{
var tokenToReplace = JsonObject.SelectToken(path);
if (tokenToReplace != null)
{// It's found
tokenToReplace.Replace(UnsavedValues[path]);
Debug.Console(1, "JSON Master[{0}] Updating '{1}'", UniqueID, path);
}
else // No token. Let's make one
{
//http://stackoverflow.com/questions/17455052/how-to-set-the-value-of-a-json-path-using-json-net
Debug.Console(1, "JSON Master[{0}] Cannot write value onto missing property: '{1}'", UniqueID, path);
}
}
using (StreamWriter sw = new StreamWriter(ActualFilePath))
{
try
{
sw.Write(JsonObject.ToString());
sw.Flush();
}
catch (Exception e)
{
string err = string.Format("Error writing JSON file:\r{0}", e);
Debug.Console(0, err);
ErrorLog.Warn(err);
return;
}
}
}
}
}
if (UnsavedValues == null || UnsavedValues.Count == 0)
{
Debug.Console(1, "Master [{0}] No updated values to save. Skipping", UniqueID);
return;
}
lock (FileLock)
{
Debug.Console(1, "Saving");
foreach (var path in UnsavedValues.Keys)
{
var tokenToReplace = JsonObject.SelectToken(path);
if (tokenToReplace != null)
{// It's found
tokenToReplace.Replace(UnsavedValues[path]);
Debug.Console(1, "JSON Master[{0}] Updating '{1}'", UniqueID, path);
}
else // No token. Let's make one
{
//http://stackoverflow.com/questions/17455052/how-to-set-the-value-of-a-json-path-using-json-net
Debug.Console(1, "JSON Master[{0}] Cannot write value onto missing property: '{1}'", UniqueID, path);
}
}
using (StreamWriter sw = new StreamWriter(ActualFilePath))
{
try
{
sw.Write(JsonObject.ToString());
sw.Flush();
}
catch (Exception e)
{
string err = string.Format("Error writing JSON file:\r{0}", e);
Debug.Console(0, err);
ErrorLog.Warn(err);
return;
}
}
}
}
}
}

View File

@@ -1,16 +1,15 @@
using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronIO;
using Crestron.SimplSharp.CrestronLogger;
using Crestron.SimplSharp.Reflection;
using Newtonsoft.Json;
using PepperDash.Core.Interfaces;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Crestron.SimplSharp;
using Crestron.SimplSharp.Reflection;
using Crestron.SimplSharp.CrestronLogger;
using Crestron.SimplSharp.CrestronIO;
using Newtonsoft.Json;
using PepperDash.Core.DebugThings;
namespace PepperDash.Core
namespace PepperDash.Core.Logging
{
/// <summary>
/// Contains debug commands for use in various situations
@@ -51,19 +50,19 @@ namespace PepperDash.Core
/// <summary>
/// Version for the currently loaded PepperDashCore dll
/// </summary>
public static string PepperDashCoreVersion { get; private set; }
public static string PepperDashCoreVersion { get; private set; }
private static CTimer _saveTimer;
/// <summary>
/// When true, the IncludedExcludedKeys dict will contain keys to include.
/// When false (default), IncludedExcludedKeys will contain keys to exclude.
/// </summary>
private static bool _excludeAllMode;
/// <summary>
/// When true, the IncludedExcludedKeys dict will contain keys to include.
/// When false (default), IncludedExcludedKeys will contain keys to exclude.
/// </summary>
private static bool _excludeAllMode;
//static bool ExcludeNoKeyMessages;
//static bool ExcludeNoKeyMessages;
private static readonly Dictionary<string, object> IncludedExcludedKeys;
private static readonly Dictionary<string, object> IncludedExcludedKeys;
static Debug()
{
@@ -85,26 +84,26 @@ namespace PepperDash.Core
LogError(ErrorLogLevel.Notice, msg);
IncludedExcludedKeys = new Dictionary<string, object>();
IncludedExcludedKeys = new Dictionary<string, object>();
//CrestronDataStoreStatic.InitCrestronDataStore();
if (CrestronEnvironment.RuntimeEnvironment == eRuntimeEnvironment.SimplSharpPro)
{
// Add command to console
CrestronConsole.AddNewConsoleCommand(SetDoNotLoadOnNextBootFromConsole, "donotloadonnextboot",
CrestronConsole.AddNewConsoleCommand(SetDoNotLoadOnNextBootFromConsole, "donotloadonnextboot",
"donotloadonnextboot:P [true/false]: Should the application load on next boot", ConsoleAccessLevelEnum.AccessOperator);
CrestronConsole.AddNewConsoleCommand(SetDebugFromConsole, "appdebug",
"appdebug:P [0-2]: Sets the application's console debug message level",
ConsoleAccessLevelEnum.AccessOperator);
CrestronConsole.AddNewConsoleCommand(ShowDebugLog, "appdebuglog",
"appdebuglog:P [all] Use \"all\" for full log.",
"appdebuglog:P [all] Use \"all\" for full log.",
ConsoleAccessLevelEnum.AccessOperator);
CrestronConsole.AddNewConsoleCommand(s => CrestronLogger.Clear(false), "appdebugclear",
"appdebugclear:P Clears the current custom log",
"appdebugclear:P Clears the current custom log",
ConsoleAccessLevelEnum.AccessOperator);
CrestronConsole.AddNewConsoleCommand(SetDebugFilterFromConsole, "appdebugfilter",
"appdebugfilter [params]", ConsoleAccessLevelEnum.AccessOperator);
CrestronConsole.AddNewConsoleCommand(SetDebugFilterFromConsole, "appdebugfilter",
"appdebugfilter [params]", ConsoleAccessLevelEnum.AccessOperator);
}
CrestronEnvironment.ProgramStatusEventHandler += CrestronEnvironment_ProgramStatusEventHandler;
@@ -115,7 +114,7 @@ namespace PepperDash.Core
Level = context.Level;
DoNotLoadOnNextBoot = context.DoNotLoadOnNextBoot;
if(DoNotLoadOnNextBoot)
if (DoNotLoadOnNextBoot)
CrestronConsole.PrintLine(string.Format("Program {0} will not load config after next boot. Use console command go:{0} to load the config manually", InitialParametersClass.ApplicationNumber));
try
@@ -140,7 +139,7 @@ namespace PepperDash.Core
var assembly = Assembly.GetExecutingAssembly();
var ver =
assembly
.GetCustomAttributes(typeof (AssemblyInformationalVersionAttribute), false);
.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false);
if (ver != null && ver.Length > 0)
{
@@ -213,7 +212,7 @@ namespace PepperDash.Core
return;
}
SetDoNotLoadOnNextBoot(Boolean.Parse(stateString));
SetDoNotLoadOnNextBoot(bool.Parse(stateString));
}
catch
{
@@ -226,79 +225,79 @@ namespace PepperDash.Core
/// </summary>
/// <param name="items"></param>
public static void SetDebugFilterFromConsole(string items)
{
var str = items.Trim();
if (str == "?")
{
CrestronConsole.ConsoleCommandResponse("Usage:\r APPDEBUGFILTER key1 key2 key3....\r " +
"+all: at beginning puts filter into 'default include' mode\r" +
" All keys that follow will be excluded from output.\r" +
"-all: at beginning puts filter into 'default excluse all' mode.\r" +
" All keys that follow will be the only keys that are shown\r" +
"+nokey: Enables messages with no key (default)\r" +
"-nokey: Disables messages with no key.\r" +
"(nokey settings are independent of all other settings)");
return;
}
var keys = Regex.Split(str, @"\s*");
foreach (var keyToken in keys)
{
var lkey = keyToken.ToLower();
if (lkey == "+all")
{
IncludedExcludedKeys.Clear();
_excludeAllMode = false;
}
else if (lkey == "-all")
{
IncludedExcludedKeys.Clear();
_excludeAllMode = true;
}
//else if (lkey == "+nokey")
//{
// ExcludeNoKeyMessages = false;
//}
//else if (lkey == "-nokey")
//{
// ExcludeNoKeyMessages = true;
//}
else
{
string key;
if (lkey.StartsWith("-"))
{
key = lkey.Substring(1);
// if in exclude all mode, we need to remove this from the inclusions
if (_excludeAllMode)
{
if (IncludedExcludedKeys.ContainsKey(key))
IncludedExcludedKeys.Remove(key);
}
// otherwise include all mode, add to the exclusions
else
{
IncludedExcludedKeys[key] = new object();
}
}
else if (lkey.StartsWith("+"))
{
key = lkey.Substring(1);
// if in exclude all mode, we need to add this as inclusion
if (_excludeAllMode)
{
{
var str = items.Trim();
if (str == "?")
{
CrestronConsole.ConsoleCommandResponse("Usage:\r APPDEBUGFILTER key1 key2 key3....\r " +
"+all: at beginning puts filter into 'default include' mode\r" +
" All keys that follow will be excluded from output.\r" +
"-all: at beginning puts filter into 'default excluse all' mode.\r" +
" All keys that follow will be the only keys that are shown\r" +
"+nokey: Enables messages with no key (default)\r" +
"-nokey: Disables messages with no key.\r" +
"(nokey settings are independent of all other settings)");
return;
}
var keys = Regex.Split(str, @"\s*");
foreach (var keyToken in keys)
{
var lkey = keyToken.ToLower();
if (lkey == "+all")
{
IncludedExcludedKeys.Clear();
_excludeAllMode = false;
}
else if (lkey == "-all")
{
IncludedExcludedKeys.Clear();
_excludeAllMode = true;
}
//else if (lkey == "+nokey")
//{
// ExcludeNoKeyMessages = false;
//}
//else if (lkey == "-nokey")
//{
// ExcludeNoKeyMessages = true;
//}
else
{
string key;
if (lkey.StartsWith("-"))
{
key = lkey.Substring(1);
// if in exclude all mode, we need to remove this from the inclusions
if (_excludeAllMode)
{
if (IncludedExcludedKeys.ContainsKey(key))
IncludedExcludedKeys.Remove(key);
}
// otherwise include all mode, add to the exclusions
else
{
IncludedExcludedKeys[key] = new object();
}
}
else if (lkey.StartsWith("+"))
{
key = lkey.Substring(1);
// if in exclude all mode, we need to add this as inclusion
if (_excludeAllMode)
{
IncludedExcludedKeys[key] = new object();
}
// otherwise include all mode, remove this from exclusions
else
{
if (IncludedExcludedKeys.ContainsKey(key))
IncludedExcludedKeys.Remove(key);
}
}
}
}
}
IncludedExcludedKeys[key] = new object();
}
// otherwise include all mode, remove this from exclusions
else
{
if (IncludedExcludedKeys.ContainsKey(key))
IncludedExcludedKeys.Remove(key);
}
}
}
}
}
/// <summary>
@@ -342,7 +341,7 @@ namespace PepperDash.Core
public static object GetDeviceDebugSettingsForKey(string deviceKey)
{
return _contexts.GetDebugSettingsForKey(deviceKey);
}
}
/// <summary>
/// Sets the flag to prevent application starting on next boot
@@ -385,7 +384,7 @@ namespace PepperDash.Core
return;
}
if(Level < level)
if (Level < level)
{
return;
}
@@ -421,9 +420,9 @@ namespace PepperDash.Core
}
}
/// <summary>
/// Logs to Console when at-level, and all messages to error log
/// </summary>
/// <summary>
/// Logs to Console when at-level, and all messages to error log
/// </summary>
public static void Console(uint level, ErrorLogLevel errorLogLevel,
string format, params object[] items)
{
@@ -432,10 +431,10 @@ namespace PepperDash.Core
{
LogError(errorLogLevel, str);
}
if (Level >= level)
{
Console(level, str);
}
if (Level >= level)
{
Console(level, str);
}
}
/// <summary>
@@ -558,19 +557,19 @@ namespace PepperDash.Core
return string.Format(@"\user\debugSettings\program{0}", InitialParametersClass.ApplicationNumber);
}
return string.Format("{0}{1}user{1}debugSettings{1}{2}.json",Directory.GetApplicationRootDirectory(), Path.DirectorySeparatorChar, InitialParametersClass.RoomId);
return string.Format("{0}{1}user{1}debugSettings{1}{2}.json", Directory.GetApplicationRootDirectory(), Path.DirectorySeparatorChar, InitialParametersClass.RoomId);
}
private static void CheckForMigration()
{
var oldFilePath = String.Format(@"\nvram\debugSettings\program{0}", InitialParametersClass.ApplicationNumber);
var newFilePath = String.Format(@"\user\debugSettings\program{0}", InitialParametersClass.ApplicationNumber);
var oldFilePath = string.Format(@"\nvram\debugSettings\program{0}", InitialParametersClass.ApplicationNumber);
var newFilePath = string.Format(@"\user\debugSettings\program{0}", InitialParametersClass.ApplicationNumber);
//check for file at old path
if (!File.Exists(oldFilePath))
{
Console(0, ErrorLogLevel.Notice,
String.Format(
string.Format(
@"Debug settings file migration not necessary. Using file at \user\debugSettings\program{0}",
InitialParametersClass.ApplicationNumber));
@@ -584,7 +583,7 @@ namespace PepperDash.Core
}
Console(0, ErrorLogLevel.Notice,
String.Format(
string.Format(
@"File found at \nvram\debugSettings\program{0}. Migrating to \user\debugSettings\program{0}", InitialParametersClass.ApplicationNumber));
//Copy file from old path to new path, then delete it. This will overwrite the existing file
@@ -608,15 +607,15 @@ namespace PepperDash.Core
/// <summary>
/// Error
/// </summary>
Error,
Error,
/// <summary>
/// Warning
/// </summary>
Warning,
Warning,
/// <summary>
/// Notice
/// </summary>
Notice,
Notice,
/// <summary>
/// None
/// </summary>

View File

@@ -1,17 +1,14 @@
using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronIO;
using Newtonsoft.Json;
using PepperDash.Core.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronDataStore;
using Crestron.SimplSharp.CrestronIO;
using Newtonsoft.Json;
using PepperDash.Core.DebugThings;
namespace PepperDash.Core
namespace PepperDash.Core.Logging
{
/// <summary>
/// Represents a debugging context

View File

@@ -1,23 +1,22 @@
using System.Collections.Generic;
using Crestron.SimplSharp;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace PepperDash.Core.DebugThings
namespace PepperDash.Core.Logging
{
/// <summary>
/// Class to persist current Debug settings across program restarts
/// </summary>
public class DebugContextCollection
{
{
/// <summary>
/// To prevent threading issues with the DeviceDebugSettings collection
/// </summary>
private readonly CCriticalSection _deviceDebugSettingsLock;
[JsonProperty("items")] private readonly Dictionary<string, DebugContextItem> _items;
[JsonProperty("items")] private readonly Dictionary<string, DebugContextItem> _items;
/// <summary>
/// Collection of the debug settings for each device where the dictionary key is the device key
@@ -26,40 +25,40 @@ namespace PepperDash.Core.DebugThings
private Dictionary<string, object> DeviceDebugSettings { get; set; }
/// <summary>
/// Default constructor
/// </summary>
public DebugContextCollection()
{
/// <summary>
/// Default constructor
/// </summary>
public DebugContextCollection()
{
_deviceDebugSettingsLock = new CCriticalSection();
DeviceDebugSettings = new Dictionary<string, object>();
_items = new Dictionary<string, DebugContextItem>();
}
_items = new Dictionary<string, DebugContextItem>();
}
/// <summary>
/// Sets the level of a given context item, and adds that item if it does not
/// exist
/// </summary>
/// <param name="contextKey"></param>
/// <param name="level"></param>
public void SetLevel(string contextKey, int level)
{
if (level < 0 || level > 2)
return;
GetOrCreateItem(contextKey).Level = level;
}
/// <summary>
/// Sets the level of a given context item, and adds that item if it does not
/// exist
/// </summary>
/// <param name="contextKey"></param>
/// <param name="level"></param>
public void SetLevel(string contextKey, int level)
{
if (level < 0 || level > 2)
return;
GetOrCreateItem(contextKey).Level = level;
}
/// <summary>
/// Gets a level or creates it if not existing
/// </summary>
/// <param name="contextKey"></param>
/// <returns></returns>
public DebugContextItem GetOrCreateItem(string contextKey)
{
if (!_items.ContainsKey(contextKey))
_items[contextKey] = new DebugContextItem { Level = 0 };
return _items[contextKey];
}
/// <summary>
/// Gets a level or creates it if not existing
/// </summary>
/// <param name="contextKey"></param>
/// <returns></returns>
public DebugContextItem GetOrCreateItem(string contextKey)
{
if (!_items.ContainsKey(contextKey))
_items[contextKey] = new DebugContextItem { Level = 0 };
return _items[contextKey];
}
/// <summary>
@@ -96,23 +95,23 @@ namespace PepperDash.Core.DebugThings
{
return DeviceDebugSettings[deviceKey];
}
}
}
/// <summary>
/// Contains information about
/// </summary>
public class DebugContextItem
{
/// <summary>
/// Contains information about
/// </summary>
public class DebugContextItem
{
/// <summary>
/// The level of debug messages to print
/// </summary>
[JsonProperty("level")]
public int Level { get; set; }
public int Level { get; set; }
/// <summary>
/// Property to tell the program not to intitialize when it boots, if desired
/// </summary>
[JsonProperty("doNotLoadOnNextBoot")]
public bool DoNotLoadOnNextBoot { get; set; }
}
}
}

View File

@@ -1,22 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
namespace PepperDash.Core
{
/// <summary>
/// Not in use
/// </summary>
public static class NetworkComm
{
/// <summary>
/// Not in use
/// </summary>
static NetworkComm()
{
}
}
}

View File

@@ -1,26 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
namespace PepperDash.Core.PasswordManagement
namespace PepperDash.Core.PasswordManagement
{
/// <summary>
/// JSON password configuration
/// </summary>
public class PasswordConfig
{
/// <summary>
/// Password object configured password
/// </summary>
public string password { get; set; }
/// <summary>
/// Constructor
/// </summary>
public PasswordConfig()
{
}
}
/// <summary>
/// JSON password configuration
/// </summary>
public class PasswordConfig
{
/// <summary>
/// Password object configured password
/// </summary>
public string password { get; set; }
/// <summary>
/// Constructor
/// </summary>
public PasswordConfig()
{
}
}
}

View File

@@ -1,57 +1,51 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
namespace PepperDash.Core.PasswordManagement
namespace PepperDash.Core.PasswordManagement
{
/// <summary>
/// Constants
/// </summary>
public class PasswordManagementConstants
{
/// <summary>
/// Generic boolean value change constant
/// </summary>
public const ushort BoolValueChange = 1;
/// <summary>
/// Evaluated boolean change constant
/// </summary>
public const ushort PasswordInitializedChange = 2;
/// <summary>
/// Update busy change const
/// </summary>
public const ushort PasswordUpdateBusyChange = 3;
/// <summary>
/// Password is valid change constant
/// </summary>
public const ushort PasswordValidationChange = 4;
/// <summary>
/// Password LED change constant
/// </summary>
public const ushort PasswordLedFeedbackChange = 5;
/// <summary>
/// Constants
/// </summary>
public class PasswordManagementConstants
{
/// <summary>
/// Generic boolean value change constant
/// </summary>
public const ushort BoolValueChange = 1;
/// <summary>
/// Evaluated boolean change constant
/// </summary>
public const ushort PasswordInitializedChange = 2;
/// <summary>
/// Update busy change const
/// </summary>
public const ushort PasswordUpdateBusyChange = 3;
/// <summary>
/// Password is valid change constant
/// </summary>
public const ushort PasswordValidationChange = 4;
/// <summary>
/// Password LED change constant
/// </summary>
public const ushort PasswordLedFeedbackChange = 5;
/// <summary>
/// Generic ushort value change constant
/// </summary>
public const ushort UshrtValueChange = 101;
/// <summary>
/// Password count
/// </summary>
public const ushort PasswordManagerCountChange = 102;
/// <summary>
/// Password selecte index change constant
/// </summary>
public const ushort PasswordSelectIndexChange = 103;
/// <summary>
/// Password length
/// </summary>
public const ushort PasswordLengthChange = 104;
/// <summary>
/// Generic string value change constant
/// </summary>
public const ushort StringValueChange = 201;
}
/// <summary>
/// Generic ushort value change constant
/// </summary>
public const ushort UshrtValueChange = 101;
/// <summary>
/// Password count
/// </summary>
public const ushort PasswordManagerCountChange = 102;
/// <summary>
/// Password selecte index change constant
/// </summary>
public const ushort PasswordSelectIndexChange = 103;
/// <summary>
/// Password length
/// </summary>
public const ushort PasswordLengthChange = 104;
/// <summary>
/// Generic string value change constant
/// </summary>
public const ushort StringValueChange = 201;
}
}

View File

@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
namespace PepperDash.Core.PasswordManagement
{
@@ -10,182 +6,182 @@ namespace PepperDash.Core.PasswordManagement
/// A class to allow user interaction with the PasswordManager
/// </summary>
public class PasswordClient
{
/// <summary>
/// Password selected
/// </summary>
public string Password { get; set; }
/// <summary>
/// Password selected key
/// </summary>
public ushort Key { get; set; }
/// <summary>
/// Used to build the password entered by the user
/// </summary>
public string PasswordToValidate { get; set; }
{
/// <summary>
/// Password selected
/// </summary>
public string Password { get; set; }
/// <summary>
/// Password selected key
/// </summary>
public ushort Key { get; set; }
/// <summary>
/// Used to build the password entered by the user
/// </summary>
public string PasswordToValidate { get; set; }
/// <summary>
/// Boolean event
/// </summary>
public event EventHandler<BoolChangeEventArgs> BoolChange;
/// <summary>
/// Ushort event
/// </summary>
public event EventHandler<UshrtChangeEventArgs> UshrtChange;
/// <summary>
/// String event
/// </summary>
public event EventHandler<StringChangeEventArgs> StringChange;
/// <summary>
/// Boolean event
/// </summary>
public event EventHandler<BoolChangeEventArgs> BoolChange;
/// <summary>
/// Ushort event
/// </summary>
public event EventHandler<UshrtChangeEventArgs> UshrtChange;
/// <summary>
/// String event
/// </summary>
public event EventHandler<StringChangeEventArgs> StringChange;
/// <summary>
/// Constructor
/// </summary>
public PasswordClient()
{
PasswordManager.PasswordChange += new EventHandler<StringChangeEventArgs>(PasswordManager_PasswordChange);
}
/// <summary>
/// Constructor
/// </summary>
public PasswordClient()
{
PasswordManager.PasswordChange += new EventHandler<StringChangeEventArgs>(PasswordManager_PasswordChange);
}
/// <summary>
/// Initialize method
/// </summary>
public void Initialize()
{
OnBoolChange(false, 0, PasswordManagementConstants.PasswordInitializedChange);
/// <summary>
/// Initialize method
/// </summary>
public void Initialize()
{
OnBoolChange(false, 0, PasswordManagementConstants.PasswordInitializedChange);
Password = "";
PasswordToValidate = "";
Password = "";
PasswordToValidate = "";
OnUshrtChange((ushort)PasswordManager.Passwords.Count, 0, PasswordManagementConstants.PasswordManagerCountChange);
OnBoolChange(true, 0, PasswordManagementConstants.PasswordInitializedChange);
}
OnUshrtChange((ushort)PasswordManager.Passwords.Count, 0, PasswordManagementConstants.PasswordManagerCountChange);
OnBoolChange(true, 0, PasswordManagementConstants.PasswordInitializedChange);
}
/// <summary>
/// Retrieve password by index
/// </summary>
/// <param name="key"></param>
public void GetPasswordByIndex(ushort key)
{
OnUshrtChange((ushort)PasswordManager.Passwords.Count, 0, PasswordManagementConstants.PasswordManagerCountChange);
/// <summary>
/// Retrieve password by index
/// </summary>
/// <param name="key"></param>
public void GetPasswordByIndex(ushort key)
{
OnUshrtChange((ushort)PasswordManager.Passwords.Count, 0, PasswordManagementConstants.PasswordManagerCountChange);
Key = key;
Key = key;
var pw = PasswordManager.Passwords[Key];
if (pw == null)
{
OnUshrtChange(0, 0, PasswordManagementConstants.PasswordLengthChange);
return;
}
var pw = PasswordManager.Passwords[Key];
if (pw == null)
{
OnUshrtChange(0, 0, PasswordManagementConstants.PasswordLengthChange);
return;
}
Password = pw;
OnUshrtChange((ushort)Password.Length, 0, PasswordManagementConstants.PasswordLengthChange);
OnUshrtChange(key, 0, PasswordManagementConstants.PasswordSelectIndexChange);
}
Password = pw;
OnUshrtChange((ushort)Password.Length, 0, PasswordManagementConstants.PasswordLengthChange);
OnUshrtChange(key, 0, PasswordManagementConstants.PasswordSelectIndexChange);
}
/// <summary>
/// Password validation method
/// </summary>
/// <param name="password"></param>
public void ValidatePassword(string password)
{
if (string.IsNullOrEmpty(password))
return;
/// <summary>
/// Password validation method
/// </summary>
/// <param name="password"></param>
public void ValidatePassword(string password)
{
if (string.IsNullOrEmpty(password))
return;
if (string.Equals(Password, password))
OnBoolChange(true, 0, PasswordManagementConstants.PasswordValidationChange);
else
OnBoolChange(false, 0, PasswordManagementConstants.PasswordValidationChange);
if (string.Equals(Password, password))
OnBoolChange(true, 0, PasswordManagementConstants.PasswordValidationChange);
else
OnBoolChange(false, 0, PasswordManagementConstants.PasswordValidationChange);
ClearPassword();
}
ClearPassword();
}
/// <summary>
/// Builds the user entered passwrod string, will attempt to validate the user entered
/// password against the selected password when the length of the 2 are equal
/// </summary>
/// <param name="data"></param>
public void BuildPassword(string data)
{
PasswordToValidate = String.Concat(PasswordToValidate, data);
OnBoolChange(true, (ushort)PasswordToValidate.Length, PasswordManagementConstants.PasswordLedFeedbackChange);
/// <summary>
/// Builds the user entered passwrod string, will attempt to validate the user entered
/// password against the selected password when the length of the 2 are equal
/// </summary>
/// <param name="data"></param>
public void BuildPassword(string data)
{
PasswordToValidate = String.Concat(PasswordToValidate, data);
OnBoolChange(true, (ushort)PasswordToValidate.Length, PasswordManagementConstants.PasswordLedFeedbackChange);
if (PasswordToValidate.Length == Password.Length)
ValidatePassword(PasswordToValidate);
}
if (PasswordToValidate.Length == Password.Length)
ValidatePassword(PasswordToValidate);
}
/// <summary>
/// Clears the user entered password and resets the LEDs
/// </summary>
public void ClearPassword()
{
PasswordToValidate = "";
OnBoolChange(false, (ushort)PasswordToValidate.Length, PasswordManagementConstants.PasswordLedFeedbackChange);
}
/// <summary>
/// Clears the user entered password and resets the LEDs
/// </summary>
public void ClearPassword()
{
PasswordToValidate = "";
OnBoolChange(false, (ushort)PasswordToValidate.Length, PasswordManagementConstants.PasswordLedFeedbackChange);
}
/// <summary>
/// Protected boolean change event handler
/// </summary>
/// <param name="state"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnBoolChange(bool state, ushort index, ushort type)
{
var handler = BoolChange;
if (handler != null)
{
var args = new BoolChangeEventArgs(state, type);
args.Index = index;
BoolChange(this, args);
}
}
/// <summary>
/// Protected boolean change event handler
/// </summary>
/// <param name="state"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnBoolChange(bool state, ushort index, ushort type)
{
var handler = BoolChange;
if (handler != null)
{
var args = new BoolChangeEventArgs(state, type);
args.Index = index;
BoolChange(this, args);
}
}
/// <summary>
/// Protected ushort change event handler
/// </summary>
/// <param name="value"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnUshrtChange(ushort value, ushort index, ushort type)
{
var handler = UshrtChange;
if (handler != null)
{
var args = new UshrtChangeEventArgs(value, type);
args.Index = index;
UshrtChange(this, args);
}
}
/// <summary>
/// Protected ushort change event handler
/// </summary>
/// <param name="value"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnUshrtChange(ushort value, ushort index, ushort type)
{
var handler = UshrtChange;
if (handler != null)
{
var args = new UshrtChangeEventArgs(value, type);
args.Index = index;
UshrtChange(this, args);
}
}
/// <summary>
/// Protected string change event handler
/// </summary>
/// <param name="value"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnStringChange(string value, ushort index, ushort type)
{
var handler = StringChange;
if (handler != null)
{
var args = new StringChangeEventArgs(value, type);
args.Index = index;
StringChange(this, args);
}
}
/// <summary>
/// Protected string change event handler
/// </summary>
/// <param name="value"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnStringChange(string value, ushort index, ushort type)
{
var handler = StringChange;
if (handler != null)
{
var args = new StringChangeEventArgs(value, type);
args.Index = index;
StringChange(this, args);
}
}
/// <summary>
/// If password changes while selected change event will be notifed and update the client
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
protected void PasswordManager_PasswordChange(object sender, StringChangeEventArgs args)
{
//throw new NotImplementedException();
if (Key == args.Index)
{
//PasswordSelectedKey = args.Index;
//PasswordSelected = args.StringValue;
GetPasswordByIndex(args.Index);
}
}
}
/// <summary>
/// If password changes while selected change event will be notifed and update the client
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
protected void PasswordManager_PasswordChange(object sender, StringChangeEventArgs args)
{
//throw new NotImplementedException();
if (Key == args.Index)
{
//PasswordSelectedKey = args.Index;
//PasswordSelected = args.StringValue;
GetPasswordByIndex(args.Index);
}
}
}
}

View File

@@ -1,14 +1,9 @@
using Crestron.SimplSharp;
using PepperDash.Core.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Crestron.SimplSharp;
using PepperDash.Core.JsonToSimpl;
using PepperDash.Core.JsonStandardObjects;
namespace PepperDash.Core.PasswordManagement
{
@@ -16,234 +11,234 @@ namespace PepperDash.Core.PasswordManagement
/// Allows passwords to be stored and managed
/// </summary>
public class PasswordManager
{
/// <summary>
/// Public dictionary of known passwords
/// </summary>
public static Dictionary<uint, string> Passwords = new Dictionary<uint, string>();
/// <summary>
/// Private dictionary, used when passwords are updated
/// </summary>
private Dictionary<uint, string> _passwords = new Dictionary<uint, string>();
{
/// <summary>
/// Public dictionary of known passwords
/// </summary>
public static Dictionary<uint, string> Passwords = new Dictionary<uint, string>();
/// <summary>
/// Private dictionary, used when passwords are updated
/// </summary>
private Dictionary<uint, string> _passwords = new Dictionary<uint, string>();
/// <summary>
/// Timer used to wait until password changes have stopped before updating the dictionary
/// </summary>
CTimer PasswordTimer;
/// <summary>
/// Timer length
/// </summary>
public long PasswordTimerElapsedMs = 5000;
/// <summary>
/// Timer used to wait until password changes have stopped before updating the dictionary
/// </summary>
CTimer PasswordTimer;
/// <summary>
/// Timer length
/// </summary>
public long PasswordTimerElapsedMs = 5000;
/// <summary>
/// Boolean event
/// </summary>
public event EventHandler<BoolChangeEventArgs> BoolChange;
/// <summary>
/// Ushort event
/// </summary>
public event EventHandler<UshrtChangeEventArgs> UshrtChange;
/// <summary>
/// String event
/// </summary>
public event EventHandler<StringChangeEventArgs> StringChange;
/// <summary>
/// Event to notify clients of an updated password at the specified index (uint)
/// </summary>
public static event EventHandler<StringChangeEventArgs> PasswordChange;
/// <summary>
/// Boolean event
/// </summary>
public event EventHandler<BoolChangeEventArgs> BoolChange;
/// <summary>
/// Ushort event
/// </summary>
public event EventHandler<UshrtChangeEventArgs> UshrtChange;
/// <summary>
/// String event
/// </summary>
public event EventHandler<StringChangeEventArgs> StringChange;
/// <summary>
/// Event to notify clients of an updated password at the specified index (uint)
/// </summary>
public static event EventHandler<StringChangeEventArgs> PasswordChange;
/// <summary>
/// Constructor
/// </summary>
public PasswordManager()
{
/// <summary>
/// Constructor
/// </summary>
public PasswordManager()
{
}
}
/// <summary>
/// Initialize password manager
/// </summary>
public void Initialize()
{
if (Passwords == null)
Passwords = new Dictionary<uint, string>();
/// <summary>
/// Initialize password manager
/// </summary>
public void Initialize()
{
if (Passwords == null)
Passwords = new Dictionary<uint, string>();
if (_passwords == null)
_passwords = new Dictionary<uint, string>();
if (_passwords == null)
_passwords = new Dictionary<uint, string>();
OnBoolChange(true, 0, PasswordManagementConstants.PasswordInitializedChange);
}
OnBoolChange(true, 0, PasswordManagementConstants.PasswordInitializedChange);
}
/// <summary>
/// Updates password stored in the dictonary
/// </summary>
/// <param name="key"></param>
/// <param name="password"></param>
public void UpdatePassword(ushort key, string password)
{
// validate the parameters
if (key > 0 && string.IsNullOrEmpty(password))
{
Debug.Console(1, string.Format("PasswordManager.UpdatePassword: key [{0}] or password are not valid", key, password));
return;
}
/// <summary>
/// Updates password stored in the dictonary
/// </summary>
/// <param name="key"></param>
/// <param name="password"></param>
public void UpdatePassword(ushort key, string password)
{
// validate the parameters
if (key > 0 && string.IsNullOrEmpty(password))
{
Debug.Console(1, string.Format("PasswordManager.UpdatePassword: key [{0}] or password are not valid", key, password));
return;
}
try
{
// if key exists, update the value
if(_passwords.ContainsKey(key))
_passwords[key] = password;
// else add the key & value
else
_passwords.Add(key, password);
Debug.Console(1, string.Format("PasswordManager.UpdatePassword: _password[{0}] = {1}", key, _passwords[key]));
try
{
// if key exists, update the value
if (_passwords.ContainsKey(key))
_passwords[key] = password;
// else add the key & value
else
_passwords.Add(key, password);
if (PasswordTimer == null)
{
PasswordTimer = new CTimer((o) => PasswordTimerElapsed(), PasswordTimerElapsedMs);
Debug.Console(1, string.Format("PasswordManager.UpdatePassword: CTimer Started"));
OnBoolChange(true, 0, PasswordManagementConstants.PasswordUpdateBusyChange);
}
else
{
PasswordTimer.Reset(PasswordTimerElapsedMs);
Debug.Console(1, string.Format("PasswordManager.UpdatePassword: CTimer Reset"));
}
}
catch (Exception e)
{
var msg = string.Format("PasswordManager.UpdatePassword key-value[{0}, {1}] failed:\r{2}", key, password, e);
Debug.Console(1, msg);
}
}
Debug.Console(1, string.Format("PasswordManager.UpdatePassword: _password[{0}] = {1}", key, _passwords[key]));
/// <summary>
/// CTimer callback function
/// </summary>
private void PasswordTimerElapsed()
{
try
{
PasswordTimer.Stop();
Debug.Console(1, string.Format("PasswordManager.PasswordTimerElapsed: CTimer Stopped"));
OnBoolChange(false, 0, PasswordManagementConstants.PasswordUpdateBusyChange);
foreach (var pw in _passwords)
{
// if key exists, continue
if (Passwords.ContainsKey(pw.Key))
{
Debug.Console(1, string.Format("PasswordManager.PasswordTimerElapsed: pw.key[{0}] = {1}", pw.Key, pw.Value));
if (Passwords[pw.Key] != _passwords[pw.Key])
{
Passwords[pw.Key] = _passwords[pw.Key];
Debug.Console(1, string.Format("PasswordManager.PasswordTimerElapsed: Updated Password[{0} = {1}", pw.Key, Passwords[pw.Key]));
OnPasswordChange(Passwords[pw.Key], (ushort)pw.Key, PasswordManagementConstants.StringValueChange);
}
}
// else add the key & value
else
{
Passwords.Add(pw.Key, pw.Value);
}
}
OnUshrtChange((ushort)Passwords.Count, 0, PasswordManagementConstants.PasswordManagerCountChange);
}
catch (Exception e)
{
var msg = string.Format("PasswordManager.PasswordTimerElapsed failed:\r{0}", e);
Debug.Console(1, msg);
}
}
if (PasswordTimer == null)
{
PasswordTimer = new CTimer((o) => PasswordTimerElapsed(), PasswordTimerElapsedMs);
Debug.Console(1, string.Format("PasswordManager.UpdatePassword: CTimer Started"));
OnBoolChange(true, 0, PasswordManagementConstants.PasswordUpdateBusyChange);
}
else
{
PasswordTimer.Reset(PasswordTimerElapsedMs);
Debug.Console(1, string.Format("PasswordManager.UpdatePassword: CTimer Reset"));
}
}
catch (Exception e)
{
var msg = string.Format("PasswordManager.UpdatePassword key-value[{0}, {1}] failed:\r{2}", key, password, e);
Debug.Console(1, msg);
}
}
/// <summary>
/// Method to change the default timer value, (default 5000ms/5s)
/// </summary>
/// <param name="time"></param>
public void PasswordTimerMs(ushort time)
{
PasswordTimerElapsedMs = Convert.ToInt64(time);
}
/// <summary>
/// CTimer callback function
/// </summary>
private void PasswordTimerElapsed()
{
try
{
PasswordTimer.Stop();
Debug.Console(1, string.Format("PasswordManager.PasswordTimerElapsed: CTimer Stopped"));
OnBoolChange(false, 0, PasswordManagementConstants.PasswordUpdateBusyChange);
foreach (var pw in _passwords)
{
// if key exists, continue
if (Passwords.ContainsKey(pw.Key))
{
Debug.Console(1, string.Format("PasswordManager.PasswordTimerElapsed: pw.key[{0}] = {1}", pw.Key, pw.Value));
if (Passwords[pw.Key] != _passwords[pw.Key])
{
Passwords[pw.Key] = _passwords[pw.Key];
Debug.Console(1, string.Format("PasswordManager.PasswordTimerElapsed: Updated Password[{0} = {1}", pw.Key, Passwords[pw.Key]));
OnPasswordChange(Passwords[pw.Key], (ushort)pw.Key, PasswordManagementConstants.StringValueChange);
}
}
// else add the key & value
else
{
Passwords.Add(pw.Key, pw.Value);
}
}
OnUshrtChange((ushort)Passwords.Count, 0, PasswordManagementConstants.PasswordManagerCountChange);
}
catch (Exception e)
{
var msg = string.Format("PasswordManager.PasswordTimerElapsed failed:\r{0}", e);
Debug.Console(1, msg);
}
}
/// <summary>
/// Helper method for debugging to see what passwords are in the lists
/// </summary>
public void ListPasswords()
{
Debug.Console(0, "PasswordManager.ListPasswords:\r");
foreach (var pw in Passwords)
Debug.Console(0, "Passwords[{0}]: {1}\r", pw.Key, pw.Value);
Debug.Console(0, "\n");
foreach (var pw in _passwords)
Debug.Console(0, "_passwords[{0}]: {1}\r", pw.Key, pw.Value);
}
/// <summary>
/// Method to change the default timer value, (default 5000ms/5s)
/// </summary>
/// <param name="time"></param>
public void PasswordTimerMs(ushort time)
{
PasswordTimerElapsedMs = Convert.ToInt64(time);
}
/// <summary>
/// Protected boolean change event handler
/// </summary>
/// <param name="state"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnBoolChange(bool state, ushort index, ushort type)
{
var handler = BoolChange;
if (handler != null)
{
var args = new BoolChangeEventArgs(state, type);
args.Index = index;
BoolChange(this, args);
}
}
/// <summary>
/// Helper method for debugging to see what passwords are in the lists
/// </summary>
public void ListPasswords()
{
Debug.Console(0, "PasswordManager.ListPasswords:\r");
foreach (var pw in Passwords)
Debug.Console(0, "Passwords[{0}]: {1}\r", pw.Key, pw.Value);
Debug.Console(0, "\n");
foreach (var pw in _passwords)
Debug.Console(0, "_passwords[{0}]: {1}\r", pw.Key, pw.Value);
}
/// <summary>
/// Protected ushort change event handler
/// </summary>
/// <summary>
/// Protected boolean change event handler
/// </summary>
/// <param name="state"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnBoolChange(bool state, ushort index, ushort type)
{
var handler = BoolChange;
if (handler != null)
{
var args = new BoolChangeEventArgs(state, type);
args.Index = index;
BoolChange(this, args);
}
}
/// <summary>
/// Protected ushort change event handler
/// </summary>
/// <param name="value"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnUshrtChange(ushort value, ushort index, ushort type)
{
var handler = UshrtChange;
if (handler != null)
{
var args = new UshrtChangeEventArgs(value, type);
args.Index = index;
UshrtChange(this, args);
}
}
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnUshrtChange(ushort value, ushort index, ushort type)
{
var handler = UshrtChange;
if (handler != null)
{
var args = new UshrtChangeEventArgs(value, type);
args.Index = index;
UshrtChange(this, args);
}
}
/// <summary>
/// Protected string change event handler
/// </summary>
/// <param name="value"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnStringChange(string value, ushort index, ushort type)
{
var handler = StringChange;
if (handler != null)
{
var args = new StringChangeEventArgs(value, type);
args.Index = index;
StringChange(this, args);
}
}
/// <summary>
/// Protected string change event handler
/// </summary>
/// <param name="value"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnStringChange(string value, ushort index, ushort type)
{
var handler = StringChange;
if (handler != null)
{
var args = new StringChangeEventArgs(value, type);
args.Index = index;
StringChange(this, args);
}
}
/// <summary>
/// Protected password change event handler
/// </summary>
/// <param name="value"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnPasswordChange(string value, ushort index, ushort type)
{
var handler = PasswordChange;
if (handler != null)
{
var args = new StringChangeEventArgs(value, type);
args.Index = index;
PasswordChange(this, args);
}
}
}
/// <summary>
/// Protected password change event handler
/// </summary>
/// <param name="value"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnPasswordChange(string value, ushort index, ushort type)
{
var handler = PasswordChange;
if (handler != null)
{
var args = new StringChangeEventArgs(value, type);
args.Index = index;
PasswordChange(this, args);
}
}
}
}

View File

@@ -1,53 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<RootNamespace>PepperDash.Core</RootNamespace>
<AssemblyName>PepperDashCore</AssemblyName>
<TargetFramework>net472</TargetFramework>
<Deterministic>false</Deterministic>
<NeutralLanguage>en</NeutralLanguage>
<OutputPath>bin\$(Configuration)\</OutputPath>
<SignAssembly>False</SignAssembly>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<Title>PepperDash Core</Title>
<Company>PepperDash Technologies</Company>
<RepositoryType>git</RepositoryType>
<RepositoryUrl>https://github.com/PepperDash/PepperDashCore</RepositoryUrl>
<PackageTags>crestron;4series;</PackageTags>
<Version>$(Version)</Version>
<PackageOutputPath>../../package</PackageOutputPath>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugType>full</DebugType>
<DefineConstants>TRACE;DEBUG;SERIES4</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<DocumentationFile>bin\4Series\$(Configuration)\PepperDashCore.xml</DocumentationFile>
</PropertyGroup>
<ItemGroup>
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Net.Http" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Crestron.SimplSharp.SDK.Library" Version="2.19.35" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.2">
<Aliases></Aliases>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Compile Remove="Comm\._GenericSshClient.cs" />
<Compile Remove="Comm\._GenericTcpIpClient.cs" />
<Compile Remove="Comm\DynamicTCPServer.cs" />
<Compile Remove="PasswordManagement\OLD-ARRAY-Config.cs" />
<Compile Remove="PasswordManagement\OLD-ARRAY-PasswordClient.cs" />
<Compile Remove="PasswordManagement\OLD-ARRAY-PasswordManager.cs" />
</ItemGroup>
<Target Name="SimplSharpNewtonsoft" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'SimplSharpNewtonsoft'">
<Aliases>crestron</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>

View File

@@ -1,264 +1,260 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
namespace PepperDash.Core.SystemInfo
{
/// <summary>
/// Constants
/// </summary>
public class SystemInfoConstants
{
/// <summary>
/// Constants
/// </summary>
public class SystemInfoConstants
{
/// <summary>
///
/// </summary>
public const ushort BoolValueChange = 1;
/// <summary>
///
/// </summary>
public const ushort CompleteBoolChange = 2;
/// <summary>
///
/// </summary>
public const ushort BusyBoolChange = 3;
/// <summary>
///
/// </summary>
public const ushort UshortValueChange = 101;
public const ushort CompleteBoolChange = 2;
/// <summary>
///
/// </summary>
public const ushort BusyBoolChange = 3;
/// <summary>
///
/// </summary>
public const ushort UshortValueChange = 101;
/// <summary>
///
/// </summary>
public const ushort StringValueChange = 201;
/// <summary>
///
/// </summary>
/// <summary>
///
/// </summary>
public const ushort ConsoleResponseChange = 202;
/// <summary>
///
/// </summary>
/// <summary>
///
/// </summary>
public const ushort ProcessorUptimeChange = 203;
/// <summary>
///
/// </summary>
/// <summary>
///
/// </summary>
public const ushort ProgramUptimeChange = 204;
/// <summary>
///
/// </summary>
public const ushort ObjectChange = 301;
/// <summary>
///
/// </summary>
/// <summary>
///
/// </summary>
public const ushort ProcessorConfigChange = 302;
/// <summary>
///
/// </summary>
/// <summary>
///
/// </summary>
public const ushort EthernetConfigChange = 303;
/// <summary>
///
/// </summary>
/// <summary>
///
/// </summary>
public const ushort ControlSubnetConfigChange = 304;
/// <summary>
///
/// </summary>
/// <summary>
///
/// </summary>
public const ushort ProgramConfigChange = 305;
}
}
/// <summary>
/// Processor Change Event Args Class
/// </summary>
public class ProcessorChangeEventArgs : EventArgs
{
/// <summary>
/// Processor Change Event Args Class
/// </summary>
public class ProcessorChangeEventArgs : EventArgs
{
/// <summary>
///
/// </summary>
public ProcessorInfo Processor { get; set; }
/// <summary>
///
/// </summary>
/// <summary>
///
/// </summary>
public ushort Type { get; set; }
/// <summary>
///
/// </summary>
/// <summary>
///
/// </summary>
public ushort Index { get; set; }
/// <summary>
/// Constructor
/// </summary>
public ProcessorChangeEventArgs()
{
/// <summary>
/// Constructor
/// </summary>
public ProcessorChangeEventArgs()
{
}
}
/// <summary>
/// Constructor overload
/// </summary>
public ProcessorChangeEventArgs(ProcessorInfo processor, ushort type)
{
Processor = processor;
Type = type;
}
/// <summary>
/// Constructor overload
/// </summary>
public ProcessorChangeEventArgs(ProcessorInfo processor, ushort type)
{
Processor = processor;
Type = type;
}
/// <summary>
/// Constructor
/// </summary>
public ProcessorChangeEventArgs(ProcessorInfo processor, ushort type, ushort index)
{
Processor = processor;
Type = type;
Index = index;
}
}
/// <summary>
/// Constructor
/// </summary>
public ProcessorChangeEventArgs(ProcessorInfo processor, ushort type, ushort index)
{
Processor = processor;
Type = type;
Index = index;
}
}
/// <summary>
/// Ethernet Change Event Args Class
/// </summary>
public class EthernetChangeEventArgs : EventArgs
{
/// <summary>
/// Ethernet Change Event Args Class
/// </summary>
public class EthernetChangeEventArgs : EventArgs
{
/// <summary>
///
/// </summary>
public EthernetInfo Adapter { get; set; }
/// <summary>
///
/// </summary>
/// <summary>
///
/// </summary>
public ushort Type { get; set; }
/// <summary>
///
/// </summary>
/// <summary>
///
/// </summary>
public ushort Index { get; set; }
/// <summary>
/// Constructor
/// </summary>
public EthernetChangeEventArgs()
{
/// <summary>
/// Constructor
/// </summary>
public EthernetChangeEventArgs()
{
}
}
/// <summary>
/// Constructor overload
/// </summary>
/// <summary>
/// Constructor overload
/// </summary>
/// <param name="ethernet"></param>
/// <param name="type"></param>
public EthernetChangeEventArgs(EthernetInfo ethernet, ushort type)
{
Adapter = ethernet;
Type = type;
}
/// <param name="type"></param>
public EthernetChangeEventArgs(EthernetInfo ethernet, ushort type)
{
Adapter = ethernet;
Type = type;
}
/// <summary>
/// Constructor overload
/// </summary>
/// <summary>
/// Constructor overload
/// </summary>
/// <param name="ethernet"></param>
/// <param name="type"></param>
/// <param name="type"></param>
/// <param name="index"></param>
public EthernetChangeEventArgs(EthernetInfo ethernet, ushort type, ushort index)
{
Adapter = ethernet;
Type = type;
Index = index;
}
}
public EthernetChangeEventArgs(EthernetInfo ethernet, ushort type, ushort index)
{
Adapter = ethernet;
Type = type;
Index = index;
}
}
/// <summary>
/// Control Subnet Chage Event Args Class
/// </summary>
public class ControlSubnetChangeEventArgs : EventArgs
{
/// <summary>
/// Control Subnet Chage Event Args Class
/// </summary>
public class ControlSubnetChangeEventArgs : EventArgs
{
/// <summary>
///
/// </summary>
public ControlSubnetInfo Adapter { get; set; }
/// <summary>
///
/// </summary>
/// <summary>
///
/// </summary>
public ushort Type { get; set; }
/// <summary>
///
/// </summary>
/// <summary>
///
/// </summary>
public ushort Index { get; set; }
/// <summary>
/// Constructor
/// </summary>
public ControlSubnetChangeEventArgs()
{
/// <summary>
/// Constructor
/// </summary>
public ControlSubnetChangeEventArgs()
{
}
}
/// <summary>
/// Constructor overload
/// </summary>
public ControlSubnetChangeEventArgs(ControlSubnetInfo controlSubnet, ushort type)
{
Adapter = controlSubnet;
Type = type;
}
/// <summary>
/// Constructor overload
/// </summary>
public ControlSubnetChangeEventArgs(ControlSubnetInfo controlSubnet, ushort type)
{
Adapter = controlSubnet;
Type = type;
}
/// <summary>
/// Constructor overload
/// </summary>
public ControlSubnetChangeEventArgs(ControlSubnetInfo controlSubnet, ushort type, ushort index)
{
Adapter = controlSubnet;
Type = type;
Index = index;
}
}
/// <summary>
/// Constructor overload
/// </summary>
public ControlSubnetChangeEventArgs(ControlSubnetInfo controlSubnet, ushort type, ushort index)
{
Adapter = controlSubnet;
Type = type;
Index = index;
}
}
/// <summary>
/// Program Change Event Args Class
/// </summary>
public class ProgramChangeEventArgs : EventArgs
{
/// <summary>
/// Program Change Event Args Class
/// </summary>
public class ProgramChangeEventArgs : EventArgs
{
/// <summary>
///
/// </summary>
public ProgramInfo Program { get; set; }
/// <summary>
///
/// </summary>
/// <summary>
///
/// </summary>
public ushort Type { get; set; }
/// <summary>
///
/// </summary>
/// <summary>
///
/// </summary>
public ushort Index { get; set; }
/// <summary>
/// Constructor
/// </summary>
public ProgramChangeEventArgs()
{
/// <summary>
/// Constructor
/// </summary>
public ProgramChangeEventArgs()
{
}
}
/// <summary>
/// Constructor overload
/// </summary>
/// <summary>
/// Constructor overload
/// </summary>
/// <param name="program"></param>
/// <param name="type"></param>
public ProgramChangeEventArgs(ProgramInfo program, ushort type)
{
Program = program;
Type = type;
}
/// <param name="type"></param>
public ProgramChangeEventArgs(ProgramInfo program, ushort type)
{
Program = program;
Type = type;
}
/// <summary>
/// Constructor overload
/// </summary>
/// <summary>
/// Constructor overload
/// </summary>
/// <param name="program"></param>
/// <param name="type"></param>
/// <param name="type"></param>
/// <param name="index"></param>
public ProgramChangeEventArgs(ProgramInfo program, ushort type, ushort index)
{
Program = program;
Type = type;
Index = index;
}
}
public ProgramChangeEventArgs(ProgramInfo program, ushort type, ushort index)
{
Program = program;
Type = type;
Index = index;
}
}
}

View File

@@ -1,16 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
namespace PepperDash.Core.SystemInfo
namespace PepperDash.Core.SystemInfo
{
/// <summary>
/// Processor info class
/// </summary>
public class ProcessorInfo
{
/// <summary>
/// Processor info class
/// </summary>
public class ProcessorInfo
{
/// <summary>
///
/// </summary>
@@ -52,20 +46,20 @@ namespace PepperDash.Core.SystemInfo
/// </summary>
public string ProgramIdTag { get; set; }
/// <summary>
/// Constructor
/// </summary>
public ProcessorInfo()
{
}
}
/// <summary>
/// Constructor
/// </summary>
public ProcessorInfo()
{
/// <summary>
/// Ethernet info class
/// </summary>
public class EthernetInfo
{
}
}
/// <summary>
/// Ethernet info class
/// </summary>
public class EthernetInfo
{
/// <summary>
///
/// </summary>
@@ -107,20 +101,20 @@ namespace PepperDash.Core.SystemInfo
/// </summary>
public string Domain { get; set; }
/// <summary>
/// Constructor
/// </summary>
public EthernetInfo()
{
}
}
/// <summary>
/// Constructor
/// </summary>
public EthernetInfo()
{
/// <summary>
/// Control subnet info class
/// </summary>
public class ControlSubnetInfo
{
}
}
/// <summary>
/// Control subnet info class
/// </summary>
public class ControlSubnetInfo
{
/// <summary>
///
/// </summary>
@@ -146,20 +140,20 @@ namespace PepperDash.Core.SystemInfo
/// </summary>
public string RouterPrefix { get; set; }
/// <summary>
/// Constructor
/// </summary>
public ControlSubnetInfo()
{
}
}
/// <summary>
/// Constructor
/// </summary>
public ControlSubnetInfo()
{
/// <summary>
/// Program info class
/// </summary>
public class ProgramInfo
{
}
}
/// <summary>
/// Program info class
/// </summary>
public class ProgramInfo
{
/// <summary>
///
/// </summary>
@@ -193,12 +187,12 @@ namespace PepperDash.Core.SystemInfo
/// </summary>
public string Programmer { get; set; }
/// <summary>
/// Constructor
/// </summary>
public ProgramInfo()
{
}
}
/// <summary>
/// Constructor
/// </summary>
public ProgramInfo()
{
}
}
}

View File

@@ -1,16 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
using Crestron.SimplSharp;
using System;
namespace PepperDash.Core.SystemInfo
{
/// <summary>
/// System Info class
/// </summary>
public class SystemInfoToSimpl
{
/// <summary>
/// System Info class
/// </summary>
public class SystemInfoToSimpl
{
/// <summary>
/// Notifies of bool change
/// </summary>
@@ -37,426 +34,426 @@ namespace PepperDash.Core.SystemInfo
/// </summary>
public event EventHandler<ProgramChangeEventArgs> ProgramChange;
/// <summary>
/// Constructor
/// </summary>
public SystemInfoToSimpl()
{
/// <summary>
/// Constructor
/// </summary>
public SystemInfoToSimpl()
{
}
}
/// <summary>
/// Gets the current processor info
/// </summary>
public void GetProcessorInfo()
{
OnBoolChange(true, 0, SystemInfoConstants.BusyBoolChange);
/// <summary>
/// Gets the current processor info
/// </summary>
public void GetProcessorInfo()
{
OnBoolChange(true, 0, SystemInfoConstants.BusyBoolChange);
try
{
var processor = new ProcessorInfo();
processor.Model = InitialParametersClass.ControllerPromptName;
processor.SerialNumber = CrestronEnvironment.SystemInfo.SerialNumber;
processor.ModuleDirectory = InitialParametersClass.ProgramDirectory.ToString();
processor.ProgramIdTag = InitialParametersClass.ProgramIDTag;
processor.DevicePlatform = CrestronEnvironment.DevicePlatform.ToString();
processor.OsVersion = CrestronEnvironment.OSVersion.Version.ToString();
processor.RuntimeEnvironment = CrestronEnvironment.RuntimeEnvironment.ToString();
processor.LocalTimeZone = CrestronEnvironment.GetTimeZone().Offset;
try
{
var processor = new ProcessorInfo();
processor.Model = InitialParametersClass.ControllerPromptName;
processor.SerialNumber = CrestronEnvironment.SystemInfo.SerialNumber;
processor.ModuleDirectory = InitialParametersClass.ProgramDirectory.ToString();
processor.ProgramIdTag = InitialParametersClass.ProgramIDTag;
processor.DevicePlatform = CrestronEnvironment.DevicePlatform.ToString();
processor.OsVersion = CrestronEnvironment.OSVersion.Version.ToString();
processor.RuntimeEnvironment = CrestronEnvironment.RuntimeEnvironment.ToString();
processor.LocalTimeZone = CrestronEnvironment.GetTimeZone().Offset;
// Does not return firmware version matching a "ver" command
// returns the "ver -v" 'CAB' version
// example return ver -v:
// RMC3 Cntrl Eng [v1.503.3568.25373 (Oct 09 2018), #4001E302] @E-00107f4420f0
// Build: 14:05:46 Oct 09 2018 (3568.25373)
// Cab: 1.503.0070
// Applications: 1.0.6855.21351
// Updater: 1.4.24
// Bootloader: 1.22.00
// RMC3-SetupProgram: 1.003.0011
// IOPVersion: FPGA [v09] slot:7
// PUF: Unknown
//Firmware = CrestronEnvironment.OSVersion.Firmware;
//Firmware = InitialParametersClass.FirmwareVersion;
// Does not return firmware version matching a "ver" command
// returns the "ver -v" 'CAB' version
// example return ver -v:
// RMC3 Cntrl Eng [v1.503.3568.25373 (Oct 09 2018), #4001E302] @E-00107f4420f0
// Build: 14:05:46 Oct 09 2018 (3568.25373)
// Cab: 1.503.0070
// Applications: 1.0.6855.21351
// Updater: 1.4.24
// Bootloader: 1.22.00
// RMC3-SetupProgram: 1.003.0011
// IOPVersion: FPGA [v09] slot:7
// PUF: Unknown
//Firmware = CrestronEnvironment.OSVersion.Firmware;
//Firmware = InitialParametersClass.FirmwareVersion;
// Use below logic to get actual firmware ver, not the 'CAB' returned by the above
// matches console return of a "ver" and on SystemInfo page
// example return ver:
// RMC3 Cntrl Eng [v1.503.3568.25373 (Oct 09 2018), #4001E302] @E-00107f4420f0
var response = "";
CrestronConsole.SendControlSystemCommand("ver", ref response);
processor.Firmware = ParseConsoleResponse(response, "Cntrl Eng", "[", "(");
processor.FirmwareDate = ParseConsoleResponse(response, "Cntrl Eng", "(", ")");
// Use below logic to get actual firmware ver, not the 'CAB' returned by the above
// matches console return of a "ver" and on SystemInfo page
// example return ver:
// RMC3 Cntrl Eng [v1.503.3568.25373 (Oct 09 2018), #4001E302] @E-00107f4420f0
var response = "";
CrestronConsole.SendControlSystemCommand("ver", ref response);
processor.Firmware = ParseConsoleResponse(response, "Cntrl Eng", "[", "(");
processor.FirmwareDate = ParseConsoleResponse(response, "Cntrl Eng", "(", ")");
OnProcessorChange(processor, 0, SystemInfoConstants.ProcessorConfigChange);
}
catch (Exception e)
{
var msg = string.Format("GetProcessorInfo failed: {0}", e.Message);
CrestronConsole.PrintLine(msg);
//ErrorLog.Error(msg);
}
OnProcessorChange(processor, 0, SystemInfoConstants.ProcessorConfigChange);
}
catch (Exception e)
{
var msg = string.Format("GetProcessorInfo failed: {0}", e.Message);
CrestronConsole.PrintLine(msg);
//ErrorLog.Error(msg);
}
OnBoolChange(false, 0, SystemInfoConstants.BusyBoolChange);
}
OnBoolChange(false, 0, SystemInfoConstants.BusyBoolChange);
}
/// <summary>
/// Gets the current ethernet info
/// </summary>
public void GetEthernetInfo()
{
OnBoolChange(true, 0, SystemInfoConstants.BusyBoolChange);
/// <summary>
/// Gets the current ethernet info
/// </summary>
public void GetEthernetInfo()
{
OnBoolChange(true, 0, SystemInfoConstants.BusyBoolChange);
var adapter = new EthernetInfo();
var adapter = new EthernetInfo();
try
{
// get lan adapter id
var adapterId = CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(EthernetAdapterType.EthernetLANAdapter);
try
{
// get lan adapter id
var adapterId = CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(EthernetAdapterType.EthernetLANAdapter);
// get lan adapter info
var dhcpState = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_DHCP_STATE, adapterId);
if (!string.IsNullOrEmpty(dhcpState))
adapter.DhcpIsOn = (ushort)(dhcpState.ToLower().Contains("on") ? 1 : 0);
// get lan adapter info
var dhcpState = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_DHCP_STATE, adapterId);
if (!string.IsNullOrEmpty(dhcpState))
adapter.DhcpIsOn = (ushort)(dhcpState.ToLower().Contains("on") ? 1 : 0);
adapter.Hostname = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_HOSTNAME, adapterId);
adapter.MacAddress = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_MAC_ADDRESS, adapterId);
adapter.IpAddress = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS, adapterId);
adapter.Subnet = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_MASK, adapterId);
adapter.Gateway = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_ROUTER, adapterId);
adapter.Domain = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_DOMAIN_NAME, adapterId);
adapter.Hostname = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_HOSTNAME, adapterId);
adapter.MacAddress = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_MAC_ADDRESS, adapterId);
adapter.IpAddress = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS, adapterId);
adapter.Subnet = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_MASK, adapterId);
adapter.Gateway = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_ROUTER, adapterId);
adapter.Domain = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_DOMAIN_NAME, adapterId);
// returns comma seperate list of dns servers with trailing comma
// example return: "8.8.8.8 (DHCP),8.8.4.4 (DHCP),"
string dns = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_DNS_SERVER, adapterId);
if (dns.Contains(","))
{
string[] dnsList = dns.Split(',');
for (var i = 0; i < dnsList.Length; i++)
{
if(i == 0)
adapter.Dns1 = !string.IsNullOrEmpty(dnsList[0]) ? dnsList[0] : "0.0.0.0";
if(i == 1)
adapter.Dns2 = !string.IsNullOrEmpty(dnsList[1]) ? dnsList[1] : "0.0.0.0";
if(i == 2)
adapter.Dns3 = !string.IsNullOrEmpty(dnsList[2]) ? dnsList[2] : "0.0.0.0";
}
}
else
{
adapter.Dns1 = !string.IsNullOrEmpty(dns) ? dns : "0.0.0.0";
adapter.Dns2 = "0.0.0.0";
adapter.Dns3 = "0.0.0.0";
}
// returns comma seperate list of dns servers with trailing comma
// example return: "8.8.8.8 (DHCP),8.8.4.4 (DHCP),"
string dns = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_DNS_SERVER, adapterId);
if (dns.Contains(","))
{
string[] dnsList = dns.Split(',');
for (var i = 0; i < dnsList.Length; i++)
{
if (i == 0)
adapter.Dns1 = !string.IsNullOrEmpty(dnsList[0]) ? dnsList[0] : "0.0.0.0";
if (i == 1)
adapter.Dns2 = !string.IsNullOrEmpty(dnsList[1]) ? dnsList[1] : "0.0.0.0";
if (i == 2)
adapter.Dns3 = !string.IsNullOrEmpty(dnsList[2]) ? dnsList[2] : "0.0.0.0";
}
}
else
{
adapter.Dns1 = !string.IsNullOrEmpty(dns) ? dns : "0.0.0.0";
adapter.Dns2 = "0.0.0.0";
adapter.Dns3 = "0.0.0.0";
}
OnEthernetInfoChange(adapter, 0, SystemInfoConstants.EthernetConfigChange);
}
catch (Exception e)
{
var msg = string.Format("GetEthernetInfo failed: {0}", e.Message);
CrestronConsole.PrintLine(msg);
//ErrorLog.Error(msg);
}
OnEthernetInfoChange(adapter, 0, SystemInfoConstants.EthernetConfigChange);
}
catch (Exception e)
{
var msg = string.Format("GetEthernetInfo failed: {0}", e.Message);
CrestronConsole.PrintLine(msg);
//ErrorLog.Error(msg);
}
OnBoolChange(false, 0, SystemInfoConstants.BusyBoolChange);
}
OnBoolChange(false, 0, SystemInfoConstants.BusyBoolChange);
}
/// <summary>
/// Gets the current control subnet info
/// </summary>
public void GetControlSubnetInfo()
{
OnBoolChange(true, 0, SystemInfoConstants.BusyBoolChange);
/// <summary>
/// Gets the current control subnet info
/// </summary>
public void GetControlSubnetInfo()
{
OnBoolChange(true, 0, SystemInfoConstants.BusyBoolChange);
var adapter = new ControlSubnetInfo();
var adapter = new ControlSubnetInfo();
try
{
// get cs adapter id
var adapterId = CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(EthernetAdapterType.EthernetCSAdapter);
if (!adapterId.Equals(EthernetAdapterType.EthernetUnknownAdapter))
{
adapter.Enabled = 1;
adapter.IsInAutomaticMode = (ushort)(CrestronEthernetHelper.IsControlSubnetInAutomaticMode ? 1 : 0);
adapter.MacAddress = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_MAC_ADDRESS, adapterId);
adapter.IpAddress = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS, adapterId);
adapter.Subnet = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_MASK, adapterId);
adapter.RouterPrefix = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CONTROL_SUBNET_ROUTER_PREFIX, adapterId);
}
}
catch (Exception e)
{
adapter.Enabled = 0;
adapter.IsInAutomaticMode = 0;
adapter.MacAddress = "NA";
adapter.IpAddress = "NA";
adapter.Subnet = "NA";
adapter.RouterPrefix = "NA";
try
{
// get cs adapter id
var adapterId = CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(EthernetAdapterType.EthernetCSAdapter);
if (!adapterId.Equals(EthernetAdapterType.EthernetUnknownAdapter))
{
adapter.Enabled = 1;
adapter.IsInAutomaticMode = (ushort)(CrestronEthernetHelper.IsControlSubnetInAutomaticMode ? 1 : 0);
adapter.MacAddress = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_MAC_ADDRESS, adapterId);
adapter.IpAddress = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS, adapterId);
adapter.Subnet = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_MASK, adapterId);
adapter.RouterPrefix = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CONTROL_SUBNET_ROUTER_PREFIX, adapterId);
}
}
catch (Exception e)
{
adapter.Enabled = 0;
adapter.IsInAutomaticMode = 0;
adapter.MacAddress = "NA";
adapter.IpAddress = "NA";
adapter.Subnet = "NA";
adapter.RouterPrefix = "NA";
var msg = string.Format("GetControlSubnetInfo failed: {0}", e.Message);
CrestronConsole.PrintLine(msg);
//ErrorLog.Error(msg);
}
var msg = string.Format("GetControlSubnetInfo failed: {0}", e.Message);
CrestronConsole.PrintLine(msg);
//ErrorLog.Error(msg);
}
OnControlSubnetInfoChange(adapter, 0, SystemInfoConstants.ControlSubnetConfigChange);
OnBoolChange(false, 0, SystemInfoConstants.BusyBoolChange);
}
OnControlSubnetInfoChange(adapter, 0, SystemInfoConstants.ControlSubnetConfigChange);
OnBoolChange(false, 0, SystemInfoConstants.BusyBoolChange);
}
/// <summary>
/// Gets the program info by index
/// </summary>
/// <param name="index"></param>
public void GetProgramInfoByIndex(ushort index)
{
if (index < 1 || index > 10)
return;
/// <summary>
/// Gets the program info by index
/// </summary>
/// <param name="index"></param>
public void GetProgramInfoByIndex(ushort index)
{
if (index < 1 || index > 10)
return;
OnBoolChange(true, 0, SystemInfoConstants.BusyBoolChange);
OnBoolChange(true, 0, SystemInfoConstants.BusyBoolChange);
var program = new ProgramInfo();
var program = new ProgramInfo();
try
{
var response = "";
CrestronConsole.SendControlSystemCommand(string.Format("progcomments:{0}", index), ref response);
// no program loaded or running
if (response.Contains("Bad or Incomplete Command"))
{
program.Name = "";
program.System = "";
program.Programmer = "";
program.CompileTime = "";
program.Database = "";
program.Environment = "";
}
else
{
// SIMPL returns
program.Name = ParseConsoleResponse(response, "Program File", ":", "\x0D");
program.System = ParseConsoleResponse(response, "System Name", ":", "\x0D");
program.ProgramIdTag = ParseConsoleResponse(response, "Friendly Name", ":", "\x0D");
program.Programmer = ParseConsoleResponse(response, "Programmer", ":", "\x0D");
program.CompileTime = ParseConsoleResponse(response, "Compiled On", ":", "\x0D");
program.Database = ParseConsoleResponse(response, "CrestronDB", ":", "\x0D");
program.Environment = ParseConsoleResponse(response, "Source Env", ":", "\x0D");
try
{
var response = "";
CrestronConsole.SendControlSystemCommand(string.Format("progcomments:{0}", index), ref response);
// S# returns
if (program.System.Length == 0)
program.System = ParseConsoleResponse(response, "Application Name", ":", "\x0D");
if (program.Database.Length == 0)
program.Database = ParseConsoleResponse(response, "PlugInVersion", ":", "\x0D");
if (program.Environment.Length == 0)
program.Environment = ParseConsoleResponse(response, "Program Tool", ":", "\x0D");
// no program loaded or running
if (response.Contains("Bad or Incomplete Command"))
{
program.Name = "";
program.System = "";
program.Programmer = "";
program.CompileTime = "";
program.Database = "";
program.Environment = "";
}
else
{
// SIMPL returns
program.Name = ParseConsoleResponse(response, "Program File", ":", "\x0D");
program.System = ParseConsoleResponse(response, "System Name", ":", "\x0D");
program.ProgramIdTag = ParseConsoleResponse(response, "Friendly Name", ":", "\x0D");
program.Programmer = ParseConsoleResponse(response, "Programmer", ":", "\x0D");
program.CompileTime = ParseConsoleResponse(response, "Compiled On", ":", "\x0D");
program.Database = ParseConsoleResponse(response, "CrestronDB", ":", "\x0D");
program.Environment = ParseConsoleResponse(response, "Source Env", ":", "\x0D");
}
OnProgramChange(program, index, SystemInfoConstants.ProgramConfigChange);
}
catch (Exception e)
{
var msg = string.Format("GetProgramInfoByIndex failed: {0}", e.Message);
CrestronConsole.PrintLine(msg);
//ErrorLog.Error(msg);
}
// S# returns
if (program.System.Length == 0)
program.System = ParseConsoleResponse(response, "Application Name", ":", "\x0D");
if (program.Database.Length == 0)
program.Database = ParseConsoleResponse(response, "PlugInVersion", ":", "\x0D");
if (program.Environment.Length == 0)
program.Environment = ParseConsoleResponse(response, "Program Tool", ":", "\x0D");
OnBoolChange(false, 0, SystemInfoConstants.BusyBoolChange);
}
}
/// <summary>
/// Gets the processor uptime and passes it to S+
/// </summary>
public void RefreshProcessorUptime()
{
try
{
string response = "";
CrestronConsole.SendControlSystemCommand("uptime", ref response);
var uptime = ParseConsoleResponse(response, "running for", "running for", "\x0D");
OnStringChange(uptime, 0, SystemInfoConstants.ProcessorUptimeChange);
}
catch (Exception e)
{
var msg = string.Format("RefreshProcessorUptime failed:\r{0}", e.Message);
CrestronConsole.PrintLine(msg);
//ErrorLog.Error(msg);
}
}
OnProgramChange(program, index, SystemInfoConstants.ProgramConfigChange);
}
catch (Exception e)
{
var msg = string.Format("GetProgramInfoByIndex failed: {0}", e.Message);
CrestronConsole.PrintLine(msg);
//ErrorLog.Error(msg);
}
/// <summary>
/// Gets the program uptime, by index, and passes it to S+
/// </summary>
/// <param name="index"></param>
public void RefreshProgramUptimeByIndex(int index)
{
try
{
string response = "";
CrestronConsole.SendControlSystemCommand(string.Format("proguptime:{0}", index), ref response);
string uptime = ParseConsoleResponse(response, "running for", "running for", "\x0D");
OnStringChange(uptime, (ushort)index, SystemInfoConstants.ProgramUptimeChange);
}
catch (Exception e)
{
var msg = string.Format("RefreshProgramUptimebyIndex({0}) failed:\r{1}", index, e.Message);
CrestronConsole.PrintLine(msg);
//ErrorLog.Error(msg);
}
}
OnBoolChange(false, 0, SystemInfoConstants.BusyBoolChange);
}
/// <summary>
/// Sends command to console, passes response back using string change event
/// </summary>
/// <param name="cmd"></param>
public void SendConsoleCommand(string cmd)
{
if (string.IsNullOrEmpty(cmd))
return;
/// <summary>
/// Gets the processor uptime and passes it to S+
/// </summary>
public void RefreshProcessorUptime()
{
try
{
string response = "";
CrestronConsole.SendControlSystemCommand("uptime", ref response);
var uptime = ParseConsoleResponse(response, "running for", "running for", "\x0D");
OnStringChange(uptime, 0, SystemInfoConstants.ProcessorUptimeChange);
}
catch (Exception e)
{
var msg = string.Format("RefreshProcessorUptime failed:\r{0}", e.Message);
CrestronConsole.PrintLine(msg);
//ErrorLog.Error(msg);
}
}
string response = "";
CrestronConsole.SendControlSystemCommand(cmd, ref response);
if (!string.IsNullOrEmpty(response))
{
if (response.EndsWith("\x0D\\x0A"))
response.Trim('\n');
/// <summary>
/// Gets the program uptime, by index, and passes it to S+
/// </summary>
/// <param name="index"></param>
public void RefreshProgramUptimeByIndex(int index)
{
try
{
string response = "";
CrestronConsole.SendControlSystemCommand(string.Format("proguptime:{0}", index), ref response);
string uptime = ParseConsoleResponse(response, "running for", "running for", "\x0D");
OnStringChange(uptime, (ushort)index, SystemInfoConstants.ProgramUptimeChange);
}
catch (Exception e)
{
var msg = string.Format("RefreshProgramUptimebyIndex({0}) failed:\r{1}", index, e.Message);
CrestronConsole.PrintLine(msg);
//ErrorLog.Error(msg);
}
}
OnStringChange(response, 0, SystemInfoConstants.ConsoleResponseChange);
}
}
/// <summary>
/// Sends command to console, passes response back using string change event
/// </summary>
/// <param name="cmd"></param>
public void SendConsoleCommand(string cmd)
{
if (string.IsNullOrEmpty(cmd))
return;
/// <summary>
/// private method to parse console messages
/// </summary>
string response = "";
CrestronConsole.SendControlSystemCommand(cmd, ref response);
if (!string.IsNullOrEmpty(response))
{
if (response.EndsWith("\x0D\\x0A"))
response.Trim('\n');
OnStringChange(response, 0, SystemInfoConstants.ConsoleResponseChange);
}
}
/// <summary>
/// private method to parse console messages
/// </summary>
/// <param name="data"></param>
/// <param name="line"></param>
/// <param name="line"></param>
/// <param name="dataStart"></param>
/// <param name="dataEnd"></param>
/// <returns></returns>
private string ParseConsoleResponse(string data, string line, string dataStart, string dataEnd)
{
var response = "";
/// <returns></returns>
private string ParseConsoleResponse(string data, string line, string dataStart, string dataEnd)
{
var response = "";
if (string.IsNullOrEmpty(data) || string.IsNullOrEmpty(line) || string.IsNullOrEmpty(dataStart) || string.IsNullOrEmpty(dataEnd))
return response;
if (string.IsNullOrEmpty(data) || string.IsNullOrEmpty(line) || string.IsNullOrEmpty(dataStart) || string.IsNullOrEmpty(dataEnd))
return response;
try
{
var linePos = data.IndexOf(line);
var startPos = data.IndexOf(dataStart, linePos) + dataStart.Length;
var endPos = data.IndexOf(dataEnd, startPos);
response = data.Substring(startPos, endPos - startPos).Trim();
}
catch (Exception e)
{
var msg = string.Format("ParseConsoleResponse failed: {0}", e.Message);
CrestronConsole.PrintLine(msg);
//ErrorLog.Error(msg);
}
try
{
var linePos = data.IndexOf(line);
var startPos = data.IndexOf(dataStart, linePos) + dataStart.Length;
var endPos = data.IndexOf(dataEnd, startPos);
response = data.Substring(startPos, endPos - startPos).Trim();
}
catch (Exception e)
{
var msg = string.Format("ParseConsoleResponse failed: {0}", e.Message);
CrestronConsole.PrintLine(msg);
//ErrorLog.Error(msg);
}
return response;
}
return response;
}
/// <summary>
/// Protected boolean change event handler
/// </summary>
/// <param name="state"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnBoolChange(bool state, ushort index, ushort type)
{
var handler = BoolChange;
if (handler != null)
{
var args = new BoolChangeEventArgs(state, type);
args.Index = index;
BoolChange(this, args);
}
}
/// <summary>
/// Protected boolean change event handler
/// </summary>
/// <param name="state"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnBoolChange(bool state, ushort index, ushort type)
{
var handler = BoolChange;
if (handler != null)
{
var args = new BoolChangeEventArgs(state, type);
args.Index = index;
BoolChange(this, args);
}
}
/// <summary>
/// Protected string change event handler
/// </summary>
/// <param name="value"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnStringChange(string value, ushort index, ushort type)
{
var handler = StringChange;
if (handler != null)
{
var args = new StringChangeEventArgs(value, type);
args.Index = index;
StringChange(this, args);
}
}
/// <summary>
/// Protected string change event handler
/// </summary>
/// <param name="value"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnStringChange(string value, ushort index, ushort type)
{
var handler = StringChange;
if (handler != null)
{
var args = new StringChangeEventArgs(value, type);
args.Index = index;
StringChange(this, args);
}
}
/// <summary>
/// Protected processor config change event handler
/// </summary>
/// <param name="processor"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnProcessorChange(ProcessorInfo processor, ushort index, ushort type)
{
var handler = ProcessorChange;
if (handler != null)
{
var args = new ProcessorChangeEventArgs(processor, type);
args.Index = index;
ProcessorChange(this, args);
}
}
/// <summary>
/// Protected processor config change event handler
/// </summary>
/// <param name="processor"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnProcessorChange(ProcessorInfo processor, ushort index, ushort type)
{
var handler = ProcessorChange;
if (handler != null)
{
var args = new ProcessorChangeEventArgs(processor, type);
args.Index = index;
ProcessorChange(this, args);
}
}
/// <summary>
/// Ethernet change event handler
/// </summary>
/// <param name="ethernet"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnEthernetInfoChange(EthernetInfo ethernet, ushort index, ushort type)
{
var handler = EthernetChange;
if (handler != null)
{
var args = new EthernetChangeEventArgs(ethernet, type);
args.Index = index;
EthernetChange(this, args);
}
}
/// <summary>
/// Ethernet change event handler
/// </summary>
/// <param name="ethernet"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnEthernetInfoChange(EthernetInfo ethernet, ushort index, ushort type)
{
var handler = EthernetChange;
if (handler != null)
{
var args = new EthernetChangeEventArgs(ethernet, type);
args.Index = index;
EthernetChange(this, args);
}
}
/// <summary>
/// Control Subnet change event handler
/// </summary>
/// <param name="ethernet"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnControlSubnetInfoChange(ControlSubnetInfo ethernet, ushort index, ushort type)
{
var handler = ControlSubnetChange;
if (handler != null)
{
var args = new ControlSubnetChangeEventArgs(ethernet, type);
args.Index = index;
ControlSubnetChange(this, args);
}
}
/// <summary>
/// Control Subnet change event handler
/// </summary>
/// <param name="ethernet"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnControlSubnetInfoChange(ControlSubnetInfo ethernet, ushort index, ushort type)
{
var handler = ControlSubnetChange;
if (handler != null)
{
var args = new ControlSubnetChangeEventArgs(ethernet, type);
args.Index = index;
ControlSubnetChange(this, args);
}
}
/// <summary>
/// Program change event handler
/// </summary>
/// <param name="program"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnProgramChange(ProgramInfo program, ushort index, ushort type)
{
var handler = ProgramChange;
/// <summary>
/// Program change event handler
/// </summary>
/// <param name="program"></param>
/// <param name="index"></param>
/// <param name="type"></param>
protected void OnProgramChange(ProgramInfo program, ushort index, ushort type)
{
var handler = ProgramChange;
if (handler != null)
{
var args = new ProgramChangeEventArgs(program, type);
args.Index = index;
ProgramChange(this, args);
}
}
}
if (handler != null)
{
var args = new ProgramChangeEventArgs(program, type);
args.Index = index;
ProgramChange(this, args);
}
}
}
}

View File

@@ -1,12 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
using Newtonsoft.Json;
namespace PepperDash.Core.WebApi.Presets
@@ -15,7 +9,7 @@ namespace PepperDash.Core.WebApi.Presets
/// Represents a preset
/// </summary>
public class Preset
{
{
/// <summary>
/// ID of preset
/// </summary>
@@ -50,23 +44,23 @@ namespace PepperDash.Core.WebApi.Presets
/// Constructor
/// </summary>
public Preset()
{
PresetName = "";
PresetNumber = 1;
Data = "{}";
}
}
{
PresetName = "";
PresetNumber = 1;
Data = "{}";
}
}
/// <summary>
///
/// </summary>
public class PresetReceivedEventArgs : EventArgs
{
/// <summary>
///
/// </summary>
public class PresetReceivedEventArgs : EventArgs
{
/// <summary>
/// True when the preset is found
/// </summary>
public bool LookupSuccess { get; private set; }
/// <summary>
/// S+ helper
/// </summary>
@@ -77,10 +71,10 @@ namespace PepperDash.Core.WebApi.Presets
/// </summary>
public Preset Preset { get; private set; }
/// <summary>
/// For Simpl+
/// </summary>
public PresetReceivedEventArgs() { }
/// <summary>
/// For Simpl+
/// </summary>
public PresetReceivedEventArgs() { }
/// <summary>
/// Constructor
@@ -88,9 +82,9 @@ namespace PepperDash.Core.WebApi.Presets
/// <param name="preset"></param>
/// <param name="success"></param>
public PresetReceivedEventArgs(Preset preset, bool success)
{
{
LookupSuccess = success;
Preset = preset;
}
}
Preset = preset;
}
}
}

View File

@@ -1,25 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
namespace PepperDash.Core.WebApi.Presets
{
/// <summary>
///
/// </summary>
public class User
{
/// <summary>
///
/// </summary>
public class User
{
/// <summary>
///
/// </summary>
public int Id { get; set; }
/// <summary>
///
/// </summary>
public string ExternalId { get; set; }
public string ExternalId { get; set; }
/// <summary>
///
@@ -30,14 +26,14 @@ namespace PepperDash.Core.WebApi.Presets
///
/// </summary>
public string LastName { get; set; }
}
}
/// <summary>
///
/// </summary>
public class UserReceivedEventArgs : EventArgs
{
/// <summary>
///
/// </summary>
public class UserReceivedEventArgs : EventArgs
{
/// <summary>
/// True when user is found
/// </summary>
@@ -53,10 +49,10 @@ namespace PepperDash.Core.WebApi.Presets
/// </summary>
public User User { get; private set; }
/// <summary>
/// For Simpl+
/// </summary>
public UserReceivedEventArgs() { }
/// <summary>
/// For Simpl+
/// </summary>
public UserReceivedEventArgs() { }
/// <summary>
/// Constructor
@@ -64,17 +60,17 @@ namespace PepperDash.Core.WebApi.Presets
/// <param name="user"></param>
/// <param name="success"></param>
public UserReceivedEventArgs(User user, bool success)
{
{
LookupSuccess = success;
User = user;
}
}
User = user;
}
}
/// <summary>
///
/// </summary>
public class UserAndRoomMessage
{
/// <summary>
///
/// </summary>
public class UserAndRoomMessage
{
/// <summary>
///
/// </summary>
@@ -89,5 +85,5 @@ namespace PepperDash.Core.WebApi.Presets
///
/// </summary>
public int PresetNumber { get; set; }
}
}
}

View File

@@ -1,17 +1,15 @@
using System;
using System.Text;
using Crestron.SimplSharp; // For Basic SIMPL# Classes
using Crestron.SimplSharp.CrestronIO;
using Crestron.SimplSharp.Net;
using Crestron.SimplSharp.Net.Http;
using Crestron.SimplSharp.Net.Https;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PepperDash.Core;
using PepperDash.Core.Interfaces;
using PepperDash.Core.JsonToSimpl;
using PepperDash.Core.Logging;
using System;
namespace PepperDash.Core.WebApi.Presets
@@ -20,7 +18,7 @@ namespace PepperDash.Core.WebApi.Presets
/// Passcode client for the WebApi
/// </summary>
public class WebApiPasscodeClient : IKeyed
{
{
/// <summary>
/// Notifies when user received
/// </summary>
@@ -36,29 +34,29 @@ namespace PepperDash.Core.WebApi.Presets
/// </summary>
public string Key { get; private set; }
//string JsonMasterKey;
//string JsonMasterKey;
/// <summary>
/// An embedded JsonToSimpl master object.
/// </summary>
JsonToSimplGenericMaster J2SMaster;
/// <summary>
/// An embedded JsonToSimpl master object.
/// </summary>
JsonToSimplGenericMaster J2SMaster;
string UrlBase;
string UrlBase;
string DefaultPresetJsonFilePath;
string DefaultPresetJsonFilePath;
User CurrentUser;
User CurrentUser;
Preset CurrentPreset;
Preset CurrentPreset;
/// <summary>
/// SIMPL+ can only execute the default constructor. If you have variables that require initialization, please
/// use an Initialize method
/// </summary>
public WebApiPasscodeClient()
{
}
/// <summary>
/// SIMPL+ can only execute the default constructor. If you have variables that require initialization, please
/// use an Initialize method
/// </summary>
public WebApiPasscodeClient()
{
}
/// <summary>
/// Initializes the instance
@@ -68,23 +66,23 @@ namespace PepperDash.Core.WebApi.Presets
/// <param name="urlBase"></param>
/// <param name="defaultPresetJsonFilePath"></param>
public void Initialize(string key, string jsonMasterKey, string urlBase, string defaultPresetJsonFilePath)
{
Key = key;
//JsonMasterKey = jsonMasterKey;
UrlBase = urlBase;
DefaultPresetJsonFilePath = defaultPresetJsonFilePath;
{
Key = key;
//JsonMasterKey = jsonMasterKey;
UrlBase = urlBase;
DefaultPresetJsonFilePath = defaultPresetJsonFilePath;
J2SMaster = new JsonToSimplGenericMaster();
J2SMaster.SaveCallback = this.SaveCallback;
J2SMaster.Initialize(jsonMasterKey);
}
J2SMaster = new JsonToSimplGenericMaster();
J2SMaster.SaveCallback = this.SaveCallback;
J2SMaster.Initialize(jsonMasterKey);
}
/// <summary>
/// Gets the user for a passcode
/// </summary>
/// <param name="passcode"></param>
public void GetUserForPasscode(string passcode)
{
{
// Bullshit duplicate code here... These two cases should be the same
// except for https/http and the certificate ignores
if (!UrlBase.StartsWith("https"))
@@ -113,32 +111,32 @@ namespace PepperDash.Core.WebApi.Presets
}
else
if (handler != null)
UserReceived(this, new UserReceivedEventArgs(null, false));
}
UserReceived(this, new UserReceivedEventArgs(null, false));
}
/// <summary>
///
/// </summary>
/// <param name="roomTypeId"></param>
/// <param name="presetNumber"></param>
public void GetPresetForThisUser(int roomTypeId, int presetNumber)
{
if (CurrentUser == null)
{
CrestronConsole.PrintLine("GetPresetForThisUser no user loaded");
return;
}
/// <summary>
///
/// </summary>
/// <param name="roomTypeId"></param>
/// <param name="presetNumber"></param>
public void GetPresetForThisUser(int roomTypeId, int presetNumber)
{
if (CurrentUser == null)
{
CrestronConsole.PrintLine("GetPresetForThisUser no user loaded");
return;
}
var msg = new UserAndRoomMessage
{
UserId = CurrentUser.Id,
RoomTypeId = roomTypeId,
PresetNumber = presetNumber
};
var msg = new UserAndRoomMessage
{
UserId = CurrentUser.Id,
RoomTypeId = roomTypeId,
PresetNumber = presetNumber
};
var handler = PresetReceived;
try
{
try
{
if (!UrlBase.StartsWith("https"))
return;
var req = new HttpsClientRequest();
@@ -179,101 +177,101 @@ namespace PepperDash.Core.WebApi.Presets
if (handler != null)
PresetReceived(this, new PresetReceivedEventArgs(null, false));
}
}
catch (HttpException e)
{
var resp = e.Response;
Debug.Console(1, this, "No preset received (code {0}). Loading default template", resp.Code);
LoadDefaultPresetData();
}
catch (HttpException e)
{
var resp = e.Response;
Debug.Console(1, this, "No preset received (code {0}). Loading default template", resp.Code);
LoadDefaultPresetData();
if (handler != null)
PresetReceived(this, new PresetReceivedEventArgs(null, false));
}
}
}
}
void LoadDefaultPresetData()
{
CurrentPreset = null;
if (!File.Exists(DefaultPresetJsonFilePath))
{
Debug.Console(0, this, "Cannot load default preset file. Saving will not work");
return;
}
using (StreamReader sr = new StreamReader(DefaultPresetJsonFilePath))
{
try
{
var data = sr.ReadToEnd();
J2SMaster.SetJsonWithoutEvaluating(data);
CurrentPreset = new Preset() { Data = data, UserId = CurrentUser.Id };
}
catch (Exception e)
{
Debug.Console(0, this, "Error reading default preset JSON: \r{0}", e);
}
}
}
void LoadDefaultPresetData()
{
CurrentPreset = null;
if (!File.Exists(DefaultPresetJsonFilePath))
{
Debug.Console(0, this, "Cannot load default preset file. Saving will not work");
return;
}
using (StreamReader sr = new StreamReader(DefaultPresetJsonFilePath))
{
try
{
var data = sr.ReadToEnd();
J2SMaster.SetJsonWithoutEvaluating(data);
CurrentPreset = new Preset() { Data = data, UserId = CurrentUser.Id };
}
catch (Exception e)
{
Debug.Console(0, this, "Error reading default preset JSON: \r{0}", e);
}
}
}
/// <summary>
///
/// </summary>
/// <param name="roomTypeId"></param>
/// <param name="presetNumber"></param>
public void SavePresetForThisUser(int roomTypeId, int presetNumber)
{
if (CurrentPreset == null)
LoadDefaultPresetData();
//return;
/// <summary>
///
/// </summary>
/// <param name="roomTypeId"></param>
/// <param name="presetNumber"></param>
public void SavePresetForThisUser(int roomTypeId, int presetNumber)
{
if (CurrentPreset == null)
LoadDefaultPresetData();
//return;
//// A new preset needs to have its numbers set
//if (CurrentPreset.IsNewPreset)
//{
CurrentPreset.UserId = CurrentUser.Id;
CurrentPreset.RoomTypeId = roomTypeId;
CurrentPreset.PresetNumber = presetNumber;
//}
J2SMaster.Save(); // Will trigger callback when ready
}
//// A new preset needs to have its numbers set
//if (CurrentPreset.IsNewPreset)
//{
CurrentPreset.UserId = CurrentUser.Id;
CurrentPreset.RoomTypeId = roomTypeId;
CurrentPreset.PresetNumber = presetNumber;
//}
J2SMaster.Save(); // Will trigger callback when ready
}
/// <summary>
/// After save operation on JSON master happens, send it to server
/// </summary>
/// <param name="json"></param>
void SaveCallback(string json)
{
CurrentPreset.Data = json;
/// <summary>
/// After save operation on JSON master happens, send it to server
/// </summary>
/// <param name="json"></param>
void SaveCallback(string json)
{
CurrentPreset.Data = json;
if (!UrlBase.StartsWith("https"))
return;
var req = new HttpsClientRequest();
req.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Post;
req.Url = new UrlParser(string.Format("{0}/api/presets/addorchange", UrlBase));
req.Header.AddHeader(new HttpsHeader("Content-Type", "application/json"));
req.Header.AddHeader(new HttpsHeader("Accept", "application/json"));
req.ContentString = JsonConvert.SerializeObject(CurrentPreset);
var req = new HttpsClientRequest();
req.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Post;
req.Url = new UrlParser(string.Format("{0}/api/presets/addorchange", UrlBase));
req.Header.AddHeader(new HttpsHeader("Content-Type", "application/json"));
req.Header.AddHeader(new HttpsHeader("Accept", "application/json"));
req.ContentString = JsonConvert.SerializeObject(CurrentPreset);
var client = new HttpsClient();
var client = new HttpsClient();
client.HostVerification = false;
client.PeerVerification = false;
try
{
var resp = client.Dispatch(req);
try
{
var resp = client.Dispatch(req);
// 201=created
// 204=empty content
if (resp.Code == 201)
CrestronConsole.PrintLine("Preset added");
else if (resp.Code == 204)
CrestronConsole.PrintLine("Preset updated");
else if (resp.Code == 209)
CrestronConsole.PrintLine("Preset already exists. Cannot save as new.");
else
CrestronConsole.PrintLine("Preset save failed: {0}\r", resp.Code, resp.ContentString);
}
catch (HttpException e)
{
// 201=created
// 204=empty content
if (resp.Code == 201)
CrestronConsole.PrintLine("Preset added");
else if (resp.Code == 204)
CrestronConsole.PrintLine("Preset updated");
else if (resp.Code == 209)
CrestronConsole.PrintLine("Preset already exists. Cannot save as new.");
else
CrestronConsole.PrintLine("Preset save failed: {0}\r", resp.Code, resp.ContentString);
}
catch (HttpException e)
{
CrestronConsole.PrintLine("Preset save exception {0}", e.Response.Code);
}
}
}
CrestronConsole.PrintLine("Preset save exception {0}", e.Response.Code);
}
}
}
}

View File

@@ -1,7 +1,7 @@
using PepperDash.Core.XSigUtility.Tokens;
using System.Collections.Generic;
using PepperDash.Core.Intersystem.Tokens;
namespace PepperDash.Core.Intersystem.Serialization
namespace PepperDash.Core.XSigUtility.Serialization
{
/// <summary>
/// Interface to determine XSig serialization for an object.

View File

@@ -1,6 +1,6 @@
using System;
namespace PepperDash.Core.Intersystem.Serialization
namespace PepperDash.Core.XSigUtility.Serialization
{
/// <summary>
/// Class to handle this specific exception type

View File

@@ -1,6 +1,6 @@
using System;
namespace PepperDash.Core.Intersystem.Tokens
namespace PepperDash.Core.XSigUtility.Tokens
{
/// <summary>
/// Represents an XSigAnalogToken
@@ -47,8 +47,8 @@ namespace PepperDash.Core.Intersystem.Tokens
public override byte[] GetBytes()
{
return new[] {
(byte)(0xC0 | ((Value & 0xC000) >> 10) | (Index - 1 >> 7)),
(byte)((Index - 1) & 0x7F),
(byte)(0xC0 | (Value & 0xC000) >> 10 | Index - 1 >> 7),
(byte)(Index - 1 & 0x7F),
(byte)((Value & 0x3F80) >> 7),
(byte)(Value & 0x7F)
};

View File

@@ -1,6 +1,6 @@
using System;
namespace PepperDash.Core.Intersystem.Tokens
namespace PepperDash.Core.XSigUtility.Tokens
{
/// <summary>
/// Represents an XSigDigitalToken
@@ -47,8 +47,8 @@ namespace PepperDash.Core.Intersystem.Tokens
public override byte[] GetBytes()
{
return new[] {
(byte)(0x80 | (Value ? 0 : 0x20) | ((Index - 1) >> 7)),
(byte)((Index - 1) & 0x7F)
(byte)(0x80 | (Value ? 0 : 0x20) | Index - 1 >> 7),
(byte)(Index - 1 & 0x7F)
};
}

View File

@@ -1,7 +1,7 @@
using System;
using System.Text;
namespace PepperDash.Core.Intersystem.Tokens
namespace PepperDash.Core.XSigUtility.Tokens
{
/// <summary>
/// Represents an XSigSerialToken
@@ -47,11 +47,11 @@ namespace PepperDash.Core.Intersystem.Tokens
/// <returns></returns>
public override byte[] GetBytes()
{
var serialBytes = String.IsNullOrEmpty(Value) ? new byte[0] : Encoding.GetEncoding(28591).GetBytes(Value);
var serialBytes = string.IsNullOrEmpty(Value) ? new byte[0] : Encoding.GetEncoding(28591).GetBytes(Value);
var xsig = new byte[serialBytes.Length + 3];
xsig[0] = (byte)(0xC8 | (Index - 1 >> 7));
xsig[1] = (byte)((Index - 1) & 0x7F);
xsig[0] = (byte)(0xC8 | Index - 1 >> 7);
xsig[1] = (byte)(Index - 1 & 0x7F);
xsig[xsig.Length - 1] = 0xFF;
Buffer.BlockCopy(serialBytes, 0, xsig, 2, serialBytes.Length);

View File

@@ -1,4 +1,4 @@
namespace PepperDash.Core.Intersystem.Tokens
namespace PepperDash.Core.XSigUtility.Tokens
{
/// <summary>
/// Represents the base class for all XSig datatypes.

View File

@@ -1,4 +1,4 @@
namespace PepperDash.Core.Intersystem.Tokens
namespace PepperDash.Core.XSigUtility.Tokens
{
/// <summary>
/// XSig token types.

View File

@@ -1,8 +1,7 @@
using Crestron.SimplSharp.CrestronIO;
using PepperDash.Core.XSigUtility.Serialization;
using System;
using System.Linq;
using Crestron.SimplSharp.CrestronIO;
using PepperDash.Core.Intersystem.Serialization;
using PepperDash.Core.Intersystem.Tokens;
/*
Digital (2 bytes)
@@ -18,7 +17,7 @@ using PepperDash.Core.Intersystem.Tokens;
11111111 <- denotes end of data
*/
namespace PepperDash.Core.Intersystem
namespace PepperDash.Core.XSigUtility
{
/// <summary>
/// Helper methods for creating XSig byte sequences compatible with the Intersystem Communications (ISC) symbol.

View File

@@ -1,10 +1,10 @@
using Crestron.SimplSharp.CrestronIO;
using PepperDash.Core.XSigUtility.Serialization;
using PepperDash.Core.XSigUtility.Tokens;
using System;
using System.Collections.Generic;
using Crestron.SimplSharp.CrestronIO;
using PepperDash.Core.Intersystem.Serialization;
using PepperDash.Core.Intersystem.Tokens;
namespace PepperDash.Core.Intersystem
namespace PepperDash.Core.XSigUtility
{
/// <summary>
/// XSigToken stream reader.
@@ -56,7 +56,7 @@ namespace PepperDash.Core.Intersystem
var buffer = new byte[2];
stream.Read(buffer, 0, 2);
value = (ushort)((buffer[0] << 8) | buffer[1]);
value = (ushort)(buffer[0] << 8 | buffer[1]);
return true;
}
@@ -73,7 +73,7 @@ namespace PepperDash.Core.Intersystem
if ((prefix & 0xF880) == 0xC800) // Serial data
{
var index = ((prefix & 0x0700) >> 1) | (prefix & 0x7F);
var index = (prefix & 0x0700) >> 1 | prefix & 0x7F;
var n = 0;
const int maxSerialDataLength = 252;
var chars = new char[maxSerialDataLength];
@@ -82,7 +82,7 @@ namespace PepperDash.Core.Intersystem
{
if (ch == -1) // Reached end of stream without end of data marker
return null;
chars[n++] = (char)ch;
}
@@ -95,14 +95,14 @@ namespace PepperDash.Core.Intersystem
if (!TryReadUInt16BE(_stream, out data))
return null;
var index = ((prefix & 0x0700) >> 1) | (prefix & 0x7F);
var value = ((prefix & 0x3000) << 2) | ((data & 0x7F00) >> 1) | (data & 0x7F);
var index = (prefix & 0x0700) >> 1 | prefix & 0x7F;
var value = (prefix & 0x3000) << 2 | (data & 0x7F00) >> 1 | data & 0x7F;
return new XSigAnalogToken((ushort)(index + 1), (ushort)value);
}
if ((prefix & 0xC080) == 0x8000) // Digital data
{
var index = ((prefix & 0x1F00) >> 1) | (prefix & 0x7F);
var index = (prefix & 0x1F00) >> 1 | prefix & 0x7F;
var value = (prefix & 0x2000) == 0;
return new XSigDigitalToken((ushort)(index + 1), value);
}

View File

@@ -1,11 +1,11 @@
using System;
using System.Linq;
using System.Collections.Generic;
using Crestron.SimplSharp.CrestronIO;
using PepperDash.Core.Intersystem.Serialization;
using PepperDash.Core.Intersystem.Tokens;
using PepperDash.Core.XSigUtility.Serialization;
using PepperDash.Core.XSigUtility.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
namespace PepperDash.Core.Intersystem
namespace PepperDash.Core.XSigUtility
{
/// <summary>
/// XSigToken stream writer.