chore: move all files to file-scoped namespace

This commit is contained in:
Andrew Welker
2025-07-04 16:02:32 -05:00
parent 8b873b7248
commit 6d2cd75cbe
552 changed files with 46137 additions and 46725 deletions

View File

@@ -6,15 +6,14 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PepperDash.Essentials.Core.Config
namespace PepperDash.Essentials.Core.Config;
public class AudioControlPointListItem
{
public class AudioControlPointListItem
{
[JsonProperty("levelControls")]
public Dictionary<string, LevelControlListItem> LevelControls { get; set; } = new Dictionary<string, LevelControlListItem>();
[JsonProperty("levelControls")]
public Dictionary<string, LevelControlListItem> LevelControls { get; set; } = new Dictionary<string, LevelControlListItem>();
[JsonProperty("presets")]
public Dictionary<string, PresetListItem> Presets { get; set; } = new Dictionary<string, PresetListItem>();
[JsonProperty("presets")]
public Dictionary<string, PresetListItem> Presets { get; set; } = new Dictionary<string, PresetListItem>();
}
}

View File

@@ -7,8 +7,8 @@ using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PepperDash.Essentials.Core.Devices;
namespace PepperDash.Essentials.Core.Config
{
namespace PepperDash.Essentials.Core.Config;
/// <summary>
/// Override this and splice on specific room type behavior, as well as other properties
/// </summary>
@@ -23,32 +23,32 @@ namespace PepperDash.Essentials.Core.Config
[JsonProperty("sourceLists")]
public Dictionary<string, Dictionary<string, SourceListItem>> SourceLists { get; set; }
[JsonProperty("destinationLists")]
public Dictionary<string, Dictionary<string, DestinationListItem>> DestinationLists { get; set; }
[JsonProperty("destinationLists")]
public Dictionary<string, Dictionary<string, DestinationListItem>> DestinationLists { get; set; }
[JsonProperty("audioControlPointLists")]
public Dictionary<string, AudioControlPointListItem> AudioControlPointLists { get; set; }
[JsonProperty("audioControlPointLists")]
public Dictionary<string, AudioControlPointListItem> AudioControlPointLists { get; set; }
[JsonProperty("cameraLists")]
public Dictionary<string, Dictionary<string, CameraListItem>> CameraLists { get; set; }
[JsonProperty("cameraLists")]
public Dictionary<string, Dictionary<string, CameraListItem>> CameraLists { get; set; }
[JsonProperty("tieLines")]
[JsonProperty("tieLines")]
public List<TieLineConfig> TieLines { get; set; }
[JsonProperty("joinMaps")]
public Dictionary<string, JObject> JoinMaps { get; set; }
[JsonProperty("joinMaps")]
public Dictionary<string, JObject> JoinMaps { get; set; }
public BasicConfig()
{
Info = new InfoConfig();
Devices = new List<DeviceConfig>();
SourceLists = new Dictionary<string, Dictionary<string, SourceListItem>>();
DestinationLists = new Dictionary<string, Dictionary<string, DestinationListItem>>();
AudioControlPointLists = new Dictionary<string, AudioControlPointListItem>();
CameraLists = new Dictionary<string, Dictionary<string, CameraListItem>>();
TieLines = new List<TieLineConfig>();
JoinMaps = new Dictionary<string, JObject>();
}
public BasicConfig()
{
Info = new InfoConfig();
Devices = new List<DeviceConfig>();
SourceLists = new Dictionary<string, Dictionary<string, SourceListItem>>();
DestinationLists = new Dictionary<string, Dictionary<string, DestinationListItem>>();
AudioControlPointLists = new Dictionary<string, AudioControlPointListItem>();
CameraLists = new Dictionary<string, Dictionary<string, CameraListItem>>();
TieLines = new List<TieLineConfig>();
JoinMaps = new Dictionary<string, JObject>();
}
/// <summary>
/// Checks SourceLists for a given list and returns it if found. Otherwise, returns null
@@ -61,11 +61,11 @@ namespace PepperDash.Essentials.Core.Config
return SourceLists[key];
}
/// <summary>
/// Retrieves a DestinationListItem based on the key
/// </summary>
/// <param name="key">key of the list to retrieve</param>
/// <returns>DestinationList if the key exists, null otherwise</returns>
/// <summary>
/// Retrieves a DestinationListItem based on the key
/// </summary>
/// <param name="key">key of the list to retrieve</param>
/// <returns>DestinationList if the key exists, null otherwise</returns>
public Dictionary<string, DestinationListItem> GetDestinationListForKey(string key)
{
if (DestinationLists == null || string.IsNullOrEmpty(key) || !DestinationLists.ContainsKey(key))
@@ -76,48 +76,47 @@ namespace PepperDash.Essentials.Core.Config
return DestinationLists[key];
}
/// <summary>
/// Retrieves a AudioControlPointList based on the key
/// </summary>
/// <param name="key">key of the list to retrieve</param>
/// <returns>AudioControlPointList if the key exists, null otherwise</returns>
public AudioControlPointListItem GetAudioControlPointListForKey(string key)
/// <summary>
/// Retrieves a AudioControlPointList based on the key
/// </summary>
/// <param name="key">key of the list to retrieve</param>
/// <returns>AudioControlPointList if the key exists, null otherwise</returns>
public AudioControlPointListItem GetAudioControlPointListForKey(string key)
{
if (AudioControlPointLists == null || string.IsNullOrEmpty(key) || !AudioControlPointLists.ContainsKey(key))
return null;
return AudioControlPointLists[key];
}
/// <summary>
/// Checks CameraLists for a given list and returns it if found. Otherwise, returns null
/// </summary>
public Dictionary<string, CameraListItem> GetCameraListForKey(string key)
{
if (CameraLists == null || string.IsNullOrEmpty(key) || !CameraLists.ContainsKey(key))
return null;
return CameraLists[key];
}
/// <summary>
/// Checks Devices for an item with a Key that matches and returns it if found. Otherwise, retunes null
/// </summary>
/// <param name="key">Key of desired device</param>
/// <returns></returns>
public DeviceConfig GetDeviceForKey(string key)
{
if (string.IsNullOrEmpty(key))
return null;
var deviceConfig = Devices.FirstOrDefault(d => d.Key.Equals(key));
if (deviceConfig != null)
return deviceConfig;
else
{
if (AudioControlPointLists == null || string.IsNullOrEmpty(key) || !AudioControlPointLists.ContainsKey(key))
return null;
return AudioControlPointLists[key];
return null;
}
/// <summary>
/// Checks CameraLists for a given list and returns it if found. Otherwise, returns null
/// </summary>
public Dictionary<string, CameraListItem> GetCameraListForKey(string key)
{
if (CameraLists == null || string.IsNullOrEmpty(key) || !CameraLists.ContainsKey(key))
return null;
return CameraLists[key];
}
/// <summary>
/// Checks Devices for an item with a Key that matches and returns it if found. Otherwise, retunes null
/// </summary>
/// <param name="key">Key of desired device</param>
/// <returns></returns>
public DeviceConfig GetDeviceForKey(string key)
{
if (string.IsNullOrEmpty(key))
return null;
var deviceConfig = Devices.FirstOrDefault(d => d.Key.Equals(key));
if (deviceConfig != null)
return deviceConfig;
else
{
return null;
}
}
}
}
}
}

