fix: update solution filename and folder paths for workflow expectations.

This commit is contained in:
Jonathan Arndt 2025-05-05 16:46:17 -07:00
parent 083b935d71
commit d84eca0cc4
83 changed files with 12323 additions and 12342 deletions

View file

@ -1,19 +0,0 @@
Microsoft Visual Studio Solution File, Format Version 10.00
# Visual Studio 2008
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PepperDash_Core", "Pepperdash Core\PepperDash_Core.csproj", "{87E29B4C-569B-4368-A4ED-984AC1440C96}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{87E29B4C-569B-4368-A4ED-984AC1440C96}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{87E29B4C-569B-4368-A4ED-984AC1440C96}.Debug|Any CPU.Build.0 = Debug|Any CPU
{87E29B4C-569B-4368-A4ED-984AC1440C96}.Release|Any CPU.ActiveCfg = Release|Any CPU
{87E29B4C-569B-4368-A4ED-984AC1440C96}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View file

@ -1,19 +1,19 @@
Microsoft Visual Studio Solution File, Format Version 10.00 Microsoft Visual Studio Solution File, Format Version 10.00
# Visual Studio 2008 # Visual Studio 2008
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PepperDash_Core", "Pepperdash Core\PepperDash_Core.csproj", "{87E29B4C-569B-4368-A4ED-984AC1440C96}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PepperDash_Core", "src\PepperDash_Core.csproj", "{87E29B4C-569B-4368-A4ED-984AC1440C96}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU Release|Any CPU = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution GlobalSection(ProjectConfigurationPlatforms) = postSolution
{87E29B4C-569B-4368-A4ED-984AC1440C96}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {87E29B4C-569B-4368-A4ED-984AC1440C96}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{87E29B4C-569B-4368-A4ED-984AC1440C96}.Debug|Any CPU.Build.0 = Debug|Any CPU {87E29B4C-569B-4368-A4ED-984AC1440C96}.Debug|Any CPU.Build.0 = Debug|Any CPU
{87E29B4C-569B-4368-A4ED-984AC1440C96}.Release|Any CPU.ActiveCfg = Release|Any CPU {87E29B4C-569B-4368-A4ED-984AC1440C96}.Release|Any CPU.ActiveCfg = Release|Any CPU
{87E29B4C-569B-4368-A4ED-984AC1440C96}.Release|Any CPU.Build.0 = Release|Any CPU {87E29B4C-569B-4368-A4ED-984AC1440C96}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
EndGlobalSection EndGlobalSection
EndGlobal EndGlobal

View file

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

View file

