diff --git a/src/Pepperdash Core/Comm/CommunicationGather.cs b/src/Pepperdash Core/Comm/CommunicationGather.cs
index 9ffe826..970ba38 100644
--- a/src/Pepperdash Core/Comm/CommunicationGather.cs
+++ b/src/Pepperdash Core/Comm/CommunicationGather.cs
@@ -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
{
- ///
- /// Defines the string event handler for line events on the gather
- ///
- ///
- public delegate void LineReceivedHandler(string text);
+ ///
+ /// Defines the string event handler for line events on the gather
+ ///
+ ///
+ public delegate void LineReceivedHandler(string text);
- ///
- /// Attaches to IBasicCommunication as a text gather
- ///
- public class CommunicationGather
- {
- ///
- /// Event that fires when a line is received from the IBasicCommunication source.
- /// The event merely contains the text, not an EventArgs type class.
- ///
- public event EventHandler LineReceived;
+ ///
+ /// Attaches to IBasicCommunication as a text gather
+ ///
+ public class CommunicationGather
+ {
+ ///
+ /// Event that fires when a line is received from the IBasicCommunication source.
+ /// The event merely contains the text, not an EventArgs type class.
+ ///
+ public event EventHandler LineReceived;
- ///
- /// The communication port that this gathers on
- ///
+ ///
+ /// The communication port that this gathers on
+ ///
public ICommunicationReceiver Port { get; private set; }
- ///
- /// Default false. If true, the delimiter will be included in the line output
- /// events
- ///
- public bool IncludeDelimiter { get; set; }
+ ///
+ /// Default false. If true, the delimiter will be included in the line output
+ /// events
+ ///
+ public bool IncludeDelimiter { get; set; }
- ///
- /// For receive buffer
- ///
- StringBuilder ReceiveBuffer = new StringBuilder();
+ ///
+ /// For receive buffer
+ ///
+ StringBuilder ReceiveBuffer = new StringBuilder();
- ///
- /// Delimiter, like it says!
- ///
- char Delimiter;
+ ///
+ /// Delimiter, like it says!
+ ///
+ char Delimiter;
- string[] StringDelimiters;
+ string[] StringDelimiters;
- ///
- /// Constructor for using a char delimiter
- ///
- ///
- ///
- public CommunicationGather(ICommunicationReceiver port, char delimiter)
- {
- Port = port;
- Delimiter = delimiter;
- port.TextReceived += new EventHandler(Port_TextReceived);
- }
+ ///
+ /// Constructor for using a char delimiter
+ ///
+ ///
+ ///
+ public CommunicationGather(ICommunicationReceiver port, char delimiter)
+ {
+ Port = port;
+ Delimiter = delimiter;
+ port.TextReceived += new EventHandler(Port_TextReceived);
+ }
- ///
- /// Constructor for using a single string delimiter
- ///
- ///
- ///
+ ///
+ /// Constructor for using a single string delimiter
+ ///
+ ///
+ ///
public CommunicationGather(ICommunicationReceiver port, string delimiter)
- :this(port, new string[] { delimiter} )
- {
- }
+ : this(port, new string[] { delimiter })
+ {
+ }
///
/// Constructor for using an array of string delimiters
@@ -84,57 +78,57 @@ namespace PepperDash.Core
port.TextReceived += Port_TextReceivedStringDelimiter;
}
- ///
- /// Disconnects this gather from the Port's TextReceived event. This will not fire LineReceived
- /// after the this call.
- ///
- public void Stop()
- {
- Port.TextReceived -= Port_TextReceived;
- Port.TextReceived -= Port_TextReceivedStringDelimiter;
- }
+ ///
+ /// Disconnects this gather from the Port's TextReceived event. This will not fire LineReceived
+ /// after the this call.
+ ///
+ public void Stop()
+ {
+ Port.TextReceived -= Port_TextReceived;
+ Port.TextReceived -= Port_TextReceivedStringDelimiter;
+ }
- ///
- /// Handler for raw data coming from port
- ///
- 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]);
- }
- }
- }
+ ///
+ /// Handler for raw data coming from port
+ ///
+ 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]);
+ }
+ }
+ }
- ///
- ///
- ///
- ///
- ///
- 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();
+ ///
+ ///
+ ///
+ ///
+ ///
+ 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]);
}
- }
- }
+ }
+ }
- ///
- /// Deconstructor. Disconnects from port TextReceived events.
- ///
- ~CommunicationGather()
- {
- Stop();
- }
- }
+ ///
+ /// Deconstructor. Disconnects from port TextReceived events.
+ ///
+ ~CommunicationGather()
+ {
+ Stop();
+ }
+ }
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/Comm/CommunicationStreamDebugging.cs b/src/Pepperdash Core/Comm/CommunicationStreamDebugging.cs
index 0a38d82..fc0d27c 100644
--- a/src/Pepperdash Core/Comm/CommunicationStreamDebugging.cs
+++ b/src/Pepperdash Core/Comm/CommunicationStreamDebugging.cs
@@ -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
{
///
/// 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;
}
}
///
/// Indicates that receive stream debugging is enabled
///
- public bool RxStreamDebuggingIsEnabled{ get; private set; }
+ public bool RxStreamDebuggingIsEnabled { get; private set; }
///
/// Indicates that transmit stream debugging is enabled
@@ -102,7 +99,7 @@ namespace PepperDash.Core
TxStreamDebuggingIsEnabled = true;
Debug.SetDeviceDebugSettings(ParentDeviceKey, setting);
-
+
}
///
@@ -144,7 +141,7 @@ namespace PepperDash.Core
///
/// Debug received data
///
- Rx = 1,
+ Rx = 1,
///
/// Debug transmitted data
///
diff --git a/src/Pepperdash Core/Comm/ControlPropertiesConfig.cs b/src/Pepperdash Core/Comm/ControlPropertiesConfig.cs
index 288f130..578cdad 100644
--- a/src/Pepperdash Core/Comm/ControlPropertiesConfig.cs
+++ b/src/Pepperdash Core/Comm/ControlPropertiesConfig.cs
@@ -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
{
///
/// Config properties that indicate how to communicate with a device for control
diff --git a/src/Pepperdash Core/Comm/EventArgs.cs b/src/Pepperdash Core/Comm/EventArgs.cs
index cf76d6b..0039264 100644
--- a/src/Pepperdash Core/Comm/EventArgs.cs
+++ b/src/Pepperdash Core/Comm/EventArgs.cs
@@ -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
{
///
/// Delegate for notifying of socket status changes
@@ -28,7 +23,7 @@ namespace PepperDash.Core
/// EventArgs class for socket status changes
///
public class GenericSocketStatusChageEventArgs : EventArgs
- {
+ {
///
///
///
@@ -39,13 +34,13 @@ namespace PepperDash.Core
///
///
public GenericSocketStatusChageEventArgs(ISocketStatus client)
- {
- Client = client;
- }
- ///
- /// S+ Constructor
- ///
- public GenericSocketStatusChageEventArgs() { }
+ {
+ Client = client;
+ }
+ ///
+ /// S+ Constructor
+ ///
+ public GenericSocketStatusChageEventArgs() { }
}
///
@@ -72,10 +67,10 @@ namespace PepperDash.Core
{
State = state;
}
- ///
- /// S+ Constructor
- ///
- public GenericTcpServerStateChangedEventArgs() { }
+ ///
+ /// S+ Constructor
+ ///
+ public GenericTcpServerStateChangedEventArgs() { }
}
///
@@ -126,10 +121,10 @@ namespace PepperDash.Core
ReceivedFromClientIndex = clientIndex;
ClientStatus = clientStatus;
}
- ///
- /// S+ Constructor
- ///
- public GenericTcpServerSocketStatusChangeEventArgs() { }
+ ///
+ /// S+ Constructor
+ ///
+ public GenericTcpServerSocketStatusChangeEventArgs() { }
}
///
@@ -146,12 +141,12 @@ namespace PepperDash.Core
///
///
public ushort ReceivedFromClientIndexShort
- {
- get
- {
- return (ushort)ReceivedFromClientIndex;
- }
- }
+ {
+ get
+ {
+ return (ushort)ReceivedFromClientIndex;
+ }
+ }
///
///
@@ -177,10 +172,10 @@ namespace PepperDash.Core
Text = text;
ReceivedFromClientIndex = clientIndex;
}
- ///
- /// S+ Constructor
- ///
- public GenericTcpServerCommMethodReceiveTextArgs() { }
+ ///
+ /// S+ Constructor
+ ///
+ public GenericTcpServerCommMethodReceiveTextArgs() { }
}
///
@@ -201,10 +196,10 @@ namespace PepperDash.Core
{
IsReady = isReady;
}
- ///
- /// S+ Constructor
- ///
- public GenericTcpServerClientReadyForcommunicationsEventArgs() { }
+ ///
+ /// S+ Constructor
+ ///
+ public GenericTcpServerClientReadyForcommunicationsEventArgs() { }
}
///
@@ -246,6 +241,6 @@ namespace PepperDash.Core
}
-
+
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/Comm/FINISH CommStatic.cs b/src/Pepperdash Core/Comm/FINISH CommStatic.cs
index 70f105e..43dec7b 100644
--- a/src/Pepperdash Core/Comm/FINISH CommStatic.cs
+++ b/src/Pepperdash Core/Comm/FINISH CommStatic.cs
@@ -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
{
///
/// 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
///
public static void AddSocket(ISocketStatus socket)
{
- if(!Sockets.Contains(socket))
+ if (!Sockets.Contains(socket))
Sockets.Add(socket);
}
diff --git a/src/Pepperdash Core/Comm/GenericHttpSseClient.cs b/src/Pepperdash Core/Comm/GenericHttpSseClient.cs
index 6992ef7..3549900 100644
--- a/src/Pepperdash Core/Comm/GenericHttpSseClient.cs
+++ b/src/Pepperdash Core/Comm/GenericHttpSseClient.cs
@@ -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
{
///
/// Client for communicating with an HTTP Server Side Event pattern
///
- public class GenericHttpSseClient : ICommunicationReceiver
+ public class GenericHttpSseClient : ICommunicationReceiver
{
///
/// Notifies when bytes have been received
@@ -90,11 +89,11 @@ namespace PepperDash.Core
///
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);
diff --git a/src/Pepperdash Core/Comm/GenericSecureTcpIpClient.cs b/src/Pepperdash Core/Comm/GenericSecureTcpIpClient.cs
index ec166f3..cf5cc0e 100644
--- a/src/Pepperdash Core/Comm/GenericSecureTcpIpClient.cs
+++ b/src/Pepperdash Core/Comm/GenericSecureTcpIpClient.cs
@@ -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
{
///
/// 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.
///
public event EventHandler TextReceivedQueueInvoke;
-
+
///
/// 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
///
/// Simpl+ Heartbeat Analog value in seconds
///
- 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
///
@@ -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
diff --git a/src/Pepperdash Core/Comm/GenericSecureTcpIpClient_ForServer.cs b/src/Pepperdash Core/Comm/GenericSecureTcpIpClient_ForServer.cs
index f99c16d..1fe4937 100644
--- a/src/Pepperdash Core/Comm/GenericSecureTcpIpClient_ForServer.cs
+++ b/src/Pepperdash Core/Comm/GenericSecureTcpIpClient_ForServer.cs
@@ -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
{
///
/// Generic secure TCP/IP client for server
@@ -250,7 +249,7 @@ namespace PepperDash.Core
///
/// Simpl+ Heartbeat Analog value in seconds
///
- 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));
diff --git a/src/Pepperdash Core/Comm/GenericSecureTcpIpServer.cs b/src/Pepperdash Core/Comm/GenericSecureTcpIpServer.cs
index c29f96b..ea48135 100644
--- a/src/Pepperdash Core/Comm/GenericSecureTcpIpServer.cs
+++ b/src/Pepperdash Core/Comm/GenericSecureTcpIpServer.cs
@@ -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
{
///
/// Generic secure TCP/IP server
@@ -257,7 +256,7 @@ namespace PepperDash.Core
///
/// Simpl+ Heartbeat Analog value in seconds
///
- public ushort HeartbeatRequiredIntervalInSeconds { set { HeartbeatRequiredIntervalMs = (value * 1000); } }
+ public ushort HeartbeatRequiredIntervalInSeconds { set { HeartbeatRequiredIntervalMs = value * 1000; } }
///
/// 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
///
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);
+ }
}
///
@@ -528,7 +527,7 @@ namespace PepperDash.Core
OnServerStateChange(SecureServer.State); //State shows both listening and connected
}
- // var o = new { };
+ // var o = new { };
}
///
@@ -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;
diff --git a/src/Pepperdash Core/Comm/GenericSshClient.cs b/src/Pepperdash Core/Comm/GenericSshClient.cs
index 51ba8f4..e11ed2d 100644
--- a/src/Pepperdash Core/Comm/GenericSshClient.cs
+++ b/src/Pepperdash Core/Comm/GenericSshClient.cs
@@ -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
{
- ///
- ///
- ///
+ ///
+ ///
+ ///
public class GenericSshClient : Device, ISocketStatusWithStreamDebugging, IAutoReconnect
- {
- private const string SPlusKey = "Uninitialized SshClient";
+ {
+ private const string SPlusKey = "Uninitialized SshClient";
///
/// Object to enable stream debugging
///
public CommunicationStreamDebugging StreamDebugging { get; private set; }
- ///
- /// Event that fires when data is received. Delivers args with byte array
- ///
- public event EventHandler BytesReceived;
+ ///
+ /// Event that fires when data is received. Delivers args with byte array
+ ///
+ public event EventHandler BytesReceived;
- ///
- /// Event that fires when data is received. Delivered as text.
- ///
- public event EventHandler TextReceived;
+ ///
+ /// Event that fires when data is received. Delivered as text.
+ ///
+ public event EventHandler TextReceived;
- ///
- /// Event when the connection status changes.
- ///
- public event EventHandler ConnectionChange;
+ ///
+ /// Event when the connection status changes.
+ ///
+ public event EventHandler ConnectionChange;
/////
/////
/////
//public event GenericSocketStatusChangeEventDelegate SocketStatusChange;
- ///
- /// Address of server
- ///
- public string Hostname { get; set; }
+ ///
+ /// Address of server
+ ///
+ public string Hostname { get; set; }
- ///
- /// Port on server
- ///
- public int Port { get; set; }
+ ///
+ /// Port on server
+ ///
+ public int Port { get; set; }
- ///
- /// Username for server
- ///
- public string Username { get; set; }
+ ///
+ /// Username for server
+ ///
+ public string Username { get; set; }
- ///
- /// And... Password for server. That was worth documenting!
- ///
- public string Password { get; set; }
+ ///
+ /// And... Password for server. That was worth documenting!
+ ///
+ public string Password { get; set; }
- ///
- /// True when the server is connected - when status == 2.
- ///
- public bool IsConnected
- {
- // returns false if no client or not connected
+ ///
+ /// True when the server is connected - when status == 2.
+ ///
+ public bool IsConnected
+ {
+ // returns false if no client or not connected
get { return Client != null && ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED; }
- }
+ }
- ///
- /// S+ helper for IsConnected
- ///
- public ushort UIsConnected
- {
- get { return (ushort)(IsConnected ? 1 : 0); }
- }
+ ///
+ /// S+ helper for IsConnected
+ ///
+ public ushort UIsConnected
+ {
+ get { return (ushort)(IsConnected ? 1 : 0); }
+ }
- ///
- ///
- ///
- public SocketStatus ClientStatus
- {
- get { return _ClientStatus; }
- private set
- {
- if (_ClientStatus == value)
- return;
- _ClientStatus = value;
- OnConnectionChange();
- }
- }
- SocketStatus _ClientStatus;
+ ///
+ ///
+ ///
+ public SocketStatus ClientStatus
+ {
+ get { return _ClientStatus; }
+ private set
+ {
+ if (_ClientStatus == value)
+ return;
+ _ClientStatus = value;
+ OnConnectionChange();
+ }
+ }
+ SocketStatus _ClientStatus;
- ///
- /// Contains the familiar Simpl analog status values. This drives the ConnectionChange event
- /// and IsConnected with be true when this == 2.
- ///
- public ushort UStatus
- {
- get { return (ushort)_ClientStatus; }
- }
+ ///
+ /// Contains the familiar Simpl analog status values. This drives the ConnectionChange event
+ /// and IsConnected with be true when this == 2.
+ ///
+ public ushort UStatus
+ {
+ get { return (ushort)_ClientStatus; }
+ }
- ///
- /// Determines whether client will attempt reconnection on failure. Default is true
- ///
- public bool AutoReconnect { get; set; }
+ ///
+ /// Determines whether client will attempt reconnection on failure. Default is true
+ ///
+ public bool AutoReconnect { get; set; }
- ///
- /// Will be set and unset by connect and disconnect only
- ///
- public bool ConnectEnabled { get; private set; }
+ ///
+ /// Will be set and unset by connect and disconnect only
+ ///
+ public bool ConnectEnabled { get; private set; }
- ///
- /// S+ helper for AutoReconnect
- ///
- public ushort UAutoReconnect
- {
- get { return (ushort)(AutoReconnect ? 1 : 0); }
- set { AutoReconnect = value == 1; }
- }
+ ///
+ /// S+ helper for AutoReconnect
+ ///
+ public ushort UAutoReconnect
+ {
+ get { return (ushort)(AutoReconnect ? 1 : 0); }
+ set { AutoReconnect = value == 1; }
+ }
- ///
- /// Millisecond value, determines the timeout period in between reconnect attempts.
- /// Set to 5000 by default
- ///
- public int AutoReconnectIntervalMs { get; set; }
+ ///
+ /// Millisecond value, determines the timeout period in between reconnect attempts.
+ /// Set to 5000 by default
+ ///
+ 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;
- ///
- /// Typical constructor.
- ///
- public GenericSshClient(string key, string hostname, int port, string username, string password) :
- base(key)
- {
+ ///
+ /// Typical constructor.
+ ///
+ 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);
+ }
- ///
- /// S+ Constructor - Must set all properties before calling Connect
- ///
- public GenericSshClient()
- : base(SPlusKey)
- {
- CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
- AutoReconnectIntervalMs = 5000;
+ ///
+ /// S+ Constructor - Must set all properties before calling Connect
+ ///
+ 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);
- }
+ }
- ///
- /// Just to help S+ set the key
- ///
- public void Initialize(string key)
- {
- Key = key;
- }
+ ///
+ /// Just to help S+ set the key
+ ///
+ public void Initialize(string key)
+ {
+ Key = key;
+ }
- ///
- /// Handles closing this up when the program shuts down
- ///
- void CrestronEnvironment_ProgramStatusEventHandler(eProgramStatusEventType programEventType)
- {
- if (programEventType == eProgramStatusEventType.Stopping)
- {
- if (Client != null)
- {
- Debug.Console(1, this, "Program stopping. Closing connection");
+ ///
+ /// Handles closing this up when the program shuts down
+ ///
+ void CrestronEnvironment_ProgramStatusEventHandler(eProgramStatusEventType programEventType)
+ {
+ if (programEventType == eProgramStatusEventType.Stopping)
+ {
+ if (Client != null)
+ {
+ Debug.Console(1, this, "Program stopping. Closing connection");
Disconnect();
- }
- }
- }
+ }
+ }
+ }
- ///
- /// Connect to the server, using the provided properties.
- ///
- public void Connect()
+ ///
+ /// Connect to the server, using the provided properties.
+ ///
+ 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
}
}
- ///
- /// Disconnect the clients and put away it's resources.
- ///
- public void Disconnect()
- {
- ConnectEnabled = false;
- // Stop trying reconnects, if we are
- if (ReconnectTimer != null)
- {
- ReconnectTimer.Stop();
- ReconnectTimer = null;
- }
+ ///
+ /// Disconnect the clients and put away it's resources.
+ ///
+ public void Disconnect()
+ {
+ ConnectEnabled = false;
+ // Stop trying reconnects, if we are
+ if (ReconnectTimer != null)
+ {
+ ReconnectTimer.Stop();
+ ReconnectTimer = null;
+ }
KillClient(SocketStatus.SOCKET_STATUS_BROKEN_LOCALLY);
- }
+ }
///
/// 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
}
}
- ///
- /// Anything to do with reestablishing connection on failures
- ///
- void HandleConnectionFailure()
- {
+ ///
+ /// Anything to do with reestablishing connection on failures
+ ///
+ 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));
+ }
+ }
+ }
///
/// Kills the stream
///
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");
- }
- }
+ }
+ }
- ///
- /// Handles the keyboard interactive authentication, should it be required.
- ///
- void kauth_AuthenticationPrompt(object sender, AuthenticationPromptEventArgs e)
- {
- foreach (AuthenticationPrompt prompt in e.Prompts)
- if (prompt.Request.IndexOf("Password:", StringComparison.InvariantCultureIgnoreCase) != -1)
- prompt.Response = Password;
- }
-
- ///
- /// Handler for data receive on ShellStream. Passes data across to queue for line parsing.
- ///
- 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);
- }
+ ///
+ /// Handles the keyboard interactive authentication, should it be required.
+ ///
+ void kauth_AuthenticationPrompt(object sender, AuthenticationPromptEventArgs e)
+ {
+ foreach (AuthenticationPrompt prompt in e.Prompts)
+ if (prompt.Request.IndexOf("Password:", StringComparison.InvariantCultureIgnoreCase) != -1)
+ prompt.Response = Password;
+ }
+
+ ///
+ /// Handler for data receive on ShellStream. Passes data across to queue for line parsing.
+ ///
+ 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));
}
- }
- }
+ }
+ }
- ///
- /// Error event handler for client events - disconnect, etc. Will forward those events via ConnectionChange
- /// event
- ///
- void Client_ErrorOccurred(object sender, Crestron.SimplSharp.Ssh.Common.ExceptionEventArgs e)
- {
+ ///
+ /// Error event handler for client events - disconnect, etc. Will forward those events via ConnectionChange
+ /// event
+ ///
+ 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);
}
});
- }
+ }
- ///
- /// Helper for ConnectionChange event
- ///
- void OnConnectionChange()
- {
- if (ConnectionChange != null)
- ConnectionChange(this, new GenericSocketStatusChageEventArgs(this));
- }
+ ///
+ /// Helper for ConnectionChange event
+ ///
+ void OnConnectionChange()
+ {
+ if (ConnectionChange != null)
+ ConnectionChange(this, new GenericSocketStatusChageEventArgs(this));
+ }
- #region IBasicCommunication Members
+ #region IBasicCommunication Members
- ///
- /// Sends text to the server
- ///
- ///
- public void SendText(string text)
- {
- try
- {
+ ///
+ /// Sends text to the server
+ ///
+ ///
+ 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");
+ }
+ }
///
/// Sends Bytes to the server
///
///
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
+ }
- //*****************************************************************************************************
- //*****************************************************************************************************
- ///
- /// Fired when connection changes
- ///
- public class SshConnectionChangeEventArgs : EventArgs
- {
+ //*****************************************************************************************************
+ //*****************************************************************************************************
+ ///
+ /// Fired when connection changes
+ ///
+ public class SshConnectionChangeEventArgs : EventArgs
+ {
///
/// Connection State
///
@@ -552,10 +552,10 @@ namespace PepperDash.Core
///
public ushort Status { get { return Client.UStatus; } }
- ///
+ ///
/// S+ Constructor
- ///
- public SshConnectionChangeEventArgs() { }
+ ///
+ public SshConnectionChangeEventArgs() { }
///
/// EventArgs class
@@ -563,9 +563,9 @@ namespace PepperDash.Core
/// Connection State
/// The Client
public SshConnectionChangeEventArgs(bool isConnected, GenericSshClient client)
- {
- IsConnected = isConnected;
- Client = client;
- }
- }
+ {
+ IsConnected = isConnected;
+ Client = client;
+ }
+ }
}
diff --git a/src/Pepperdash Core/Comm/GenericTcpIpClient.cs b/src/Pepperdash Core/Comm/GenericTcpIpClient.cs
index 277aecd..a4bddf9 100644
--- a/src/Pepperdash Core/Comm/GenericTcpIpClient.cs
+++ b/src/Pepperdash Core/Comm/GenericTcpIpClient.cs
@@ -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
{
///
/// A class to handle basic TCP/IP communications with a server
@@ -21,44 +21,44 @@ namespace PepperDash.Core
///
public CommunicationStreamDebugging StreamDebugging { get; private set; }
- ///
- /// Fires when data is received from the server and returns it as a Byte array
- ///
- public event EventHandler BytesReceived;
+ ///
+ /// Fires when data is received from the server and returns it as a Byte array
+ ///
+ public event EventHandler BytesReceived;
- ///
- /// Fires when data is received from the server and returns it as text
- ///
- public event EventHandler TextReceived;
+ ///
+ /// Fires when data is received from the server and returns it as text
+ ///
+ public event EventHandler TextReceived;
- ///
- ///
- ///
- //public event GenericSocketStatusChangeEventDelegate SocketStatusChange;
- public event EventHandler ConnectionChange;
+ ///
+ ///
+ ///
+ //public event GenericSocketStatusChangeEventDelegate SocketStatusChange;
+ public event EventHandler ConnectionChange;
- private string _hostname;
+ private string _hostname;
///
/// Address of server
///
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;
+ }
+ }
+ }
///
/// Port on server
@@ -80,19 +80,19 @@ namespace PepperDash.Core
///
public int BufferSize { get; set; }
- ///
- /// The actual client class
- ///
- private TCPClient _client;
+ ///
+ /// The actual client class
+ ///
+ private TCPClient _client;
- ///
- /// Bool showing if socket is connected
- ///
- public bool IsConnected
- {
- get { return _client != null && _client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED; }
+ ///
+ /// Bool showing if socket is connected
+ ///
+ public bool IsConnected
+ {
+ get { return _client != null && _client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED; }
}
-
+
///
/// S+ helper for IsConnected
///
@@ -101,15 +101,15 @@ namespace PepperDash.Core
get { return (ushort)(IsConnected ? 1 : 0); }
}
- ///
- /// _client socket status Read only
- ///
- public SocketStatus ClientStatus
- {
- get
+ ///
+ /// _client socket status Read only
+ ///
+ public SocketStatus ClientStatus
+ {
+ get
{
- return _client == null ? SocketStatus.SOCKET_STATUS_NO_CONNECT : _client.ClientStatus;
- }
+ return _client == null ? SocketStatus.SOCKET_STATUS_NO_CONNECT : _client.ClientStatus;
+ }
}
///
@@ -121,26 +121,26 @@ namespace PepperDash.Core
get { return (ushort)ClientStatus; }
}
- ///
+ ///
/// Status text shows the message associated with socket status
- ///
- public string ClientStatusText { get { return ClientStatus.ToString(); } }
+ ///
+ public string ClientStatusText { get { return ClientStatus.ToString(); } }
- ///
- /// Ushort representation of client status
- ///
+ ///
+ /// Ushort representation of client status
+ ///
[Obsolete]
- public ushort UClientStatus { get { return (ushort)ClientStatus; } }
+ public ushort UClientStatus { get { return (ushort)ClientStatus; } }
- ///
- /// Connection failure reason
- ///
- public string ConnectionFailure { get { return ClientStatus.ToString(); } }
+ ///
+ /// Connection failure reason
+ ///
+ public string ConnectionFailure { get { return ClientStatus.ToString(); } }
- ///
- /// bool to track if auto reconnect should be set on the socket
- ///
- public bool AutoReconnect { get; set; }
+ ///
+ /// bool to track if auto reconnect should be set on the socket
+ ///
+ public bool AutoReconnect { get; set; }
///
/// S+ helper for AutoReconnect
@@ -151,29 +151,29 @@ namespace PepperDash.Core
set { AutoReconnect = value == 1; }
}
- ///
- /// Milliseconds to wait before attempting to reconnect. Defaults to 5000
- ///
- public int AutoReconnectIntervalMs { get; set; }
+ ///
+ /// Milliseconds to wait before attempting to reconnect. Defaults to 5000
+ ///
+ public int AutoReconnectIntervalMs { get; set; }
- ///
- /// Set only when the disconnect method is called
- ///
- bool DisconnectCalledByUser;
+ ///
+ /// Set only when the disconnect method is called
+ ///
+ bool DisconnectCalledByUser;
- ///
- ///
- ///
- public bool Connected
- {
- get { return _client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED; }
- }
+ ///
+ ///
+ ///
+ 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;
///
/// Constructor
@@ -183,8 +183,8 @@ namespace PepperDash.Core
///
///
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+
///
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);
- }
+ }
///
/// Just to help S+ set the key
@@ -257,22 +257,22 @@ namespace PepperDash.Core
///
///
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;
+ }
///
/// Attempts to connect to the server
///
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
///
public void Disconnect()
- {
+ {
try
{
connectLock.Enter();
@@ -353,7 +353,7 @@ namespace PepperDash.Core
{
connectLock.Leave();
}
- }
+ }
///
/// Does the actual disconnect business
@@ -373,7 +373,7 @@ namespace PepperDash.Core
///
///
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);
}
- }
+ }
///
/// Disconnects, waits and attemtps to connect again
///
void WaitAndTryReconnect()
- {
+ {
CrestronInvoke.BeginInvoke(o =>
{
try
@@ -407,7 +407,7 @@ namespace PepperDash.Core
connectLock.Leave();
}
});
- }
+ }
///
/// Recieves incoming data
@@ -415,7 +415,7 @@ namespace PepperDash.Core
///
///
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);
}
- }
+ }
- ///
- /// General send method
- ///
- public void SendText(string text)
- {
- var bytes = Encoding.GetEncoding(28591).GetBytes(text);
- // Check debug level before processing byte array
+ ///
+ /// General send method
+ ///
+ 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);
+ }
- ///
- /// This is useful from console and...?
- ///
- public void SendEscapedText(string text)
- {
- var unescapedText = Regex.Replace(text, @"\\x([0-9a-fA-F][0-9a-fA-F])", s =>
- {
- var hex = s.Groups[1].Value;
- return ((char)Convert.ToByte(hex, 16)).ToString();
- });
- SendText(unescapedText);
- }
+ ///
+ /// This is useful from console and...?
+ ///
+ public void SendEscapedText(string text)
+ {
+ var unescapedText = Regex.Replace(text, @"\\x([0-9a-fA-F][0-9a-fA-F])", s =>
+ {
+ var hex = s.Groups[1].Value;
+ return ((char)Convert.ToByte(hex, 16)).ToString();
+ });
+ SendText(unescapedText);
+ }
///
/// Sends Bytes to the server
///
///
public void SendBytes(byte[] bytes)
- {
+ {
if (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);
+ }
///
/// Socket Status Change Handler
@@ -491,7 +491,7 @@ namespace PepperDash.Core
///
///
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));
+ }
+ }
///
/// Configuration properties for TCP/SSH Connections
///
public class TcpSshPropertiesConfig
- {
+ {
///
/// Address to connect to
///
[JsonProperty(Required = Required.Always)]
- public string Address { get; set; }
-
+ public string Address { get; set; }
+
///
/// Port to connect to
///
- [JsonProperty(Required = Required.Always)]
- public int Port { get; set; }
-
+ [JsonProperty(Required = Required.Always)]
+ public int Port { get; set; }
+
///
/// Username credential
///
- public string Username { get; set; }
+ public string Username { get; set; }
///
/// Passord credential
///
public string Password { get; set; }
- ///
- /// Defaults to 32768
- ///
- public int BufferSize { get; set; }
+ ///
+ /// Defaults to 32768
+ ///
+ public int BufferSize { get; set; }
- ///
- /// Defaults to true
- ///
- public bool AutoReconnect { get; set; }
+ ///
+ /// Defaults to true
+ ///
+ public bool AutoReconnect { get; set; }
- ///
- /// Defaults to 5000ms
- ///
- public int AutoReconnectIntervalMs { get; set; }
+ ///
+ /// Defaults to 5000ms
+ ///
+ public int AutoReconnectIntervalMs { get; set; }
///
/// Default constructor
///
public TcpSshPropertiesConfig()
- {
- BufferSize = 32768;
- AutoReconnect = true;
- AutoReconnectIntervalMs = 5000;
+ {
+ BufferSize = 32768;
+ AutoReconnect = true;
+ AutoReconnectIntervalMs = 5000;
Username = "";
Password = "";
- }
+ }
- }
+ }
}
diff --git a/src/Pepperdash Core/Comm/GenericTcpIpClient_ForServer.cs b/src/Pepperdash Core/Comm/GenericTcpIpClient_ForServer.cs
index df277f0..81e4bcf 100644
--- a/src/Pepperdash Core/Comm/GenericTcpIpClient_ForServer.cs
+++ b/src/Pepperdash Core/Comm/GenericTcpIpClient_ForServer.cs
@@ -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
{
///
/// 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
}
-
+
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/Comm/GenericTcpIpServer.cs b/src/Pepperdash Core/Comm/GenericTcpIpServer.cs
index 1b8a360..c4ac326 100644
--- a/src/Pepperdash Core/Comm/GenericTcpIpServer.cs
+++ b/src/Pepperdash Core/Comm/GenericTcpIpServer.cs
@@ -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
{
///
/// Generic TCP/IP server device
@@ -238,7 +237,7 @@ namespace PepperDash.Core
///
/// Simpl+ Heartbeat Analog value in seconds
///
- public ushort HeartbeatRequiredIntervalInSeconds { set { HeartbeatRequiredIntervalMs = (value * 1000); } }
+ public ushort HeartbeatRequiredIntervalInSeconds { set { HeartbeatRequiredIntervalMs = value * 1000; } }
///
/// 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
///
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;
diff --git a/src/Pepperdash Core/Comm/GenericUdpServer.cs b/src/Pepperdash Core/Comm/GenericUdpServer.cs
index e83d5b6..5a7af34 100644
--- a/src/Pepperdash Core/Comm/GenericUdpServer.cs
+++ b/src/Pepperdash Core/Comm/GenericUdpServer.cs
@@ -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
{
///
/// Generic UDP Server device
@@ -131,7 +123,7 @@ namespace PepperDash.Core
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
CrestronEnvironment.EthernetEventHandler += new EthernetEventHandler(CrestronEnvironment_EthernetEventHandler);
}
-
+
///
///
///
@@ -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
///
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
///
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
///
///
public class GenericUdpReceiveTextExtraArgs : EventArgs
- {
+ {
///
///
///
@@ -343,7 +335,7 @@ namespace PepperDash.Core
///
///
///
- public int Port { get; private set; }
+ public int Port { get; private set; }
///
///
///
@@ -357,18 +349,18 @@ namespace PepperDash.Core
///
///
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;
+ }
- ///
- /// Stupid S+ Constructor
- ///
- public GenericUdpReceiveTextExtraArgs() { }
- }
+ ///
+ /// Stupid S+ Constructor
+ ///
+ public GenericUdpReceiveTextExtraArgs() { }
+ }
///
///
diff --git a/src/Pepperdash Core/Comm/QscCoreDoubleTcpIpClient.cs b/src/Pepperdash Core/Comm/QscCoreDoubleTcpIpClient.cs
index 7011325..6ea6076 100644
--- a/src/Pepperdash Core/Comm/QscCoreDoubleTcpIpClient.cs
+++ b/src/Pepperdash Core/Comm/QscCoreDoubleTcpIpClient.cs
@@ -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
{
///
/// Allows for two simultaneous TCP clients to connect to a redundant pair of QSC Core DSPs and manages
diff --git a/src/Pepperdash Core/Comm/TcpClientConfigObject.cs b/src/Pepperdash Core/Comm/TcpClientConfigObject.cs
index 0539441..241b32b 100644
--- a/src/Pepperdash Core/Comm/TcpClientConfigObject.cs
+++ b/src/Pepperdash Core/Comm/TcpClientConfigObject.cs
@@ -2,7 +2,7 @@
using Newtonsoft.Json;
-namespace PepperDash.Core
+namespace PepperDash.Core.Comm
{
///
/// Client config object for TCP client with server that inherits from TcpSshPropertiesConfig and adds properties for shared key and heartbeat
diff --git a/src/Pepperdash Core/Comm/TcpServerConfigObject.cs b/src/Pepperdash Core/Comm/TcpServerConfigObject.cs
index 043cf58..b215426 100644
--- a/src/Pepperdash Core/Comm/TcpServerConfigObject.cs
+++ b/src/Pepperdash Core/Comm/TcpServerConfigObject.cs
@@ -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
{
///
/// Tcp Server Config object with properties for a tcp server with shared key and heartbeat capabilities
diff --git a/src/Pepperdash Core/Comm/eControlMethods.cs b/src/Pepperdash Core/Comm/eControlMethods.cs
index 28a95b1..2f8d015 100644
--- a/src/Pepperdash Core/Comm/eControlMethods.cs
+++ b/src/Pepperdash Core/Comm/eControlMethods.cs
@@ -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
{
///
/// Crestron Control Methods for a comm object
diff --git a/src/Pepperdash Core/CommunicationExtras.cs b/src/Pepperdash Core/CommunicationExtras.cs
deleted file mode 100644
index cd1ce71..0000000
--- a/src/Pepperdash Core/CommunicationExtras.cs
+++ /dev/null
@@ -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
-{
- ///
- /// An incoming communication stream
- ///
- public interface ICommunicationReceiver : IKeyed
- {
- ///
- /// Notifies of bytes received
- ///
- event EventHandler BytesReceived;
- ///
- /// Notifies of text received
- ///
- event EventHandler TextReceived;
-
- ///
- /// Indicates connection status
- ///
- bool IsConnected { get; }
- ///
- /// Connect to the device
- ///
- void Connect();
- ///
- /// Disconnect from the device
- ///
- void Disconnect();
- }
-
- ///
- /// Represents a device that uses basic connection
- ///
- public interface IBasicCommunication : ICommunicationReceiver
- {
- ///
- /// Send text to the device
- ///
- ///
- void SendText(string text);
-
- ///
- /// Send bytes to the device
- ///
- ///
- void SendBytes(byte[] bytes);
- }
-
- ///
- /// Represents a device that implements IBasicCommunication and IStreamDebugging
- ///
- public interface IBasicCommunicationWithStreamDebugging : IBasicCommunication, IStreamDebugging
- {
-
- }
-
- ///
- /// Represents a device with stream debugging capablities
- ///
- public interface IStreamDebugging
- {
- ///
- /// Object to enable stream debugging
- ///
- CommunicationStreamDebugging StreamDebugging { get; }
- }
-
- ///
- /// For IBasicCommunication classes that have SocketStatus. GenericSshClient,
- /// GenericTcpIpClient
- ///
- public interface ISocketStatus : IBasicCommunication
- {
- ///
- /// Notifies of socket status changes
- ///
- event EventHandler ConnectionChange;
-
- ///
- /// The current socket status of the client
- ///
- SocketStatus ClientStatus { get; }
- }
-
- ///
- /// Describes a device that implements ISocketStatus and IStreamDebugging
- ///
- public interface ISocketStatusWithStreamDebugging : ISocketStatus, IStreamDebugging
- {
-
- }
-
- ///
- /// Describes a device that can automatically attempt to reconnect
- ///
- public interface IAutoReconnect
- {
- ///
- /// Enable automatic recconnect
- ///
- bool AutoReconnect { get; set; }
- ///
- /// Interval in ms to attempt automatic recconnections
- ///
- int AutoReconnectIntervalMs { get; set; }
- }
-
- ///
- ///
- ///
- public enum eGenericCommMethodStatusChangeType
- {
- ///
- /// Connected
- ///
- Connected,
- ///
- /// Disconnected
- ///
- Disconnected
- }
-
- ///
- /// This delegate defines handler for IBasicCommunication status changes
- ///
- /// Device firing the status change
- ///
- public delegate void GenericCommMethodStatusHandler(IBasicCommunication comm, eGenericCommMethodStatusChangeType status);
-
- ///
- ///
- ///
- public class GenericCommMethodReceiveBytesArgs : EventArgs
- {
- ///
- ///
- ///
- public byte[] Bytes { get; private set; }
-
- ///
- ///
- ///
- ///
- public GenericCommMethodReceiveBytesArgs(byte[] bytes)
- {
- Bytes = bytes;
- }
-
- ///
- /// S+ Constructor
- ///
- public GenericCommMethodReceiveBytesArgs() { }
- }
-
- ///
- ///
- ///
- public class GenericCommMethodReceiveTextArgs : EventArgs
- {
- ///
- ///
- ///
- public string Text { get; private set; }
- ///
- ///
- ///
- public string Delimiter { get; private set; }
- ///
- ///
- ///
- ///
- public GenericCommMethodReceiveTextArgs(string text)
- {
- Text = text;
- }
-
- ///
- ///
- ///
- ///
- ///
- public GenericCommMethodReceiveTextArgs(string text, string delimiter)
- :this(text)
- {
- Delimiter = delimiter;
- }
-
- ///
- /// S+ Constructor
- ///
- public GenericCommMethodReceiveTextArgs() { }
- }
-
-
-
- ///
- ///
- ///
- public class ComTextHelper
- {
- ///
- /// Gets escaped text for a byte array
- ///
- ///
- ///
- public static string GetEscapedText(byte[] bytes)
- {
- return String.Concat(bytes.Select(b => string.Format(@"[{0:X2}]", (int)b)).ToArray());
- }
-
- ///
- /// Gets escaped text for a string
- ///
- ///
- ///
- 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());
- }
-
- ///
- /// Gets debug text for a string
- ///
- ///
- ///
- public static string GetDebugText(string text)
- {
- return Regex.Replace(text, @"[^\u0020-\u007E]", a => GetEscapedText(a.Value));
- }
- }
-}
\ No newline at end of file
diff --git a/src/Pepperdash Core/Config/PortalConfigReader.cs b/src/Pepperdash Core/Config/PortalConfigReader.cs
index e4611f5..b06f46f 100644
--- a/src/Pepperdash Core/Config/PortalConfigReader.cs
+++ b/src/Pepperdash Core/Config/PortalConfigReader.cs
@@ -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
///
public class PortalConfigReader
- {
- ///
- /// Reads the config file, checks if it needs a merge, merges and saves, then returns the merged Object.
- ///
- /// JObject of config file
- 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);
- }
+ {
+ ///
+ /// Reads the config file, checks if it needs a merge, merges and saves, then returns the merged Object.
+ ///
+ /// JObject of config file
+ 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();
- }
+ 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();
+ }
- if (jsonObj["template_url"] != null)
- {
- merged["templateUrl"] = jsonObj["template_url"].Value();
- }
+ if (jsonObj["template_url"] != null)
+ {
+ merged["templateUrl"] = jsonObj["template_url"].Value();
+ }
- 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);
+ }
+ }
- ///
- ///
- ///
- ///
- ///
- public static JObject MergeConfigs(JObject doubleConfig)
- {
- var system = JObject.FromObject(doubleConfig["system"]);
- var template = JObject.FromObject(doubleConfig["template"]);
- var merged = new JObject();
+ ///
+ ///
+ ///
+ ///
+ ///
+ 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;
+ }
- ///
- /// 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.
- ///
- 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)
- {
+ ///
+ /// 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.
+ ///
+ 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;
+ }
- ///
- /// Helper for using with JTokens. Converts to JObject
- ///
- static JObject Merge(JToken t1, JToken t2, string path)
- {
- return Merge(JObject.FromObject(t1), JObject.FromObject(t2), path);
- }
+ ///
+ /// Helper for using with JTokens. Converts to JObject
+ ///
+ static JObject Merge(JToken t1, JToken t2, string path)
+ {
+ return Merge(JObject.FromObject(t1), JObject.FromObject(t2), path);
+ }
- ///
- /// Merge o2 onto o1
- ///
+ ///
+ /// Merge o2 onto o1
+ ///
///
///
///
- 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;
+ }
+ }
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/Conversion/Convert.cs b/src/Pepperdash Core/Conversion/Convert.cs
index 2bafdcb..fba9cfb 100644
--- a/src/Pepperdash Core/Conversion/Convert.cs
+++ b/src/Pepperdash Core/Conversion/Convert.cs
@@ -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
{
diff --git a/src/Pepperdash Core/CoreInterfaces.cs b/src/Pepperdash Core/CoreInterfaces.cs
deleted file mode 100644
index 3a5df42..0000000
--- a/src/Pepperdash Core/CoreInterfaces.cs
+++ /dev/null
@@ -1,30 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using Crestron.SimplSharp;
-
-namespace PepperDash.Core
-{
- ///
- /// Unique key interface to require a unique key for the class
- ///
- public interface IKeyed
- {
- ///
- /// Unique Key
- ///
- string Key { get; }
- }
-
- ///
- /// Named Keyed device interface. Forces the devie to have a Unique Key and a name.
- ///
- public interface IKeyName : IKeyed
- {
- ///
- /// Isn't it obvious :)
- ///
- string Name { get; }
- }
-}
\ No newline at end of file
diff --git a/src/Pepperdash Core/Device.cs b/src/Pepperdash Core/Device.cs
index 55d4c15..966ddec 100644
--- a/src/Pepperdash Core/Device.cs
+++ b/src/Pepperdash Core/Device.cs
@@ -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
{
- //*********************************************************************************************************
- ///
- /// The core event and status-bearing class that most if not all device and connectors can derive from.
- ///
- public class Device : IKeyName
- {
+ //*********************************************************************************************************
+ ///
+ /// The core event and status-bearing class that most if not all device and connectors can derive from.
+ ///
+ public class Device : IKeyName
+ {
///
/// Unique Key
///
public string Key { get; protected set; }
- ///
- /// Name of the devie
- ///
+ ///
+ /// Name of the devie
+ ///
public string Name { get; protected set; }
///
///
@@ -33,26 +35,26 @@ namespace PepperDash.Core
/////
//public bool HasConfig { get { return Config != null; } }
- List _PreActivationActions;
- List _PostActivationActions;
+ List _PreActivationActions;
+ List _PostActivationActions;
///
///
///
public static Device DefaultDevice { get { return _DefaultDevice; } }
- static Device _DefaultDevice = new Device("Default", "Default");
+ static Device _DefaultDevice = new Device("Default", "Default");
- ///
- /// Base constructor for all Devices.
- ///
- ///
- public Device(string key)
- {
- Key = key;
- if (key.Contains('.')) Debug.Console(0, this, "WARNING: Device name's should not include '.'");
- Name = "";
+ ///
+ /// Base constructor for all Devices.
+ ///
+ ///
+ public Device(string key)
+ {
+ Key = key;
+ if (key.Contains('.')) Debug.Console(0, this, "WARNING: Device name's should not include '.'");
+ Name = "";
- }
+ }
///
/// Constructor with key and name
@@ -60,10 +62,10 @@ namespace PepperDash.Core
///
///
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
///
///
public void AddPreActivationAction(Action act)
- {
- if (_PreActivationActions == null)
- _PreActivationActions = new List();
- _PreActivationActions.Add(act);
- }
+ {
+ if (_PreActivationActions == null)
+ _PreActivationActions = new List();
+ _PreActivationActions.Add(act);
+ }
///
/// Adds a post activation action
///
///
public void AddPostActivationAction(Action act)
- {
- if (_PostActivationActions == null)
- _PostActivationActions = new List();
- _PostActivationActions.Add(act);
- }
+ {
+ if (_PostActivationActions == null)
+ _PostActivationActions = new List();
+ _PostActivationActions.Add(act);
+ }
///
/// Executes the preactivation actions
@@ -102,20 +104,20 @@ namespace PepperDash.Core
_PreActivationActions.ForEach(a => a.Invoke());
}
- ///
- /// 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()
- ///
- public bool Activate()
- {
+ ///
+ /// 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()
+ ///
+ 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;
+ }
///
/// Executes the postactivation actions
@@ -126,37 +128,37 @@ namespace PepperDash.Core
_PostActivationActions.ForEach(a => a.Invoke());
}
- ///
- /// 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()
- ///
- /// true if device activated successfully.
- public virtual bool CustomActivate() { return true; }
+ ///
+ /// 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()
+ ///
+ /// true if device activated successfully.
+ public virtual bool CustomActivate() { return true; }
- ///
- /// Call to deactivate device - unlink events, etc. Overriding classes do not
- /// need to call base.Deactivate()
- ///
- ///
- public virtual bool Deactivate() { return true; }
+ ///
+ /// Call to deactivate device - unlink events, etc. Overriding classes do not
+ /// need to call base.Deactivate()
+ ///
+ ///
+ public virtual bool Deactivate() { return true; }
///
/// Call this method to start communications with a device. Overriding classes do not need to call base.Initialize()
///
public virtual void Initialize()
- {
- }
+ {
+ }
- ///
- /// Helper method to check object for bool value false and fire an Action method
- ///
- /// Should be of type bool, others will be ignored
- /// Action to be run when o is false
- public void OnFalse(object o, Action a)
- {
- if (o is bool && !(bool)o) a();
- }
+ ///
+ /// Helper method to check object for bool value false and fire an Action method
+ ///
+ /// Should be of type bool, others will be ignored
+ /// Action to be run when o is false
+ public void OnFalse(object o, Action a)
+ {
+ if (o is bool && !(bool)o) a();
+ }
- }
+ }
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/EthernetHelper.cs b/src/Pepperdash Core/EthernetHelper.cs
index 3b1a2e4..e77622a 100644
--- a/src/Pepperdash Core/EthernetHelper.cs
+++ b/src/Pepperdash Core/EthernetHelper.cs
@@ -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
///
public class EthernetHelper
- {
- ///
- ///
- ///
- public static EthernetHelper LanHelper
- {
- get
- {
- if (_LanHelper == null) _LanHelper = new EthernetHelper(0);
- return _LanHelper;
- }
- }
- static EthernetHelper _LanHelper;
+ {
+ ///
+ ///
+ ///
+ 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
- ///
- ///
- ///
- public int PortNumber { get; private set; }
+ ///
+ ///
+ ///
+ public int PortNumber { get; private set; }
- private EthernetHelper(int portNumber)
- {
- PortNumber = portNumber;
- }
+ private EthernetHelper(int portNumber)
+ {
+ PortNumber = portNumber;
+ }
- ///
- ///
- ///
- [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 == "";
- }
- }
+ ///
+ ///
+ ///
+ [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 == "";
+ }
+ }
- ///
- ///
- ///
- [JsonProperty("dchpActive")]
- public bool DhcpActive
- {
- get
- {
- return CrestronEthernetHelper.GetEthernetParameter(
- CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_DHCP_STATE, 0) == "ON";
- }
- }
+ ///
+ ///
+ ///
+ [JsonProperty("dchpActive")]
+ public bool DhcpActive
+ {
+ get
+ {
+ return CrestronEthernetHelper.GetEthernetParameter(
+ CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_DHCP_STATE, 0) == "ON";
+ }
+ }
- ///
- ///
- ///
- [JsonProperty("hostname")]
- public string Hostname
- {
- get
- {
- return CrestronEthernetHelper.GetEthernetParameter(
- CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_HOSTNAME, 0);
- }
- }
+ ///
+ ///
+ ///
+ [JsonProperty("hostname")]
+ public string Hostname
+ {
+ get
+ {
+ return CrestronEthernetHelper.GetEthernetParameter(
+ CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_HOSTNAME, 0);
+ }
+ }
- ///
- ///
- ///
- [JsonProperty("ipAddress")]
- public string IPAddress
- {
- get
- {
- return CrestronEthernetHelper.GetEthernetParameter(
- CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS, 0);
- }
- }
+ ///
+ ///
+ ///
+ [JsonProperty("ipAddress")]
+ public string IPAddress
+ {
+ get
+ {
+ return CrestronEthernetHelper.GetEthernetParameter(
+ CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS, 0);
+ }
+ }
- ///
- ///
- ///
- [JsonProperty("subnetMask")]
- public string SubnetMask
- {
- get
- {
- return CrestronEthernetHelper.GetEthernetParameter(
- CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_MASK, 0);
- }
- }
+ ///
+ ///
+ ///
+ [JsonProperty("subnetMask")]
+ public string SubnetMask
+ {
+ get
+ {
+ return CrestronEthernetHelper.GetEthernetParameter(
+ CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_MASK, 0);
+ }
+ }
- ///
- ///
- ///
- [JsonProperty("defaultGateway")]
- public string DefaultGateway
- {
- get
- {
- return CrestronEthernetHelper.GetEthernetParameter(
- CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_ROUTER, 0);
- }
- }
- }
+ ///
+ ///
+ ///
+ [JsonProperty("defaultGateway")]
+ public string DefaultGateway
+ {
+ get
+ {
+ return CrestronEthernetHelper.GetEthernetParameter(
+ CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_ROUTER, 0);
+ }
+ }
+ }
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/EventArgs.cs b/src/Pepperdash Core/EventArgs.cs
index 29ef13a..9d8a358 100644
--- a/src/Pepperdash Core/EventArgs.cs
+++ b/src/Pepperdash Core/EventArgs.cs
@@ -1,172 +1,168 @@
using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using Crestron.SimplSharp;
namespace PepperDash.Core
{
- ///
- /// Bool change event args
- ///
- public class BoolChangeEventArgs : EventArgs
- {
- ///
- /// Boolean state property
- ///
- public bool State { get; set; }
-
- ///
- /// Boolean ushort value property
- ///
- public ushort IntValue { get { return (ushort)(State ? 1 : 0); } }
-
- ///
- /// Boolean change event args type
- ///
- public ushort Type { get; set; }
-
- ///
- /// Boolean change event args index
- ///
- public ushort Index { get; set; }
-
- ///
- /// Constructor
- ///
- public BoolChangeEventArgs()
- {
+ ///
+ /// Bool change event args
+ ///
+ public class BoolChangeEventArgs : EventArgs
+ {
+ ///
+ /// Boolean state property
+ ///
+ public bool State { get; set; }
- }
-
- ///
- /// Constructor overload
- ///
- ///
- ///
- public BoolChangeEventArgs(bool state, ushort type)
- {
- State = state;
- Type = type;
- }
-
- ///
- /// Constructor overload
- ///
- ///
- ///
- ///
- public BoolChangeEventArgs(bool state, ushort type, ushort index)
- {
- State = state;
- Type = type;
- Index = index;
- }
- }
+ ///
+ /// Boolean ushort value property
+ ///
+ public ushort IntValue { get { return (ushort)(State ? 1 : 0); } }
- ///
- /// Ushort change event args
- ///
- public class UshrtChangeEventArgs : EventArgs
- {
- ///
- /// Ushort change event args integer value
- ///
- public ushort IntValue { get; set; }
-
- ///
- /// Ushort change event args type
- ///
- public ushort Type { get; set; }
-
- ///
- /// Ushort change event args index
- ///
- public ushort Index { get; set; }
-
- ///
- /// Constructor
- ///
- public UshrtChangeEventArgs()
- {
+ ///
+ /// Boolean change event args type
+ ///
+ public ushort Type { get; set; }
- }
+ ///
+ /// Boolean change event args index
+ ///
+ public ushort Index { get; set; }
- ///
- /// Constructor overload
- ///
- ///
- ///
- public UshrtChangeEventArgs(ushort intValue, ushort type)
- {
- IntValue = intValue;
- Type = type;
- }
+ ///
+ /// Constructor
+ ///
+ public BoolChangeEventArgs()
+ {
- ///
- /// Constructor overload
- ///
- ///
- ///
- ///
- public UshrtChangeEventArgs(ushort intValue, ushort type, ushort index)
- {
- IntValue = intValue;
- Type = type;
- Index = index;
- }
- }
+ }
- ///
- /// String change event args
- ///
- public class StringChangeEventArgs : EventArgs
- {
- ///
- /// String change event args value
- ///
- public string StringValue { get; set; }
+ ///
+ /// Constructor overload
+ ///
+ ///
+ ///
+ public BoolChangeEventArgs(bool state, ushort type)
+ {
+ State = state;
+ Type = type;
+ }
- ///
- /// String change event args type
- ///
- public ushort Type { get; set; }
+ ///
+ /// Constructor overload
+ ///
+ ///
+ ///
+ ///
+ public BoolChangeEventArgs(bool state, ushort type, ushort index)
+ {
+ State = state;
+ Type = type;
+ Index = index;
+ }
+ }
- ///
- /// string change event args index
- ///
- public ushort Index { get; set; }
+ ///
+ /// Ushort change event args
+ ///
+ public class UshrtChangeEventArgs : EventArgs
+ {
+ ///
+ /// Ushort change event args integer value
+ ///
+ public ushort IntValue { get; set; }
- ///
- /// Constructor
- ///
- public StringChangeEventArgs()
- {
+ ///
+ /// Ushort change event args type
+ ///
+ public ushort Type { get; set; }
- }
+ ///
+ /// Ushort change event args index
+ ///
+ public ushort Index { get; set; }
- ///
- /// Constructor overload
- ///
- ///
- ///
- public StringChangeEventArgs(string stringValue, ushort type)
- {
- StringValue = stringValue;
- Type = type;
- }
+ ///
+ /// Constructor
+ ///
+ public UshrtChangeEventArgs()
+ {
- ///
- /// Constructor overload
- ///
- ///
- ///
- ///
- public StringChangeEventArgs(string stringValue, ushort type, ushort index)
- {
- StringValue = stringValue;
- Type = type;
- Index = index;
- }
- }
+ }
+
+ ///
+ /// Constructor overload
+ ///
+ ///
+ ///
+ public UshrtChangeEventArgs(ushort intValue, ushort type)
+ {
+ IntValue = intValue;
+ Type = type;
+ }
+
+ ///
+ /// Constructor overload
+ ///
+ ///
+ ///
+ ///
+ public UshrtChangeEventArgs(ushort intValue, ushort type, ushort index)
+ {
+ IntValue = intValue;
+ Type = type;
+ Index = index;
+ }
+ }
+
+ ///
+ /// String change event args
+ ///
+ public class StringChangeEventArgs : EventArgs
+ {
+ ///
+ /// String change event args value
+ ///
+ public string StringValue { get; set; }
+
+ ///
+ /// String change event args type
+ ///
+ public ushort Type { get; set; }
+
+ ///
+ /// string change event args index
+ ///
+ public ushort Index { get; set; }
+
+ ///
+ /// Constructor
+ ///
+ public StringChangeEventArgs()
+ {
+
+ }
+
+ ///
+ /// Constructor overload
+ ///
+ ///
+ ///
+ public StringChangeEventArgs(string stringValue, ushort type)
+ {
+ StringValue = stringValue;
+ Type = type;
+ }
+
+ ///
+ /// Constructor overload
+ ///
+ ///
+ ///
+ ///
+ public StringChangeEventArgs(string stringValue, ushort type, ushort index)
+ {
+ StringValue = stringValue;
+ Type = type;
+ Index = index;
+ }
+ }
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/GenericRESTfulCommunications/Constants.cs b/src/Pepperdash Core/GenericRESTfulCommunications/Constants.cs
index 1b78c33..ec441f3 100644
--- a/src/Pepperdash Core/GenericRESTfulCommunications/Constants.cs
+++ b/src/Pepperdash Core/GenericRESTfulCommunications/Constants.cs
@@ -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
{
- ///
- /// Constants
- ///
+ ///
+ /// Constants
+ ///
public class GenericRESTfulConstants
{
- ///
- /// Generic boolean change
- ///
- public const ushort BoolValueChange = 1;
- ///
- /// Generic Ushort change
- ///
- public const ushort UshrtValueChange = 101;
- ///
- /// Response Code Ushort change
- ///
- public const ushort ResponseCodeChange = 102;
- ///
- /// Generic String chagne
- ///
- public const ushort StringValueChange = 201;
- ///
- /// Response string change
- ///
- public const ushort ResponseStringChange = 202;
- ///
- /// Error string change
- ///
- public const ushort ErrorStringChange = 203;
+ ///
+ /// Generic boolean change
+ ///
+ public const ushort BoolValueChange = 1;
+ ///
+ /// Generic Ushort change
+ ///
+ public const ushort UshrtValueChange = 101;
+ ///
+ /// Response Code Ushort change
+ ///
+ public const ushort ResponseCodeChange = 102;
+ ///
+ /// Generic String chagne
+ ///
+ public const ushort StringValueChange = 201;
+ ///
+ /// Response string change
+ ///
+ public const ushort ResponseStringChange = 202;
+ ///
+ /// Error string change
+ ///
+ public const ushort ErrorStringChange = 203;
}
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/GenericRESTfulCommunications/GenericRESTfulClient.cs b/src/Pepperdash Core/GenericRESTfulCommunications/GenericRESTfulClient.cs
index bd33e13..fbacbb4 100644
--- a/src/Pepperdash Core/GenericRESTfulCommunications/GenericRESTfulClient.cs
+++ b/src/Pepperdash Core/GenericRESTfulCommunications/GenericRESTfulClient.cs
@@ -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
{
- ///
- /// Generic RESTful communication class
- ///
- public class GenericRESTfulClient
- {
- ///
- /// Boolean event handler
- ///
- public event EventHandler BoolChange;
- ///
- /// Ushort event handler
- ///
- public event EventHandler UshrtChange;
- ///
- /// String event handler
- ///
- public event EventHandler StringChange;
+ ///
+ /// Generic RESTful communication class
+ ///
+ public class GenericRESTfulClient
+ {
+ ///
+ /// Boolean event handler
+ ///
+ public event EventHandler BoolChange;
+ ///
+ /// Ushort event handler
+ ///
+ public event EventHandler UshrtChange;
+ ///
+ /// String event handler
+ ///
+ public event EventHandler StringChange;
- ///
- /// Constructor
- ///
- public GenericRESTfulClient()
- {
+ ///
+ /// Constructor
+ ///
+ public GenericRESTfulClient()
+ {
- }
+ }
- ///
- /// Generic RESTful submit request
- ///
- ///
- ///
- ///
- ///
- ///
+ ///
+ /// Generic RESTful submit request
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
///
- 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);
+ }
+ }
- ///
- /// Private HTTP submit request
- ///
- ///
- ///
- ///
+ ///
+ /// Private HTTP submit request
+ ///
+ ///
+ ///
+ ///
///
- ///
- ///
- 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;
+ ///
+ ///
+ 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);
- ///
- /// Private HTTPS submit 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(e.Message);
+ OnStringChange(e.Message, 0, GenericRESTfulConstants.ErrorStringChange);
+ }
+ }
+
+ ///
+ /// Private HTTPS submit request
+ ///
+ ///
+ ///
+ ///
///
- ///
- ///
- 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;
+ ///
+ ///
+ 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);
- ///
- /// Private method to encode username and password to Base64 string
- ///
- ///
- ///
- /// authorization
- 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;
- }
+ ///
+ /// Private method to encode username and password to Base64 string
+ ///
+ ///
+ ///
+ /// authorization
+ private string EncodeBase64(string username, string password)
+ {
+ var authorization = "";
- ///
- /// Protected method to handle boolean change events
- ///
- ///
- ///
- ///
- 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 "";
+ }
- ///
- /// Protected mehtod to handle ushort change events
- ///
- ///
- ///
- ///
- 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;
+ }
- ///
- /// Protected method to handle string change events
- ///
- ///
- ///
- ///
- 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);
- }
- }
- }
+ ///
+ /// Protected method to handle boolean change events
+ ///
+ ///
+ ///
+ ///
+ 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 mehtod to handle ushort change events
+ ///
+ ///
+ ///
+ ///
+ 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);
+ }
+ }
+
+ ///
+ /// Protected method to handle string change events
+ ///
+ ///
+ ///
+ ///
+ 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);
+ }
+ }
+ }
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/JsonStandardObjects/EventArgs and Constants.cs b/src/Pepperdash Core/JsonStandardObjects/EventArgs and Constants.cs
index ed02ccb..03cae46 100644
--- a/src/Pepperdash Core/JsonStandardObjects/EventArgs and Constants.cs
+++ b/src/Pepperdash Core/JsonStandardObjects/EventArgs and Constants.cs
@@ -1,77 +1,73 @@
using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using Crestron.SimplSharp;
namespace PepperDash.Core.JsonStandardObjects
{
- ///
- /// Constants for simpl modules
- ///
- public class JsonStandardDeviceConstants
- {
- ///
- /// Json object evaluated constant
- ///
- public const ushort JsonObjectEvaluated = 2;
+ ///
+ /// Constants for simpl modules
+ ///
+ public class JsonStandardDeviceConstants
+ {
+ ///
+ /// Json object evaluated constant
+ ///
+ public const ushort JsonObjectEvaluated = 2;
- ///
- /// Json object changed constant
- ///
- public const ushort JsonObjectChanged = 104;
- }
+ ///
+ /// Json object changed constant
+ ///
+ public const ushort JsonObjectChanged = 104;
+ }
- ///
- ///
- ///
- public class DeviceChangeEventArgs : EventArgs
- {
- ///
- /// Device change event args object
- ///
- public DeviceConfig Device { get; set; }
+ ///
+ ///
+ ///
+ public class DeviceChangeEventArgs : EventArgs
+ {
+ ///
+ /// Device change event args object
+ ///
+ public DeviceConfig Device { get; set; }
- ///
- /// Device change event args type
- ///
- public ushort Type { get; set; }
+ ///
+ /// Device change event args type
+ ///
+ public ushort Type { get; set; }
- ///
- /// Device change event args index
- ///
- public ushort Index { get; set; }
+ ///
+ /// Device change event args index
+ ///
+ public ushort Index { get; set; }
- ///
- /// Default constructor
- ///
- public DeviceChangeEventArgs()
- {
+ ///
+ /// Default constructor
+ ///
+ public DeviceChangeEventArgs()
+ {
- }
+ }
- ///
- /// Constructor overload
- ///
- ///
- ///
- public DeviceChangeEventArgs(DeviceConfig device, ushort type)
- {
- Device = device;
- Type = type;
- }
+ ///
+ /// Constructor overload
+ ///
+ ///
+ ///
+ public DeviceChangeEventArgs(DeviceConfig device, ushort type)
+ {
+ Device = device;
+ Type = type;
+ }
- ///
- /// Constructor overload
- ///
- ///
- ///
- ///
- public DeviceChangeEventArgs(DeviceConfig device, ushort type, ushort index)
- {
- Device = device;
- Type = type;
- Index = index;
- }
- }
+ ///
+ /// Constructor overload
+ ///
+ ///
+ ///
+ ///
+ public DeviceChangeEventArgs(DeviceConfig device, ushort type, ushort index)
+ {
+ Device = device;
+ Type = type;
+ Index = index;
+ }
+ }
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/JsonStandardObjects/JsonToSimplDevice.cs b/src/Pepperdash Core/JsonStandardObjects/JsonToSimplDevice.cs
index 61c12b1..4cb10b0 100644
--- a/src/Pepperdash Core/JsonStandardObjects/JsonToSimplDevice.cs
+++ b/src/Pepperdash Core/JsonStandardObjects/JsonToSimplDevice.cs
@@ -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
{
- ///
- /// Device class
- ///
- public class DeviceConfig
- {
- ///
- /// JSON config key property
- ///
- public string key { get; set; }
- ///
- /// JSON config name property
- ///
- public string name { get; set; }
- ///
- /// JSON config type property
- ///
- public string type { get; set; }
- ///
- /// JSON config properties
- ///
- public PropertiesConfig properties { get; set; }
+ ///
+ /// Device class
+ ///
+ public class DeviceConfig
+ {
+ ///
+ /// JSON config key property
+ ///
+ public string key { get; set; }
+ ///
+ /// JSON config name property
+ ///
+ public string name { get; set; }
+ ///
+ /// JSON config type property
+ ///
+ public string type { get; set; }
+ ///
+ /// JSON config properties
+ ///
+ public PropertiesConfig properties { get; set; }
- ///
- /// Bool change event handler
- ///
- public event EventHandler BoolChange;
- ///
- /// Ushort change event handler
- ///
- public event EventHandler UshrtChange;
- ///
- /// String change event handler
- ///
- public event EventHandler StringChange;
- ///
- /// Object change event handler
- ///
- public event EventHandler DeviceChange;
+ ///
+ /// Bool change event handler
+ ///
+ public event EventHandler BoolChange;
+ ///
+ /// Ushort change event handler
+ ///
+ public event EventHandler UshrtChange;
+ ///
+ /// String change event handler
+ ///
+ public event EventHandler StringChange;
+ ///
+ /// Object change event handler
+ ///
+ public event EventHandler DeviceChange;
- ///
- /// Constructor
- ///
- public DeviceConfig()
- {
- properties = new PropertiesConfig();
- }
+ ///
+ /// Constructor
+ ///
+ public DeviceConfig()
+ {
+ properties = new PropertiesConfig();
+ }
- ///
- /// Initialize method
- ///
- ///
- ///
- 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;
- }
+ ///
+ /// Initialize method
+ ///
+ ///
+ ///
+ 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().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().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
- ///
- /// BoolChange event handler helper
- ///
- ///
- ///
- ///
- 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);
- }
- }
+ ///
+ /// BoolChange event handler helper
+ ///
+ ///
+ ///
+ ///
+ 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);
+ }
+ }
- ///
- /// UshrtChange event handler helper
- ///
- ///
- ///
- ///
- 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);
- }
- }
+ ///
+ /// UshrtChange event handler helper
+ ///
+ ///
+ ///
+ ///
+ 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);
+ }
+ }
- ///
- /// StringChange event handler helper
- ///
- ///
- ///
- ///
- 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);
- }
- }
+ ///
+ /// StringChange event handler helper
+ ///
+ ///
+ ///
+ ///
+ 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);
+ }
+ }
- ///
- /// ObjectChange event handler helper
- ///
- ///
- ///
- ///
- protected void OnObjectChange(DeviceConfig device, ushort index, ushort type)
- {
- if (DeviceChange != null)
- {
- var args = new DeviceChangeEventArgs(device, type);
- args.Index = index;
- DeviceChange(this, args);
- }
- }
+ ///
+ /// ObjectChange event handler helper
+ ///
+ ///
+ ///
+ ///
+ 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
+ }
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/JsonStandardObjects/JsonToSimplDeviceConfig.cs b/src/Pepperdash Core/JsonStandardObjects/JsonToSimplDeviceConfig.cs
index fa23d87..3e651f7 100644
--- a/src/Pepperdash Core/JsonStandardObjects/JsonToSimplDeviceConfig.cs
+++ b/src/Pepperdash Core/JsonStandardObjects/JsonToSimplDeviceConfig.cs
@@ -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
]
}
*/
- ///
- /// Device communication parameter class
- ///
- public class ComParamsConfig
- {
+ ///
+ /// Device communication parameter class
+ ///
+ public class ComParamsConfig
+ {
///
///
///
@@ -85,11 +82,11 @@ namespace PepperDash.Core.JsonStandardObjects
///
public int pacing { get; set; }
- // convert properties for simpl
+ // convert properties for simpl
///
///
///
- public ushort simplBaudRate { get { return Convert.ToUInt16(baudRate); } }
+ public ushort simplBaudRate { get { return Convert.ToUInt16(baudRate); } }
///
///
///
@@ -103,20 +100,20 @@ namespace PepperDash.Core.JsonStandardObjects
///
public ushort simplPacing { get { return Convert.ToUInt16(pacing); } }
- ///
- /// Constructor
- ///
- public ComParamsConfig()
- {
+ ///
+ /// Constructor
+ ///
+ public ComParamsConfig()
+ {
- }
- }
+ }
+ }
- ///
- /// Device TCP/SSH properties class
- ///
- public class TcpSshPropertiesConfig
- {
+ ///
+ /// Device TCP/SSH properties class
+ ///
+ public class TcpSshPropertiesConfig
+ {
///
///
///
@@ -142,11 +139,11 @@ namespace PepperDash.Core.JsonStandardObjects
///
public int autoReconnectIntervalMs { get; set; }
- // convert properties for simpl
+ // convert properties for simpl
///
///
///
- public ushort simplPort { get { return Convert.ToUInt16(port); } }
+ public ushort simplPort { get { return Convert.ToUInt16(port); } }
///
///
///
@@ -156,20 +153,20 @@ namespace PepperDash.Core.JsonStandardObjects
///
public ushort simplAutoReconnectIntervalMs { get { return Convert.ToUInt16(autoReconnectIntervalMs); } }
- ///
- /// Constructor
- ///
- public TcpSshPropertiesConfig()
- {
+ ///
+ /// Constructor
+ ///
+ public TcpSshPropertiesConfig()
+ {
- }
- }
+ }
+ }
- ///
- /// Device control class
- ///
- public class ControlConfig
- {
+ ///
+ /// Device control class
+ ///
+ public class ControlConfig
+ {
///
///
///
@@ -191,27 +188,27 @@ namespace PepperDash.Core.JsonStandardObjects
///
public TcpSshPropertiesConfig tcpSshProperties { get; set; }
- // convert properties for simpl
+ // convert properties for simpl
///
///
///
- public ushort simplControlPortNumber { get { return Convert.ToUInt16(controlPortNumber); } }
+ public ushort simplControlPortNumber { get { return Convert.ToUInt16(controlPortNumber); } }
- ///
- /// Constructor
- ///
- public ControlConfig()
- {
- comParams = new ComParamsConfig();
- tcpSshProperties = new TcpSshPropertiesConfig();
- }
- }
+ ///
+ /// Constructor
+ ///
+ public ControlConfig()
+ {
+ comParams = new ComParamsConfig();
+ tcpSshProperties = new TcpSshPropertiesConfig();
+ }
+ }
- ///
- /// Device properties class
- ///
- public class PropertiesConfig
- {
+ ///
+ /// Device properties class
+ ///
+ public class PropertiesConfig
+ {
///
///
///
@@ -225,33 +222,33 @@ namespace PepperDash.Core.JsonStandardObjects
///
public ControlConfig control { get; set; }
- // convert properties for simpl
+ // convert properties for simpl
///
///
///
- public ushort simplDeviceId { get { return Convert.ToUInt16(deviceId); } }
+ public ushort simplDeviceId { get { return Convert.ToUInt16(deviceId); } }
///
///
///
public ushort simplEnabled { get { return (ushort)(enabled ? 1 : 0); } }
- ///
- /// Constructor
- ///
- public PropertiesConfig()
- {
- control = new ControlConfig();
- }
- }
+ ///
+ /// Constructor
+ ///
+ public PropertiesConfig()
+ {
+ control = new ControlConfig();
+ }
+ }
- ///
- /// Root device class
- ///
- public class RootObject
- {
+ ///
+ /// Root device class
+ ///
+ public class RootObject
+ {
///
/// The collection of devices
///
public List devices { get; set; }
- }
+ }
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/JsonToSimpl/Constants.cs b/src/Pepperdash Core/JsonToSimpl/Constants.cs
index d87b50c..cb7afe0 100644
--- a/src/Pepperdash Core/JsonToSimpl/Constants.cs
+++ b/src/Pepperdash Core/JsonToSimpl/Constants.cs
@@ -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
{
- ///
- /// Constants for Simpl modules
- ///
- public class JsonToSimplConstants
- {
+ ///
+ /// Constants for Simpl modules
+ ///
+ public class JsonToSimplConstants
+ {
///
///
///
@@ -38,12 +32,12 @@ namespace PepperDash.Core.JsonToSimpl
///
///
///
- public const ushort UshortValueChange = 101;
-
+ public const ushort UshortValueChange = 101;
+
///
///
///
- public const ushort StringValueChange = 201;
+ public const ushort StringValueChange = 201;
///
///
///
@@ -76,18 +70,18 @@ namespace PepperDash.Core.JsonToSimpl
/// Reports the room name change
///
public const ushort RoomNameChange = 208;
- }
+ }
- ///
- /// S+ values delegate
- ///
- public delegate void SPlusValuesDelegate();
+ ///
+ /// S+ values delegate
+ ///
+ public delegate void SPlusValuesDelegate();
- ///
- /// S+ values wrapper
- ///
- public class SPlusValueWrapper
- {
+ ///
+ /// S+ values wrapper
+ ///
+ public class SPlusValueWrapper
+ {
///
///
///
@@ -108,7 +102,7 @@ namespace PepperDash.Core.JsonToSimpl
///
///
///
- public SPlusValueWrapper() {}
+ public SPlusValueWrapper() { }
///
///
@@ -116,28 +110,28 @@ namespace PepperDash.Core.JsonToSimpl
///
///
public SPlusValueWrapper(SPlusType type, ushort index)
- {
- ValueType = type;
- Index = index;
- }
- }
+ {
+ ValueType = type;
+ Index = index;
+ }
+ }
- ///
- /// S+ types enum
- ///
- public enum SPlusType
- {
+ ///
+ /// S+ types enum
+ ///
+ public enum SPlusType
+ {
///
/// Digital
///
- Digital,
+ Digital,
///
/// Analog
///
- Analog,
+ Analog,
///
/// String
///
String
- }
+ }
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/JsonToSimpl/Global.cs b/src/Pepperdash Core/JsonToSimpl/Global.cs
index be2e795..ed44c90 100644
--- a/src/Pepperdash Core/JsonToSimpl/Global.cs
+++ b/src/Pepperdash Core/JsonToSimpl/Global.cs
@@ -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
///
public class J2SGlobal
- {
- static List Masters = new List();
+ {
+ static List Masters = new List();
- ///
- /// Adds a file master. If the master's key or filename is equivalent to any existing
- /// master, this will fail
- ///
- /// New master to add
+ ///
+ /// Adds a file master. If the master's key or filename is equivalent to any existing
+ /// master, this will fail
+ ///
+ /// New master to add
///
- 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;
- ///
- /// Gets a master by its key. Case-insensitive
- ///
- 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);
+ }
+ }
+
+ ///
+ /// Gets a master by its key. Case-insensitive
+ ///
+ public static JsonToSimplMaster GetMasterByFile(string file)
+ {
+ return Masters.FirstOrDefault(m => m.UniqueID.Equals(file, StringComparison.OrdinalIgnoreCase));
+ }
+ }
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/JsonToSimpl/JsonToSimplArrayLookupChild.cs b/src/Pepperdash Core/JsonToSimpl/JsonToSimplArrayLookupChild.cs
index 690aa94..4f22cb7 100644
--- a/src/Pepperdash Core/JsonToSimpl/JsonToSimplArrayLookupChild.cs
+++ b/src/Pepperdash Core/JsonToSimpl/JsonToSimplArrayLookupChild.cs
@@ -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
///
public class JsonToSimplArrayLookupChild : JsonToSimplChildObjectBase
- {
+ {
///
///
///
@@ -23,144 +20,144 @@ namespace PepperDash.Core.JsonToSimpl
///
public string SearchPropertyValue { get; set; }
- int ArrayIndex;
+ int ArrayIndex;
- ///
- /// For gt2.4.1 array lookups
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- 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;
- }
+ ///
+ /// For gt2.4.1 array lookups
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ 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;
+ }
- ///
- /// For newer >=2.4.1 array lookups.
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- 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);
+ ///
+ /// For newer >=2.4.1 array lookups.
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ 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
- ///
- ///
- ///
- ///
- ///
- 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
+ ///
+ ///
+ ///
+ ///
+ ///
+ protected override string GetFullPath(string path)
+ {
+ return string.Format("{0}[{1}].{2}{3}",
+ PathPrefix == null ? "" : PathPrefix,
+ ArrayIndex,
+ path,
+ PathSuffix == null ? "" : PathSuffix);
+ }
///
/// Process all values
///
public override void ProcessAll()
- {
- if (FindInArray())
- base.ProcessAll();
- }
+ {
+ if (FindInArray())
+ base.ProcessAll();
+ }
- ///
- /// Provides the path append for GetFullPath
- ///
- ///
- string GetPathAppend(string a)
- {
- if (string.IsNullOrEmpty(a))
- {
- return "";
- }
- if (a.StartsWith("."))
- {
- return a;
- }
- else
- {
- return "." + a;
- }
- }
+ ///
+ /// Provides the path append for GetFullPath
+ ///
+ ///
+ string GetPathAppend(string a)
+ {
+ if (string.IsNullOrEmpty(a))
+ {
+ return "";
+ }
+ if (a.StartsWith("."))
+ {
+ return a;
+ }
+ else
+ {
+ return "." + a;
+ }
+ }
- ///
- ///
- ///
- ///
- 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");
+ ///
+ ///
+ ///
+ ///
+ 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()
- .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()
+ .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;
+ }
+ }
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/JsonToSimpl/JsonToSimplChildObjectBase.cs b/src/Pepperdash Core/JsonToSimpl/JsonToSimplChildObjectBase.cs
index 01e4e0c..5afb6f8 100644
--- a/src/Pepperdash Core/JsonToSimpl/JsonToSimplChildObjectBase.cs
+++ b/src/Pepperdash Core/JsonToSimpl/JsonToSimplChildObjectBase.cs
@@ -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
///
public abstract class JsonToSimplChildObjectBase : IKeyed
- {
+ {
///
/// Notifies of bool change
///
@@ -32,26 +31,26 @@ namespace PepperDash.Core.JsonToSimpl
///
public SPlusValuesDelegate GetAllValuesDelegate { get; set; }
- ///
- /// Use a callback to reduce task switch/threading
- ///
- public SPlusValuesDelegate SetAllPathsDelegate { get; set; }
+ ///
+ /// Use a callback to reduce task switch/threading
+ ///
+ public SPlusValuesDelegate SetAllPathsDelegate { get; set; }
///
/// Unique identifier for instance
///
public string Key { get; protected set; }
- ///
- /// This will be prepended to all paths to allow path swapping or for more organized
- /// sub-paths
- ///
- public string PathPrefix { get; protected set; }
+ ///
+ /// This will be prepended to all paths to allow path swapping or for more organized
+ /// sub-paths
+ ///
+ public string PathPrefix { get; protected set; }
- ///
- /// This is added to the end of all paths
- ///
- public string PathSuffix { get; protected set; }
+ ///
+ /// This is added to the end of all paths
+ ///
+ public string PathSuffix { get; protected set; }
///
/// Indicates if the instance is linked to an object
@@ -76,107 +75,109 @@ namespace PepperDash.Core.JsonToSimpl
///
protected Dictionary StringPaths = new Dictionary();
- ///
- /// Call this before doing anything else
- ///
+ ///
+ /// Call this before doing anything else
+ ///
///
- ///
- ///
- ///
- public void Initialize(string masterUniqueId, string key, string pathPrefix, string pathSuffix)
- {
- Key = key;
- PathPrefix = pathPrefix;
- PathSuffix = pathSuffix;
+ ///
+ ///
+ ///
+ 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);
+ }
///
/// Sets the path prefix for the object
///
///
public void SetPathPrefix(string pathPrefix)
- {
- PathPrefix = pathPrefix;
- }
- ///
- /// Set the JPath to evaluate for a given bool out index.
- ///
- 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;
+ }
+ ///
+ /// Set the JPath to evaluate for a given bool out index.
+ ///
+ 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;
+ }
- ///
- /// Set the JPath for a ushort out index.
- ///
- 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;
- }
+ ///
+ /// Set the JPath for a ushort out index.
+ ///
+ 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;
+ }
- ///
- /// Set the JPath for a string output index.
- ///
- 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;
- }
+ ///
+ /// Set the JPath for a string output index.
+ ///
+ 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;
+ }
- ///
- /// Evalutates all outputs with defined paths. called by S+ when paths are ready to process
- /// and by Master when file is read.
- ///
- public virtual void ProcessAll()
- {
- if (!LinkedToObject)
- {
- Debug.Console(1, this, "Not linked to object in file. Skipping");
- return;
- }
+ ///
+ /// Evalutates all outputs with defined paths. called by S+ when paths are ready to process
+ /// and by Master when file is read.
+ ///
+ 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);
+ }
- ///
- /// Processes a bool property, converting to bool, firing off a BoolChange event
- ///
- 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) {
+ ///
+ /// Processes a bool property, converting to bool, firing off a BoolChange event
+ ///
+ 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);
+ }
- ///
- /// Processes the given path.
- ///
- /// JPath formatted path to the desired property
- /// The string value of the property, or a default value if it
- /// doesn't exist
- /// This will return false in the case that EvaulateAllOnJsonChange
- /// is false and the path does not evaluate to a property in the incoming JSON.
- 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;
- }
+ ///
+ /// Processes the given path.
+ ///
+ /// JPath formatted path to the desired property
+ /// The string value of the property, or a default value if it
+ /// doesn't exist
+ /// This will return false in the case that EvaulateAllOnJsonChange
+ /// is false and the path does not evaluate to a property in the incoming JSON.
+ 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();
- 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();
+ 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
- ///
- /// Called from Master to read inputs and update their values in master JObject
- /// Callback should hit one of the following four methods
- ///
- public void UpdateInputsForMaster()
- {
- if (!LinkedToObject)
- {
- Debug.Console(1, this, "Not linked to object in file. Skipping");
- return;
- }
+ ///
+ /// Called from Master to read inputs and update their values in master JObject
+ /// Callback should hit one of the following four methods
+ ///
+ 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();
+ }
///
///
@@ -282,9 +283,9 @@ namespace PepperDash.Core.JsonToSimpl
///
///
public void USetBoolValue(ushort key, ushort theValue)
- {
- SetBoolValue(key, theValue == 1);
- }
+ {
+ SetBoolValue(key, theValue == 1);
+ }
///
///
@@ -292,10 +293,10 @@ namespace PepperDash.Core.JsonToSimpl
///
///
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));
+ }
///
///
@@ -303,10 +304,10 @@ namespace PepperDash.Core.JsonToSimpl
///
///
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));
+ }
///
///
@@ -314,10 +315,10 @@ namespace PepperDash.Core.JsonToSimpl
///
///
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));
+ }
///
///
@@ -325,68 +326,68 @@ namespace PepperDash.Core.JsonToSimpl
///
///
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);
+ }
+ }
- ///
- /// 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.
- ///
- protected virtual string GetFullPath(string path)
- {
- return (PathPrefix != null ? PathPrefix : "") +
- path + (PathSuffix != null ? PathSuffix : "");
- }
+ ///
+ /// 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.
+ ///
+ protected virtual string GetFullPath(string path)
+ {
+ return (PathPrefix != null ? PathPrefix : "") +
+ path + (PathSuffix != null ? PathSuffix : "");
+ }
- // Helpers for events
- //******************************************************************************************
+ // Helpers for events
+ //******************************************************************************************
///
/// Event helper
///
///
///
///
- 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);
+ }
+ }
- //******************************************************************************************
+ //******************************************************************************************
///
/// Event helper
///
///
///
///
- 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);
+ }
+ }
///
/// Event helper
@@ -395,14 +396,14 @@ namespace PepperDash.Core.JsonToSimpl
///
///
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);
+ }
+ }
+ }
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/JsonToSimpl/JsonToSimplFileMaster.cs b/src/Pepperdash Core/JsonToSimpl/JsonToSimplFileMaster.cs
index 0cb79b1..cebb69a 100644
--- a/src/Pepperdash Core/JsonToSimpl/JsonToSimplFileMaster.cs
+++ b/src/Pepperdash Core/JsonToSimpl/JsonToSimplFileMaster.cs
@@ -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);
diff --git a/src/Pepperdash Core/JsonToSimpl/JsonToSimplFixedPathObject.cs b/src/Pepperdash Core/JsonToSimpl/JsonToSimplFixedPathObject.cs
index c12053e..7e251e5 100644
--- a/src/Pepperdash Core/JsonToSimpl/JsonToSimplFixedPathObject.cs
+++ b/src/Pepperdash Core/JsonToSimpl/JsonToSimplFixedPathObject.cs
@@ -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
///
///
public class JsonToSimplFixedPathObject : JsonToSimplChildObjectBase
- {
+ {
///
/// Constructor
///
public JsonToSimplFixedPathObject()
- {
- this.LinkedToObject = true;
- }
- }
+ {
+ this.LinkedToObject = true;
+ }
+ }
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/JsonToSimpl/JsonToSimplGenericMaster.cs b/src/Pepperdash Core/JsonToSimpl/JsonToSimplGenericMaster.cs
index de9faf1..a1e81e5 100644
--- a/src/Pepperdash Core/JsonToSimpl/JsonToSimplGenericMaster.cs
+++ b/src/Pepperdash Core/JsonToSimpl/JsonToSimplGenericMaster.cs
@@ -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
///
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();
///
/// Callback action for saving
///
public Action SaveCallback { get; set; }
- /*****************************************************************************************/
+ /*****************************************************************************************/
- ///
+ ///
/// SIMPL+ default constructor.
///
- public JsonToSimplGenericMaster()
+ public JsonToSimplGenericMaster()
{
- }
+ }
- ///
- /// Loads in JSON and triggers evaluation on all children
- ///
- ///
- 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);
- }
- }
+ ///
+ /// Loads in JSON and triggers evaluation on all children
+ ///
+ ///
+ 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);
+ }
+ }
- ///
- /// Loads JSON into JsonObject, but does not trigger evaluation by children
- ///
- ///
- public void SetJsonWithoutEvaluating(string json)
- {
- try
- {
- JsonObject = JObject.Parse(json);
- }
- catch (Exception e)
- {
- Debug.Console(0, this, "JSON parsing failed:\r{0}", e);
- }
- }
+ ///
+ /// Loads JSON into JsonObject, but does not trigger evaluation by children
+ ///
+ ///
+ public void SetJsonWithoutEvaluating(string json)
+ {
+ try
+ {
+ JsonObject = JObject.Parse(json);
+ }
+ catch (Exception e)
+ {
+ Debug.Console(0, this, "JSON parsing failed:\r{0}", e);
+ }
+ }
- ///
- ///
- ///
- public override void Save()
- {
- // this code is duplicated in the other masters!!!!!!!!!!!!!
- UnsavedValues = new Dictionary();
- // 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();
- }
+ ///
+ ///
+ ///
+ public override void Save()
+ {
+ // this code is duplicated in the other masters!!!!!!!!!!!!!
+ UnsavedValues = new Dictionary();
+ // 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.");
+ }
+ }
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/JsonToSimpl/JsonToSimplMaster.cs b/src/Pepperdash Core/JsonToSimpl/JsonToSimplMaster.cs
index 05f61dd..78cb6f8 100644
--- a/src/Pepperdash Core/JsonToSimpl/JsonToSimplMaster.cs
+++ b/src/Pepperdash Core/JsonToSimpl/JsonToSimplMaster.cs
@@ -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
///
public abstract class JsonToSimplMaster : IKeyed
- {
+ {
///
/// Notifies of bool change
///
@@ -35,116 +34,116 @@ namespace PepperDash.Core.JsonToSimpl
///
protected List Children = new List();
- /*****************************************************************************************/
+ /*****************************************************************************************/
- ///
- /// Mirrors the Unique ID for now.
- ///
- public string Key { get { return UniqueID; } }
+ ///
+ /// Mirrors the Unique ID for now.
+ ///
+ public string Key { get { return UniqueID; } }
///
/// A unique ID
///
public string UniqueID { get; protected set; }
- ///
- /// Merely for use in debug messages
- ///
- public string DebugName
- {
- get { return _DebugName; }
- set { if (DebugName == null) _DebugName = ""; else _DebugName = value; }
- }
- string _DebugName = "";
+ ///
+ /// Merely for use in debug messages
+ ///
+ public string DebugName
+ {
+ get { return _DebugName; }
+ set { if (DebugName == null) _DebugName = ""; else _DebugName = value; }
+ }
+ string _DebugName = "";
- ///
- /// This will be prepended to all paths to allow path swapping or for more organized
- /// sub-paths
- ///
- public string PathPrefix { get; set; }
+ ///
+ /// This will be prepended to all paths to allow path swapping or for more organized
+ /// sub-paths
+ ///
+ public string PathPrefix { get; set; }
- ///
- /// This is added to the end of all paths
- ///
- public string PathSuffix { get; set; }
+ ///
+ /// This is added to the end of all paths
+ ///
+ public string PathSuffix { get; set; }
- ///
- /// Enables debugging output to the console. Certain error messages will be logged to the
- /// system's error log regardless of this setting
- ///
- public bool DebugOn { get; set; }
+ ///
+ /// Enables debugging output to the console. Certain error messages will be logged to the
+ /// system's error log regardless of this setting
+ ///
+ public bool DebugOn { get; set; }
- ///
- /// Ushort helper for Debug property
- ///
- public ushort UDebug
- {
- get { return (ushort)(DebugOn ? 1 : 0); }
- set
- {
- DebugOn = (value == 1);
- CrestronConsole.PrintLine("JsonToSimpl debug={0}", DebugOn);
- }
- }
+ ///
+ /// Ushort helper for Debug property
+ ///
+ public ushort UDebug
+ {
+ get { return (ushort)(DebugOn ? 1 : 0); }
+ set
+ {
+ DebugOn = (value == 1);
+ CrestronConsole.PrintLine("JsonToSimpl debug={0}", DebugOn);
+ }
+ }
///
///
///
public JObject JsonObject { get; protected set; }
- /*****************************************************************************************/
- /** Privates **/
+ /*****************************************************************************************/
+ /** Privates **/
- // The JSON file in JObject form
- // For gathering the incoming data
- protected Dictionary UnsavedValues = new Dictionary();
+ // The JSON file in JObject form
+ // For gathering the incoming data
+ protected Dictionary UnsavedValues = new Dictionary();
- /*****************************************************************************************/
+ /*****************************************************************************************/
- ///
- /// SIMPL+ default constructor.
- ///
- public JsonToSimplMaster()
- {
- }
+ ///
+ /// SIMPL+ default constructor.
+ ///
+ public JsonToSimplMaster()
+ {
+ }
- ///
- /// Sets up class - overriding methods should always call this.
- ///
- ///
- public virtual void Initialize(string uniqueId)
- {
- UniqueID = uniqueId;
- J2SGlobal.AddMaster(this); // Should not re-add
- }
+ ///
+ /// Sets up class - overriding methods should always call this.
+ ///
+ ///
+ public virtual void Initialize(string uniqueId)
+ {
+ UniqueID = uniqueId;
+ J2SGlobal.AddMaster(this); // Should not re-add
+ }
- ///
- /// Adds a child "module" to this master
- ///
- ///
- public void AddChild(JsonToSimplChildObjectBase child)
- {
- if (!Children.Contains(child))
- {
- Children.Add(child);
- }
- }
+ ///
+ /// Adds a child "module" to this master
+ ///
+ ///
+ public void AddChild(JsonToSimplChildObjectBase child)
+ {
+ if (!Children.Contains(child))
+ {
+ Children.Add(child);
+ }
+ }
- ///
- /// Called from the child to add changed or new values for saving
- ///
- 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);
- }
+ ///
+ /// Called from the child to add changed or new values for saving
+ ///
+ 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);
+ }
///
/// Saves the file
@@ -152,27 +151,27 @@ namespace PepperDash.Core.JsonToSimpl
public abstract void Save();
- ///
- ///
- ///
- public static class JsonFixes
- {
+ ///
+ ///
+ ///
+ public static class JsonFixes
+ {
///
/// Deserializes a string into a JObject
///
///
///
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;
+ }
+ }
///
/// Deserializes a string into a JArray
@@ -180,49 +179,49 @@ namespace PepperDash.Core.JsonToSimpl
///
///
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;
+ }
+ }
+ }
- ///
- /// Helper event
- ///
- ///
- ///
- ///
- protected void OnBoolChange(bool state, ushort index, ushort type)
- {
- if (BoolChange != null)
- {
- var args = new BoolChangeEventArgs(state, type);
- args.Index = index;
- BoolChange(this, args);
- }
- }
+ ///
+ /// Helper event
+ ///
+ ///
+ ///
+ ///
+ protected void OnBoolChange(bool state, ushort index, ushort type)
+ {
+ if (BoolChange != null)
+ {
+ var args = new BoolChangeEventArgs(state, type);
+ args.Index = index;
+ BoolChange(this, args);
+ }
+ }
- ///
- /// Helper event
- ///
- ///
- ///
- ///
- protected void OnUshrtChange(ushort state, ushort index, ushort type)
- {
- if (UshrtChange != null)
- {
- var args = new UshrtChangeEventArgs(state, type);
- args.Index = index;
- UshrtChange(this, args);
- }
- }
+ ///
+ /// Helper event
+ ///
+ ///
+ ///
+ ///
+ protected void OnUshrtChange(ushort state, ushort index, ushort type)
+ {
+ if (UshrtChange != null)
+ {
+ var args = new UshrtChangeEventArgs(state, type);
+ args.Index = index;
+ UshrtChange(this, args);
+ }
+ }
///
/// Helper event
@@ -231,13 +230,13 @@ namespace PepperDash.Core.JsonToSimpl
///
///
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);
+ }
+ }
+ }
}
diff --git a/src/Pepperdash Core/JsonToSimpl/JsonToSimplPortalFileMaster.cs b/src/Pepperdash Core/JsonToSimpl/JsonToSimplPortalFileMaster.cs
index 74b10eb..dbeebb2 100644
--- a/src/Pepperdash Core/JsonToSimpl/JsonToSimplPortalFileMaster.cs
+++ b/src/Pepperdash Core/JsonToSimpl/JsonToSimplPortalFileMaster.cs
@@ -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
///
public class JsonToSimplPortalFileMaster : JsonToSimplMaster
{
- ///
- /// Sets the filepath as well as registers this with the Global.Masters list
- ///
- public string PortalFilepath { get; private set; }
+ ///
+ /// Sets the filepath as well as registers this with the Global.Masters list
+ ///
+ public string PortalFilepath { get; private set; }
///
/// File path of the actual file being read (Portal or local)
///
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();
- /*****************************************************************************************/
+ /*****************************************************************************************/
- ///
+ ///
/// SIMPL+ default constructor.
///
- public JsonToSimplPortalFileMaster()
+ public JsonToSimplPortalFileMaster()
{
- }
+ }
- ///
- /// Read, evaluate and udpate status
- ///
- public void EvaluateFile(string portalFilepath)
- {
- PortalFilepath = portalFilepath;
+ ///
+ /// Read, evaluate and udpate status
+ ///
+ 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;
+ }
+ }
- ///
- /// Returns the FileInfo object for a given path, with possible wildcards
- ///
- ///
- ///
- 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();
- }
+ ///
+ /// Returns the FileInfo object for a given path, with possible wildcards
+ ///
+ ///
+ ///
+ 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();
+ }
- ///
- ///
- ///
- ///
- public void setDebugLevel(int level)
- {
- Debug.SetDebugLevel(level);
- }
+ ///
+ ///
+ ///
+ ///
+ public void setDebugLevel(int level)
+ {
+ Debug.SetDebugLevel(level);
+ }
- ///
- ///
- ///
- public override void Save()
- {
- // this code is duplicated in the other masters!!!!!!!!!!!!!
- UnsavedValues = new Dictionary();
- // 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();
- }
+ ///
+ ///
+ ///
+ public override void Save()
+ {
+ // this code is duplicated in the other masters!!!!!!!!!!!!!
+ UnsavedValues = new Dictionary();
+ // 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;
+ }
+ }
+ }
+ }
+ }
}
diff --git a/src/Pepperdash Core/Logging/Debug.cs b/src/Pepperdash Core/Logging/Debug.cs
index 19961cc..12c7332 100644
--- a/src/Pepperdash Core/Logging/Debug.cs
+++ b/src/Pepperdash Core/Logging/Debug.cs
@@ -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
{
///
/// Contains debug commands for use in various situations
@@ -51,19 +50,19 @@ namespace PepperDash.Core
///
/// Version for the currently loaded PepperDashCore dll
///
- public static string PepperDashCoreVersion { get; private set; }
+ public static string PepperDashCoreVersion { get; private set; }
private static CTimer _saveTimer;
- ///
- /// When true, the IncludedExcludedKeys dict will contain keys to include.
- /// When false (default), IncludedExcludedKeys will contain keys to exclude.
- ///
- private static bool _excludeAllMode;
+ ///
+ /// When true, the IncludedExcludedKeys dict will contain keys to include.
+ /// When false (default), IncludedExcludedKeys will contain keys to exclude.
+ ///
+ private static bool _excludeAllMode;
- //static bool ExcludeNoKeyMessages;
+ //static bool ExcludeNoKeyMessages;
- private static readonly Dictionary IncludedExcludedKeys;
+ private static readonly Dictionary IncludedExcludedKeys;
static Debug()
{
@@ -85,26 +84,26 @@ namespace PepperDash.Core
LogError(ErrorLogLevel.Notice, msg);
- IncludedExcludedKeys = new Dictionary();
+ IncludedExcludedKeys = new Dictionary();
//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
///
///
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);
+ }
+ }
+ }
+ }
+ }
///
@@ -342,7 +341,7 @@ namespace PepperDash.Core
public static object GetDeviceDebugSettingsForKey(string deviceKey)
{
return _contexts.GetDebugSettingsForKey(deviceKey);
- }
+ }
///
/// 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
}
}
- ///
- /// Logs to Console when at-level, and all messages to error log
- ///
+ ///
+ /// Logs to Console when at-level, and all messages to error log
+ ///
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);
+ }
}
///
@@ -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
///
/// Error
///
- Error,
+ Error,
///
/// Warning
///
- Warning,
+ Warning,
///
/// Notice
///
- Notice,
+ Notice,
///
/// None
///
diff --git a/src/Pepperdash Core/Logging/DebugContext.cs b/src/Pepperdash Core/Logging/DebugContext.cs
index 2ff52be..3d0e9b0 100644
--- a/src/Pepperdash Core/Logging/DebugContext.cs
+++ b/src/Pepperdash Core/Logging/DebugContext.cs
@@ -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
{
///
/// Represents a debugging context
diff --git a/src/Pepperdash Core/Logging/DebugMemory.cs b/src/Pepperdash Core/Logging/DebugMemory.cs
index 0c74f1f..b10f001 100644
--- a/src/Pepperdash Core/Logging/DebugMemory.cs
+++ b/src/Pepperdash Core/Logging/DebugMemory.cs
@@ -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
{
///
/// Class to persist current Debug settings across program restarts
///
public class DebugContextCollection
- {
+ {
///
/// To prevent threading issues with the DeviceDebugSettings collection
///
private readonly CCriticalSection _deviceDebugSettingsLock;
- [JsonProperty("items")] private readonly Dictionary _items;
+ [JsonProperty("items")] private readonly Dictionary _items;
///
/// 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 DeviceDebugSettings { get; set; }
- ///
- /// Default constructor
- ///
- public DebugContextCollection()
- {
+ ///
+ /// Default constructor
+ ///
+ public DebugContextCollection()
+ {
_deviceDebugSettingsLock = new CCriticalSection();
DeviceDebugSettings = new Dictionary();
- _items = new Dictionary();
- }
+ _items = new Dictionary();
+ }
- ///
- /// Sets the level of a given context item, and adds that item if it does not
- /// exist
- ///
- ///
- ///
- public void SetLevel(string contextKey, int level)
- {
- if (level < 0 || level > 2)
- return;
- GetOrCreateItem(contextKey).Level = level;
- }
+ ///
+ /// Sets the level of a given context item, and adds that item if it does not
+ /// exist
+ ///
+ ///
+ ///
+ public void SetLevel(string contextKey, int level)
+ {
+ if (level < 0 || level > 2)
+ return;
+ GetOrCreateItem(contextKey).Level = level;
+ }
- ///
- /// Gets a level or creates it if not existing
- ///
- ///
- ///
- public DebugContextItem GetOrCreateItem(string contextKey)
- {
- if (!_items.ContainsKey(contextKey))
- _items[contextKey] = new DebugContextItem { Level = 0 };
- return _items[contextKey];
- }
+ ///
+ /// Gets a level or creates it if not existing
+ ///
+ ///
+ ///
+ public DebugContextItem GetOrCreateItem(string contextKey)
+ {
+ if (!_items.ContainsKey(contextKey))
+ _items[contextKey] = new DebugContextItem { Level = 0 };
+ return _items[contextKey];
+ }
///
@@ -96,23 +95,23 @@ namespace PepperDash.Core.DebugThings
{
return DeviceDebugSettings[deviceKey];
}
- }
+ }
- ///
- /// Contains information about
- ///
- public class DebugContextItem
- {
+ ///
+ /// Contains information about
+ ///
+ public class DebugContextItem
+ {
///
/// The level of debug messages to print
///
[JsonProperty("level")]
- public int Level { get; set; }
+ public int Level { get; set; }
///
/// Property to tell the program not to intitialize when it boots, if desired
///
[JsonProperty("doNotLoadOnNextBoot")]
public bool DoNotLoadOnNextBoot { get; set; }
- }
+ }
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/Network/DiscoveryThings.cs b/src/Pepperdash Core/Network/DiscoveryThings.cs
deleted file mode 100644
index 973c03a..0000000
--- a/src/Pepperdash Core/Network/DiscoveryThings.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using Crestron.SimplSharp;
-
-namespace PepperDash.Core
-{
- ///
- /// Not in use
- ///
- public static class NetworkComm
- {
- ///
- /// Not in use
- ///
- static NetworkComm()
- {
- }
- }
-
-}
\ No newline at end of file
diff --git a/src/Pepperdash Core/PasswordManagement/Config.cs b/src/Pepperdash Core/PasswordManagement/Config.cs
index 22aa488..b9f25e8 100644
--- a/src/Pepperdash Core/PasswordManagement/Config.cs
+++ b/src/Pepperdash Core/PasswordManagement/Config.cs
@@ -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
{
- ///
- /// JSON password configuration
- ///
- public class PasswordConfig
- {
- ///
- /// Password object configured password
- ///
- public string password { get; set; }
- ///
- /// Constructor
- ///
- public PasswordConfig()
- {
-
- }
- }
+ ///
+ /// JSON password configuration
+ ///
+ public class PasswordConfig
+ {
+ ///
+ /// Password object configured password
+ ///
+ public string password { get; set; }
+ ///
+ /// Constructor
+ ///
+ public PasswordConfig()
+ {
+
+ }
+ }
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/PasswordManagement/Constants.cs b/src/Pepperdash Core/PasswordManagement/Constants.cs
index 65a1bf4..2cf683c 100644
--- a/src/Pepperdash Core/PasswordManagement/Constants.cs
+++ b/src/Pepperdash Core/PasswordManagement/Constants.cs
@@ -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
{
- ///
- /// Constants
- ///
- public class PasswordManagementConstants
- {
- ///
- /// Generic boolean value change constant
- ///
- public const ushort BoolValueChange = 1;
- ///
- /// Evaluated boolean change constant
- ///
- public const ushort PasswordInitializedChange = 2;
- ///
- /// Update busy change const
- ///
- public const ushort PasswordUpdateBusyChange = 3;
- ///
- /// Password is valid change constant
- ///
- public const ushort PasswordValidationChange = 4;
- ///
- /// Password LED change constant
- ///
- public const ushort PasswordLedFeedbackChange = 5;
+ ///
+ /// Constants
+ ///
+ public class PasswordManagementConstants
+ {
+ ///
+ /// Generic boolean value change constant
+ ///
+ public const ushort BoolValueChange = 1;
+ ///
+ /// Evaluated boolean change constant
+ ///
+ public const ushort PasswordInitializedChange = 2;
+ ///
+ /// Update busy change const
+ ///
+ public const ushort PasswordUpdateBusyChange = 3;
+ ///
+ /// Password is valid change constant
+ ///
+ public const ushort PasswordValidationChange = 4;
+ ///
+ /// Password LED change constant
+ ///
+ public const ushort PasswordLedFeedbackChange = 5;
- ///
- /// Generic ushort value change constant
- ///
- public const ushort UshrtValueChange = 101;
- ///
- /// Password count
- ///
- public const ushort PasswordManagerCountChange = 102;
- ///
- /// Password selecte index change constant
- ///
- public const ushort PasswordSelectIndexChange = 103;
- ///
- /// Password length
- ///
- public const ushort PasswordLengthChange = 104;
-
- ///
- /// Generic string value change constant
- ///
- public const ushort StringValueChange = 201;
- }
+ ///
+ /// Generic ushort value change constant
+ ///
+ public const ushort UshrtValueChange = 101;
+ ///
+ /// Password count
+ ///
+ public const ushort PasswordManagerCountChange = 102;
+ ///
+ /// Password selecte index change constant
+ ///
+ public const ushort PasswordSelectIndexChange = 103;
+ ///
+ /// Password length
+ ///
+ public const ushort PasswordLengthChange = 104;
+
+ ///
+ /// Generic string value change constant
+ ///
+ public const ushort StringValueChange = 201;
+ }
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/PasswordManagement/PasswordClient.cs b/src/Pepperdash Core/PasswordManagement/PasswordClient.cs
index 933bd10..08252b0 100644
--- a/src/Pepperdash Core/PasswordManagement/PasswordClient.cs
+++ b/src/Pepperdash Core/PasswordManagement/PasswordClient.cs
@@ -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
///
public class PasswordClient
- {
- ///
- /// Password selected
- ///
- public string Password { get; set; }
- ///
- /// Password selected key
- ///
- public ushort Key { get; set; }
- ///
- /// Used to build the password entered by the user
- ///
- public string PasswordToValidate { get; set; }
+ {
+ ///
+ /// Password selected
+ ///
+ public string Password { get; set; }
+ ///
+ /// Password selected key
+ ///
+ public ushort Key { get; set; }
+ ///
+ /// Used to build the password entered by the user
+ ///
+ public string PasswordToValidate { get; set; }
- ///
- /// Boolean event
- ///
- public event EventHandler BoolChange;
- ///
- /// Ushort event
- ///
- public event EventHandler UshrtChange;
- ///
- /// String event
- ///
- public event EventHandler StringChange;
+ ///
+ /// Boolean event
+ ///
+ public event EventHandler BoolChange;
+ ///
+ /// Ushort event
+ ///
+ public event EventHandler UshrtChange;
+ ///
+ /// String event
+ ///
+ public event EventHandler StringChange;
- ///
- /// Constructor
- ///
- public PasswordClient()
- {
- PasswordManager.PasswordChange += new EventHandler(PasswordManager_PasswordChange);
- }
+ ///
+ /// Constructor
+ ///
+ public PasswordClient()
+ {
+ PasswordManager.PasswordChange += new EventHandler(PasswordManager_PasswordChange);
+ }
- ///
- /// Initialize method
- ///
- public void Initialize()
- {
- OnBoolChange(false, 0, PasswordManagementConstants.PasswordInitializedChange);
+ ///
+ /// Initialize method
+ ///
+ 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);
+ }
- ///
- /// Retrieve password by index
- ///
- ///
- public void GetPasswordByIndex(ushort key)
- {
- OnUshrtChange((ushort)PasswordManager.Passwords.Count, 0, PasswordManagementConstants.PasswordManagerCountChange);
+ ///
+ /// Retrieve password by index
+ ///
+ ///
+ 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);
+ }
- ///
- /// Password validation method
- ///
- ///
- public void ValidatePassword(string password)
- {
- if (string.IsNullOrEmpty(password))
- return;
+ ///
+ /// Password validation method
+ ///
+ ///
+ 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();
+ }
- ///
- /// 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
- ///
- ///
- public void BuildPassword(string data)
- {
- PasswordToValidate = String.Concat(PasswordToValidate, data);
- OnBoolChange(true, (ushort)PasswordToValidate.Length, PasswordManagementConstants.PasswordLedFeedbackChange);
+ ///
+ /// 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
+ ///
+ ///
+ 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);
+ }
- ///
- /// Clears the user entered password and resets the LEDs
- ///
- public void ClearPassword()
- {
- PasswordToValidate = "";
- OnBoolChange(false, (ushort)PasswordToValidate.Length, PasswordManagementConstants.PasswordLedFeedbackChange);
- }
+ ///
+ /// Clears the user entered password and resets the LEDs
+ ///
+ public void ClearPassword()
+ {
+ PasswordToValidate = "";
+ OnBoolChange(false, (ushort)PasswordToValidate.Length, PasswordManagementConstants.PasswordLedFeedbackChange);
+ }
- ///
- /// Protected boolean change event handler
- ///
- ///
- ///
- ///
- 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 boolean change event handler
+ ///
+ ///
+ ///
+ ///
+ 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 ushort change event handler
- ///
- ///
- ///
- ///
- 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);
- }
- }
+ ///
+ /// Protected ushort change event handler
+ ///
+ ///
+ ///
+ ///
+ 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);
+ }
+ }
- ///
- /// Protected string change event handler
- ///
- ///
- ///
- ///
- 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);
- }
- }
+ ///
+ /// Protected string change event handler
+ ///
+ ///
+ ///
+ ///
+ 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);
+ }
+ }
- ///
- /// If password changes while selected change event will be notifed and update the client
- ///
- ///
- ///
- protected void PasswordManager_PasswordChange(object sender, StringChangeEventArgs args)
- {
- //throw new NotImplementedException();
- if (Key == args.Index)
- {
- //PasswordSelectedKey = args.Index;
- //PasswordSelected = args.StringValue;
- GetPasswordByIndex(args.Index);
- }
- }
- }
+ ///
+ /// If password changes while selected change event will be notifed and update the client
+ ///
+ ///
+ ///
+ protected void PasswordManager_PasswordChange(object sender, StringChangeEventArgs args)
+ {
+ //throw new NotImplementedException();
+ if (Key == args.Index)
+ {
+ //PasswordSelectedKey = args.Index;
+ //PasswordSelected = args.StringValue;
+ GetPasswordByIndex(args.Index);
+ }
+ }
+ }
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/PasswordManagement/PasswordManager.cs b/src/Pepperdash Core/PasswordManagement/PasswordManager.cs
index d869e54..5cb56f7 100644
--- a/src/Pepperdash Core/PasswordManagement/PasswordManager.cs
+++ b/src/Pepperdash Core/PasswordManagement/PasswordManager.cs
@@ -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
///
public class PasswordManager
- {
- ///
- /// Public dictionary of known passwords
- ///
- public static Dictionary Passwords = new Dictionary();
- ///
- /// Private dictionary, used when passwords are updated
- ///
- private Dictionary _passwords = new Dictionary();
+ {
+ ///
+ /// Public dictionary of known passwords
+ ///
+ public static Dictionary Passwords = new Dictionary();
+ ///
+ /// Private dictionary, used when passwords are updated
+ ///
+ private Dictionary _passwords = new Dictionary();
- ///
- /// Timer used to wait until password changes have stopped before updating the dictionary
- ///
- CTimer PasswordTimer;
- ///
- /// Timer length
- ///
- public long PasswordTimerElapsedMs = 5000;
+ ///
+ /// Timer used to wait until password changes have stopped before updating the dictionary
+ ///
+ CTimer PasswordTimer;
+ ///
+ /// Timer length
+ ///
+ public long PasswordTimerElapsedMs = 5000;
- ///
- /// Boolean event
- ///
- public event EventHandler BoolChange;
- ///
- /// Ushort event
- ///
- public event EventHandler UshrtChange;
- ///
- /// String event
- ///
- public event EventHandler StringChange;
- ///
- /// Event to notify clients of an updated password at the specified index (uint)
- ///
- public static event EventHandler PasswordChange;
+ ///
+ /// Boolean event
+ ///
+ public event EventHandler BoolChange;
+ ///
+ /// Ushort event
+ ///
+ public event EventHandler UshrtChange;
+ ///
+ /// String event
+ ///
+ public event EventHandler StringChange;
+ ///
+ /// Event to notify clients of an updated password at the specified index (uint)
+ ///
+ public static event EventHandler PasswordChange;
- ///
- /// Constructor
- ///
- public PasswordManager()
- {
+ ///
+ /// Constructor
+ ///
+ public PasswordManager()
+ {
- }
+ }
- ///
- /// Initialize password manager
- ///
- public void Initialize()
- {
- if (Passwords == null)
- Passwords = new Dictionary();
+ ///
+ /// Initialize password manager
+ ///
+ public void Initialize()
+ {
+ if (Passwords == null)
+ Passwords = new Dictionary();
- if (_passwords == null)
- _passwords = new Dictionary();
+ if (_passwords == null)
+ _passwords = new Dictionary();
- OnBoolChange(true, 0, PasswordManagementConstants.PasswordInitializedChange);
- }
+ OnBoolChange(true, 0, PasswordManagementConstants.PasswordInitializedChange);
+ }
- ///
- /// Updates password stored in the dictonary
- ///
- ///
- ///
- 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;
- }
+ ///
+ /// Updates password stored in the dictonary
+ ///
+ ///
+ ///
+ 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]));
- ///
- /// CTimer callback function
- ///
- 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);
+ }
+ }
- ///
- /// Method to change the default timer value, (default 5000ms/5s)
- ///
- ///
- public void PasswordTimerMs(ushort time)
- {
- PasswordTimerElapsedMs = Convert.ToInt64(time);
- }
+ ///
+ /// CTimer callback function
+ ///
+ 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);
+ }
+ }
- ///
- /// Helper method for debugging to see what passwords are in the lists
- ///
- 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);
- }
+ ///
+ /// Method to change the default timer value, (default 5000ms/5s)
+ ///
+ ///
+ public void PasswordTimerMs(ushort time)
+ {
+ PasswordTimerElapsedMs = Convert.ToInt64(time);
+ }
- ///
- /// Protected boolean change event handler
- ///
- ///
- ///
- ///
- 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);
- }
- }
+ ///
+ /// Helper method for debugging to see what passwords are in the lists
+ ///
+ 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);
+ }
- ///
- /// Protected ushort change event handler
- ///
+ ///
+ /// Protected boolean change event handler
+ ///
+ ///
+ ///
+ ///
+ 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 ushort change event handler
+ ///
///
- ///
- ///
- 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);
- }
- }
+ ///
+ ///
+ 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);
+ }
+ }
- ///
- /// Protected string change event handler
- ///
- ///
- ///
- ///
- 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);
- }
- }
+ ///
+ /// Protected string change event handler
+ ///
+ ///
+ ///
+ ///
+ 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);
+ }
+ }
- ///
- /// Protected password change event handler
- ///
- ///
- ///
- ///
- 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);
- }
- }
- }
+ ///
+ /// Protected password change event handler
+ ///
+ ///
+ ///
+ ///
+ 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);
+ }
+ }
+ }
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/PepperDash_Core.csproj b/src/Pepperdash Core/PepperDash_Core.csproj
deleted file mode 100644
index 78b17a2..0000000
--- a/src/Pepperdash Core/PepperDash_Core.csproj
+++ /dev/null
@@ -1,53 +0,0 @@
-
-
- PepperDash.Core
- PepperDashCore
- net472
- false
- en
- bin\$(Configuration)\
- False
- True
- PepperDash Core
- PepperDash Technologies
- git
- https://github.com/PepperDash/PepperDashCore
- crestron;4series;
- $(Version)
- ../../package
-
-
- full
- TRACE;DEBUG;SERIES4
-
-
- pdbonly
- bin\4Series\$(Configuration)\PepperDashCore.xml
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- crestron
-
-
-
-
\ No newline at end of file
diff --git a/src/Pepperdash Core/PepperDash_Core.projectinfo b/src/Pepperdash Core/PepperDash_Core.projectinfo
deleted file mode 100644
index ded18d3..0000000
Binary files a/src/Pepperdash Core/PepperDash_Core.projectinfo and /dev/null differ
diff --git a/src/Pepperdash Core/SystemInfo/EventArgs and Constants.cs b/src/Pepperdash Core/SystemInfo/EventArgs and Constants.cs
index cc71e30..d387c82 100644
--- a/src/Pepperdash Core/SystemInfo/EventArgs and Constants.cs
+++ b/src/Pepperdash Core/SystemInfo/EventArgs and Constants.cs
@@ -1,264 +1,260 @@
using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using Crestron.SimplSharp;
namespace PepperDash.Core.SystemInfo
{
- ///
- /// Constants
- ///
- public class SystemInfoConstants
- {
+ ///
+ /// Constants
+ ///
+ public class SystemInfoConstants
+ {
///
///
///
public const ushort BoolValueChange = 1;
- ///
- ///
- ///
- public const ushort CompleteBoolChange = 2;
- ///
- ///
- ///
- public const ushort BusyBoolChange = 3;
-
///
///
///
- public const ushort UshortValueChange = 101;
+ public const ushort CompleteBoolChange = 2;
+ ///
+ ///
+ ///
+ public const ushort BusyBoolChange = 3;
+
+ ///
+ ///
+ ///
+ public const ushort UshortValueChange = 101;
///
///
///
public const ushort StringValueChange = 201;
- ///
- ///
- ///
+ ///
+ ///
+ ///
public const ushort ConsoleResponseChange = 202;
- ///
- ///
- ///
+ ///
+ ///
+ ///
public const ushort ProcessorUptimeChange = 203;
- ///
- ///
- ///
+ ///
+ ///
+ ///
public const ushort ProgramUptimeChange = 204;
///
///
///
public const ushort ObjectChange = 301;
- ///
- ///
- ///
+ ///
+ ///
+ ///
public const ushort ProcessorConfigChange = 302;
- ///
- ///
- ///
+ ///
+ ///
+ ///
public const ushort EthernetConfigChange = 303;
- ///
- ///
- ///
+ ///
+ ///
+ ///
public const ushort ControlSubnetConfigChange = 304;
- ///
- ///
- ///
+ ///
+ ///
+ ///
public const ushort ProgramConfigChange = 305;
- }
+ }
- ///
- /// Processor Change Event Args Class
- ///
- public class ProcessorChangeEventArgs : EventArgs
- {
+ ///
+ /// Processor Change Event Args Class
+ ///
+ public class ProcessorChangeEventArgs : EventArgs
+ {
///
///
///
public ProcessorInfo Processor { get; set; }
- ///
- ///
- ///
+ ///
+ ///
+ ///
public ushort Type { get; set; }
- ///
- ///
- ///
+ ///
+ ///
+ ///
public ushort Index { get; set; }
- ///
- /// Constructor
- ///
- public ProcessorChangeEventArgs()
- {
+ ///
+ /// Constructor
+ ///
+ public ProcessorChangeEventArgs()
+ {
- }
+ }
- ///
- /// Constructor overload
- ///
- public ProcessorChangeEventArgs(ProcessorInfo processor, ushort type)
- {
- Processor = processor;
- Type = type;
- }
+ ///
+ /// Constructor overload
+ ///
+ public ProcessorChangeEventArgs(ProcessorInfo processor, ushort type)
+ {
+ Processor = processor;
+ Type = type;
+ }
- ///
- /// Constructor
- ///
- public ProcessorChangeEventArgs(ProcessorInfo processor, ushort type, ushort index)
- {
- Processor = processor;
- Type = type;
- Index = index;
- }
- }
+ ///
+ /// Constructor
+ ///
+ public ProcessorChangeEventArgs(ProcessorInfo processor, ushort type, ushort index)
+ {
+ Processor = processor;
+ Type = type;
+ Index = index;
+ }
+ }
- ///
- /// Ethernet Change Event Args Class
- ///
- public class EthernetChangeEventArgs : EventArgs
- {
+ ///
+ /// Ethernet Change Event Args Class
+ ///
+ public class EthernetChangeEventArgs : EventArgs
+ {
///
///
///
public EthernetInfo Adapter { get; set; }
- ///
- ///
- ///
+ ///
+ ///
+ ///
public ushort Type { get; set; }
- ///
- ///
- ///
+ ///
+ ///
+ ///
public ushort Index { get; set; }
- ///
- /// Constructor
- ///
- public EthernetChangeEventArgs()
- {
+ ///
+ /// Constructor
+ ///
+ public EthernetChangeEventArgs()
+ {
- }
+ }
- ///
- /// Constructor overload
- ///
+ ///
+ /// Constructor overload
+ ///
///
- ///
- public EthernetChangeEventArgs(EthernetInfo ethernet, ushort type)
- {
- Adapter = ethernet;
- Type = type;
- }
+ ///
+ public EthernetChangeEventArgs(EthernetInfo ethernet, ushort type)
+ {
+ Adapter = ethernet;
+ Type = type;
+ }
- ///
- /// Constructor overload
- ///
+ ///
+ /// Constructor overload
+ ///
///
- ///
+ ///
///
- 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;
+ }
+ }
- ///
- /// Control Subnet Chage Event Args Class
- ///
- public class ControlSubnetChangeEventArgs : EventArgs
- {
+ ///
+ /// Control Subnet Chage Event Args Class
+ ///
+ public class ControlSubnetChangeEventArgs : EventArgs
+ {
///
///
///
public ControlSubnetInfo Adapter { get; set; }
- ///
- ///
- ///
+ ///
+ ///
+ ///
public ushort Type { get; set; }
- ///
- ///
- ///
+ ///
+ ///
+ ///
public ushort Index { get; set; }
- ///
- /// Constructor
- ///
- public ControlSubnetChangeEventArgs()
- {
+ ///
+ /// Constructor
+ ///
+ public ControlSubnetChangeEventArgs()
+ {
- }
+ }
- ///
- /// Constructor overload
- ///
- public ControlSubnetChangeEventArgs(ControlSubnetInfo controlSubnet, ushort type)
- {
- Adapter = controlSubnet;
- Type = type;
- }
+ ///
+ /// Constructor overload
+ ///
+ public ControlSubnetChangeEventArgs(ControlSubnetInfo controlSubnet, ushort type)
+ {
+ Adapter = controlSubnet;
+ Type = type;
+ }
- ///
- /// Constructor overload
- ///
- public ControlSubnetChangeEventArgs(ControlSubnetInfo controlSubnet, ushort type, ushort index)
- {
- Adapter = controlSubnet;
- Type = type;
- Index = index;
- }
- }
+ ///
+ /// Constructor overload
+ ///
+ public ControlSubnetChangeEventArgs(ControlSubnetInfo controlSubnet, ushort type, ushort index)
+ {
+ Adapter = controlSubnet;
+ Type = type;
+ Index = index;
+ }
+ }
- ///
- /// Program Change Event Args Class
- ///
- public class ProgramChangeEventArgs : EventArgs
- {
+ ///
+ /// Program Change Event Args Class
+ ///
+ public class ProgramChangeEventArgs : EventArgs
+ {
///
///
///
public ProgramInfo Program { get; set; }
- ///
- ///
- ///
+ ///
+ ///
+ ///
public ushort Type { get; set; }
- ///
- ///
- ///
+ ///
+ ///
+ ///
public ushort Index { get; set; }
- ///
- /// Constructor
- ///
- public ProgramChangeEventArgs()
- {
+ ///
+ /// Constructor
+ ///
+ public ProgramChangeEventArgs()
+ {
- }
+ }
- ///
- /// Constructor overload
- ///
+ ///
+ /// Constructor overload
+ ///
///
- ///
- public ProgramChangeEventArgs(ProgramInfo program, ushort type)
- {
- Program = program;
- Type = type;
- }
+ ///
+ public ProgramChangeEventArgs(ProgramInfo program, ushort type)
+ {
+ Program = program;
+ Type = type;
+ }
- ///
- /// Constructor overload
- ///
+ ///
+ /// Constructor overload
+ ///
///
- ///
+ ///
///
- 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;
+ }
+ }
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/SystemInfo/SystemInfoConfig.cs b/src/Pepperdash Core/SystemInfo/SystemInfoConfig.cs
index 8dc3aca..120fc4a 100644
--- a/src/Pepperdash Core/SystemInfo/SystemInfoConfig.cs
+++ b/src/Pepperdash Core/SystemInfo/SystemInfoConfig.cs
@@ -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
{
- ///
- /// Processor info class
- ///
- public class ProcessorInfo
- {
+ ///
+ /// Processor info class
+ ///
+ public class ProcessorInfo
+ {
///
///
///
@@ -52,20 +46,20 @@ namespace PepperDash.Core.SystemInfo
///
public string ProgramIdTag { get; set; }
- ///
- /// Constructor
- ///
- public ProcessorInfo()
- {
-
- }
- }
+ ///
+ /// Constructor
+ ///
+ public ProcessorInfo()
+ {
- ///
- /// Ethernet info class
- ///
- public class EthernetInfo
- {
+ }
+ }
+
+ ///
+ /// Ethernet info class
+ ///
+ public class EthernetInfo
+ {
///
///
///
@@ -107,20 +101,20 @@ namespace PepperDash.Core.SystemInfo
///
public string Domain { get; set; }
- ///
- /// Constructor
- ///
- public EthernetInfo()
- {
-
- }
- }
+ ///
+ /// Constructor
+ ///
+ public EthernetInfo()
+ {
- ///
- /// Control subnet info class
- ///
- public class ControlSubnetInfo
- {
+ }
+ }
+
+ ///
+ /// Control subnet info class
+ ///
+ public class ControlSubnetInfo
+ {
///
///
///
@@ -146,20 +140,20 @@ namespace PepperDash.Core.SystemInfo
///
public string RouterPrefix { get; set; }
- ///
- /// Constructor
- ///
- public ControlSubnetInfo()
- {
-
- }
- }
+ ///
+ /// Constructor
+ ///
+ public ControlSubnetInfo()
+ {
- ///
- /// Program info class
- ///
- public class ProgramInfo
- {
+ }
+ }
+
+ ///
+ /// Program info class
+ ///
+ public class ProgramInfo
+ {
///
///
///
@@ -193,12 +187,12 @@ namespace PepperDash.Core.SystemInfo
///
public string Programmer { get; set; }
- ///
- /// Constructor
- ///
- public ProgramInfo()
- {
-
- }
- }
+ ///
+ /// Constructor
+ ///
+ public ProgramInfo()
+ {
+
+ }
+ }
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/SystemInfo/SystemInfoToSimpl.cs b/src/Pepperdash Core/SystemInfo/SystemInfoToSimpl.cs
index 6677b9e..8ec84b5 100644
--- a/src/Pepperdash Core/SystemInfo/SystemInfoToSimpl.cs
+++ b/src/Pepperdash Core/SystemInfo/SystemInfoToSimpl.cs
@@ -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
{
- ///
- /// System Info class
- ///
- public class SystemInfoToSimpl
- {
+ ///
+ /// System Info class
+ ///
+ public class SystemInfoToSimpl
+ {
///
/// Notifies of bool change
///
@@ -37,426 +34,426 @@ namespace PepperDash.Core.SystemInfo
///
public event EventHandler ProgramChange;
- ///
- /// Constructor
- ///
- public SystemInfoToSimpl()
- {
+ ///
+ /// Constructor
+ ///
+ public SystemInfoToSimpl()
+ {
- }
+ }
- ///
- /// Gets the current processor info
- ///
- public void GetProcessorInfo()
- {
- OnBoolChange(true, 0, SystemInfoConstants.BusyBoolChange);
+ ///
+ /// Gets the current processor info
+ ///
+ 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);
+ }
- ///
- /// Gets the current ethernet info
- ///
- public void GetEthernetInfo()
- {
- OnBoolChange(true, 0, SystemInfoConstants.BusyBoolChange);
+ ///
+ /// Gets the current ethernet info
+ ///
+ 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);
+ }
- ///
- /// Gets the current control subnet info
- ///
- public void GetControlSubnetInfo()
- {
- OnBoolChange(true, 0, SystemInfoConstants.BusyBoolChange);
+ ///
+ /// Gets the current control subnet info
+ ///
+ 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);
+ }
- ///
- /// Gets the program info by index
- ///
- ///
- public void GetProgramInfoByIndex(ushort index)
- {
- if (index < 1 || index > 10)
- return;
+ ///
+ /// Gets the program info by index
+ ///
+ ///
+ 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);
- }
+ }
- ///
- /// Gets the processor uptime and passes it to S+
- ///
- 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);
+ }
- ///
- /// Gets the program uptime, by index, and passes it to S+
- ///
- ///
- 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);
+ }
- ///
- /// Sends command to console, passes response back using string change event
- ///
- ///
- public void SendConsoleCommand(string cmd)
- {
- if (string.IsNullOrEmpty(cmd))
- return;
+ ///
+ /// Gets the processor uptime and passes it to S+
+ ///
+ 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');
+ ///
+ /// Gets the program uptime, by index, and passes it to S+
+ ///
+ ///
+ 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);
- }
- }
+ ///
+ /// Sends command to console, passes response back using string change event
+ ///
+ ///
+ public void SendConsoleCommand(string cmd)
+ {
+ if (string.IsNullOrEmpty(cmd))
+ return;
- ///
- /// private method to parse console messages
- ///
+ string response = "";
+ CrestronConsole.SendControlSystemCommand(cmd, ref response);
+ if (!string.IsNullOrEmpty(response))
+ {
+ if (response.EndsWith("\x0D\\x0A"))
+ response.Trim('\n');
+
+ OnStringChange(response, 0, SystemInfoConstants.ConsoleResponseChange);
+ }
+ }
+
+ ///
+ /// private method to parse console messages
+ ///
///
- ///
+ ///
///
///
- ///
- private string ParseConsoleResponse(string data, string line, string dataStart, string dataEnd)
- {
- var response = "";
+ ///
+ 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;
+ }
- ///
- /// Protected boolean change event handler
- ///
- ///
- ///
- ///
- 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 boolean change event handler
+ ///
+ ///
+ ///
+ ///
+ 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 string change event handler
- ///
- ///
- ///
- ///
- 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);
- }
- }
+ ///
+ /// Protected string change event handler
+ ///
+ ///
+ ///
+ ///
+ 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);
+ }
+ }
- ///
- /// Protected processor config change event handler
- ///
- ///
- ///
- ///
- 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);
- }
- }
+ ///
+ /// Protected processor config change event handler
+ ///
+ ///
+ ///
+ ///
+ 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);
+ }
+ }
- ///
- /// Ethernet change event handler
- ///
- ///
- ///
- ///
- 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);
- }
- }
+ ///
+ /// Ethernet change event handler
+ ///
+ ///
+ ///
+ ///
+ 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);
+ }
+ }
- ///
- /// Control Subnet change event handler
- ///
- ///
- ///
- ///
- 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);
- }
- }
+ ///
+ /// Control Subnet change event handler
+ ///
+ ///
+ ///
+ ///
+ 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);
+ }
+ }
- ///
- /// Program change event handler
- ///
- ///
- ///
- ///
- protected void OnProgramChange(ProgramInfo program, ushort index, ushort type)
- {
- var handler = ProgramChange;
+ ///
+ /// Program change event handler
+ ///
+ ///
+ ///
+ ///
+ 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);
+ }
+ }
+ }
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/WebApi/Presets/Preset.cs b/src/Pepperdash Core/WebApi/Presets/Preset.cs
index 2cc762e..6ac5d3c 100644
--- a/src/Pepperdash Core/WebApi/Presets/Preset.cs
+++ b/src/Pepperdash Core/WebApi/Presets/Preset.cs
@@ -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
///
public class Preset
- {
+ {
///
/// ID of preset
///
@@ -50,23 +44,23 @@ namespace PepperDash.Core.WebApi.Presets
/// Constructor
///
public Preset()
- {
- PresetName = "";
- PresetNumber = 1;
- Data = "{}";
- }
- }
+ {
+ PresetName = "";
+ PresetNumber = 1;
+ Data = "{}";
+ }
+ }
- ///
- ///
- ///
- public class PresetReceivedEventArgs : EventArgs
- {
+ ///
+ ///
+ ///
+ public class PresetReceivedEventArgs : EventArgs
+ {
///
/// True when the preset is found
///
public bool LookupSuccess { get; private set; }
-
+
///
/// S+ helper
///
@@ -77,10 +71,10 @@ namespace PepperDash.Core.WebApi.Presets
///
public Preset Preset { get; private set; }
- ///
- /// For Simpl+
- ///
- public PresetReceivedEventArgs() { }
+ ///
+ /// For Simpl+
+ ///
+ public PresetReceivedEventArgs() { }
///
/// Constructor
@@ -88,9 +82,9 @@ namespace PepperDash.Core.WebApi.Presets
///
///
public PresetReceivedEventArgs(Preset preset, bool success)
- {
+ {
LookupSuccess = success;
- Preset = preset;
- }
- }
+ Preset = preset;
+ }
+ }
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/WebApi/Presets/User.cs b/src/Pepperdash Core/WebApi/Presets/User.cs
index c82824f..54fce7f 100644
--- a/src/Pepperdash Core/WebApi/Presets/User.cs
+++ b/src/Pepperdash Core/WebApi/Presets/User.cs
@@ -1,25 +1,21 @@
using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using Crestron.SimplSharp;
namespace PepperDash.Core.WebApi.Presets
{
- ///
- ///
- ///
- public class User
- {
+ ///
+ ///
+ ///
+ public class User
+ {
///
///
///
public int Id { get; set; }
-
+
///
///
///
- public string ExternalId { get; set; }
+ public string ExternalId { get; set; }
///
///
@@ -30,14 +26,14 @@ namespace PepperDash.Core.WebApi.Presets
///
///
public string LastName { get; set; }
- }
+ }
- ///
- ///
- ///
- public class UserReceivedEventArgs : EventArgs
- {
+ ///
+ ///
+ ///
+ public class UserReceivedEventArgs : EventArgs
+ {
///
/// True when user is found
///
@@ -53,10 +49,10 @@ namespace PepperDash.Core.WebApi.Presets
///
public User User { get; private set; }
- ///
- /// For Simpl+
- ///
- public UserReceivedEventArgs() { }
+ ///
+ /// For Simpl+
+ ///
+ public UserReceivedEventArgs() { }
///
/// Constructor
@@ -64,17 +60,17 @@ namespace PepperDash.Core.WebApi.Presets
///
///
public UserReceivedEventArgs(User user, bool success)
- {
+ {
LookupSuccess = success;
- User = user;
- }
- }
+ User = user;
+ }
+ }
- ///
- ///
- ///
- public class UserAndRoomMessage
- {
+ ///
+ ///
+ ///
+ public class UserAndRoomMessage
+ {
///
///
///
@@ -89,5 +85,5 @@ namespace PepperDash.Core.WebApi.Presets
///
///
public int PresetNumber { get; set; }
- }
+ }
}
\ No newline at end of file
diff --git a/src/Pepperdash Core/WebApi/Presets/WebApiPasscodeClient.cs b/src/Pepperdash Core/WebApi/Presets/WebApiPasscodeClient.cs
index a16a6e0..8bff2cf 100644
--- a/src/Pepperdash Core/WebApi/Presets/WebApiPasscodeClient.cs
+++ b/src/Pepperdash Core/WebApi/Presets/WebApiPasscodeClient.cs
@@ -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
///
public class WebApiPasscodeClient : IKeyed
- {
+ {
///
/// Notifies when user received
///
@@ -36,29 +34,29 @@ namespace PepperDash.Core.WebApi.Presets
///
public string Key { get; private set; }
- //string JsonMasterKey;
+ //string JsonMasterKey;
- ///
- /// An embedded JsonToSimpl master object.
- ///
- JsonToSimplGenericMaster J2SMaster;
+ ///
+ /// An embedded JsonToSimpl master object.
+ ///
+ JsonToSimplGenericMaster J2SMaster;
- string UrlBase;
+ string UrlBase;
- string DefaultPresetJsonFilePath;
+ string DefaultPresetJsonFilePath;
- User CurrentUser;
+ User CurrentUser;
- Preset CurrentPreset;
+ Preset CurrentPreset;
- ///
- /// SIMPL+ can only execute the default constructor. If you have variables that require initialization, please
- /// use an Initialize method
- ///
- public WebApiPasscodeClient()
- {
- }
+ ///
+ /// SIMPL+ can only execute the default constructor. If you have variables that require initialization, please
+ /// use an Initialize method
+ ///
+ public WebApiPasscodeClient()
+ {
+ }
///
/// Initializes the instance
@@ -68,23 +66,23 @@ namespace PepperDash.Core.WebApi.Presets
///
///
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);
+ }
///
/// Gets the user for a passcode
///
///
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));
+ }
- ///
- ///
- ///
- ///
- ///
- public void GetPresetForThisUser(int roomTypeId, int presetNumber)
- {
- if (CurrentUser == null)
- {
- CrestronConsole.PrintLine("GetPresetForThisUser no user loaded");
- return;
- }
+ ///
+ ///
+ ///
+ ///
+ ///
+ 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);
+ }
+ }
+ }
- ///
- ///
- ///
- ///
- ///
- public void SavePresetForThisUser(int roomTypeId, int presetNumber)
- {
- if (CurrentPreset == null)
- LoadDefaultPresetData();
- //return;
+ ///
+ ///
+ ///
+ ///
+ ///
+ 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
+ }
- ///
- /// After save operation on JSON master happens, send it to server
- ///
- ///
- void SaveCallback(string json)
- {
- CurrentPreset.Data = json;
+ ///
+ /// After save operation on JSON master happens, send it to server
+ ///
+ ///
+ 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);
+ }
+ }
+ }
}
diff --git a/src/Pepperdash Core/XSigUtility/Serialization/IXSigSerialization.cs b/src/Pepperdash Core/XSigUtility/Serialization/IXSigSerialization.cs
index 8303731..df42d47 100644
--- a/src/Pepperdash Core/XSigUtility/Serialization/IXSigSerialization.cs
+++ b/src/Pepperdash Core/XSigUtility/Serialization/IXSigSerialization.cs
@@ -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
{
///
/// Interface to determine XSig serialization for an object.
diff --git a/src/Pepperdash Core/XSigUtility/Serialization/XSigSerializationException.cs b/src/Pepperdash Core/XSigUtility/Serialization/XSigSerializationException.cs
index 8f3fc04..6d02bde 100644
--- a/src/Pepperdash Core/XSigUtility/Serialization/XSigSerializationException.cs
+++ b/src/Pepperdash Core/XSigUtility/Serialization/XSigSerializationException.cs
@@ -1,6 +1,6 @@
using System;
-namespace PepperDash.Core.Intersystem.Serialization
+namespace PepperDash.Core.XSigUtility.Serialization
{
///
/// Class to handle this specific exception type
diff --git a/src/Pepperdash Core/XSigUtility/Tokens/XSigAnalogToken.cs b/src/Pepperdash Core/XSigUtility/Tokens/XSigAnalogToken.cs
index 5847336..e2ce0aa 100644
--- a/src/Pepperdash Core/XSigUtility/Tokens/XSigAnalogToken.cs
+++ b/src/Pepperdash Core/XSigUtility/Tokens/XSigAnalogToken.cs
@@ -1,6 +1,6 @@
using System;
-namespace PepperDash.Core.Intersystem.Tokens
+namespace PepperDash.Core.XSigUtility.Tokens
{
///
/// 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)
};
diff --git a/src/Pepperdash Core/XSigUtility/Tokens/XSigDigitalToken.cs b/src/Pepperdash Core/XSigUtility/Tokens/XSigDigitalToken.cs
index 70ccc85..80f3819 100644
--- a/src/Pepperdash Core/XSigUtility/Tokens/XSigDigitalToken.cs
+++ b/src/Pepperdash Core/XSigUtility/Tokens/XSigDigitalToken.cs
@@ -1,6 +1,6 @@
using System;
-namespace PepperDash.Core.Intersystem.Tokens
+namespace PepperDash.Core.XSigUtility.Tokens
{
///
/// 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)
};
}
diff --git a/src/Pepperdash Core/XSigUtility/Tokens/XSigSerialToken.cs b/src/Pepperdash Core/XSigUtility/Tokens/XSigSerialToken.cs
index 25ee3fd..5e7b19d 100644
--- a/src/Pepperdash Core/XSigUtility/Tokens/XSigSerialToken.cs
+++ b/src/Pepperdash Core/XSigUtility/Tokens/XSigSerialToken.cs
@@ -1,7 +1,7 @@
using System;
using System.Text;
-namespace PepperDash.Core.Intersystem.Tokens
+namespace PepperDash.Core.XSigUtility.Tokens
{
///
/// Represents an XSigSerialToken
@@ -47,11 +47,11 @@ namespace PepperDash.Core.Intersystem.Tokens
///
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);
diff --git a/src/Pepperdash Core/XSigUtility/Tokens/XSigToken.cs b/src/Pepperdash Core/XSigUtility/Tokens/XSigToken.cs
index 4c00a2e..1c004a0 100644
--- a/src/Pepperdash Core/XSigUtility/Tokens/XSigToken.cs
+++ b/src/Pepperdash Core/XSigUtility/Tokens/XSigToken.cs
@@ -1,4 +1,4 @@
-namespace PepperDash.Core.Intersystem.Tokens
+namespace PepperDash.Core.XSigUtility.Tokens
{
///
/// Represents the base class for all XSig datatypes.
diff --git a/src/Pepperdash Core/XSigUtility/Tokens/XSigTokenType.cs b/src/Pepperdash Core/XSigUtility/Tokens/XSigTokenType.cs
index 26d6c12..b644352 100644
--- a/src/Pepperdash Core/XSigUtility/Tokens/XSigTokenType.cs
+++ b/src/Pepperdash Core/XSigUtility/Tokens/XSigTokenType.cs
@@ -1,4 +1,4 @@
-namespace PepperDash.Core.Intersystem.Tokens
+namespace PepperDash.Core.XSigUtility.Tokens
{
///
/// XSig token types.
diff --git a/src/Pepperdash Core/XSigUtility/XSigHelpers.cs b/src/Pepperdash Core/XSigUtility/XSigHelpers.cs
index 4ea6f63..dab7784 100644
--- a/src/Pepperdash Core/XSigUtility/XSigHelpers.cs
+++ b/src/Pepperdash Core/XSigUtility/XSigHelpers.cs
@@ -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
{
///
/// Helper methods for creating XSig byte sequences compatible with the Intersystem Communications (ISC) symbol.
diff --git a/src/Pepperdash Core/XSigUtility/XSigTokenStreamReader.cs b/src/Pepperdash Core/XSigUtility/XSigTokenStreamReader.cs
index 9d70d02..94adf02 100644
--- a/src/Pepperdash Core/XSigUtility/XSigTokenStreamReader.cs
+++ b/src/Pepperdash Core/XSigUtility/XSigTokenStreamReader.cs
@@ -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
{
///
/// 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);
}
diff --git a/src/Pepperdash Core/XSigUtility/XSigTokenStreamWriter.cs b/src/Pepperdash Core/XSigUtility/XSigTokenStreamWriter.cs
index 934f2c2..148fe28 100644
--- a/src/Pepperdash Core/XSigUtility/XSigTokenStreamWriter.cs
+++ b/src/Pepperdash Core/XSigUtility/XSigTokenStreamWriter.cs
@@ -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
{
///
/// XSigToken stream writer.
diff --git a/src/Pepperdash Core/lib/net35/PepperDash_Core.clz b/src/Pepperdash Core/lib/net35/PepperDash_Core.clz
deleted file mode 100644
index 93e2b02..0000000
Binary files a/src/Pepperdash Core/lib/net35/PepperDash_Core.clz and /dev/null differ
diff --git a/src/Pepperdash Core/lib/net35/PepperDash_Core.dll b/src/Pepperdash Core/lib/net35/PepperDash_Core.dll
deleted file mode 100644
index 1b3d097..0000000
Binary files a/src/Pepperdash Core/lib/net35/PepperDash_Core.dll and /dev/null differ