View File

@@ -9,24 +9,23 @@ using PepperDash.Essentials.Core;
using PepperDash.Core;
using Newtonsoft.Json.Linq;
namespace PepperDash.Essentials.Core.Config
{
public class ConfigPropertiesHelpers
{
/// <summary>
/// Returns the value of properties.hasAudio, or false if not defined
/// </summary>
public static bool GetHasAudio(DeviceConfig deviceConfig)
{
return deviceConfig.Properties.Value<bool>("hasAudio");
}
namespace PepperDash.Essentials.Core.Config;
/// <summary>
/// Returns the value of properties.hasControls, or false if not defined
/// </summary>
public static bool GetHasControls(DeviceConfig deviceConfig)
{
return deviceConfig.Properties.Value<bool>("hasControls");
}
public class ConfigPropertiesHelpers
{
/// <summary>
/// Returns the value of properties.hasAudio, or false if not defined
/// </summary>
public static bool GetHasAudio(DeviceConfig deviceConfig)
{
return deviceConfig.Properties.Value<bool>("hasAudio");
}
/// <summary>
/// Returns the value of properties.hasControls, or false if not defined
/// </summary>
public static bool GetHasControls(DeviceConfig deviceConfig)
{
return deviceConfig.Properties.Value<bool>("hasControls");
}
}

View File

@@ -11,72 +11,71 @@ using Newtonsoft.Json.Linq;
using PepperDash.Core;
using PepperDash.Essentials.Core;
namespace PepperDash.Essentials.Core.Config
namespace PepperDash.Essentials.Core.Config;
public class DeviceConfig
{
public class DeviceConfig
[JsonProperty("key")]
public string Key { get; set; }
[JsonProperty("uid")]
public int Uid { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("group")]
public string Group { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("properties")]
[JsonConverter(typeof(DevicePropertiesConverter))]
public JToken Properties { get; set; }
public DeviceConfig(DeviceConfig dc)
{
[JsonProperty("key")]
public string Key { get; set; }
Key = dc.Key;
Uid = dc.Uid;
Name = dc.Name;
Group = dc.Group;
Type = dc.Type;
[JsonProperty("uid")]
public int Uid { get; set; }
Properties = JToken.Parse(dc.Properties.ToString());
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("group")]
public string Group { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("properties")]
[JsonConverter(typeof(DevicePropertiesConverter))]
public JToken Properties { get; set; }
public DeviceConfig(DeviceConfig dc)
{
Key = dc.Key;
Uid = dc.Uid;
Name = dc.Name;
Group = dc.Group;
Type = dc.Type;
Properties = JToken.Parse(dc.Properties.ToString());
//Properties = JToken.FromObject(dc.Properties);
}
public DeviceConfig() {}
//Properties = JToken.FromObject(dc.Properties);
}
/// <summary>
///
/// </summary>
public class DevicePropertiesConverter : JsonConverter
public DeviceConfig() {}
}
/// <summary>
///
/// </summary>
public class DevicePropertiesConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(JToken);
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(JToken);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return JToken.ReadFrom(reader);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
public override bool CanWrite
{
get
{
return JToken.ReadFrom(reader);
return false;
}
}
public override bool CanWrite
{
get
{
return false;
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException("SOD OFF HOSER");
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException("SOD OFF HOSER");
}
}

View File

@@ -11,15 +11,15 @@ using PepperDash.Core;
using PepperDash.Core.Config;
using Serilog.Events;
namespace PepperDash.Essentials.Core.Config
{
namespace PepperDash.Essentials.Core.Config;
/// <summary>
/// Loads the ConfigObject from the file
/// </summary>
public class ConfigReader
{
public const string LocalConfigPresent =
@"
@"
***************************************************
************* Using Local config file *************
***************************************************";
@@ -31,227 +31,226 @@ namespace PepperDash.Essentials.Core.Config
Debug.LogMessage(LogEventLevel.Information, "Loading unmerged system/template portal configuration file.");
try
{
// Check for local config file first
var filePath = Global.FilePathPrefix + ConfigWriter.LocalConfigFolder + Global.DirectorySeparator + Global.ConfigFileName;
// Check for local config file first
var filePath = Global.FilePathPrefix + ConfigWriter.LocalConfigFolder + Global.DirectorySeparator + Global.ConfigFileName;
bool localConfigFound = false;
bool localConfigFound = false;
Debug.LogMessage(LogEventLevel.Information, "Attempting to load Local config file: '{0}'", filePath);
Debug.LogMessage(LogEventLevel.Information, "Attempting to load Local config file: '{0}'", filePath);
// Check for local config directory first
// Check for local config directory first
var configFiles = GetConfigFiles(filePath);
var configFiles = GetConfigFiles(filePath);
if (configFiles != null)
{
if (configFiles.Length > 1)
{
Debug.LogMessage(LogEventLevel.Information,
"****Error: Multiple Local Configuration files present. Please ensure only a single file exists and reset program.****");
return false;
}
if(configFiles.Length == 1)
{
localConfigFound = true;
}
}
else
{
Debug.LogMessage(LogEventLevel.Information,
"Local Configuration file not present.", filePath);
}
// Check for Portal Config
if(!localConfigFound)
{
filePath = Global.FilePathPrefix + Global.ConfigFileName;
Debug.LogMessage(LogEventLevel.Information, "Attempting to load Portal config file: '{0}'", filePath);
configFiles = GetConfigFiles(filePath);
if (configFiles != null)
{
Debug.LogMessage(LogEventLevel.Verbose, "{0} config files found matching pattern", configFiles.Length);
if (configFiles.Length > 1)
{
Debug.LogMessage(LogEventLevel.Information,
"****Error: Multiple Local Configuration files present. Please ensure only a single file exists and reset program.****");
"****Error: Multiple Portal Configuration files present. Please ensure only a single file exists and reset program.****");
return false;
}
if(configFiles.Length == 1)
else if (configFiles.Length == 1)
{
localConfigFound = true;
Debug.LogMessage(LogEventLevel.Information, "Found Portal config file: '{0}'", filePath);
}
else
{
Debug.LogMessage(LogEventLevel.Information, "No config file found.");
return false;
}
}
else
{
Debug.LogMessage(LogEventLevel.Information,
"Local Configuration file not present.", filePath);
"ERROR: Portal Configuration file not present. Please load file and reset program.");
return false;
}
}
// Check for Portal Config
if(!localConfigFound)
{
filePath = Global.FilePathPrefix + Global.ConfigFileName;
// Get the actual file path
filePath = configFiles[0].FullName;
Debug.LogMessage(LogEventLevel.Information, "Attempting to load Portal config file: '{0}'", filePath);
configFiles = GetConfigFiles(filePath);
if (configFiles != null)
{
Debug.LogMessage(LogEventLevel.Verbose, "{0} config files found matching pattern", configFiles.Length);
if (configFiles.Length > 1)
{
Debug.LogMessage(LogEventLevel.Information,
"****Error: Multiple Portal Configuration files present. Please ensure only a single file exists and reset program.****");
return false;
}
else if (configFiles.Length == 1)
{
Debug.LogMessage(LogEventLevel.Information, "Found Portal config file: '{0}'", filePath);
}
else
{
Debug.LogMessage(LogEventLevel.Information, "No config file found.");
return false;
}
}
else
{
Debug.LogMessage(LogEventLevel.Information,
"ERROR: Portal Configuration file not present. Please load file and reset program.");
return false;
}
}
// Get the actual file path
filePath = configFiles[0].FullName;
// Generate debug statement if using a local file.
// Generate debug statement if using a local file.
if (localConfigFound)
{
GetLocalFileMessage(filePath);
GetLocalFileMessage(filePath);
}
// Read the file
using (StreamReader fs = new StreamReader(filePath))
// Read the file
using (StreamReader fs = new StreamReader(filePath))
{
Debug.LogMessage(LogEventLevel.Information, "Loading config file: '{0}'", filePath);
if (localConfigFound)
{
Debug.LogMessage(LogEventLevel.Information, "Loading config file: '{0}'", filePath);
ConfigObject = JObject.Parse(fs.ReadToEnd()).ToObject<EssentialsConfig>();
if (localConfigFound)
{
ConfigObject = JObject.Parse(fs.ReadToEnd()).ToObject<EssentialsConfig>();
Debug.LogMessage(LogEventLevel.Information, "Successfully Loaded Local Config");
return true;
}
else
{
var doubleObj = JObject.Parse(fs.ReadToEnd());
ConfigObject = PortalConfigReader.MergeConfigs(doubleObj).ToObject<EssentialsConfig>();
// Extract SystemUrl and TemplateUrl into final config output
if (doubleObj["system_url"] != null)
{
ConfigObject.SystemUrl = doubleObj["system_url"].Value<string>();
}
if (doubleObj["template_url"] != null)
{
ConfigObject.TemplateUrl = doubleObj["template_url"].Value<string>();
}
}
Debug.LogMessage(LogEventLevel.Information, "Successfully Loaded Merged Config");
Debug.LogMessage(LogEventLevel.Information, "Successfully Loaded Local Config");
return true;
}
else
{
var doubleObj = JObject.Parse(fs.ReadToEnd());
ConfigObject = PortalConfigReader.MergeConfigs(doubleObj).ToObject<EssentialsConfig>();
// Extract SystemUrl and TemplateUrl into final config output
if (doubleObj["system_url"] != null)
{
ConfigObject.SystemUrl = doubleObj["system_url"].Value<string>();
}
if (doubleObj["template_url"] != null)
{
ConfigObject.TemplateUrl = doubleObj["template_url"].Value<string>();
}
}
Debug.LogMessage(LogEventLevel.Information, "Successfully Loaded Merged Config");
return true;
}
}
catch (Exception e)
{
Debug.LogMessage(LogEventLevel.Information, "ERROR: Config load failed: \r{0}", e);
Debug.LogMessage(LogEventLevel.Information, "ERROR: Config load failed: \r{0}", e);
return false;
}
}
/// <summary>
/// Returns all the files from the directory specified.
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static FileInfo[] GetConfigFiles(string filePath)
/// <summary>
/// Returns all the files from the directory specified.
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static FileInfo[] GetConfigFiles(string filePath)
{
// Get the directory
var dir = Path.GetDirectoryName(filePath);
if (Directory.Exists(dir))
{
// Get the directory
var dir = Path.GetDirectoryName(filePath);
Debug.LogMessage(LogEventLevel.Debug, "Searching in Directory '{0}'", dir);
// Get the directory info
var dirInfo = new DirectoryInfo(dir);
if (Directory.Exists(dir))
{
Debug.LogMessage(LogEventLevel.Debug, "Searching in Directory '{0}'", dir);
// Get the directory info
var dirInfo = new DirectoryInfo(dir);
// Get the file name
var fileName = Path.GetFileName(filePath);
Debug.LogMessage(LogEventLevel.Debug, "For Config Files matching: '{0}'", fileName);
// Get the file name
var fileName = Path.GetFileName(filePath);
Debug.LogMessage(LogEventLevel.Debug, "For Config Files matching: '{0}'", fileName);
// Get the files that match from the directory
return dirInfo.GetFiles(fileName);
}
else
{
Debug.LogMessage(LogEventLevel.Information,
"Directory not found: ", dir);
return null;
}
// Get the files that match from the directory
return dirInfo.GetFiles(fileName);
}
else
{
Debug.LogMessage(LogEventLevel.Information,
"Directory not found: ", dir);
return null;
}
}
/// <summary>
/// Returns the group for a given device key in config
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static string GetGroupForDeviceKey(string key)
{
var dev = ConfigObject.Devices.FirstOrDefault(d => d.Key.Equals(key, StringComparison.OrdinalIgnoreCase));
return dev == null ? null : dev.Group;
}
public static string GetGroupForDeviceKey(string key)
{
var dev = ConfigObject.Devices.FirstOrDefault(d => d.Key.Equals(key, StringComparison.OrdinalIgnoreCase));
return dev == null ? null : dev.Group;
}
private static void GetLocalFileMessage(string filePath)
{
var filePathLength = filePath.Length + 2;
var debugStringWidth = filePathLength + 12;
var filePathLength = filePath.Length + 2;
var debugStringWidth = filePathLength + 12;
if (debugStringWidth < 51)
{
debugStringWidth = 51;
}
var qualifier = (filePathLength % 2 != 0)
? " Using Local Config File "
: " Using Local Config File ";
var bookend1 = (debugStringWidth - qualifier.Length) / 2;
var bookend2 = (debugStringWidth - filePathLength) / 2;
if (debugStringWidth < 51)
{
debugStringWidth = 51;
}
var qualifier = (filePathLength % 2 != 0)
? " Using Local Config File "
: " Using Local Config File ";
var bookend1 = (debugStringWidth - qualifier.Length) / 2;
var bookend2 = (debugStringWidth - filePathLength) / 2;
var newDebugString = new StringBuilder()
.Append(CrestronEnvironment.NewLine)
// Line 1
// Line 1
.Append(new string('*', debugStringWidth))
.Append(CrestronEnvironment.NewLine)
// Line 2
// Line 2
.Append(new string('*', debugStringWidth))
.Append(CrestronEnvironment.NewLine)
// Line 3
// Line 3
.Append(new string('*', 2))
.Append(new string(' ', debugStringWidth - 4))
.Append(new string('*', 2))
.Append(CrestronEnvironment.NewLine)
// Line 4
// Line 4
.Append(new string('*', 2))
.Append(new string(' ', bookend1 - 2))
.Append(qualifier)
.Append(new string(' ', bookend1 - 2))
.Append(new string('*', 2))
.Append(CrestronEnvironment.NewLine)
// Line 5
// Line 5
.Append(new string('*', 2))
.Append(new string(' ', bookend2 - 2))
.Append(" " + filePath + " ")
.Append(new string(' ', bookend2 - 2))
.Append(new string('*', 2))
.Append(CrestronEnvironment.NewLine)
// Line 6
// Line 6
.Append(new string('*', 2))
.Append(new string(' ', debugStringWidth - 4))
.Append(new string('*', 2))
.Append(CrestronEnvironment.NewLine)
// Line 7
// Line 7
.Append(new string('*', debugStringWidth))
.Append(CrestronEnvironment.NewLine)
// Line 8
// Line 8
.Append(new string('*', debugStringWidth));
Debug.LogMessage(LogEventLevel.Verbose, "Found Local config file: '{0}'", filePath);
Debug.LogMessage(LogEventLevel.Information, newDebugString.ToString());
Debug.LogMessage(LogEventLevel.Verbose, "Found Local config file: '{0}'", filePath);
Debug.LogMessage(LogEventLevel.Information, newDebugString.ToString());
}
}
}
}