@ -1,251 +1,251 @@
/*PepperDash Technology Corp. /*PepperDash Technology Corp.
Copyright: 2017 Copyright: 2017
------------------------------------ ------------------------------------
***Notice of Ownership and Copyright*** ***Notice of Ownership and Copyright***
The material in which this notice appears is the property of PepperDash Technology Corporation, The material in which this notice appears is the property of PepperDash Technology Corporation,
which claims copyright under the laws of the United States of America in the entire body of material which claims copyright under the laws of the United States of America in the entire body of material
and in all parts thereof, regardless of the use to which it is being put. Any use, in whole or in part, and in all parts thereof, regardless of the use to which it is being put. Any use, in whole or in part,
of this material by another party without the express written permission of PepperDash Technology Corporation is prohibited. 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. PepperDash Technology Corporation reserves all rights under applicable laws.
------------------------------------ */ ------------------------------------ */
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Crestron.SimplSharp; using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronSockets; using Crestron.SimplSharp.CrestronSockets;
namespace PepperDash.Core namespace PepperDash.Core
{ {
/// <summary> /// <summary>
/// Delegate for notifying of socket status changes /// Delegate for notifying of socket status changes
/// </summary> /// </summary>
/// <param name="client"></param> /// <param name="client"></param>
public delegate void GenericSocketStatusChangeEventDelegate(ISocketStatus client); public delegate void GenericSocketStatusChangeEventDelegate(ISocketStatus client);
/// <summary> /// <summary>
/// EventArgs class for socket status changes /// EventArgs class for socket status changes
/// </summary> /// </summary>
public class GenericSocketStatusChageEventArgs : EventArgs public class GenericSocketStatusChageEventArgs : EventArgs
{ {
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public ISocketStatus Client { get; private set; } public ISocketStatus Client { get; private set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <param name="client"></param> /// <param name="client"></param>
public GenericSocketStatusChageEventArgs(ISocketStatus client) public GenericSocketStatusChageEventArgs(ISocketStatus client)
{ {
Client = client; Client = client;
} }
/// <summary> /// <summary>
/// S+ Constructor /// S+ Constructor
/// </summary> /// </summary>
public GenericSocketStatusChageEventArgs() { } public GenericSocketStatusChageEventArgs() { }
} }
/// <summary> /// <summary>
/// Delegate for notifying of TCP Server state changes /// Delegate for notifying of TCP Server state changes
/// </summary> /// </summary>
/// <param name="state"></param> /// <param name="state"></param>
public delegate void GenericTcpServerStateChangedEventDelegate(ServerState state); public delegate void GenericTcpServerStateChangedEventDelegate(ServerState state);
/// <summary> /// <summary>
/// EventArgs class for TCP Server state changes /// EventArgs class for TCP Server state changes
/// </summary> /// </summary>
public class GenericTcpServerStateChangedEventArgs : EventArgs public class GenericTcpServerStateChangedEventArgs : EventArgs
{ {
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public ServerState State { get; private set; } public ServerState State { get; private set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <param name="state"></param> /// <param name="state"></param>
public GenericTcpServerStateChangedEventArgs(ServerState state) public GenericTcpServerStateChangedEventArgs(ServerState state)
{ {
State = state; State = state;
} }
/// <summary> /// <summary>
/// S+ Constructor /// S+ Constructor
/// </summary> /// </summary>
public GenericTcpServerStateChangedEventArgs() { } public GenericTcpServerStateChangedEventArgs() { }
} }
/// <summary> /// <summary>
/// Delegate for TCP Server socket status changes /// Delegate for TCP Server socket status changes
/// </summary> /// </summary>
/// <param name="socket"></param> /// <param name="socket"></param>
/// <param name="clientIndex"></param> /// <param name="clientIndex"></param>
/// <param name="clientStatus"></param> /// <param name="clientStatus"></param>
public delegate void GenericTcpServerSocketStatusChangeEventDelegate(object socket, uint clientIndex, SocketStatus clientStatus); public delegate void GenericTcpServerSocketStatusChangeEventDelegate(object socket, uint clientIndex, SocketStatus clientStatus);
/// <summary> /// <summary>
/// EventArgs for TCP server socket status changes /// EventArgs for TCP server socket status changes
/// </summary> /// </summary>
public class GenericTcpServerSocketStatusChangeEventArgs : EventArgs public class GenericTcpServerSocketStatusChangeEventArgs : EventArgs
{ {
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public object Socket { get; private set; } public object Socket { get; private set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public uint ReceivedFromClientIndex { get; private set; } public uint ReceivedFromClientIndex { get; private set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public SocketStatus ClientStatus { get; set; } public SocketStatus ClientStatus { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <param name="socket"></param> /// <param name="socket"></param>
/// <param name="clientStatus"></param> /// <param name="clientStatus"></param>
public GenericTcpServerSocketStatusChangeEventArgs(object socket, SocketStatus clientStatus) public GenericTcpServerSocketStatusChangeEventArgs(object socket, SocketStatus clientStatus)
{ {
Socket = socket; Socket = socket;
ClientStatus = clientStatus; ClientStatus = clientStatus;
} }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <param name="socket"></param> /// <param name="socket"></param>
/// <param name="clientIndex"></param> /// <param name="clientIndex"></param>
/// <param name="clientStatus"></param> /// <param name="clientStatus"></param>
public GenericTcpServerSocketStatusChangeEventArgs(object socket, uint clientIndex, SocketStatus clientStatus) public GenericTcpServerSocketStatusChangeEventArgs(object socket, uint clientIndex, SocketStatus clientStatus)
{ {
Socket = socket; Socket = socket;
ReceivedFromClientIndex = clientIndex; ReceivedFromClientIndex = clientIndex;
ClientStatus = clientStatus; ClientStatus = clientStatus;
} }
/// <summary> /// <summary>
/// S+ Constructor /// S+ Constructor
/// </summary> /// </summary>
public GenericTcpServerSocketStatusChangeEventArgs() { } public GenericTcpServerSocketStatusChangeEventArgs() { }
} }
/// <summary> /// <summary>
/// EventArgs for TCP server com method receive text /// EventArgs for TCP server com method receive text
/// </summary> /// </summary>
public class GenericTcpServerCommMethodReceiveTextArgs : EventArgs public class GenericTcpServerCommMethodReceiveTextArgs : EventArgs
{ {
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public uint ReceivedFromClientIndex { get; private set; } public uint ReceivedFromClientIndex { get; private set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public ushort ReceivedFromClientIndexShort public ushort ReceivedFromClientIndexShort
{ {
get get
{ {
return (ushort)ReceivedFromClientIndex; return (ushort)ReceivedFromClientIndex;
} }
} }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string Text { get; private set; } public string Text { get; private set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <param name="text"></param> /// <param name="text"></param>
public GenericTcpServerCommMethodReceiveTextArgs(string text) public GenericTcpServerCommMethodReceiveTextArgs(string text)
{ {
Text = text; Text = text;
} }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <param name="text"></param> /// <param name="text"></param>
/// <param name="clientIndex"></param> /// <param name="clientIndex"></param>
public GenericTcpServerCommMethodReceiveTextArgs(string text, uint clientIndex) public GenericTcpServerCommMethodReceiveTextArgs(string text, uint clientIndex)
{ {
Text = text; Text = text;
ReceivedFromClientIndex = clientIndex; ReceivedFromClientIndex = clientIndex;
} }
/// <summary> /// <summary>
/// S+ Constructor /// S+ Constructor
/// </summary> /// </summary>
public GenericTcpServerCommMethodReceiveTextArgs() { } public GenericTcpServerCommMethodReceiveTextArgs() { }
} }
/// <summary> /// <summary>
/// EventArgs for TCP server client ready for communication /// EventArgs for TCP server client ready for communication
/// </summary> /// </summary>
public class GenericTcpServerClientReadyForcommunicationsEventArgs : EventArgs public class GenericTcpServerClientReadyForcommunicationsEventArgs : EventArgs
{ {
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public bool IsReady; public bool IsReady;
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <param name="isReady"></param> /// <param name="isReady"></param>
public GenericTcpServerClientReadyForcommunicationsEventArgs(bool isReady) public GenericTcpServerClientReadyForcommunicationsEventArgs(bool isReady)
{ {
IsReady = isReady; IsReady = isReady;
} }
/// <summary> /// <summary>
/// S+ Constructor /// S+ Constructor
/// </summary> /// </summary>
public GenericTcpServerClientReadyForcommunicationsEventArgs() { } public GenericTcpServerClientReadyForcommunicationsEventArgs() { }
} }
/// <summary> /// <summary>
/// EventArgs for UDP connected /// EventArgs for UDP connected
/// </summary> /// </summary>
public class GenericUdpConnectedEventArgs : EventArgs public class GenericUdpConnectedEventArgs : EventArgs
{ {
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public ushort UConnected; public ushort UConnected;
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public bool Connected; public bool Connected;
/// <summary> /// <summary>
/// Constructor /// Constructor
/// </summary> /// </summary>
public GenericUdpConnectedEventArgs() { } public GenericUdpConnectedEventArgs() { }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <param name="uconnected"></param> /// <param name="uconnected"></param>
public GenericUdpConnectedEventArgs(ushort uconnected) public GenericUdpConnectedEventArgs(ushort uconnected)
{ {
UConnected = uconnected; UConnected = uconnected;
} }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <param name="connected"></param> /// <param name="connected"></param>
public GenericUdpConnectedEventArgs(bool connected) public GenericUdpConnectedEventArgs(bool connected)
{ {
Connected = connected; Connected = connected;
} }
} }
} }

View file

@ -1,314 +1,314 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Crestron.SimplSharp; using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronIO; using Crestron.SimplSharp.CrestronIO;
using Crestron.SimplSharp.Net.Http; using Crestron.SimplSharp.Net.Http;
namespace PepperDash.Core namespace PepperDash.Core
{ {
/// <summary> /// <summary>
/// Client for communicating with an HTTP Server Side Event pattern /// Client for communicating with an HTTP Server Side Event pattern
/// </summary> /// </summary>
public class GenericHttpSseClient : ICommunicationReceiver public class GenericHttpSseClient : ICommunicationReceiver
{ {
/// <summary> /// <summary>
/// Notifies when bytes have been received /// Notifies when bytes have been received
/// </summary> /// </summary>
public event EventHandler<GenericCommMethodReceiveBytesArgs> BytesReceived; public event EventHandler<GenericCommMethodReceiveBytesArgs> BytesReceived;
/// <summary> /// <summary>
/// Notifies when text has been received /// Notifies when text has been received
/// </summary> /// </summary>
public event EventHandler<GenericCommMethodReceiveTextArgs> TextReceived; public event EventHandler<GenericCommMethodReceiveTextArgs> TextReceived;
/// <summary> /// <summary>
/// Indicates connection status /// Indicates connection status
/// </summary> /// </summary>
public bool IsConnected public bool IsConnected
{ {
get; get;
private set; private set;
} }
/// <summary> /// <summary>
/// Unique identifier for the instance /// Unique identifier for the instance
/// </summary> /// </summary>
public string Key public string Key
{ {
get; get;
private set; private set;
} }
/// <summary> /// <summary>
/// Name for the instance /// Name for the instance
/// </summary> /// </summary>
public string Name public string Name
{ {
get; get;
private set; private set;
} }
/// <summary> /// <summary>
/// URL of the server /// URL of the server
/// </summary> /// </summary>
public string Url { get; set; } public string Url { get; set; }
HttpClient Client; HttpClient Client;
HttpClientRequest Request; HttpClientRequest Request;
/// <summary> /// <summary>
/// Constructor /// Constructor
/// </summary> /// </summary>
/// <param name="key"></param> /// <param name="key"></param>
/// <param name="name"></param> /// <param name="name"></param>
public GenericHttpSseClient(string key, string name) public GenericHttpSseClient(string key, string name)
{ {
Key = key; Key = key;
Name = name; Name = name;
} }
/// <summary> /// <summary>
/// Connects to the server. Requires Url to be set first. /// Connects to the server. Requires Url to be set first.
/// </summary> /// </summary>
public void Connect() public void Connect()
{ {
InitiateConnection(Url); InitiateConnection(Url);
} }
/// <summary> /// <summary>
/// Disconnects from the server /// Disconnects from the server
/// </summary> /// </summary>
public void Disconnect() public void Disconnect()
{ {
CloseConnection(null); CloseConnection(null);
} }
/// <summary> /// <summary>
/// Initiates connection to the server /// Initiates connection to the server
/// </summary> /// </summary>
/// <param name="url"></param> /// <param name="url"></param>
public void InitiateConnection(string url) public void InitiateConnection(string url)
{ {
CrestronInvoke.BeginInvoke(o => CrestronInvoke.BeginInvoke(o =>
{ {
try try
{ {
if(string.IsNullOrEmpty(url)) if(string.IsNullOrEmpty(url))
{ {
Debug.Console(0, this, "Error connecting to Server. No URL specified"); Debug.Console(0, this, "Error connecting to Server. No URL specified");
return; return;
} }
Client = new HttpClient(); Client = new HttpClient();
Request = new HttpClientRequest(); Request = new HttpClientRequest();
Client.Verbose = true; Client.Verbose = true;
Client.KeepAlive = true; Client.KeepAlive = true;
Request.Url.Parse(url); Request.Url.Parse(url);
Request.RequestType = RequestType.Get; Request.RequestType = RequestType.Get;
Request.Header.SetHeaderValue("Accept", "text/event-stream"); Request.Header.SetHeaderValue("Accept", "text/event-stream");
// In order to get a handle on the response stream, we have to get // In order to get a handle on the response stream, we have to get
// the request stream first. Boo // the request stream first. Boo
Client.BeginGetRequestStream(GetRequestStreamCallback, Request, null); Client.BeginGetRequestStream(GetRequestStreamCallback, Request, null);
CrestronConsole.PrintLine("Request made!"); CrestronConsole.PrintLine("Request made!");
} }
catch (Exception e) catch (Exception e)
{ {
ErrorLog.Notice("Exception occured in AsyncWebPostHttps(): " + e.ToString()); ErrorLog.Notice("Exception occured in AsyncWebPostHttps(): " + e.ToString());
} }
}); });
} }
/// <summary> /// <summary>
/// Closes the connection to the server /// Closes the connection to the server
/// </summary> /// </summary>
/// <param name="s"></param> /// <param name="s"></param>
public void CloseConnection(string s) public void CloseConnection(string s)
{ {
if (Client != null) if (Client != null)
{ {
Client.Abort(); Client.Abort();
IsConnected = false; IsConnected = false;
Debug.Console(1, this, "Client Disconnected"); Debug.Console(1, this, "Client Disconnected");
} }
} }
private void GetRequestStreamCallback(HttpClientRequest request, HTTP_CALLBACK_ERROR error, object status) private void GetRequestStreamCallback(HttpClientRequest request, HTTP_CALLBACK_ERROR error, object status)
{ {
try try
{ {
// End the the async request operation and return the data stream // End the the async request operation and return the data stream
Stream requestStream = request.ThisClient.EndGetRequestStream(request, null); Stream requestStream = request.ThisClient.EndGetRequestStream(request, null);
// If this were something other than a GET we could write to the stream here // If this were something other than a GET we could write to the stream here
// Closing makes the request happen // Closing makes the request happen
requestStream.Close(); requestStream.Close();
// Get a handle on the response stream. // Get a handle on the response stream.
request.ThisClient.BeginGetResponseStream(GetResponseStreamCallback, request, status); request.ThisClient.BeginGetResponseStream(GetResponseStreamCallback, request, status);
} }
catch (Exception e) catch (Exception e)
{ {
ErrorLog.Notice("Exception occured in GetSecureRequestStreamCallback(): " + e.ToString()); ErrorLog.Notice("Exception occured in GetSecureRequestStreamCallback(): " + e.ToString());
} }
} }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <param name="request"></param> /// <param name="request"></param>
/// <param name="error"></param> /// <param name="error"></param>
/// <param name="status"></param> /// <param name="status"></param>
private void GetResponseStreamCallback(HttpClientRequest request, HTTP_CALLBACK_ERROR error, object status) private void GetResponseStreamCallback(HttpClientRequest request, HTTP_CALLBACK_ERROR error, object status)
{ {
try try
{ {
// This closes up the GetResponseStream async // This closes up the GetResponseStream async
var response = request.ThisClient.EndGetResponseStream(request); var response = request.ThisClient.EndGetResponseStream(request);
response.DataConnection.OnBytesReceived += new EventHandler(DataConnection_OnBytesReceived); response.DataConnection.OnBytesReceived += new EventHandler(DataConnection_OnBytesReceived);
IsConnected = true; IsConnected = true;
Debug.Console(1, this, "Client Disconnected"); Debug.Console(1, this, "Client Disconnected");
Stream streamResponse = response.ContentStream; Stream streamResponse = response.ContentStream;
// Object containing various states to be passed back to async callback below // Object containing various states to be passed back to async callback below
RequestState asyncState = new RequestState(); RequestState asyncState = new RequestState();
asyncState.Request = request; asyncState.Request = request;
asyncState.Response = response; asyncState.Response = response;
asyncState.StreamResponse = streamResponse; asyncState.StreamResponse = streamResponse;
asyncState.HttpClient = request.ThisClient; asyncState.HttpClient = request.ThisClient;
// This processes the ongoing data stream // This processes the ongoing data stream
Crestron.SimplSharp.CrestronIO.IAsyncResult asyncResult = null; Crestron.SimplSharp.CrestronIO.IAsyncResult asyncResult = null;
do 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); new Crestron.SimplSharp.CrestronIO.AsyncCallback(ReadCallBack), asyncState);
} }
while (asyncResult.CompletedSynchronously && !asyncState.Done); while (asyncResult.CompletedSynchronously && !asyncState.Done);
//Console.WriteLine("\r\nExit Response Callback\r\n"); //Console.WriteLine("\r\nExit Response Callback\r\n");
} }
catch (Exception e) catch (Exception e)
{ {
ErrorLog.Notice("Exception occured in GetSecureRequestStreamCallback(): " + e.ToString()); ErrorLog.Notice("Exception occured in GetSecureRequestStreamCallback(): " + e.ToString());
} }
} }
void DataConnection_OnBytesReceived(object sender, EventArgs e) void DataConnection_OnBytesReceived(object sender, EventArgs e)
{ {
Debug.Console(1, this, "DataConnection OnBytesReceived Fired"); Debug.Console(1, this, "DataConnection OnBytesReceived Fired");
} }
private void ReadCallBack(Crestron.SimplSharp.CrestronIO.IAsyncResult asyncResult) private void ReadCallBack(Crestron.SimplSharp.CrestronIO.IAsyncResult asyncResult)
{ {
//we are getting back everything here, so cast the state from the call //we are getting back everything here, so cast the state from the call
RequestState requestState = asyncResult.AsyncState as RequestState; RequestState requestState = asyncResult.AsyncState as RequestState;
Stream responseStream = requestState.StreamResponse; Stream responseStream = requestState.StreamResponse;
int read = responseStream.EndRead(asyncResult); int read = responseStream.EndRead(asyncResult);
// Read the HTML page and then print it to the console. // Read the HTML page and then print it to the console.
if (read > 0) if (read > 0)
{ {
var bytes = requestState.BufferRead; var bytes = requestState.BufferRead;
var bytesHandler = BytesReceived; var bytesHandler = BytesReceived;
if (bytesHandler != null) if (bytesHandler != null)
bytesHandler(this, new GenericCommMethodReceiveBytesArgs(bytes)); bytesHandler(this, new GenericCommMethodReceiveBytesArgs(bytes));
var textHandler = TextReceived; var textHandler = TextReceived;
if (textHandler != null) if (textHandler != null)
{ {
var str = Encoding.GetEncoding(28591).GetString(bytes, 0, bytes.Length); var str = Encoding.GetEncoding(28591).GetString(bytes, 0, bytes.Length);
textHandler(this, new GenericCommMethodReceiveTextArgs(str)); textHandler(this, new GenericCommMethodReceiveTextArgs(str));
} }
//requestState.RequestData.Append(Encoding.ASCII.GetString(requestState.BufferRead, 0, read)); //requestState.RequestData.Append(Encoding.ASCII.GetString(requestState.BufferRead, 0, read));
//CrestronConsole.PrintLine(requestState.RequestData.ToString()); //CrestronConsole.PrintLine(requestState.RequestData.ToString());
//clear the byte array buffer used. //clear the byte array buffer used.
Array.Clear(requestState.BufferRead, 0, requestState.BufferRead.Length); Array.Clear(requestState.BufferRead, 0, requestState.BufferRead.Length);
if (asyncResult.CompletedSynchronously) if (asyncResult.CompletedSynchronously)
{ {
return; return;
} }
Crestron.SimplSharp.CrestronIO.IAsyncResult asynchronousResult; Crestron.SimplSharp.CrestronIO.IAsyncResult asynchronousResult;
do 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); new Crestron.SimplSharp.CrestronIO.AsyncCallback(ReadCallBack), requestState);
} }
while (asynchronousResult.CompletedSynchronously && !requestState.Done); while (asynchronousResult.CompletedSynchronously && !requestState.Done);
} }
else else
{ {
requestState.Done = true; requestState.Done = true;
} }
} }
} }
/// <summary> /// <summary>
/// Stores the state of the request /// Stores the state of the request
/// </summary> /// </summary>
public class RequestState public class RequestState
{ {
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public const int BUFFER_SIZE = 10000; public const int BUFFER_SIZE = 10000;
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public byte[] BufferRead; public byte[] BufferRead;
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public HttpClient HttpClient; public HttpClient HttpClient;
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public HttpClientRequest Request; public HttpClientRequest Request;
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public HttpClientResponse Response; public HttpClientResponse Response;
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public Stream StreamResponse; public Stream StreamResponse;
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public bool Done; public bool Done;
/// <summary> /// <summary>
/// Constructor /// Constructor
/// </summary> /// </summary>
public RequestState() public RequestState()
{ {
BufferRead = new byte[BUFFER_SIZE]; BufferRead = new byte[BUFFER_SIZE];
HttpClient = null; HttpClient = null;
Request = null; Request = null;
Response = null; Response = null;
StreamResponse = null; StreamResponse = null;
Done = false; Done = false;
} }
} }
/// <summary> /// <summary>
/// Waithandle for main thread. /// Waithandle for main thread.
/// </summary> /// </summary>
public class StreamAsyncTest public class StreamAsyncTest
{ {
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public CEvent wait_for_response = new CEvent(true, false); public CEvent wait_for_response = new CEvent(true, false);
} }
} }

View file

