Completed development and testing of PDC-25. Reviewed with Heath, tweaked a few things for better efficency, I have a sample program available for review

This commit is contained in:
Jason DeVito
2019-10-02 18:38:35 -05:00
parent c9b06ec3ca
commit 9ba46eb3d5
4 changed files with 513 additions and 466 deletions

View File

@@ -3,10 +3,12 @@ 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.Linq;
using PepperDash.Core.JsonToSimpl; using PepperDash.Core.JsonToSimpl;
namespace PepperDash.Core.JsonStandardObjects namespace PepperDash.Core.JsonStandardObjects
{ {
/* /*
Convert JSON snippt to C#: http://json2csharp.com/# Convert JSON snippt to C#: http://json2csharp.com/#
@@ -52,8 +54,8 @@ namespace PepperDash.Core.JsonStandardObjects
/// <summary> /// <summary>
/// Device class /// Device class
/// </summary> /// </summary>
public class DeviceConfig public class DeviceConfig : JsonToSimplChildObjectBase
{ {
/// <summary> /// <summary>
/// JSON config key property /// JSON config key property
/// </summary> /// </summary>
@@ -93,53 +95,63 @@ namespace PepperDash.Core.JsonStandardObjects
/// </summary> /// </summary>
public DeviceConfig() public DeviceConfig()
{ {
// add logic here if necessary properties = new PropertiesConfig();
} }
/// <summary> /// <summary>
/// Initialize Device Module /// Initialize method
/// </summary> /// </summary>
/// <param name="uniqueID">JSON master unique ID</param> /// <param name="uniqueID"></param>
/// <param name="key">Device key to search for</param> /// <param name="deviceKey"></param>
public void Initialize(string uniqueID, string key) 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)) if (string.IsNullOrEmpty(uniqueID) || string.IsNullOrEmpty(deviceKey))
{ {
Debug.Console(1, "UniqueID is null or empty"); Debug.Console(1, "UniqueID ({0} or key ({1} is null or empty", uniqueID, deviceKey);
return; // S+ set EvaluteFb high
} OnBoolChange(true, 0, JsonStandardDeviceConstants.JsonObjectEvaluated);
if (string.IsNullOrEmpty(key))
{
Debug.Console(1, "Device key is null or empty");
return; return;
} }
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);
var device = jsonMaster.JsonObject.ToObject<RootObject>().devices.FirstOrDefault(d => d.key.Equals(key)); if (jsonMaster == null)
{
Debug.Console(1, "Could not find JSON file with uniqueID {0}", uniqueID);
return;
}
name = device.name; // get the device configuration using the key
type = device.type; var devices = jsonMaster.JsonObject.ToObject<RootObject>().devices;
properties = device.properties; var device = devices.FirstOrDefault(d => d.key.Equals(key));
// Pass object to S+ if (device == null)
OnObjectChange(this, 0, JsonStandardDeviceConstants.JsonObjectChanged); {
Debug.Console(1, "Could not find device with key {0}", key);
return;
}
OnObjectChange(device, 0, JsonStandardDeviceConstants.JsonObjectChanged);
var index = devices.IndexOf(device);
OnStringChange(string.Format("devices[{0}]", index), 0, JsonToSimplConstants.FullPathToArrayChange);
} }
catch (Exception e) catch (Exception e)
{ {
var msg = string.Format("Device lookup failed:\r{0}", 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);
return;
} }
finally
// S+ set EvaluteFb high {
OnBoolChange(true, 0, JsonStandardDeviceConstants.JsonObjectEvaluated); // S+ set EvaluteFb high
OnBoolChange(true, 0, JsonStandardDeviceConstants.JsonObjectEvaluated);
}
} }
#region EventHandler Helpers #region EventHandler Helpers
@@ -228,10 +240,18 @@ namespace PepperDash.Core.JsonStandardObjects
public int pacing { get; set; } public int pacing { get; set; }
// convert properties for simpl // convert properties for simpl
public ushort simplBaudRate { get { return (ushort)Convert.ToUInt16(baudRate); } } public ushort simplBaudRate { get { return Convert.ToUInt16(baudRate); } }
public ushort simplDataBits { get { return Convert.ToUInt16(dataBits); } } public ushort simplDataBits { get { return Convert.ToUInt16(dataBits); } }
public ushort simplStopBits { get { return Convert.ToUInt16(stopBits); } } public ushort simplStopBits { get { return Convert.ToUInt16(stopBits); } }
public ushort simplPacing { get { return Convert.ToUInt16(pacing); } } public ushort simplPacing { get { return Convert.ToUInt16(pacing); } }
/// <summary>
/// Constructor
/// </summary>
public ComParamsConfig()
{
}
} }
/// <summary> /// <summary>
@@ -247,9 +267,17 @@ namespace PepperDash.Core.JsonStandardObjects
public int autoReconnectIntervalMs { get; set; } public int autoReconnectIntervalMs { get; set; }
// convert properties for simpl // convert properties for simpl
public ushort simplPort { get { return (ushort)Convert.ToUInt16(port); } } public ushort simplPort { get { return Convert.ToUInt16(port); } }
public ushort simplAutoReconnect { get { return (ushort)(autoReconnect ? 1 : 0); } } public ushort simplAutoReconnect { get { return (ushort)(autoReconnect ? 1 : 0); } }
public ushort simplAutoReconnectIntervalMs { get { return Convert.ToUInt16(autoReconnectIntervalMs); } } public ushort simplAutoReconnectIntervalMs { get { return Convert.ToUInt16(autoReconnectIntervalMs); } }
/// <summary>
/// Constructor
/// </summary>
public TcpSshPropertiesConfig()
{
}
} }
/// <summary> /// <summary>
@@ -265,6 +293,15 @@ namespace PepperDash.Core.JsonStandardObjects
// convert properties for simpl // convert properties for simpl
public ushort simplControlPortNumber { get { return Convert.ToUInt16(controlPortNumber); } } public ushort simplControlPortNumber { get { return Convert.ToUInt16(controlPortNumber); } }
/// <summary>
/// Constructor
/// </summary>
public ControlConfig()
{
comParams = new ComParamsConfig();
tcpSshProperties = new TcpSshPropertiesConfig();
}
} }
/// <summary> /// <summary>
@@ -279,6 +316,14 @@ namespace PepperDash.Core.JsonStandardObjects
// convert properties for simpl // convert properties for simpl
public ushort simplDeviceId { get { return Convert.ToUInt16(deviceId); } } public ushort simplDeviceId { get { return Convert.ToUInt16(deviceId); } }
public ushort simplEnabled { get { return (ushort)(enabled ? 1 : 0); } } public ushort simplEnabled { get { return (ushort)(enabled ? 1 : 0); } }
/// <summary>
/// Constructor
/// </summary>
public PropertiesConfig()
{
control = new ControlConfig();
}
} }
/// <summary> /// <summary>

View File

@@ -1,116 +1,116 @@
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
{ {
public class JsonToSimplArrayLookupChild : JsonToSimplChildObjectBase public class JsonToSimplArrayLookupChild : JsonToSimplChildObjectBase
{ {
public string SearchPropertyName { get; set; } public string SearchPropertyName { get; set; }
public string SearchPropertyValue { get; set; } public string SearchPropertyValue { get; set; }
int ArrayIndex; int ArrayIndex;
/// <summary> /// <summary>
/// For <2.4.1 array lookups /// For <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="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);
base.Initialize(file, key, pathPrefixWithAppend, pathSuffix);
SearchPropertyName = searchPropertyName;
SearchPropertyValue = searchPropertyValue;
}
//PathPrefix+ArrayName+[x]+path+PathSuffix
/// <summary>
///
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
protected override string GetFullPath(string path)
{ {
string pathPrefixWithAppend = (pathPrefix != null ? pathPrefix : "") + GetPathAppend(pathAppend);
base.Initialize(file, key, pathPrefixWithAppend, pathSuffix);
SearchPropertyName = searchPropertyName;
SearchPropertyValue = searchPropertyValue;
}
//PathPrefix+ArrayName+[x]+path+PathSuffix
/// <summary>
///
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
protected override string GetFullPath(string path)
{
return string.Format("{0}[{1}].{2}{3}", return string.Format("{0}[{1}].{2}{3}",
PathPrefix == null ? "" : PathPrefix, PathPrefix == null ? "" : PathPrefix,
ArrayIndex, ArrayIndex,
path, path,
PathSuffix == null ? "" : PathSuffix); PathSuffix == null ? "" : PathSuffix);
} }
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;
@@ -139,15 +139,15 @@ namespace PepperDash.Core.JsonToSimpl
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,327 +1,327 @@
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
{ {
public abstract class JsonToSimplChildObjectBase: IKeyed public abstract class JsonToSimplChildObjectBase: IKeyed
{ {
public event EventHandler<BoolChangeEventArgs> BoolChange; public event EventHandler<BoolChangeEventArgs> BoolChange;
public event EventHandler<UshrtChangeEventArgs> UShortChange; public event EventHandler<UshrtChangeEventArgs> UShortChange;
public event EventHandler<StringChangeEventArgs> StringChange; public event EventHandler<StringChangeEventArgs> StringChange;
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; }
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; }
public bool LinkedToObject { get; protected set; } public bool LinkedToObject { get; protected set; }
protected JsonToSimplMaster Master; protected JsonToSimplMaster Master;
// The sent-in JPaths for the various types // The sent-in JPaths for the various types
protected Dictionary<ushort, string> BoolPaths = new Dictionary<ushort, string>(); protected Dictionary<ushort, string> BoolPaths = new Dictionary<ushort, string>();
protected Dictionary<ushort, string> UshortPaths = new Dictionary<ushort, string>(); protected Dictionary<ushort, string> UshortPaths = new Dictionary<ushort, string>();
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="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>
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);
} }
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, firing off UshrtChange event // Processes the path to a ushort, converting to ushort if able, 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.ToUInt16(response); } catch { val = 0; } try { val = Convert.ToUInt16(response); } 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();
} }
public void USetBoolValue(ushort key, ushort theValue) public void USetBoolValue(ushort key, ushort theValue)
{ {
SetBoolValue(key, theValue == 1); SetBoolValue(key, theValue == 1);
} }
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));
} }
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));
} }
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));
} }
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
//****************************************************************************************** //******************************************************************************************
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);
} }
} }
//****************************************************************************************** //******************************************************************************************
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);
} }
} }
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

@@ -119,5 +119,7 @@
</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>
</PropertyGroup> </PropertyGroup>
</Project> </Project>