View File

@@ -14,213 +14,212 @@ using Crestron.SimplSharpPro.Diagnostics;
using PepperDash.Core;
using Serilog.Events;
namespace PepperDash.Essentials.Core.Config
namespace PepperDash.Essentials.Core.Config;
public static class ConfigUpdater
{
public static class ConfigUpdater
public static event EventHandler<ConfigStatusEventArgs> ConfigStatusChanged;
public static void GetConfigFromServer(string url)
{
public static event EventHandler<ConfigStatusEventArgs> ConfigStatusChanged;
Debug.LogMessage(LogEventLevel.Information, "Attempting to get new config from '{0}'", url);
public static void GetConfigFromServer(string url)
// HTTP GET
var req = new HttpClientRequest();
try
{
Debug.LogMessage(LogEventLevel.Information, "Attempting to get new config from '{0}'", url);
req.RequestType = RequestType.Get;
req.Url.Parse(url);
// HTTP GET
var req = new HttpClientRequest();
try
{
req.RequestType = RequestType.Get;
req.Url.Parse(url);
new HttpClient().DispatchAsync(req, (r, e) =>
new HttpClient().DispatchAsync(req, (r, e) =>
{
if (e == HTTP_CALLBACK_ERROR.COMPLETED)
{
if (e == HTTP_CALLBACK_ERROR.COMPLETED)
if (r.Code == 200)
{
if (r.Code == 200)
{
var newConfig = r.ContentString;
var newConfig = r.ContentString;
OnStatusUpdate(eUpdateStatus.ConfigFileReceived);
OnStatusUpdate(eUpdateStatus.ConfigFileReceived);
ArchiveExistingPortalConfigs();
ArchiveExistingPortalConfigs();
CheckForLocalConfigAndDelete();
CheckForLocalConfigAndDelete();
WriteConfigToFile(newConfig);
WriteConfigToFile(newConfig);
RestartProgram();
}
else
{
Debug.LogMessage(LogEventLevel.Information, "Config Update Process Stopped. Failed to get config file from server: {0}", r.Code);
OnStatusUpdate(eUpdateStatus.UpdateFailed);
}
RestartProgram();
}
else
Debug.LogMessage(LogEventLevel.Information, "Request for config from Server Failed: {0}", e);
});
}
catch (Exception e)
{
Debug.LogMessage(LogEventLevel.Debug, "Error Getting Config from Server: {0}", e);
}
}
static void OnStatusUpdate(eUpdateStatus status)
{
var handler = ConfigStatusChanged;
if(handler != null)
{
handler(typeof(ConfigUpdater), new ConfigStatusEventArgs(status));
}
}
static void WriteConfigToFile(string configData)
{
var filePath = Global.FilePathPrefix+ "configurationFile-updated.json";
try
{
var config = JObject.Parse(configData).ToObject<EssentialsConfig>();
ConfigWriter.WriteFile(filePath, configData);
OnStatusUpdate(eUpdateStatus.WritingConfigFile);
}
catch (Exception e)
{
Debug.LogMessage(LogEventLevel.Debug, "Error parsing new config: {0}", e);
OnStatusUpdate(eUpdateStatus.UpdateFailed);
}
}
/// <summary>
/// Checks for any existing portal config files and archives them
/// </summary>
static void ArchiveExistingPortalConfigs()
{
var filePath = Global.FilePathPrefix + Global.ConfigFileName;
var configFiles = ConfigReader.GetConfigFiles(filePath);
if (configFiles != null)
{
Debug.LogMessage(LogEventLevel.Information, "Existing config files found. Moving to Archive folder.");
OnStatusUpdate(eUpdateStatus.ArchivingConfigs);
MoveFilesToArchiveFolder(configFiles);
}
else
{
Debug.LogMessage(LogEventLevel.Information, "No Existing config files found in '{0}'. Nothing to archive", filePath);
}
}
/// <summary>
/// Checks for presence of archive folder and if found deletes contents.
/// Moves any config files to the archive folder and adds a .bak suffix
/// </summary>
/// <param name="files"></param>
static void MoveFilesToArchiveFolder(FileInfo[] files)
{
string archiveDirectoryPath = Global.FilePathPrefix + "archive";
if (!Directory.Exists(archiveDirectoryPath))
{
// Directory does not exist, create it
Directory.Create(archiveDirectoryPath);
}
else
{
// Directory exists, first clear any contents
var archivedConfigFiles = ConfigReader.GetConfigFiles(archiveDirectoryPath + Global.DirectorySeparator + Global.ConfigFileName + ".bak");
if(archivedConfigFiles != null || archivedConfigFiles.Length > 0)
{
Debug.LogMessage(LogEventLevel.Information, "{0} Existing files found in archive folder. Deleting.", archivedConfigFiles.Length);
for (int i = 0; i < archivedConfigFiles.Length; i++ )
{
var file = archivedConfigFiles[i];
Debug.LogMessage(LogEventLevel.Information, "Deleting archived file: '{0}'", file.FullName);
file.Delete();
{
Debug.LogMessage(LogEventLevel.Information, "Config Update Process Stopped. Failed to get config file from server: {0}", r.Code);
OnStatusUpdate(eUpdateStatus.UpdateFailed);
}
}
}
else
Debug.LogMessage(LogEventLevel.Information, "Request for config from Server Failed: {0}", e);
});
}
catch (Exception e)
{
Debug.LogMessage(LogEventLevel.Debug, "Error Getting Config from Server: {0}", e);
}
}
}
// Move any files from the program folder to the archive folder
foreach (var file in files)
static void OnStatusUpdate(eUpdateStatus status)
{
var handler = ConfigStatusChanged;
if(handler != null)
{
handler(typeof(ConfigUpdater), new ConfigStatusEventArgs(status));
}
}
static void WriteConfigToFile(string configData)
{
var filePath = Global.FilePathPrefix+ "configurationFile-updated.json";
try
{
var config = JObject.Parse(configData).ToObject<EssentialsConfig>();
ConfigWriter.WriteFile(filePath, configData);
OnStatusUpdate(eUpdateStatus.WritingConfigFile);
}
catch (Exception e)
{
Debug.LogMessage(LogEventLevel.Debug, "Error parsing new config: {0}", e);
OnStatusUpdate(eUpdateStatus.UpdateFailed);
}
}
/// <summary>
/// Checks for any existing portal config files and archives them
/// </summary>
static void ArchiveExistingPortalConfigs()
{
var filePath = Global.FilePathPrefix + Global.ConfigFileName;
var configFiles = ConfigReader.GetConfigFiles(filePath);
if (configFiles != null)
{
Debug.LogMessage(LogEventLevel.Information, "Existing config files found. Moving to Archive folder.");
OnStatusUpdate(eUpdateStatus.ArchivingConfigs);
MoveFilesToArchiveFolder(configFiles);
}
else
{
Debug.LogMessage(LogEventLevel.Information, "No Existing config files found in '{0}'. Nothing to archive", filePath);
}
}
/// <summary>
/// Checks for presence of archive folder and if found deletes contents.
/// Moves any config files to the archive folder and adds a .bak suffix
/// </summary>
/// <param name="files"></param>
static void MoveFilesToArchiveFolder(FileInfo[] files)
{
string archiveDirectoryPath = Global.FilePathPrefix + "archive";
if (!Directory.Exists(archiveDirectoryPath))
{
// Directory does not exist, create it
Directory.Create(archiveDirectoryPath);
}
else
{
// Directory exists, first clear any contents
var archivedConfigFiles = ConfigReader.GetConfigFiles(archiveDirectoryPath + Global.DirectorySeparator + Global.ConfigFileName + ".bak");
if(archivedConfigFiles != null || archivedConfigFiles.Length > 0)
{
Debug.LogMessage(LogEventLevel.Information, "Moving config file '{0}' to archive folder", file.FullName);
Debug.LogMessage(LogEventLevel.Information, "{0} Existing files found in archive folder. Deleting.", archivedConfigFiles.Length);
// Moves the file and appends the .bak extension
var fileDest = archiveDirectoryPath + "/" + file.Name + ".bak";
if(!File.Exists(fileDest))
for (int i = 0; i < archivedConfigFiles.Length; i++ )
{
file.MoveTo(fileDest);
var file = archivedConfigFiles[i];
Debug.LogMessage(LogEventLevel.Information, "Deleting archived file: '{0}'", file.FullName);
file.Delete();
}
else
Debug.LogMessage(LogEventLevel.Information, "Cannot move file to archive folder. Existing file already exists with same name: '{0}'", fileDest);
}
}
/// <summary>
/// Checks for LocalConfig folder in file system and deletes if found
/// </summary>
static void CheckForLocalConfigAndDelete()
// Move any files from the program folder to the archive folder
foreach (var file in files)
{
var folderPath = Global.FilePathPrefix + ConfigWriter.LocalConfigFolder;
Debug.LogMessage(LogEventLevel.Information, "Moving config file '{0}' to archive folder", file.FullName);
if (Directory.Exists(folderPath))
// Moves the file and appends the .bak extension
var fileDest = archiveDirectoryPath + "/" + file.Name + ".bak";
if(!File.Exists(fileDest))
{
OnStatusUpdate(eUpdateStatus.DeletingLocalConfig);
Directory.Delete(folderPath);
Debug.LogMessage(LogEventLevel.Information, "Local Config Found in '{0}'. Deleting.", folderPath);
file.MoveTo(fileDest);
}
else
Debug.LogMessage(LogEventLevel.Information, "Cannot move file to archive folder. Existing file already exists with same name: '{0}'", fileDest);
}
/// <summary>
/// Connects to the processor via SSH and restarts the program
/// </summary>
static void RestartProgram()
{
Debug.LogMessage(LogEventLevel.Information, "Attempting to Reset Program");
OnStatusUpdate(eUpdateStatus.RestartingProgram);
string response = string.Empty;
CrestronConsole.SendControlSystemCommand(string.Format("progreset -p:{0}", InitialParametersClass.ApplicationNumber), ref response);
Debug.LogMessage(LogEventLevel.Debug, "Console Response: {0}", response);
}
}
public enum eUpdateStatus
/// <summary>
/// Checks for LocalConfig folder in file system and deletes if found
/// </summary>
static void CheckForLocalConfigAndDelete()
{
UpdateStarted,
ConfigFileReceived,
ArchivingConfigs,
DeletingLocalConfig,
WritingConfigFile,
RestartingProgram,
UpdateSucceeded,
UpdateFailed
var folderPath = Global.FilePathPrefix + ConfigWriter.LocalConfigFolder;
if (Directory.Exists(folderPath))
{
OnStatusUpdate(eUpdateStatus.DeletingLocalConfig);
Directory.Delete(folderPath);
Debug.LogMessage(LogEventLevel.Information, "Local Config Found in '{0}'. Deleting.", folderPath);
}
}
public class ConfigStatusEventArgs : EventArgs
/// <summary>
/// Connects to the processor via SSH and restarts the program
/// </summary>
static void RestartProgram()
{
public eUpdateStatus UpdateStatus { get; private set; }
Debug.LogMessage(LogEventLevel.Information, "Attempting to Reset Program");
public ConfigStatusEventArgs(eUpdateStatus status)
{
UpdateStatus = status;
}
OnStatusUpdate(eUpdateStatus.RestartingProgram);
string response = string.Empty;
CrestronConsole.SendControlSystemCommand(string.Format("progreset -p:{0}", InitialParametersClass.ApplicationNumber), ref response);
Debug.LogMessage(LogEventLevel.Debug, "Console Response: {0}", response);
}
}
public enum eUpdateStatus
{
UpdateStarted,
ConfigFileReceived,
ArchivingConfigs,
DeletingLocalConfig,
WritingConfigFile,
RestartingProgram,
UpdateSucceeded,
UpdateFailed
}
public class ConfigStatusEventArgs : EventArgs
{
public eUpdateStatus UpdateStatus { get; private set; }
public ConfigStatusEventArgs(eUpdateStatus status)
{
UpdateStatus = status;
}
}