@ -1,60 +1,60 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Crestron.SimplSharp; using Crestron.SimplSharp;
namespace PepperDash.Core namespace PepperDash.Core
{ {
/// <summary> /// <summary>
/// Tcp Server Config object with properties for a tcp server with shared key and heartbeat capabilities /// Tcp Server Config object with properties for a tcp server with shared key and heartbeat capabilities
/// </summary> /// </summary>
public class TcpServerConfigObject public class TcpServerConfigObject
{ {
/// <summary> /// <summary>
/// Uique key /// Uique key
/// </summary> /// </summary>
public string Key { get; set; } public string Key { get; set; }
/// <summary> /// <summary>
/// Max Clients that the server will allow to connect. /// Max Clients that the server will allow to connect.
/// </summary> /// </summary>
public ushort MaxClients { get; set; } public ushort MaxClients { get; set; }
/// <summary> /// <summary>
/// Bool value for secure. Currently not implemented in TCP sockets as they are not dynamic /// Bool value for secure. Currently not implemented in TCP sockets as they are not dynamic
/// </summary> /// </summary>
public bool Secure { get; set; } public bool Secure { get; set; }
/// <summary> /// <summary>
/// Port for the server to listen on /// Port for the server to listen on
/// </summary> /// </summary>
public int Port { get; set; } public int Port { get; set; }
/// <summary> /// <summary>
/// Require a shared key that both server and client negotiate. If negotiation fails server disconnects the client /// Require a shared key that both server and client negotiate. If negotiation fails server disconnects the client
/// </summary> /// </summary>
public bool SharedKeyRequired { get; set; } public bool SharedKeyRequired { get; set; }
/// <summary> /// <summary>
/// The shared key that must match on the server and client /// The shared key that must match on the server and client
/// </summary> /// </summary>
public string SharedKey { get; set; } public string SharedKey { get; set; }
/// <summary> /// <summary>
/// Require a heartbeat on the client/server connection that will cause the server/client to disconnect if the heartbeat is not received. /// Require a heartbeat on the client/server connection that will cause the server/client to disconnect if the heartbeat is not received.
/// heartbeats do not raise received events. /// heartbeats do not raise received events.
/// </summary> /// </summary>
public bool HeartbeatRequired { get; set; } public bool HeartbeatRequired { get; set; }
/// <summary> /// <summary>
/// The interval in seconds for the heartbeat from the client. If not received client is disconnected /// The interval in seconds for the heartbeat from the client. If not received client is disconnected
/// </summary> /// </summary>
public ushort HeartbeatRequiredIntervalInSeconds { get; set; } public ushort HeartbeatRequiredIntervalInSeconds { get; set; }
/// <summary> /// <summary>
/// HeartbeatString that will be checked against the message received. defaults to heartbeat if no string is provided. /// HeartbeatString that will be checked against the message received. defaults to heartbeat if no string is provided.
/// </summary> /// </summary>
public string HeartbeatStringToMatch { get; set; } public string HeartbeatStringToMatch { get; set; }
/// <summary> /// <summary>
/// Client buffer size. See Crestron help. defaults to 2000 if not greater than 2000 /// Client buffer size. See Crestron help. defaults to 2000 if not greater than 2000
/// </summary> /// </summary>
public int BufferSize { get; set; } public int BufferSize { get; set; }
/// <summary> /// <summary>
/// Receive Queue size must be greater than 20 or defaults to 20 /// Receive Queue size must be greater than 20 or defaults to 20
/// </summary> /// </summary>
public int ReceiveQueueSize { get; set; } public int ReceiveQueueSize { get; set; }
} }
} }

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,257 +1,257 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Crestron.SimplSharp; using Crestron.SimplSharp;
namespace PepperDash.Core.JsonStandardObjects namespace PepperDash.Core.JsonStandardObjects
{ {
/* /*
Convert JSON snippt to C#: http://json2csharp.com/# Convert JSON snippt to C#: http://json2csharp.com/#
JSON Snippet: JSON Snippet:
{ {
"devices": [ "devices": [
{ {
"key": "deviceKey", "key": "deviceKey",
"name": "deviceName", "name": "deviceName",
"type": "deviceType", "type": "deviceType",
"properties": { "properties": {
"deviceId": 1, "deviceId": 1,
"enabled": true, "enabled": true,
"control": { "control": {
"method": "methodName", "method": "methodName",
"controlPortDevKey": "deviceControlPortDevKey", "controlPortDevKey": "deviceControlPortDevKey",
"controlPortNumber": 1, "controlPortNumber": 1,
"comParams": { "comParams": {
"baudRate": 9600, "baudRate": 9600,
"dataBits": 8, "dataBits": 8,
"stopBits": 1, "stopBits": 1,
"parity": "None", "parity": "None",
"protocol": "RS232", "protocol": "RS232",
"hardwareHandshake": "None", "hardwareHandshake": "None",
"softwareHandshake": "None", "softwareHandshake": "None",
"pacing": 0 "pacing": 0
}, },
"tcpSshProperties": { "tcpSshProperties": {
"address": "172.22.1.101", "address": "172.22.1.101",
"port": 23, "port": 23,
"username": "user01", "username": "user01",
"password": "password01", "password": "password01",
"autoReconnect": false, "autoReconnect": false,
"autoReconnectIntervalMs": 10000 "autoReconnectIntervalMs": 10000
} }
} }
} }
} }
] ]
} }
*/ */
/// <summary> /// <summary>
/// Device communication parameter class /// Device communication parameter class
/// </summary> /// </summary>
public class ComParamsConfig public class ComParamsConfig
{ {
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public int baudRate { get; set; } public int baudRate { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public int dataBits { get; set; } public int dataBits { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public int stopBits { get; set; } public int stopBits { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string parity { get; set; } public string parity { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string protocol { get; set; } public string protocol { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string hardwareHandshake { get; set; } public string hardwareHandshake { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string softwareHandshake { get; set; } public string softwareHandshake { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public int pacing { get; set; } public int pacing { get; set; }
// convert properties for simpl // convert properties for simpl
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public ushort simplBaudRate { get { return Convert.ToUInt16(baudRate); } } public ushort simplBaudRate { get { return Convert.ToUInt16(baudRate); } }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public ushort simplDataBits { get { return Convert.ToUInt16(dataBits); } } public ushort simplDataBits { get { return Convert.ToUInt16(dataBits); } }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public ushort simplStopBits { get { return Convert.ToUInt16(stopBits); } } public ushort simplStopBits { get { return Convert.ToUInt16(stopBits); } }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public ushort simplPacing { get { return Convert.ToUInt16(pacing); } } public ushort simplPacing { get { return Convert.ToUInt16(pacing); } }
/// <summary> /// <summary>
/// Constructor /// Constructor
/// </summary> /// </summary>
public ComParamsConfig() public ComParamsConfig()
{ {
} }
} }
/// <summary> /// <summary>
/// Device TCP/SSH properties class /// Device TCP/SSH properties class
/// </summary> /// </summary>
public class TcpSshPropertiesConfig public class TcpSshPropertiesConfig
{ {
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string address { get; set; } public string address { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public int port { get; set; } public int port { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string username { get; set; } public string username { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string password { get; set; } public string password { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public bool autoReconnect { get; set; } public bool autoReconnect { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public int autoReconnectIntervalMs { get; set; } public int autoReconnectIntervalMs { get; set; }
// convert properties for simpl // convert properties for simpl
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public ushort simplPort { get { return Convert.ToUInt16(port); } } public ushort simplPort { get { return Convert.ToUInt16(port); } }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public ushort simplAutoReconnect { get { return (ushort)(autoReconnect ? 1 : 0); } } public ushort simplAutoReconnect { get { return (ushort)(autoReconnect ? 1 : 0); } }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public ushort simplAutoReconnectIntervalMs { get { return Convert.ToUInt16(autoReconnectIntervalMs); } } public ushort simplAutoReconnectIntervalMs { get { return Convert.ToUInt16(autoReconnectIntervalMs); } }
/// <summary> /// <summary>
/// Constructor /// Constructor
/// </summary> /// </summary>
public TcpSshPropertiesConfig() public TcpSshPropertiesConfig()
{ {
} }
} }
/// <summary> /// <summary>
/// Device control class /// Device control class
/// </summary> /// </summary>
public class ControlConfig public class ControlConfig
{ {
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string method { get; set; } public string method { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string controlPortDevKey { get; set; } public string controlPortDevKey { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public int controlPortNumber { get; set; } public int controlPortNumber { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public ComParamsConfig comParams { get; set; } public ComParamsConfig comParams { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public TcpSshPropertiesConfig tcpSshProperties { get; set; } public TcpSshPropertiesConfig tcpSshProperties { get; set; }
// convert properties for simpl // convert properties for simpl
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public ushort simplControlPortNumber { get { return Convert.ToUInt16(controlPortNumber); } } public ushort simplControlPortNumber { get { return Convert.ToUInt16(controlPortNumber); } }
/// <summary> /// <summary>
/// Constructor /// Constructor
/// </summary> /// </summary>
public ControlConfig() public ControlConfig()
{ {
comParams = new ComParamsConfig(); comParams = new ComParamsConfig();
tcpSshProperties = new TcpSshPropertiesConfig(); tcpSshProperties = new TcpSshPropertiesConfig();
} }
} }
/// <summary> /// <summary>
/// Device properties class /// Device properties class
/// </summary> /// </summary>
public class PropertiesConfig public class PropertiesConfig
{ {
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public int deviceId { get; set; } public int deviceId { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public bool enabled { get; set; } public bool enabled { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public ControlConfig control { get; set; } public ControlConfig control { get; set; }
// convert properties for simpl // convert properties for simpl
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public ushort simplDeviceId { get { return Convert.ToUInt16(deviceId); } } public ushort simplDeviceId { get { return Convert.ToUInt16(deviceId); } }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public ushort simplEnabled { get { return (ushort)(enabled ? 1 : 0); } } public ushort simplEnabled { get { return (ushort)(enabled ? 1 : 0); } }
/// <summary> /// <summary>
/// Constructor /// Constructor
/// </summary> /// </summary>
public PropertiesConfig() public PropertiesConfig()
{ {
control = new ControlConfig(); control = new ControlConfig();
} }
} }
/// <summary> /// <summary>
/// Root device class /// Root device class
/// </summary> /// </summary>
public class RootObject public class RootObject
{ {
/// <summary> /// <summary>
/// The collection of devices /// The collection of devices
/// </summary> /// </summary>
public List<DeviceConfig> devices { get; set; } public List<DeviceConfig> devices { get; set; }
} }
} }

View file

@ -1,143 +1,143 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Crestron.SimplSharp; using Crestron.SimplSharp;
namespace PepperDash.Core.JsonToSimpl namespace PepperDash.Core.JsonToSimpl
{ {
/// <summary> /// <summary>
/// Constants for Simpl modules /// Constants for Simpl modules
/// </summary> /// </summary>
public class JsonToSimplConstants public class JsonToSimplConstants
{ {
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public const ushort BoolValueChange = 1; public const ushort BoolValueChange = 1;
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public const ushort JsonIsValidBoolChange = 2; public const ushort JsonIsValidBoolChange = 2;
/// <summary> /// <summary>
/// Reports the if the device is 3-series compatible /// Reports the if the device is 3-series compatible
/// </summary> /// </summary>
public const ushort ProgramCompatibility3SeriesChange = 3; public const ushort ProgramCompatibility3SeriesChange = 3;
/// <summary> /// <summary>
/// Reports the if the device is 4-series compatible /// Reports the if the device is 4-series compatible
/// </summary> /// </summary>
public const ushort ProgramCompatibility4SeriesChange = 4; public const ushort ProgramCompatibility4SeriesChange = 4;
/// <summary> /// <summary>
/// Reports the device platform enum value /// Reports the device platform enum value
/// </summary> /// </summary>
public const ushort DevicePlatformValueChange = 5; public const ushort DevicePlatformValueChange = 5;
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public const ushort UshortValueChange = 101; public const ushort UshortValueChange = 101;
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public const ushort StringValueChange = 201; public const ushort StringValueChange = 201;
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public const ushort FullPathToArrayChange = 202; public const ushort FullPathToArrayChange = 202;
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public const ushort ActualFilePathChange = 203; public const ushort ActualFilePathChange = 203;
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public const ushort FilenameResolvedChange = 204; public const ushort FilenameResolvedChange = 204;
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public const ushort FilePathResolvedChange = 205; public const ushort FilePathResolvedChange = 205;
/// <summary> /// <summary>
/// Reports the root directory change /// Reports the root directory change
/// </summary> /// </summary>
public const ushort RootDirectoryChange = 206; public const ushort RootDirectoryChange = 206;
/// <summary> /// <summary>
/// Reports the room ID change /// Reports the room ID change
/// </summary> /// </summary>
public const ushort RoomIdChange = 207; public const ushort RoomIdChange = 207;
/// <summary> /// <summary>
/// Reports the room name change /// Reports the room name change
/// </summary> /// </summary>
public const ushort RoomNameChange = 208; public const ushort RoomNameChange = 208;
} }
/// <summary> /// <summary>
/// S+ values delegate /// S+ values delegate
/// </summary> /// </summary>
public delegate void SPlusValuesDelegate(); public delegate void SPlusValuesDelegate();
/// <summary> /// <summary>
/// S+ values wrapper /// S+ values wrapper
/// </summary> /// </summary>
public class SPlusValueWrapper public class SPlusValueWrapper
{ {
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public SPlusType ValueType { get; private set; } public SPlusType ValueType { get; private set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public ushort Index { get; private set; } public ushort Index { get; private set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public ushort BoolUShortValue { get; set; } public ushort BoolUShortValue { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string StringValue { get; set; } public string StringValue { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public SPlusValueWrapper() {} public SPlusValueWrapper() {}
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <param name="type"></param> /// <param name="type"></param>
/// <param name="index"></param> /// <param name="index"></param>
public SPlusValueWrapper(SPlusType type, ushort index) public SPlusValueWrapper(SPlusType type, ushort index)
{ {
ValueType = type; ValueType = type;
Index = index; Index = index;
} }
} }
/// <summary> /// <summary>
/// S+ types enum /// S+ types enum
/// </summary> /// </summary>
public enum SPlusType public enum SPlusType
{ {
/// <summary> /// <summary>
/// Digital /// Digital
/// </summary> /// </summary>
Digital, Digital,
/// <summary> /// <summary>
/// Analog /// Analog
/// </summary> /// </summary>
Analog, Analog,
/// <summary> /// <summary>
/// String /// String
/// </summary> /// </summary>
String String
} }
} }

View file

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

View file

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

View file

@ -1,291 +1,291 @@
using System; using System;
//using System.IO; //using System.IO;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Crestron.SimplSharp; using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronIO; using Crestron.SimplSharp.CrestronIO;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
namespace PepperDash.Core.JsonToSimpl namespace PepperDash.Core.JsonToSimpl
{ {
/// <summary> /// <summary>
/// Represents a JSON file that can be read and written to /// Represents a JSON file that can be read and written to
/// </summary> /// </summary>
public class JsonToSimplFileMaster : JsonToSimplMaster public class JsonToSimplFileMaster : JsonToSimplMaster
{ {
/// <summary> /// <summary>
/// Sets the filepath as well as registers this with the Global.Masters list /// Sets the filepath as well as registers this with the Global.Masters list
/// </summary> /// </summary>
public string Filepath { get; private set; } public string Filepath { get; private set; }
/// <summary> /// <summary>
/// Filepath to the actual file that will be read (Portal or local) /// Filepath to the actual file that will be read (Portal or local)
/// </summary> /// </summary>
public string ActualFilePath { get; private set; } public string ActualFilePath { get; private set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string Filename { get; private set; } public string Filename { get; private set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string FilePathName { get; private set; } public string FilePathName { get; private set; }
/*****************************************************************************************/ /*****************************************************************************************/
/** Privates **/ /** Privates **/
// The JSON file in JObject form // The JSON file in JObject form
// For gathering the incoming data // For gathering the incoming data
object StringBuilderLock = new object(); object StringBuilderLock = new object();
// To prevent multiple same-file access // To prevent multiple same-file access
static object FileLock = new object(); static object FileLock = new object();
/*****************************************************************************************/ /*****************************************************************************************/
/// <summary> /// <summary>
/// SIMPL+ default constructor. /// SIMPL+ default constructor.
/// </summary> /// </summary>
public JsonToSimplFileMaster() public JsonToSimplFileMaster()
{ {
} }
/// <summary> /// <summary>
/// Read, evaluate and udpate status /// Read, evaluate and udpate status
/// </summary> /// </summary>
public void EvaluateFile(string filepath) public void EvaluateFile(string filepath)
{ {
try try
{ {
OnBoolChange(false, 0, JsonToSimplConstants.JsonIsValidBoolChange); OnBoolChange(false, 0, JsonToSimplConstants.JsonIsValidBoolChange);
var dirSeparator = Path.DirectorySeparatorChar; var dirSeparator = Path.DirectorySeparatorChar;
var dirSeparatorAlt = Path.AltDirectorySeparatorChar; var dirSeparatorAlt = Path.AltDirectorySeparatorChar;
var series = CrestronEnvironment.ProgramCompatibility; var series = CrestronEnvironment.ProgramCompatibility;
var is3Series = (eCrestronSeries.Series3 == (series & eCrestronSeries.Series3)); var is3Series = (eCrestronSeries.Series3 == (series & eCrestronSeries.Series3));
OnBoolChange(is3Series, 0, OnBoolChange(is3Series, 0,
JsonToSimplConstants.ProgramCompatibility3SeriesChange); JsonToSimplConstants.ProgramCompatibility3SeriesChange);
var is4Series = (eCrestronSeries.Series4 == (series & eCrestronSeries.Series4)); var is4Series = (eCrestronSeries.Series4 == (series & eCrestronSeries.Series4));
OnBoolChange(is4Series, 0, OnBoolChange(is4Series, 0,
JsonToSimplConstants.ProgramCompatibility4SeriesChange); JsonToSimplConstants.ProgramCompatibility4SeriesChange);
var isServer = CrestronEnvironment.DevicePlatform == eDevicePlatform.Server; var isServer = CrestronEnvironment.DevicePlatform == eDevicePlatform.Server;
OnBoolChange(isServer, 0, OnBoolChange(isServer, 0,
JsonToSimplConstants.DevicePlatformValueChange); JsonToSimplConstants.DevicePlatformValueChange);
// get the roomID // get the roomID
var roomId = Crestron.SimplSharp.InitialParametersClass.RoomId; var roomId = Crestron.SimplSharp.InitialParametersClass.RoomId;
if (!string.IsNullOrEmpty(roomId)) if (!string.IsNullOrEmpty(roomId))
{ {
OnStringChange(roomId, 0, JsonToSimplConstants.RoomIdChange); OnStringChange(roomId, 0, JsonToSimplConstants.RoomIdChange);
} }
// get the roomName // get the roomName
var roomName = Crestron.SimplSharp.InitialParametersClass.RoomName; var roomName = Crestron.SimplSharp.InitialParametersClass.RoomName;
if (!string.IsNullOrEmpty(roomName)) if (!string.IsNullOrEmpty(roomName))
{ {
OnStringChange(roomName, 0, JsonToSimplConstants.RoomNameChange); OnStringChange(roomName, 0, JsonToSimplConstants.RoomNameChange);
} }
var rootDirectory = Directory.GetApplicationRootDirectory(); var rootDirectory = Directory.GetApplicationRootDirectory();
OnStringChange(rootDirectory, 0, JsonToSimplConstants.RootDirectoryChange); OnStringChange(rootDirectory, 0, JsonToSimplConstants.RootDirectoryChange);
var splusPath = string.Empty; var splusPath = string.Empty;
if (Regex.IsMatch(filepath, @"user", RegexOptions.IgnoreCase)) if (Regex.IsMatch(filepath, @"user", RegexOptions.IgnoreCase))
{ {
if (is4Series) if (is4Series)
splusPath = Regex.Replace(filepath, "user", "user", RegexOptions.IgnoreCase); splusPath = Regex.Replace(filepath, "user", "user", RegexOptions.IgnoreCase);
else if (isServer) else if (isServer)
splusPath = Regex.Replace(filepath, "user", "User", RegexOptions.IgnoreCase); splusPath = Regex.Replace(filepath, "user", "User", RegexOptions.IgnoreCase);
else else
splusPath = filepath; splusPath = filepath;
} }
filepath = splusPath.Replace(dirSeparatorAlt, dirSeparator); filepath = splusPath.Replace(dirSeparatorAlt, dirSeparator);
Filepath = string.Format("{1}{0}{2}", dirSeparator, rootDirectory, Filepath = string.Format("{1}{0}{2}", dirSeparator, rootDirectory,
filepath.TrimStart(dirSeparator, dirSeparatorAlt)); filepath.TrimStart(dirSeparator, dirSeparatorAlt));
OnStringChange(string.Format("Attempting to evaluate {0}", Filepath), 0, JsonToSimplConstants.StringValueChange); OnStringChange(string.Format("Attempting to evaluate {0}", Filepath), 0, JsonToSimplConstants.StringValueChange);
if (string.IsNullOrEmpty(Filepath)) if (string.IsNullOrEmpty(Filepath))
{ {
OnStringChange(string.Format("Cannot evaluate file. JSON file path not set"), 0, JsonToSimplConstants.StringValueChange); OnStringChange(string.Format("Cannot evaluate file. JSON file path not set"), 0, JsonToSimplConstants.StringValueChange);
CrestronConsole.PrintLine("Cannot evaluate file. JSON file path not set"); CrestronConsole.PrintLine("Cannot evaluate file. JSON file path not set");
return; return;
} }
// get file directory and name to search // get file directory and name to search
var fileDirectory = Path.GetDirectoryName(Filepath); var fileDirectory = Path.GetDirectoryName(Filepath);
var fileName = Path.GetFileName(Filepath); var fileName = Path.GetFileName(Filepath);
OnStringChange(string.Format("Checking '{0}' for '{1}'", fileDirectory, fileName), 0, JsonToSimplConstants.StringValueChange); OnStringChange(string.Format("Checking '{0}' for '{1}'", fileDirectory, fileName), 0, JsonToSimplConstants.StringValueChange);
Debug.Console(1, "Checking '{0}' for '{1}'", fileDirectory, fileName); Debug.Console(1, "Checking '{0}' for '{1}'", fileDirectory, fileName);
if (Directory.Exists(fileDirectory)) if (Directory.Exists(fileDirectory))
{ {
// get the directory info // get the directory info
var directoryInfo = new DirectoryInfo(fileDirectory); var directoryInfo = new DirectoryInfo(fileDirectory);
// get the file to be read // get the file to be read
var actualFile = directoryInfo.GetFiles(fileName).FirstOrDefault(); var actualFile = directoryInfo.GetFiles(fileName).FirstOrDefault();
if (actualFile == null) if (actualFile == null)
{ {
var msg = string.Format("JSON file not found: {0}", Filepath); var msg = string.Format("JSON file not found: {0}", Filepath);
OnStringChange(msg, 0, JsonToSimplConstants.StringValueChange); OnStringChange(msg, 0, JsonToSimplConstants.StringValueChange);
CrestronConsole.PrintLine(msg); CrestronConsole.PrintLine(msg);
ErrorLog.Error(msg); ErrorLog.Error(msg);
return; return;
} }
// \xSE\xR\PDT000-Template_Main_Config-Combined_DSP_v00.02.json // \xSE\xR\PDT000-Template_Main_Config-Combined_DSP_v00.02.json
// \USER\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(ActualFilePath, 0, JsonToSimplConstants.ActualFilePathChange);
OnStringChange(string.Format("Actual JSON file is {0}", ActualFilePath), 0, JsonToSimplConstants.StringValueChange); OnStringChange(string.Format("Actual JSON file is {0}", ActualFilePath), 0, JsonToSimplConstants.StringValueChange);
Debug.Console(1, "Actual JSON file is {0}", ActualFilePath); Debug.Console(1, "Actual JSON file is {0}", ActualFilePath);
Filename = actualFile.Name; Filename = actualFile.Name;
OnStringChange(Filename, 0, JsonToSimplConstants.FilenameResolvedChange); OnStringChange(Filename, 0, JsonToSimplConstants.FilenameResolvedChange);
OnStringChange(string.Format("JSON Filename is {0}", Filename), 0, JsonToSimplConstants.StringValueChange); OnStringChange(string.Format("JSON Filename is {0}", Filename), 0, JsonToSimplConstants.StringValueChange);
Debug.Console(1, "JSON Filename is {0}", Filename); Debug.Console(1, "JSON Filename is {0}", Filename);
FilePathName = string.Format(@"{0}{1}", actualFile.DirectoryName, dirSeparator); FilePathName = string.Format(@"{0}{1}", actualFile.DirectoryName, dirSeparator);
OnStringChange(string.Format(@"{0}", actualFile.DirectoryName), 0, JsonToSimplConstants.FilePathResolvedChange); OnStringChange(string.Format(@"{0}", actualFile.DirectoryName), 0, JsonToSimplConstants.FilePathResolvedChange);
OnStringChange(string.Format(@"JSON File Path is {0}", actualFile.DirectoryName), 0, JsonToSimplConstants.StringValueChange); 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); var json = File.ReadToEnd(ActualFilePath, System.Text.Encoding.ASCII);
JsonObject = JObject.Parse(json); JsonObject = JObject.Parse(json);
foreach (var child in Children) foreach (var child in Children)
child.ProcessAll(); child.ProcessAll();
OnBoolChange(true, 0, JsonToSimplConstants.JsonIsValidBoolChange); OnBoolChange(true, 0, JsonToSimplConstants.JsonIsValidBoolChange);
} }
else else
{ {
OnStringChange(string.Format("'{0}' not found", fileDirectory), 0, JsonToSimplConstants.StringValueChange); OnStringChange(string.Format("'{0}' not found", fileDirectory), 0, JsonToSimplConstants.StringValueChange);
Debug.Console(1, "'{0}' not found", fileDirectory); Debug.Console(1, "'{0}' not found", fileDirectory);
} }
} }
catch (Exception e) catch (Exception e)
{ {
var msg = string.Format("EvaluateFile Exception: Message\r{0}", e.Message); var msg = string.Format("EvaluateFile Exception: Message\r{0}", e.Message);
OnStringChange(msg, 0, JsonToSimplConstants.StringValueChange); OnStringChange(msg, 0, JsonToSimplConstants.StringValueChange);
CrestronConsole.PrintLine(msg); CrestronConsole.PrintLine(msg);
ErrorLog.Error(msg); ErrorLog.Error(msg);
var stackTrace = string.Format("EvaluateFile: Stack Trace\r{0}", e.StackTrace); var stackTrace = string.Format("EvaluateFile: Stack Trace\r{0}", e.StackTrace);
OnStringChange(stackTrace, 0, JsonToSimplConstants.StringValueChange); OnStringChange(stackTrace, 0, JsonToSimplConstants.StringValueChange);
CrestronConsole.PrintLine(stackTrace); CrestronConsole.PrintLine(stackTrace);
ErrorLog.Error(stackTrace); ErrorLog.Error(stackTrace);
} }
} }
/// <summary> /// <summary>
/// Sets the debug level /// Sets the debug level
/// </summary> /// </summary>
/// <param name="level"></param> /// <param name="level"></param>
public void setDebugLevel(int level) public void setDebugLevel(int level)
{ {
Debug.SetDebugLevel(level); Debug.SetDebugLevel(level);
} }
/// <summary> /// <summary>
/// Saves the values to the file /// Saves the values to the file
/// </summary> /// </summary>
public override void Save() public override void Save()
{ {
// this code is duplicated in the other masters!!!!!!!!!!!!! // this code is duplicated in the other masters!!!!!!!!!!!!!
UnsavedValues = new Dictionary<string, JValue>(); UnsavedValues = new Dictionary<string, JValue>();
// Make each child update their values into master object // Make each child update their values into master object
foreach (var child in Children) foreach (var child in Children)
{ {
Debug.Console(1, "Master [{0}] checking child [{1}] for updates to save", UniqueID, child.Key); Debug.Console(1, "Master [{0}] checking child [{1}] for updates to save", UniqueID, child.Key);
child.UpdateInputsForMaster(); child.UpdateInputsForMaster();
} }
if (UnsavedValues == null || UnsavedValues.Count == 0) if (UnsavedValues == null || UnsavedValues.Count == 0)
{ {
Debug.Console(1, "Master [{0}] No updated values to save. Skipping", UniqueID); Debug.Console(1, "Master [{0}] No updated values to save. Skipping", UniqueID);
return; return;
} }
lock (FileLock) lock (FileLock)
{ {
Debug.Console(1, "Saving"); Debug.Console(1, "Saving");
foreach (var path in UnsavedValues.Keys) foreach (var path in UnsavedValues.Keys)
{ {
var tokenToReplace = JsonObject.SelectToken(path); var tokenToReplace = JsonObject.SelectToken(path);
if (tokenToReplace != null) if (tokenToReplace != null)
{// It's found {// It's found
tokenToReplace.Replace(UnsavedValues[path]); tokenToReplace.Replace(UnsavedValues[path]);
Debug.Console(1, "JSON Master[{0}] Updating '{1}'", UniqueID, path); Debug.Console(1, "JSON Master[{0}] Updating '{1}'", UniqueID, path);
} }
else // No token. Let's make one else // No token. Let's make one
{ {
//http://stackoverflow.com/questions/17455052/how-to-set-the-value-of-a-json-path-using-json-net //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); Debug.Console(1, "JSON Master[{0}] Cannot write value onto missing property: '{1}'", UniqueID, path);
// JContainer jpart = JsonObject; // JContainer jpart = JsonObject;
// // walk down the path and find where it goes // // walk down the path and find where it goes
//#warning Does not handle arrays. //#warning Does not handle arrays.
// foreach (var part in path.Split('.')) // foreach (var part in path.Split('.'))
// { // {
// var openPos = part.IndexOf('['); // var openPos = part.IndexOf('[');
// if (openPos > -1) // if (openPos > -1)
// { // {
// openPos++; // move to number // openPos++; // move to number
// var closePos = part.IndexOf(']'); // var closePos = part.IndexOf(']');
// var arrayName = part.Substring(0, openPos - 1); // get the name // var arrayName = part.Substring(0, openPos - 1); // get the name
// var index = Convert.ToInt32(part.Substring(openPos, closePos - openPos)); // var index = Convert.ToInt32(part.Substring(openPos, closePos - openPos));
// // Check if the array itself exists and add the item if so // // Check if the array itself exists and add the item if so
// if (jpart[arrayName] != null) // if (jpart[arrayName] != null)
// { // {
// var arrayObj = jpart[arrayName] as JArray; // var arrayObj = jpart[arrayName] as JArray;
// var item = arrayObj[index]; // var item = arrayObj[index];
// if (item == null) // if (item == null)
// arrayObj.Add(new JObject()); // arrayObj.Add(new JObject());
// } // }
// Debug.Console(0, "IGNORING MISSING ARRAY VALUE FOR NOW"); // Debug.Console(0, "IGNORING MISSING ARRAY VALUE FOR NOW");
// continue; // continue;
// } // }
// // Build the // // Build the
// if (jpart[part] == null) // if (jpart[part] == null)
// jpart.Add(new JProperty(part, new JObject())); // jpart.Add(new JProperty(part, new JObject()));
// jpart = jpart[part] as JContainer; // jpart = jpart[part] as JContainer;
// } // }
// jpart.Replace(UnsavedValues[path]); // jpart.Replace(UnsavedValues[path]);
} }
} }
using (StreamWriter sw = new StreamWriter(ActualFilePath)) using (StreamWriter sw = new StreamWriter(ActualFilePath))
{ {
try try
{ {
sw.Write(JsonObject.ToString()); sw.Write(JsonObject.ToString());
sw.Flush(); sw.Flush();
} }
catch (Exception e) catch (Exception e)
{ {
string err = string.Format("Error writing JSON file:\r{0}", e); string err = string.Format("Error writing JSON file:\r{0}", e);
Debug.Console(0, err); Debug.Console(0, err);
ErrorLog.Warn(err); ErrorLog.Warn(err);
return; return;
} }
} }
} }
} }
} }
} }

View file

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

View file

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

View file

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

View file

@ -1,149 +1,149 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Crestron.SimplSharp; using Crestron.SimplSharp;
namespace PepperDash.Core.PasswordManagement namespace PepperDash.Core.PasswordManagement
{ {
// Example JSON password array configuration object // Example JSON password array configuration object
//{ //{
// "global":{ // "global":{
// "passwords":[ // "passwords":[
// { // {
// "key": "Password01", // "key": "Password01",
// "name": "Technician Password", // "name": "Technician Password",
// "enabled": true, // "enabled": true,
// "password": "1988" // "password": "1988"
// } // }
// ] // ]
// } // }
//} //}
/// <summary> /// <summary>
/// JSON password array configuration object /// JSON password array configuration object
/// </summary> /// </summary>
//public class PasswordConfig //public class PasswordConfig
//{ //{
// /// <summary> // /// <summary>
// /// Key used to search for object in JSON array // /// Key used to search for object in JSON array
// /// </summary> // /// </summary>
// public string key { get; set; } // public string key { get; set; }
// /// <summary> // /// <summary>
// /// Friendly name of password object // /// Friendly name of password object
// /// </summary> // /// </summary>
// public string name { get; set; } // public string name { get; set; }
// /// <summary> // /// <summary>
// /// Password object enabled // /// Password object enabled
// /// </summary> // /// </summary>
// public bool enabled { get; set; } // public bool enabled { get; set; }
// /// <summary> // /// <summary>
// /// // ///
// /// </summary> // /// </summary>
// public ushort simplEnabled // public ushort simplEnabled
// { // {
// get { return (ushort)(enabled ? 1 : 0); } // get { return (ushort)(enabled ? 1 : 0); }
// set { enabled = Convert.ToBoolean(value); } // set { enabled = Convert.ToBoolean(value); }
// } // }
// /// <summary> // /// <summary>
// /// Password object configured password // /// Password object configured password
// /// </summary> // /// </summary>
// public string password { get; set; } // public string password { get; set; }
// /// <summary> // /// <summary>
// /// Password type // /// Password type
// /// </summary> // /// </summary>
// private int type { get; set; } // private int type { get; set; }
// /// <summary> // /// <summary>
// /// Password Type for S+ // /// Password Type for S+
// /// </summary> // /// </summary>
// public ushort simplType // public ushort simplType
// { // {
// get { return Convert.ToUInt16(type); } // get { return Convert.ToUInt16(type); }
// set { type = value; } // set { type = value; }
// } // }
// /// <summary> // /// <summary>
// /// Password path // /// Password path
// /// **FUTURE** implementation of saving passwords recieved from Fusion or other external sources back to config // /// **FUTURE** implementation of saving passwords recieved from Fusion or other external sources back to config
// /// </summary> // /// </summary>
// public string path { get; set; } // public string path { get; set; }
// /// <summary> // /// <summary>
// /// Constructor // /// Constructor
// /// </summary> // /// </summary>
// public PasswordConfig() // public PasswordConfig()
// { // {
// simplEnabled = 0; // simplEnabled = 0;
// simplType = 0; // simplType = 0;
// } // }
//} //}
// Example JSON password collections configuration object // Example JSON password collections configuration object
//{ //{
// "global": { // "global": {
// "passwords": { // "passwords": {
// "1": { // "1": {
// "name": "Technician Password", // "name": "Technician Password",
// "password": "2468" // "password": "2468"
// }, // },
// "2": { // "2": {
// "name": "System Password", // "name": "System Password",
// "password": "123456" // "password": "123456"
// }, // },
// "3": { // "3": {
// "name": "Master Password", // "name": "Master Password",
// "password": "abc123" // "password": "abc123"
// }, // },
// "5": { // "5": {
// "name": "Backdoor Password", // "name": "Backdoor Password",
// "password": "1988" // "password": "1988"
// }, // },
// "10": { // "10": {
// "name": "Backdoor Password", // "name": "Backdoor Password",
// "password": "1988" // "password": "1988"
// } // }
// } // }
// } // }
//} //}
/// <summary> /// <summary>
/// JSON password array configuration object /// JSON password array configuration object
/// </summary> /// </summary>
public class PasswordConfig public class PasswordConfig
{ {
/// <summary> /// <summary>
/// Password object configured password /// Password object configured password
/// </summary> /// </summary>
public string password { get; set; } public string password { get; set; }
/// <summary> /// <summary>
/// Constructor /// Constructor
/// </summary> /// </summary>
public PasswordConfig() public PasswordConfig()
{ {
} }
} }
/// <summary> /// <summary>
/// Global JSON object /// Global JSON object
/// </summary> /// </summary>
//public class GlobalConfig //public class GlobalConfig
//{ //{
// //public List<PasswordConfig> passwords { get; set; } // //public List<PasswordConfig> passwords { get; set; }
// public Dictionary<uint, PasswordConfig> passwords { get; set; } // public Dictionary<uint, PasswordConfig> passwords { get; set; }
// /// <summary> // /// <summary>
// /// Constructor // /// Constructor
// /// </summary> // /// </summary>
// public GlobalConfig() // public GlobalConfig()
// { // {
// } // }
//} //}
/// <summary> /// <summary>
/// Root JSON object /// Root JSON object
/// </summary> /// </summary>
//public class RootObject //public class RootObject
//{ //{
// public GlobalConfig global { get; set; } // public GlobalConfig global { get; set; }
//} //}
} }

View file

@ -1,207 +1,207 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Crestron.SimplSharp; using Crestron.SimplSharp;
namespace PepperDash.Core.PasswordManagement namespace PepperDash.Core.PasswordManagement
{ {
public class PasswordClient public class PasswordClient
{ {
/// <summary> /// <summary>
/// Password Client /// Password Client
/// </summary> /// </summary>
public PasswordConfig Client { get; set; } public PasswordConfig Client { get; set; }
/// <summary> /// <summary>
/// Used to build the password entered by the user /// Used to build the password entered by the user
/// </summary> /// </summary>
public string PasswordToValidate { get; set; } public string PasswordToValidate { get; set; }
/// <summary> /// <summary>
/// Boolean event /// Boolean event
/// </summary> /// </summary>
public event EventHandler<BoolChangeEventArgs> BoolChange; public event EventHandler<BoolChangeEventArgs> BoolChange;
/// <summary> /// <summary>
/// Ushort event /// Ushort event
/// </summary> /// </summary>
public event EventHandler<UshrtChangeEventArgs> UshrtChange; public event EventHandler<UshrtChangeEventArgs> UshrtChange;
/// <summary> /// <summary>
/// String event /// String event
/// </summary> /// </summary>
public event EventHandler<StringChangeEventArgs> StringChange; public event EventHandler<StringChangeEventArgs> StringChange;
/// <summary> /// <summary>
/// Constructor /// Constructor
/// </summary> /// </summary>
public PasswordClient() public PasswordClient()
{ {
} }
/// <summary> /// <summary>
/// Initialize method /// Initialize method
/// </summary> /// </summary>
/// <param name="key"></param> /// <param name="key"></param>
public void Initialize(string key) public void Initialize(string key)
{ {
OnBoolChange(false, 0, PasswordManagementConstants.BoolEvaluatedChange); OnBoolChange(false, 0, PasswordManagementConstants.BoolEvaluatedChange);
Client = new PasswordConfig(); Client = new PasswordConfig();
PasswordToValidate = ""; PasswordToValidate = "";
// there has to be a better way to get the index of the current index of password // there has to be a better way to get the index of the current index of password
ushort i = 0; ushort i = 0;
foreach (var password in PasswordManager.Passwords) foreach (var password in PasswordManager.Passwords)
{ {
i++; i++;
OnUshrtChange((ushort)password.Key, (ushort)password.Key, PasswordManagementConstants.PasswordKey); OnUshrtChange((ushort)password.Key, (ushort)password.Key, PasswordManagementConstants.PasswordKey);
} }
OnBoolChange(true, 0, PasswordManagementConstants.BoolEvaluatedChange); OnBoolChange(true, 0, PasswordManagementConstants.BoolEvaluatedChange);
} }
/// <summary> /// <summary>
/// Retrieves password by key /// Retrieves password by key
/// </summary> /// </summary>
/// <param name="key"></param> /// <param name="key"></param>
//public void GetPasswordByKey(string key) //public void GetPasswordByKey(string key)
//{ //{
// if (string.IsNullOrEmpty(key)) // if (string.IsNullOrEmpty(key))
// { // {
// Debug.Console(1, "PassowrdClient.GetPasswordByKey failed:\rKey {0} is null or empty", key); // Debug.Console(1, "PassowrdClient.GetPasswordByKey failed:\rKey {0} is null or empty", key);
// return; // return;
// } // }
// PasswordConfig password = PasswordManager.Passwords.FirstOrDefault(p => p.key.Equals(key)); // PasswordConfig password = PasswordManager.Passwords.FirstOrDefault(p => p.key.Equals(key));
// if (password == null) // if (password == null)
// { // {
// OnUshrtChange(0, 0, PasswordManagementConstants.SelectedPasswordLength); // OnUshrtChange(0, 0, PasswordManagementConstants.SelectedPasswordLength);
// return; // return;
// } // }
// Client = password; // Client = password;
// OnUshrtChange((ushort)Client.password.Length, 0, PasswordManagementConstants.SelectedPasswordLength); // OnUshrtChange((ushort)Client.password.Length, 0, PasswordManagementConstants.SelectedPasswordLength);
// OnStringChange(Client.key, 0, PasswordManagementConstants.PasswordKeySelected); // OnStringChange(Client.key, 0, PasswordManagementConstants.PasswordKeySelected);
//} //}
/// <summary> /// <summary>
/// Retrieve password by index /// Retrieve password by index
/// </summary> /// </summary>
/// <param name="index"></param> /// <param name="index"></param>
public void GetPasswordByIndex(ushort key) public void GetPasswordByIndex(ushort key)
{ {
PasswordConfig pw = PasswordManager.Passwords[key]; PasswordConfig pw = PasswordManager.Passwords[key];
if (pw == null) if (pw == null)
{ {
OnUshrtChange(0, 0, PasswordManagementConstants.SelectedPasswordLength); OnUshrtChange(0, 0, PasswordManagementConstants.SelectedPasswordLength);
return; return;
} }
Client = pw; Client = pw;
OnUshrtChange((ushort)Client.password.Length, 0, PasswordManagementConstants.SelectedPasswordLength); OnUshrtChange((ushort)Client.password.Length, 0, PasswordManagementConstants.SelectedPasswordLength);
OnUshrtChange(key, 0, PasswordManagementConstants.PasswordKeySelected); OnUshrtChange(key, 0, PasswordManagementConstants.PasswordKeySelected);
} }
/// <summary> /// <summary>
/// Password validation method /// Password validation method
/// </summary> /// </summary>
/// <param name="password"></param> /// <param name="password"></param>
public void ValidatePassword(string password) public void ValidatePassword(string password)
{ {
if (string.IsNullOrEmpty(password)) if (string.IsNullOrEmpty(password))
return; return;
if (string.Equals(Client.password, password)) if (string.Equals(Client.password, password))
{ {
OnBoolChange(true, 0, PasswordManagementConstants.PasswordIsValid); OnBoolChange(true, 0, PasswordManagementConstants.PasswordIsValid);
} }
else else
{ {
OnBoolChange(true, 0, PasswordManagementConstants.PasswordIsInvalid); OnBoolChange(true, 0, PasswordManagementConstants.PasswordIsInvalid);
} }
OnBoolChange(false, 0, PasswordManagementConstants.PasswordIsValid); OnBoolChange(false, 0, PasswordManagementConstants.PasswordIsValid);
OnBoolChange(false, 0, PasswordManagementConstants.PasswordIsInvalid); OnBoolChange(false, 0, PasswordManagementConstants.PasswordIsInvalid);
ClearPassword(); ClearPassword();
} }
/// <summary> /// <summary>
/// Builds the user entered passwrod string, will attempt to validate the user entered /// 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 /// password against the selected password when the length of the 2 are equal
/// </summary> /// </summary>
/// <param name="data"></param> /// <param name="data"></param>
public void BuildPassword(string data) public void BuildPassword(string data)
{ {
PasswordToValidate = String.Concat(PasswordToValidate, data); PasswordToValidate = String.Concat(PasswordToValidate, data);
OnBoolChange(true, (ushort)PasswordToValidate.Length, PasswordManagementConstants.PasswordLedChange); OnBoolChange(true, (ushort)PasswordToValidate.Length, PasswordManagementConstants.PasswordLedChange);
if (PasswordToValidate.Length == Client.password.Length) if (PasswordToValidate.Length == Client.password.Length)
ValidatePassword(PasswordToValidate); ValidatePassword(PasswordToValidate);
} }
/// <summary> /// <summary>
/// Clears the user entered password and resets the LEDs /// Clears the user entered password and resets the LEDs
/// </summary> /// </summary>
public void ClearPassword() public void ClearPassword()
{ {
PasswordToValidate = ""; PasswordToValidate = "";
OnBoolChange(true, (ushort)PasswordToValidate.Length, PasswordManagementConstants.PasswordLedChange); OnBoolChange(true, (ushort)PasswordToValidate.Length, PasswordManagementConstants.PasswordLedChange);
for(var i = 1; i <= Client.password.Length; i++) for(var i = 1; i <= Client.password.Length; i++)
OnBoolChange(false, (ushort)i, PasswordManagementConstants.PasswordLedChange); OnBoolChange(false, (ushort)i, PasswordManagementConstants.PasswordLedChange);
} }
/// <summary> /// <summary>
/// Protected boolean change event handler /// Protected boolean change event handler
/// </summary> /// </summary>
/// <param name="state"></param> /// <param name="state"></param>
/// <param name="index"></param> /// <param name="index"></param>
/// <param name="type"></param> /// <param name="type"></param>
protected void OnBoolChange(bool state, ushort index, ushort type) protected void OnBoolChange(bool state, ushort index, ushort type)
{ {
var handler = BoolChange; var handler = BoolChange;
if (handler != null) if (handler != null)
{ {
var args = new BoolChangeEventArgs(state, type); var args = new BoolChangeEventArgs(state, type);
args.Index = index; args.Index = index;
BoolChange(this, args); BoolChange(this, args);
} }
} }
/// <summary> /// <summary>
/// Protected ushort change event handler /// Protected ushort change event handler
/// </summary> /// </summary>
/// <param name="value"></param> /// <param name="value"></param>
/// <param name="index"></param> /// <param name="index"></param>
/// <param name="type"></param> /// <param name="type"></param>
protected void OnUshrtChange(ushort value, ushort index, ushort type) protected void OnUshrtChange(ushort value, ushort index, ushort type)
{ {
var handler = UshrtChange; var handler = UshrtChange;
if (handler != null) if (handler != null)
{ {
var args = new UshrtChangeEventArgs(value, type); var args = new UshrtChangeEventArgs(value, type);
args.Index = index; args.Index = index;
UshrtChange(this, args); UshrtChange(this, args);
} }
} }
/// <summary> /// <summary>
/// Protected string change event handler /// Protected string change event handler
/// </summary> /// </summary>
/// <param name="value"></param> /// <param name="value"></param>
/// <param name="index"></param> /// <param name="index"></param>
/// <param name="type"></param> /// <param name="type"></param>
protected void OnStringChange(string value, ushort index, ushort type) protected void OnStringChange(string value, ushort index, ushort type)
{ {
var handler = StringChange; var handler = StringChange;
if (handler != null) if (handler != null)
{ {
var args = new StringChangeEventArgs(value, type); var args = new StringChangeEventArgs(value, type);
args.Index = index; args.Index = index;
StringChange(this, args); StringChange(this, args);
} }
} }
} }
} }

View file

@ -1,233 +1,233 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using Crestron.SimplSharp; using Crestron.SimplSharp;
using PepperDash.Core.JsonToSimpl; using PepperDash.Core.JsonToSimpl;
using PepperDash.Core.JsonStandardObjects; using PepperDash.Core.JsonStandardObjects;
namespace PepperDash.Core.PasswordManagement namespace PepperDash.Core.PasswordManagement
{ {
public class PasswordManager public class PasswordManager
{ {
/// <summary> /// <summary>
/// List of passwords configured /// List of passwords configured
/// </summary> /// </summary>
public static Dictionary<uint, PasswordConfig> Passwords = new Dictionary<uint, PasswordConfig>(); public static Dictionary<uint, PasswordConfig> Passwords = new Dictionary<uint, PasswordConfig>();
private Dictionary<uint, PasswordConfig> TempPasswords = new Dictionary<uint, PasswordConfig>(); private Dictionary<uint, PasswordConfig> TempPasswords = new Dictionary<uint, PasswordConfig>();
CTimer UpdateTimer; CTimer UpdateTimer;
public long UpdateTimerElapsedMs = 5000; public long UpdateTimerElapsedMs = 5000;
/// <summary> /// <summary>
/// Boolean event /// Boolean event
/// </summary> /// </summary>
public event EventHandler<BoolChangeEventArgs> BoolChange; public event EventHandler<BoolChangeEventArgs> BoolChange;
/// <summary> /// <summary>
/// Ushort event /// Ushort event
/// </summary> /// </summary>
public event EventHandler<UshrtChangeEventArgs> UshrtChange; public event EventHandler<UshrtChangeEventArgs> UshrtChange;
/// <summary> /// <summary>
/// String event /// String event
/// </summary> /// </summary>
public event EventHandler<StringChangeEventArgs> StringChange; public event EventHandler<StringChangeEventArgs> StringChange;
/// <summary> /// <summary>
/// Constructor /// Constructor
/// </summary> /// </summary>
public PasswordManager() public PasswordManager()
{ {
Passwords.Clear(); Passwords.Clear();
} }
/// <summary> /// <summary>
/// Initialize method /// Initialize method
/// </summary> /// </summary>
/// <param name="key"></param> /// <param name="key"></param>
/// <param name="uniqueId"></param> /// <param name="uniqueId"></param>
//public void Initialize(string uniqueId, string key) //public void Initialize(string uniqueId, string key)
//{ //{
// OnBoolChange(false, 0, PasswordManagementConstants.BoolEvaluatedChange); // OnBoolChange(false, 0, PasswordManagementConstants.BoolEvaluatedChange);
// try // try
// { // {
// if(string.IsNullOrEmpty(uniqueId) || string.IsNullOrEmpty(key)) // if(string.IsNullOrEmpty(uniqueId) || string.IsNullOrEmpty(key))
// { // {
// Debug.Console(1, "PasswordManager.Initialize({0}, {1}) null or empty parameters", uniqueId, key); // Debug.Console(1, "PasswordManager.Initialize({0}, {1}) null or empty parameters", uniqueId, key);
// return; // return;
// } // }
// JsonToSimplMaster master = J2SGlobal.GetMasterByFile(uniqueId); // JsonToSimplMaster master = J2SGlobal.GetMasterByFile(uniqueId);
// if(master == null) // if(master == null)
// { // {
// Debug.Console(1, "PassowrdManager.Initialize failed:\rCould not find JSON file with uniqueID {0}", uniqueId); // Debug.Console(1, "PassowrdManager.Initialize failed:\rCould not find JSON file with uniqueID {0}", uniqueId);
// return; // return;
// } // }
// var global = master.JsonObject.ToObject<RootObject>().global; // var global = master.JsonObject.ToObject<RootObject>().global;
// var passwords = global.passwords; // var passwords = global.passwords;
// if(passwords == null) // if(passwords == null)
// { // {
// Debug.Console(1, "PasswordManager.Initialize failed:\rCould not find password object"); // Debug.Console(1, "PasswordManager.Initialize failed:\rCould not find password object");
// return; // return;
// } // }
// foreach(var password in passwords) // foreach(var password in passwords)
// { // {
// if (password != null) // if (password != null)
// { // {
// var index = passwords.IndexOf(password); // var index = passwords.IndexOf(password);
// password.path = string.Format("global.passwords[{0}]", index); // password.path = string.Format("global.passwords[{0}]", index);
// Debug.Console(1, "PasswordManager.Initialize: {0}, {1}, {2}, {3}, {4}, {5}", password.key, password.name, password.simplEnabled, password.simplType, password.password, password.path); // Debug.Console(1, "PasswordManager.Initialize: {0}, {1}, {2}, {3}, {4}, {5}", password.key, password.name, password.simplEnabled, password.simplType, password.password, password.path);
// //AddPassword(password); // //AddPassword(password);
// OnStringChange(password.path, (ushort)index, PasswordManagementConstants.FullPathToPassword); // OnStringChange(password.path, (ushort)index, PasswordManagementConstants.FullPathToPassword);
// OnStringChange(password.key, (ushort)index, PasswordManagementConstants.PasswordKey); // OnStringChange(password.key, (ushort)index, PasswordManagementConstants.PasswordKey);
// } // }
// } // }
// OnUshrtChange(Convert.ToUInt16(Passwords.Count), 0, PasswordManagementConstants.PasswordListCount); // OnUshrtChange(Convert.ToUInt16(Passwords.Count), 0, PasswordManagementConstants.PasswordListCount);
// } // }
// catch(Exception e) // catch(Exception e)
// { // {
// var msg = string.Format("PasswordManager.Initialize({0}, {1}) failed:\r{2}", uniqueId, key, e.Message); // var msg = string.Format("PasswordManager.Initialize({0}, {1}) failed:\r{2}", uniqueId, key, e.Message);
// CrestronConsole.PrintLine(msg); // CrestronConsole.PrintLine(msg);
// ErrorLog.Error(msg); // ErrorLog.Error(msg);
// } // }
// finally // finally
// { // {
// OnBoolChange(true, 0, PasswordManagementConstants.BoolEvaluatedChange); // OnBoolChange(true, 0, PasswordManagementConstants.BoolEvaluatedChange);
// } // }
//} //}
/// <summary> /// <summary>
/// Adds password to the list /// Adds password to the list
/// </summary> /// </summary>
/// <param name="password"></param> /// <param name="password"></param>
//private void AddPassword(PasswordConfig password) //private void AddPassword(PasswordConfig password)
//{ //{
// if (password == null) // if (password == null)
// return; // return;
// var item = Passwords.FirstOrDefault(i => i.key.Equals(password.key)); // var item = Passwords.FirstOrDefault(i => i.key.Equals(password.key));
// if (item != null) // if (item != null)
// Passwords.Remove(item); // Passwords.Remove(item);
// Passwords.Add(password); // Passwords.Add(password);
// Passwords.Sort((x, y) => string.Compare(x.key, y.key)); // Passwords.Sort((x, y) => string.Compare(x.key, y.key));
//} //}
/// <summary> /// <summary>
/// Removes password from the list /// Removes password from the list
/// </summary> /// </summary>
/// <param name="password"></param> /// <param name="password"></param>
//private void RemovePassword(PasswordConfig password) //private void RemovePassword(PasswordConfig password)
//{ //{
// if (password == null) // if (password == null)
// return; // return;
// var item = Passwords.FirstOrDefault(i => i.key.Equals(password.key)); // var item = Passwords.FirstOrDefault(i => i.key.Equals(password.key));
// if (item != null) // if (item != null)
// Passwords.Remove(item); // Passwords.Remove(item);
//} //}
/// <summary> /// <summary>
/// Updates password stored in the dictonary /// Updates password stored in the dictonary
/// </summary> /// </summary>
/// <param name="uniqueId"></param> /// <param name="uniqueId"></param>
/// <param name="key"></param> /// <param name="key"></param>
/// <param name="password"></param> /// <param name="password"></param>
public void UpdatePassword(ushort key, string password) public void UpdatePassword(ushort key, string password)
{ {
if (string.IsNullOrEmpty(password)) if (string.IsNullOrEmpty(password))
return; return;
var pw = TempPasswords[key]; var pw = TempPasswords[key];
if (pw == null) if (pw == null)
{ {
pw = new PasswordConfig(); pw = new PasswordConfig();
} }
pw.password = password; pw.password = password;
if (UpdateTimer == null) if (UpdateTimer == null)
{ {
// (o) => SavePasswords removes the need to create a callback method that takes in an object // (o) => SavePasswords removes the need to create a callback method that takes in an object
UpdateTimer = new CTimer((o) => StorePassword(), UpdateTimerElapsedMs); UpdateTimer = new CTimer((o) => StorePassword(), UpdateTimerElapsedMs);
} }
else else
{ {
UpdateTimer.Reset(); UpdateTimer.Reset();
} }
} }
/// <summary> /// <summary>
/// Stores the updated passwords in TempPassword in the Passwords dictionary /// Stores the updated passwords in TempPassword in the Passwords dictionary
/// </summary> /// </summary>
private void StorePassword() private void StorePassword()
{ {
UpdateTimer.Stop(); UpdateTimer.Stop();
foreach (var tempPw in TempPasswords) foreach (var tempPw in TempPasswords)
{ {
Passwords[tempPw.Key] = tempPw.Value; Passwords[tempPw.Key] = tempPw.Value;
} }
TempPasswords.Clear(); TempPasswords.Clear();
} }
/// <summary> /// <summary>
/// Protected boolean change event handler /// Protected boolean change event handler
/// </summary> /// </summary>
/// <param name="state"></param> /// <param name="state"></param>
/// <param name="index"></param> /// <param name="index"></param>
/// <param name="type"></param> /// <param name="type"></param>
protected void OnBoolChange(bool state, ushort index, ushort type) protected void OnBoolChange(bool state, ushort index, ushort type)
{ {
var handler = BoolChange; var handler = BoolChange;
if (handler != null) if (handler != null)
{ {
var args = new BoolChangeEventArgs(state, type); var args = new BoolChangeEventArgs(state, type);
args.Index = index; args.Index = index;
BoolChange(this, args); BoolChange(this, args);
} }
} }
/// <summary> /// <summary>
/// Protected ushort change event handler /// Protected ushort change event handler
/// </summary> /// </summary>
/// <param name="state"></param> /// <param name="state"></param>
/// <param name="index"></param> /// <param name="index"></param>
/// <param name="type"></param> /// <param name="type"></param>
protected void OnUshrtChange(ushort value, ushort index, ushort type) protected void OnUshrtChange(ushort value, ushort index, ushort type)
{ {
var handler = UshrtChange; var handler = UshrtChange;
if (handler != null) if (handler != null)
{ {
var args = new UshrtChangeEventArgs(value, type); var args = new UshrtChangeEventArgs(value, type);
args.Index = index; args.Index = index;
UshrtChange(this, args); UshrtChange(this, args);
} }
} }
/// <summary> /// <summary>
/// Protected string change event handler /// Protected string change event handler
/// </summary> /// </summary>
/// <param name="value"></param> /// <param name="value"></param>
/// <param name="index"></param> /// <param name="index"></param>
/// <param name="type"></param> /// <param name="type"></param>
protected void OnStringChange(string value, ushort index, ushort type) protected void OnStringChange(string value, ushort index, ushort type)
{ {
var handler = StringChange; var handler = StringChange;
if (handler != null) if (handler != null)
{ {
var args = new StringChangeEventArgs(value, type); var args = new StringChangeEventArgs(value, type);
args.Index = index; args.Index = index;
StringChange(this, args); StringChange(this, args);
} }
} }
} }
} }

View file

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

View file

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

View file

@ -1,156 +1,156 @@
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Release</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Release</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion> <ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion> <SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{87E29B4C-569B-4368-A4ED-984AC1440C96}</ProjectGuid> <ProjectGuid>{87E29B4C-569B-4368-A4ED-984AC1440C96}</ProjectGuid>
<OutputType>Library</OutputType> <OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder> <AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>PepperDash.Core</RootNamespace> <RootNamespace>PepperDash.Core</RootNamespace>
<AssemblyName>PepperDash_Core</AssemblyName> <AssemblyName>PepperDash_Core</AssemblyName>
<ProjectTypeGuids>{0B4745B0-194B-4BB6-8E21-E9057CA92500};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> <ProjectTypeGuids>{0B4745B0-194B-4BB6-8E21-E9057CA92500};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<PlatformFamilyName>WindowsCE</PlatformFamilyName> <PlatformFamilyName>WindowsCE</PlatformFamilyName>
<PlatformID>E2BECB1F-8C8C-41ba-B736-9BE7D946A398</PlatformID> <PlatformID>E2BECB1F-8C8C-41ba-B736-9BE7D946A398</PlatformID>
<OSVersion>5.0</OSVersion> <OSVersion>5.0</OSVersion>
<DeployDirSuffix>SmartDeviceProject1</DeployDirSuffix> <DeployDirSuffix>SmartDeviceProject1</DeployDirSuffix>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<NativePlatformName>Windows CE</NativePlatformName> <NativePlatformName>Windows CE</NativePlatformName>
<FormFactorID> <FormFactorID>
</FormFactorID> </FormFactorID>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<AllowedReferenceRelatedFileExtensions>.allowedReferenceRelatedFileExtensions</AllowedReferenceRelatedFileExtensions> <AllowedReferenceRelatedFileExtensions>.allowedReferenceRelatedFileExtensions</AllowedReferenceRelatedFileExtensions>
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType> <DebugType>full</DebugType>
<Optimize>false</Optimize> <Optimize>false</Optimize>
<OutputPath>bin\</OutputPath> <OutputPath>bin\</OutputPath>
<DefineConstants>DEBUG;TRACE;</DefineConstants> <DefineConstants>DEBUG;TRACE;</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<NoStdLib>true</NoStdLib> <NoStdLib>true</NoStdLib>
<NoConfig>true</NoConfig> <NoConfig>true</NoConfig>
<DocumentationFile>bin\PepperDash_Core.xml</DocumentationFile> <DocumentationFile>bin\PepperDash_Core.xml</DocumentationFile>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<AllowedReferenceRelatedFileExtensions>.allowedReferenceRelatedFileExtensions</AllowedReferenceRelatedFileExtensions> <AllowedReferenceRelatedFileExtensions>.allowedReferenceRelatedFileExtensions</AllowedReferenceRelatedFileExtensions>
<DebugType>none</DebugType> <DebugType>none</DebugType>
<Optimize>true</Optimize> <Optimize>true</Optimize>
<OutputPath>bin\</OutputPath> <OutputPath>bin\</OutputPath>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<NoStdLib>true</NoStdLib> <NoStdLib>true</NoStdLib>
<NoConfig>true</NoConfig> <NoConfig>true</NoConfig>
<DocumentationFile>bin\PepperDash_Core.xml</DocumentationFile> <DocumentationFile>bin\PepperDash_Core.xml</DocumentationFile>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="mscorlib" /> <Reference Include="mscorlib" />
<Reference Include="SimplSharpCustomAttributesInterface, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1099c178b3b54c3b, processorArchitecture=MSIL"> <Reference Include="SimplSharpCustomAttributesInterface, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1099c178b3b54c3b, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion> <SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\..\..\..\ProgramData\Crestron\SDK\SimplSharpCustomAttributesInterface.dll</HintPath> <HintPath>..\..\..\..\..\..\..\..\ProgramData\Crestron\SDK\SimplSharpCustomAttributesInterface.dll</HintPath>
</Reference> </Reference>
<Reference Include="SimplSharpCWSHelperInterface, Version=2.0.0.0, Culture=neutral, PublicKeyToken=1099c178b3b54c3b, processorArchitecture=MSIL"> <Reference Include="SimplSharpCWSHelperInterface, Version=2.0.0.0, Culture=neutral, PublicKeyToken=1099c178b3b54c3b, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion> <SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\..\..\..\ProgramData\Crestron\SDK\SimplSharpCWSHelperInterface.dll</HintPath> <HintPath>..\..\..\..\..\..\..\..\ProgramData\Crestron\SDK\SimplSharpCWSHelperInterface.dll</HintPath>
</Reference> </Reference>
<Reference Include="SimplSharpHelperInterface, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1099c178b3b54c3b, processorArchitecture=MSIL"> <Reference Include="SimplSharpHelperInterface, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1099c178b3b54c3b, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion> <SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\..\..\..\ProgramData\Crestron\SDK\SimplSharpHelperInterface.dll</HintPath> <HintPath>..\..\..\..\..\..\..\..\ProgramData\Crestron\SDK\SimplSharpHelperInterface.dll</HintPath>
</Reference> </Reference>
<Reference Include="SimplSharpNewtonsoft, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1099c178b3b54c3b, processorArchitecture=MSIL"> <Reference Include="SimplSharpNewtonsoft, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1099c178b3b54c3b, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion> <SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\..\..\..\ProgramData\Crestron\SDK\SimplSharpNewtonsoft.dll</HintPath> <HintPath>..\..\..\..\..\..\..\..\ProgramData\Crestron\SDK\SimplSharpNewtonsoft.dll</HintPath>
</Reference> </Reference>
<Reference Include="SimplSharpReflectionInterface, Version=1.0.5583.25238, Culture=neutral, PublicKeyToken=1099c178b3b54c3b, processorArchitecture=MSIL"> <Reference Include="SimplSharpReflectionInterface, Version=1.0.5583.25238, Culture=neutral, PublicKeyToken=1099c178b3b54c3b, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion> <SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\..\..\..\ProgramData\Crestron\SDK\SimplSharpReflectionInterface.dll</HintPath> <HintPath>..\..\..\..\..\..\..\..\ProgramData\Crestron\SDK\SimplSharpReflectionInterface.dll</HintPath>
</Reference> </Reference>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
<Reference Include="System.Data" /> <Reference Include="System.Data" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="CommunicationExtras.cs" /> <Compile Include="CommunicationExtras.cs" />
<Compile Include="Comm\CommunicationStreamDebugging.cs" /> <Compile Include="Comm\CommunicationStreamDebugging.cs" />
<Compile Include="Comm\ControlPropertiesConfig.cs" /> <Compile Include="Comm\ControlPropertiesConfig.cs" />
<Compile Include="Comm\GenericSecureTcpIpClient.cs" /> <Compile Include="Comm\GenericSecureTcpIpClient.cs" />
<Compile Include="Comm\GenericTcpIpClient_ForServer.cs" /> <Compile Include="Comm\GenericTcpIpClient_ForServer.cs" />
<Compile Include="Comm\GenericHttpSseClient.cs" /> <Compile Include="Comm\GenericHttpSseClient.cs" />
<Compile Include="Comm\GenericSecureTcpIpServer.cs" /> <Compile Include="Comm\GenericSecureTcpIpServer.cs" />
<Compile Include="Comm\GenericSecureTcpIpClient_ForServer.cs"> <Compile Include="Comm\GenericSecureTcpIpClient_ForServer.cs">
<SubType>Code</SubType> <SubType>Code</SubType>
</Compile> </Compile>
<Compile Include="Comm\eControlMethods.cs" /> <Compile Include="Comm\eControlMethods.cs" />
<Compile Include="Comm\FINISH CommStatic.cs" /> <Compile Include="Comm\FINISH CommStatic.cs" />
<Compile Include="Comm\CommunicationGather.cs" /> <Compile Include="Comm\CommunicationGather.cs" />
<Compile Include="Comm\EventArgs.cs" /> <Compile Include="Comm\EventArgs.cs" />
<Compile Include="Comm\GenericSshClient.cs" /> <Compile Include="Comm\GenericSshClient.cs" />
<Compile Include="Comm\GenericUdpServer.cs" /> <Compile Include="Comm\GenericUdpServer.cs" />
<Compile Include="Comm\QscCoreDoubleTcpIpClient.cs" /> <Compile Include="Comm\QscCoreDoubleTcpIpClient.cs" />
<Compile Include="Comm\TcpClientConfigObject.cs" /> <Compile Include="Comm\TcpClientConfigObject.cs" />
<Compile Include="Comm\TcpServerConfigObject.cs" /> <Compile Include="Comm\TcpServerConfigObject.cs" />
<Compile Include="Config\PortalConfigReader.cs" /> <Compile Include="Config\PortalConfigReader.cs" />
<Compile Include="CoreInterfaces.cs" /> <Compile Include="CoreInterfaces.cs" />
<Compile Include="Web\RequestHandlers\DefaultRequestHandler.cs" /> <Compile Include="Web\RequestHandlers\DefaultRequestHandler.cs" />
<Compile Include="Web\RequestHandlers\WebApiBaseRequestHandler.cs" /> <Compile Include="Web\RequestHandlers\WebApiBaseRequestHandler.cs" />
<Compile Include="Web\WebApiServer.cs" /> <Compile Include="Web\WebApiServer.cs" />
<Compile Include="EventArgs.cs" /> <Compile Include="EventArgs.cs" />
<Compile Include="GenericRESTfulCommunications\Constants.cs" /> <Compile Include="GenericRESTfulCommunications\Constants.cs" />
<Compile Include="GenericRESTfulCommunications\GenericRESTfulClient.cs" /> <Compile Include="GenericRESTfulCommunications\GenericRESTfulClient.cs" />
<Compile Include="JsonStandardObjects\EventArgs and Constants.cs" /> <Compile Include="JsonStandardObjects\EventArgs and Constants.cs" />
<Compile Include="JsonStandardObjects\JsonToSimplDeviceConfig.cs" /> <Compile Include="JsonStandardObjects\JsonToSimplDeviceConfig.cs" />
<Compile Include="JsonStandardObjects\JsonToSimplDevice.cs" /> <Compile Include="JsonStandardObjects\JsonToSimplDevice.cs" />
<Compile Include="JsonToSimpl\JsonToSimplPortalFileMaster.cs" /> <Compile Include="JsonToSimpl\JsonToSimplPortalFileMaster.cs" />
<Compile Include="Logging\Debug.cs" /> <Compile Include="Logging\Debug.cs" />
<Compile Include="Logging\DebugContext.cs" /> <Compile Include="Logging\DebugContext.cs" />
<Compile Include="Logging\DebugMemory.cs" /> <Compile Include="Logging\DebugMemory.cs" />
<Compile Include="Device.cs" /> <Compile Include="Device.cs" />
<Compile Include="Comm\GenericTcpIpServer.cs" /> <Compile Include="Comm\GenericTcpIpServer.cs" />
<Compile Include="EthernetHelper.cs" /> <Compile Include="EthernetHelper.cs" />
<Compile Include="Comm\GenericTcpIpClient.cs" /> <Compile Include="Comm\GenericTcpIpClient.cs" />
<Compile Include="JsonToSimpl\Constants.cs" /> <Compile Include="JsonToSimpl\Constants.cs" />
<Compile Include="JsonToSimpl\Global.cs" /> <Compile Include="JsonToSimpl\Global.cs" />
<Compile Include="JsonToSimpl\JsonToSimplArrayLookupChild.cs" /> <Compile Include="JsonToSimpl\JsonToSimplArrayLookupChild.cs" />
<Compile Include="JsonToSimpl\JsonToSimplChildObjectBase.cs" /> <Compile Include="JsonToSimpl\JsonToSimplChildObjectBase.cs" />
<Compile Include="JsonToSimpl\JsonToSimplFileMaster.cs" /> <Compile Include="JsonToSimpl\JsonToSimplFileMaster.cs" />
<Compile Include="JsonToSimpl\JsonToSimplFixedPathObject.cs" /> <Compile Include="JsonToSimpl\JsonToSimplFixedPathObject.cs" />
<Compile Include="JsonToSimpl\REMOVE JsonToSimplFixedPathObject.cs" /> <Compile Include="JsonToSimpl\REMOVE JsonToSimplFixedPathObject.cs" />
<Compile Include="JsonToSimpl\JsonToSimplGenericMaster.cs" /> <Compile Include="JsonToSimpl\JsonToSimplGenericMaster.cs" />
<Compile Include="JsonToSimpl\JsonToSimplMaster.cs" /> <Compile Include="JsonToSimpl\JsonToSimplMaster.cs" />
<Compile Include="Network\DiscoveryThings.cs" /> <Compile Include="Network\DiscoveryThings.cs" />
<Compile Include="PasswordManagement\Config.cs" /> <Compile Include="PasswordManagement\Config.cs" />
<Compile Include="PasswordManagement\Constants.cs" /> <Compile Include="PasswordManagement\Constants.cs" />
<Compile Include="PasswordManagement\PasswordClient.cs" /> <Compile Include="PasswordManagement\PasswordClient.cs" />
<Compile Include="PasswordManagement\PasswordManager.cs" /> <Compile Include="PasswordManagement\PasswordManager.cs" />
<Compile Include="SystemInfo\EventArgs and Constants.cs" /> <Compile Include="SystemInfo\EventArgs and Constants.cs" />
<Compile Include="SystemInfo\SystemInfoConfig.cs" /> <Compile Include="SystemInfo\SystemInfoConfig.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SystemInfo\SystemInfoToSimpl.cs" /> <Compile Include="SystemInfo\SystemInfoToSimpl.cs" />
<Compile Include="WebApi\Presets\Preset.cs" /> <Compile Include="WebApi\Presets\Preset.cs" />
<Compile Include="WebApi\Presets\User.cs" /> <Compile Include="WebApi\Presets\User.cs" />
<Compile Include="WebApi\Presets\WebApiPasscodeClient.cs" /> <Compile Include="WebApi\Presets\WebApiPasscodeClient.cs" />
<Compile Include="XSigUtility\Serialization\IXSigSerialization.cs" /> <Compile Include="XSigUtility\Serialization\IXSigSerialization.cs" />
<Compile Include="XSigUtility\Serialization\XSigSerializationException.cs" /> <Compile Include="XSigUtility\Serialization\XSigSerializationException.cs" />
<Compile Include="XSigUtility\Tokens\XSigAnalogToken.cs" /> <Compile Include="XSigUtility\Tokens\XSigAnalogToken.cs" />
<Compile Include="XSigUtility\Tokens\XSigDigitalToken.cs" /> <Compile Include="XSigUtility\Tokens\XSigDigitalToken.cs" />
<Compile Include="XSigUtility\Tokens\XSigSerialToken.cs" /> <Compile Include="XSigUtility\Tokens\XSigSerialToken.cs" />
<Compile Include="XSigUtility\Tokens\XSigToken.cs" /> <Compile Include="XSigUtility\Tokens\XSigToken.cs" />
<Compile Include="XSigUtility\Tokens\XSigTokenType.cs" /> <Compile Include="XSigUtility\Tokens\XSigTokenType.cs" />
<Compile Include="XSigUtility\XSigHelpers.cs" /> <Compile Include="XSigUtility\XSigHelpers.cs" />
<Compile Include="XSigUtility\XSigTokenStreamReader.cs" /> <Compile Include="XSigUtility\XSigTokenStreamReader.cs" />
<Compile Include="XSigUtility\XSigTokenStreamWriter.cs" /> <Compile Include="XSigUtility\XSigTokenStreamWriter.cs" />
<None Include="Properties\ControlSystem.cfg" /> <None Include="Properties\ControlSystem.cfg" />
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CompactFramework.CSharp.targets" /> <Import Project="$(MSBuildBinPath)\Microsoft.CompactFramework.CSharp.targets" />
<ProjectExtensions> <ProjectExtensions>
<VisualStudio> <VisualStudio>
</VisualStudio> </VisualStudio>
</ProjectExtensions> </ProjectExtensions>
<PropertyGroup> <PropertyGroup>
<PostBuildEvent>rem S# preparation will execute after these operations</PostBuildEvent> <PostBuildEvent>rem S# preparation will execute after these operations</PostBuildEvent>
<PreBuildEvent>del "$(TargetDir)PepperDash_Core.*" /q <PreBuildEvent>del "$(TargetDir)PepperDash_Core.*" /q
</PreBuildEvent> </PreBuildEvent>
</PropertyGroup> </PropertyGroup>
</Project> </Project>

View file

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<ControlSystem> <ControlSystem>
<Name>MC3 SSH</Name> <Name>MC3 SSH</Name>
<Address>ssh 10.0.0.15</Address> <Address>ssh 10.0.0.15</Address>
<ProgramSlot>Program01</ProgramSlot> <ProgramSlot>Program01</ProgramSlot>
<Storage>Internal Flash</Storage> <Storage>Internal Flash</Storage>
</ControlSystem> </ControlSystem>

View file

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

View file

@ -1,204 +1,204 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Crestron.SimplSharp; using Crestron.SimplSharp;
namespace PepperDash.Core.SystemInfo namespace PepperDash.Core.SystemInfo
{ {
/// <summary> /// <summary>
/// Processor info class /// Processor info class
/// </summary> /// </summary>
public class ProcessorInfo public class ProcessorInfo
{ {
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string Model { get; set; } public string Model { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string SerialNumber { get; set; } public string SerialNumber { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string Firmware { get; set; } public string Firmware { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string FirmwareDate { get; set; } public string FirmwareDate { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string OsVersion { get; set; } public string OsVersion { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string RuntimeEnvironment { get; set; } public string RuntimeEnvironment { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string DevicePlatform { get; set; } public string DevicePlatform { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string ModuleDirectory { get; set; } public string ModuleDirectory { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string LocalTimeZone { get; set; } public string LocalTimeZone { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string ProgramIdTag { get; set; } public string ProgramIdTag { get; set; }
/// <summary> /// <summary>
/// Constructor /// Constructor
/// </summary> /// </summary>
public ProcessorInfo() public ProcessorInfo()
{ {
} }
} }
/// <summary> /// <summary>
/// Ethernet info class /// Ethernet info class
/// </summary> /// </summary>
public class EthernetInfo public class EthernetInfo
{ {
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public ushort DhcpIsOn { get; set; } public ushort DhcpIsOn { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string Hostname { get; set; } public string Hostname { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string MacAddress { get; set; } public string MacAddress { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string IpAddress { get; set; } public string IpAddress { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string Subnet { get; set; } public string Subnet { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string Gateway { get; set; } public string Gateway { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string Dns1 { get; set; } public string Dns1 { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string Dns2 { get; set; } public string Dns2 { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string Dns3 { get; set; } public string Dns3 { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string Domain { get; set; } public string Domain { get; set; }
/// <summary> /// <summary>
/// Constructor /// Constructor
/// </summary> /// </summary>
public EthernetInfo() public EthernetInfo()
{ {
} }
} }
/// <summary> /// <summary>
/// Control subnet info class /// Control subnet info class
/// </summary> /// </summary>
public class ControlSubnetInfo public class ControlSubnetInfo
{ {
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public ushort Enabled { get; set; } public ushort Enabled { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public ushort IsInAutomaticMode { get; set; } public ushort IsInAutomaticMode { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string MacAddress { get; set; } public string MacAddress { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string IpAddress { get; set; } public string IpAddress { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string Subnet { get; set; } public string Subnet { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string RouterPrefix { get; set; } public string RouterPrefix { get; set; }
/// <summary> /// <summary>
/// Constructor /// Constructor
/// </summary> /// </summary>
public ControlSubnetInfo() public ControlSubnetInfo()
{ {
} }
} }
/// <summary> /// <summary>
/// Program info class /// Program info class
/// </summary> /// </summary>
public class ProgramInfo public class ProgramInfo
{ {
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string Name { get; set; } public string Name { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string Header { get; set; } public string Header { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string System { get; set; } public string System { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string ProgramIdTag { get; set; } public string ProgramIdTag { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string CompileTime { get; set; } public string CompileTime { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string Database { get; set; } public string Database { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string Environment { get; set; } public string Environment { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string Programmer { get; set; } public string Programmer { get; set; }
/// <summary> /// <summary>
/// Constructor /// Constructor
/// </summary> /// </summary>
public ProgramInfo() public ProgramInfo()
{ {
} }
} }
} }

View file

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

View file

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

View file

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

View file

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