View File

@@ -11,155 +11,154 @@ using Newtonsoft.Json.Linq;
using PepperDash.Core;
using Serilog.Events;
namespace PepperDash.Essentials.Core.Config
namespace PepperDash.Essentials.Core.Config;
/// <summary>
/// Responsible for updating config at runtime, and writing the updates out to a local file
/// </summary>
public class ConfigWriter
{
/// <summary>
/// Responsible for updating config at runtime, and writing the updates out to a local file
/// </summary>
public class ConfigWriter
{
public const string LocalConfigFolder = "LocalConfig";
public const string LocalConfigFolder = "LocalConfig";
public const long WriteTimeout = 30000;
public const long WriteTimeout = 30000;
public static CTimer WriteTimer;
public static CTimer WriteTimer;
static CCriticalSection fileLock = new CCriticalSection();
/// <summary>
/// Updates the config properties of a device
/// </summary>
/// <param name="deviceKey"></param>
/// <param name="properties"></param>
/// <returns></returns>
public static bool UpdateDeviceProperties(string deviceKey, JToken properties)
/// <summary>
/// Updates the config properties of a device
/// </summary>
/// <param name="deviceKey"></param>
/// <param name="properties"></param>
/// <returns></returns>
public static bool UpdateDeviceProperties(string deviceKey, JToken properties)
{
bool success = false;
// Get the current device config
var deviceConfig = ConfigReader.ConfigObject.Devices.FirstOrDefault(d => d.Key.Equals(deviceKey));
if (deviceConfig != null)
{
bool success = false;
// Replace the current properties JToken with the new one passed into this method
deviceConfig.Properties = properties;
// Get the current device config
var deviceConfig = ConfigReader.ConfigObject.Devices.FirstOrDefault(d => d.Key.Equals(deviceKey));
Debug.LogMessage(LogEventLevel.Debug, "Updated properties of device: '{0}'", deviceKey);
if (deviceConfig != null)
{
// Replace the current properties JToken with the new one passed into this method
deviceConfig.Properties = properties;
Debug.LogMessage(LogEventLevel.Debug, "Updated properties of device: '{0}'", deviceKey);
success = true;
}
ResetTimer();
return success;
success = true;
}
public static bool UpdateDeviceConfig(DeviceConfig config)
ResetTimer();
return success;
}
public static bool UpdateDeviceConfig(DeviceConfig config)
{
bool success = false;
var deviceConfigIndex = ConfigReader.ConfigObject.Devices.FindIndex(d => d.Key.Equals(config.Key));
if (deviceConfigIndex >= 0)
{
bool success = false;
ConfigReader.ConfigObject.Devices[deviceConfigIndex] = config;
var deviceConfigIndex = ConfigReader.ConfigObject.Devices.FindIndex(d => d.Key.Equals(config.Key));
Debug.LogMessage(LogEventLevel.Debug, "Updated config of device: '{0}'", config.Key);
if (deviceConfigIndex >= 0)
{
ConfigReader.ConfigObject.Devices[deviceConfigIndex] = config;
Debug.LogMessage(LogEventLevel.Debug, "Updated config of device: '{0}'", config.Key);
success = true;
}
ResetTimer();
return success;
success = true;
}
public static bool UpdateRoomConfig(DeviceConfig config)
{
bool success = false;
ResetTimer();
return success;
}
public static bool UpdateRoomConfig(DeviceConfig config)
{
bool success = false;
var roomConfigIndex = ConfigReader.ConfigObject.Rooms.FindIndex(d => d.Key.Equals(config.Key));
if (roomConfigIndex >= 0)
{
ConfigReader.ConfigObject.Rooms[roomConfigIndex] = config;
Debug.LogMessage(LogEventLevel.Debug, "Updated room of device: '{0}'", config.Key);
success = true;
}
ResetTimer();
return success;
}
/// <summary>
/// Resets (or starts) the write timer
/// </summary>
static void ResetTimer()
{
if (WriteTimer == null)
WriteTimer = new CTimer(WriteConfigFile, WriteTimeout);
ConfigReader.ConfigObject.Rooms[roomConfigIndex] = config;
WriteTimer.Reset(WriteTimeout);
Debug.LogMessage(LogEventLevel.Debug, "Updated room of device: '{0}'", config.Key);
Debug.LogMessage(LogEventLevel.Debug, "Config File write timer has been reset.");
}
/// <summary>
/// Writes the current config to a file in the LocalConfig subfolder
/// </summary>
/// <returns></returns>
private static void WriteConfigFile(object o)
{
var filePath = Global.FilePathPrefix + LocalConfigFolder + Global.DirectorySeparator + "configurationFile.json";
var configData = JsonConvert.SerializeObject(ConfigReader.ConfigObject);
WriteFile(filePath, configData);
}
/// <summary>
/// Writes
/// </summary>
/// <param name="filepath"></param>
/// <param name="o"></param>
public static void WriteFile(string filePath, string configData)
{
if (WriteTimer != null)
WriteTimer.Stop();
Debug.LogMessage(LogEventLevel.Information, "Writing Configuration to file");
Debug.LogMessage(LogEventLevel.Information, "Attempting to write config file: '{0}'", filePath);
try
{
if (fileLock.TryEnter())
{
using (StreamWriter sw = new StreamWriter(filePath))
{
sw.Write(configData);
sw.Flush();
}
}
else
{
Debug.LogMessage(LogEventLevel.Information, "Unable to enter FileLock");
}
}
catch (Exception e)
{
Debug.LogMessage(LogEventLevel.Information, "Error: Config write failed: \r{0}", e);
}
finally
{
if (fileLock != null && !fileLock.Disposed)
fileLock.Leave();
}
success = true;
}
ResetTimer();
return success;
}
/// <summary>
/// Resets (or starts) the write timer
/// </summary>
static void ResetTimer()
{
if (WriteTimer == null)
WriteTimer = new CTimer(WriteConfigFile, WriteTimeout);
WriteTimer.Reset(WriteTimeout);
Debug.LogMessage(LogEventLevel.Debug, "Config File write timer has been reset.");
}
/// <summary>
/// Writes the current config to a file in the LocalConfig subfolder
/// </summary>
/// <returns></returns>
private static void WriteConfigFile(object o)
{
var filePath = Global.FilePathPrefix + LocalConfigFolder + Global.DirectorySeparator + "configurationFile.json";
var configData = JsonConvert.SerializeObject(ConfigReader.ConfigObject);
WriteFile(filePath, configData);
}
/// <summary>
/// Writes
/// </summary>
/// <param name="filepath"></param>
/// <param name="o"></param>
public static void WriteFile(string filePath, string configData)
{
if (WriteTimer != null)
WriteTimer.Stop();
Debug.LogMessage(LogEventLevel.Information, "Writing Configuration to file");
Debug.LogMessage(LogEventLevel.Information, "Attempting to write config file: '{0}'", filePath);
try
{
if (fileLock.TryEnter())
{
using (StreamWriter sw = new StreamWriter(filePath))
{
sw.Write(configData);
sw.Flush();
}
}
else
{
Debug.LogMessage(LogEventLevel.Information, "Unable to enter FileLock");
}
}
catch (Exception e)
{
Debug.LogMessage(LogEventLevel.Information, "Error: Config write failed: \r{0}", e);
}
finally
{
if (fileLock != null && !fileLock.Disposed)
fileLock.Leave();
}
}
}

View File

@@ -9,25 +9,25 @@ using Newtonsoft.Json;
using PepperDash.Core;
namespace PepperDash.Essentials.Core.Config
{
namespace PepperDash.Essentials.Core.Config;
/// <summary>
/// Loads the ConfigObject from the file
/// </summary>
public class EssentialsConfig : BasicConfig
{
[JsonProperty("system_url")]
public string SystemUrl { get; set; }
public string SystemUrl { get; set; }
[JsonProperty("template_url")]
public string TemplateUrl { get; set; }
public string TemplateUrl { get; set; }
[JsonProperty("systemUuid")]
public string SystemUuid
{
get
{
get
{
if (string.IsNullOrEmpty(SystemUrl))
return "missing url";
@@ -38,18 +38,18 @@ namespace PepperDash.Essentials.Core.Config
return uuid;
} else
{
var result = Regex.Match(SystemUrl, @"https?:\/\/.*\/systems\/(.*)\/.*");
string uuid = result.Groups[1].Value;
return uuid;
}
var result = Regex.Match(SystemUrl, @"https?:\/\/.*\/systems\/(.*)\/.*");
string uuid = result.Groups[1].Value;
return uuid;
}
}
}
[JsonProperty("templateUuid")]
public string TemplateUuid
{
get
{
get
{
if (string.IsNullOrEmpty(TemplateUrl))
return "missing template url";
@@ -60,22 +60,22 @@ namespace PepperDash.Essentials.Core.Config
return uuid;
} else
{
var result = Regex.Match(TemplateUrl, @"https?:\/\/.*\/system-templates\/(.*)\/system-template-versions\/(.*)\/.*");
string uuid = result.Groups[2].Value;
return uuid;
}
var result = Regex.Match(TemplateUrl, @"https?:\/\/.*\/system-templates\/(.*)\/system-template-versions\/(.*)\/.*");
string uuid = result.Groups[2].Value;
return uuid;
}
}
}
[JsonProperty("rooms")]
public List<DeviceConfig> Rooms { get; set; }
public List<DeviceConfig> Rooms { get; set; }
public EssentialsConfig()
: base()
{
Rooms = new List<DeviceConfig>();
}
public EssentialsConfig()
: base()
{
Rooms = new List<DeviceConfig>();
}
}
/// <summary>
@@ -86,5 +86,4 @@ namespace PepperDash.Essentials.Core.Config
public EssentialsConfig System { get; set; }
public EssentialsConfig Template { get; set; }
}
}
}

View File

@@ -4,10 +4,9 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PepperDash.Essentials.Core
namespace PepperDash.Essentials.Core;
public interface ILoadConfig
{
public interface ILoadConfig
{
void GoWithLoad();
}
void GoWithLoad();
}

View File

@@ -5,12 +5,12 @@ using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace PepperDash.Essentials.Core.Config
{
/// <summary>
/// Represents the info section of a Config file
/// </summary>
public class InfoConfig
namespace PepperDash.Essentials.Core.Config;
/// <summary>
/// Represents the info section of a Config file
/// </summary>
public class InfoConfig
{
[JsonProperty("name")]
public string Name { get; set; }
@@ -24,17 +24,17 @@ namespace PepperDash.Essentials.Core.Config
[JsonProperty("version")]
public string Version { get; set; }
[JsonProperty("runtimeInfo")]
public RuntimeInfo RuntimeInfo { get; set; }
[JsonProperty("runtimeInfo")]
public RuntimeInfo RuntimeInfo { get; set; }
[JsonProperty("comment")]
public string Comment { get; set; }
[JsonProperty("hostname")]
public string HostName { get; set; }
[JsonProperty("hostname")]
public string HostName { get; set; }
[JsonProperty("appNumber")]
public uint AppNumber { get; set; }
[JsonProperty("appNumber")]
public uint AppNumber { get; set; }
public InfoConfig()
{
@@ -43,49 +43,49 @@ namespace PepperDash.Essentials.Core.Config
Type = "";
Version = "";
Comment = "";
HostName = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_HOSTNAME, 0);
AppNumber = InitialParametersClass.ApplicationNumber;
HostName = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_HOSTNAME, 0);
AppNumber = InitialParametersClass.ApplicationNumber;
RuntimeInfo = new RuntimeInfo();
RuntimeInfo = new RuntimeInfo();
}
}
/// <summary>
/// Represents runtime information about the program/processor
/// </summary>
public class RuntimeInfo
{
/// <summary>
/// Represents runtime information about the program/processor
/// The name of the running application
/// </summary>
public class RuntimeInfo
{
/// <summary>
/// The name of the running application
/// </summary>
[JsonProperty("appName")]
public string AppName {get; set;}
//{
// get
// {
// return Assembly.GetExecutingAssembly().GetName().Name;
// }
//}
[JsonProperty("appName")]
public string AppName {get; set;}
//{
// get
// {
// return Assembly.GetExecutingAssembly().GetName().Name;
// }
//}
/// <summary>
/// The Assembly version of the running application
/// </summary>
[JsonProperty("assemblyVersion")]
public string AssemblyVersion {get; set;}
//{
// get
// {
// var version = Assembly.GetExecutingAssembly().GetName().Version;
// return string.Format("{0}.{1}.{2}", version.Major, version.Minor, version.Build);
// }
//}
/// <summary>
/// The Assembly version of the running application
/// </summary>
[JsonProperty("assemblyVersion")]
public string AssemblyVersion {get; set;}
//{
// get
// {
// var version = Assembly.GetExecutingAssembly().GetName().Version;
// return string.Format("{0}.{1}.{2}", version.Major, version.Minor, version.Build);
// }
//}
/// <summary>,
/// The OS Version of the processor (Firmware Version)
/// </summary>
[JsonProperty("osVersion")]
public string OsVersion {get; set;}
/// <summary>,
/// The OS Version of the processor (Firmware Version)
/// </summary>
[JsonProperty("osVersion")]
public string OsVersion {get; set;}
//{
// get
// {
@@ -93,17 +93,15 @@ namespace PepperDash.Essentials.Core.Config
// }
//}
/// <summary>
/// The information gathered by the processor at runtime about it's NICs and their IP addresses.
/// </summary>
[JsonProperty("ipInfo")]
public Dictionary<short, EthernetAdapterInfo> IpInfo
/// <summary>
/// The information gathered by the processor at runtime about it's NICs and their IP addresses.
/// </summary>
[JsonProperty("ipInfo")]
public Dictionary<short, EthernetAdapterInfo> IpInfo
{
get
{
get
{
return Global.EthernetAdapterInfoCollection;
}
return Global.EthernetAdapterInfoCollection;
}
}
}

View File

@@ -4,10 +4,9 @@ using System.Linq;
using System.Text;
using Crestron.SimplSharp;
namespace PepperDash.Essentials.Core.Config
{
namespace PepperDash.Essentials.Core.Config;
public class SourceDevicePropertiesConfigBase
{
public bool DisableSharing { get; set; }
}
}
}