fix: only build the bouncy cert and use the websocket if 472

This commit is contained in:
Nick Genovese
2024-11-04 12:26:40 -05:00
parent f86d9d56bc
commit ba89ea2578
9 changed files with 68 additions and 84 deletions

View File

@@ -60,7 +60,12 @@ namespace PepperDash.Core
/// </summary> /// </summary>
public static string PepperDashCoreVersion { get; } public static string PepperDashCoreVersion { get; }
public static int WebsocketPort { get; } public static string WebsocketUrl { get; } = "";
public static LogEventLevel WebsocketMinimumLevel => WebsocketLoggingLevelSwitch.MinimumLevel;
public static LogEventLevel ConsoleMinimumLevel => ConsoleLoggingLevelSwitch.MinimumLevel;
public static LogEventLevel ErrorLogMinimumLevel => ErrorLogLevelSwitch.MinimumLevel;
public static LogEventLevel FileLogMinimumLevel => FileLevelSwitch.MinimumLevel;
public static readonly LoggerConfiguration DefaultLoggerConfiguration; public static readonly LoggerConfiguration DefaultLoggerConfiguration;
@@ -69,10 +74,11 @@ namespace PepperDash.Core
static Debug() static Debug()
{ {
CrestronDataStoreStatic.InitCrestronDataStore(); CrestronDataStoreStatic.InitCrestronDataStore();
var directorySeparator = Path.DirectorySeparatorChar.ToString();
var logFilePath = CrestronEnvironment.DevicePlatform == eDevicePlatform.Appliance ? var logFilePath = CrestronEnvironment.DevicePlatform == eDevicePlatform.Appliance
$@"{Directory.GetCurrentDirectory()}{Path.DirectorySeparatorChar}user{Path.DirectorySeparatorChar}debug{Path.DirectorySeparatorChar}app{InitialParametersClass.ApplicationNumber}{Path.DirectorySeparatorChar}global-log.log" : ? Path.Combine(directorySeparator, "user", "program" + InitialParametersClass.ApplicationNumber, "logs", "global-log.log")
$@"{Directory.GetCurrentDirectory()}{Path.DirectorySeparatorChar}user{Path.DirectorySeparatorChar}debug{Path.DirectorySeparatorChar}room{InitialParametersClass.RoomId}{Path.DirectorySeparatorChar}global-log.log"; : Path.Combine(directorySeparator, "User", "logs", "global-log.log");
CrestronConsole.PrintLine($"Saving log files to {logFilePath}"); CrestronConsole.PrintLine($"Saving log files to {logFilePath}");
@@ -97,51 +103,41 @@ namespace PepperDash.Core
); );
#if NET472 #if NET472
var certPath = IsRunningOnAppliance ? Path.Combine("/", "user") : Path.Combine("/", "User");
const string certFilename = "cert.pfx";
var certPath = IsRunningOnAppliance ? Path.Combine(Path.DirectorySeparatorChar.ToString(), "user", certFilename) : Path.Combine("User", certFilename);
var websocket = new DebugNet472WebSocket(certPath); var websocket = new DebugNet472WebSocket(certPath);
WebsocketPort = websocket.Port; WebsocketUrl = websocket.Url;
DefaultLoggerConfiguration.WriteTo.Sink(new DebugWebsocketSink(websocket, new JsonFormatter(renderMessage: true)), levelSwitch: WebsocketLoggingLevelSwitch); DefaultLoggerConfiguration.WriteTo.Sink(new DebugWebsocketSink(websocket, new JsonFormatter(renderMessage: true)), levelSwitch: WebsocketLoggingLevelSwitch);
#endif #endif
var supportsRemovableDrive = false;
try try
{ {
if (InitialParametersClass.NumberOfRemovableDrives > 0) CrestronLogger.Initialize(1, LoggerModeEnum.RM);
{ supportsRemovableDrive = true;
CrestronConsole.PrintLine("{0} RM Drive(s) Present. Initializing Crestron Logger", InitialParametersClass.NumberOfRemovableDrives);
DefaultLoggerConfiguration.WriteTo.Sink(new DebugCrestronLoggerSink());
}
else
CrestronConsole.PrintLine("No RM Drive(s) Present. Not using Crestron Logger");
} }
catch (Exception e) catch (Exception)
{ {
CrestronConsole.PrintLine("Initializing of CrestronLogger failed: {0}", e); CrestronConsole.PrintLine("No RM Drive(s) Present. Not using Crestron Logger");
} }
if (supportsRemovableDrive)
DefaultLoggerConfiguration.WriteTo.Sink(new DebugCrestronLoggerSink());
var storedConsoleLevel = DebugContext.GetDataForKey(ConsoleLevelStoreKey, LogEventLevel.Information); var storedConsoleLevel = DebugContext.GetDataForKey(ConsoleLevelStoreKey, LogEventLevel.Information);
ConsoleLoggingLevelSwitch.MinimumLevel = storedConsoleLevel.Level; ConsoleLoggingLevelSwitch.MinimumLevel = storedConsoleLevel.Level;
CrestronConsole.PrintLine("Beginning console logging with level:{0}", storedConsoleLevel.Level);
Log.Logger = DefaultLoggerConfiguration.CreateLogger(); Log.Logger = DefaultLoggerConfiguration.CreateLogger();
PepperDashCoreVersion = GetVersion(); PepperDashCoreVersion = GetVersion();
LogMessage(LogEventLevel.Information, "Using PepperDash_Core v{PepperDashCoreVersion}", PepperDashCoreVersion);
var msg = $"[App {InitialParametersClass.ApplicationNumber}] Using PepperDash_Core v{PepperDashCoreVersion}";
if (CrestronEnvironment.DevicePlatform == eDevicePlatform.Server)
{
msg = $"[Room {InitialParametersClass.RoomId}] Using PepperDash_Core v{PepperDashCoreVersion}";
}
LogMessage(LogEventLevel.Information,msg);
if (CrestronEnvironment.RuntimeEnvironment == eRuntimeEnvironment.SimplSharpPro) if (CrestronEnvironment.RuntimeEnvironment == eRuntimeEnvironment.SimplSharpPro)
{ {
CrestronConsole.AddNewConsoleCommand(SetDoNotLoadOnNextBootFromConsole, "donotloadonnextboot", CrestronConsole.AddNewConsoleCommand(SetDoNotLoadOnNextBootFromConsole, "donotloadonnextboot",
"donotloadonnextboot:P [true/false]: Should the application load on next boot", ConsoleAccessLevelEnum.AccessOperator); "donotloadonnextboot:P [true/false]: Should the application load on next boot", ConsoleAccessLevelEnum.AccessOperator);
CrestronConsole.AddNewConsoleCommand(SetDebugFromConsole, "appdebug", CrestronConsole.AddNewConsoleCommand(SetDebugFromConsole, "appdebug",
"appdebug:P [0-5] --devices [devices]: Sets the application's console debug message level.", "appdebug:[p] [0-5] --devices [devices]: Sets console debug message level",
ConsoleAccessLevelEnum.AccessOperator); ConsoleAccessLevelEnum.AccessOperator);
CrestronConsole.AddNewConsoleCommand(ShowDebugLog, "appdebuglog", CrestronConsole.AddNewConsoleCommand(ShowDebugLog, "appdebuglog",
@@ -213,8 +209,10 @@ namespace PepperDash.Core
CrestronConsole.ConsoleCommandResponse($"Error: Unable to parse {levelString} to valid log level"); CrestronConsole.ConsoleCommandResponse($"Error: Unable to parse {levelString} to valid log level");
} }
} }
else
CrestronConsole.ConsoleCommandResponse($"Error: Unable to parse {levelString} to valid log level"); {
CrestronConsole.ConsoleCommandResponse($"Error: Unable to parse {levelString} to valid log level");
}
} }
catch catch
{ {

View File

@@ -24,39 +24,35 @@ namespace PepperDash.Core.Logging
public DebugClient() public DebugClient()
{ {
Debug.Console(0, "DebugClient Created"); Debug.LogInformation<DebugClient>("DebugClient Created");
} }
protected override void OnOpen() protected override void OnOpen()
{ {
base.OnOpen(); base.OnOpen();
var url = Context.WebSocket.Url; var url = Context.WebSocket.Url;
Debug.Console(0, Debug.ErrorLogLevel.Notice, "New WebSocket Connection from: {0}", url); Debug.LogInformation<DebugClient>("New WebSocket Connection from: {Url}", url);
connectionTime = DateTime.Now; connectionTime = DateTime.Now;
} }
protected override void OnMessage(MessageEventArgs e) protected override void OnMessage(MessageEventArgs e)
{ {
base.OnMessage(e); base.OnMessage(e);
Debug.LogVerbose<DebugClient>("WebSocket UiClient Message: {Data}", e.Data);
Debug.Console(0, "WebSocket UiClient Message: {0}", e.Data);
} }
protected override void OnClose(CloseEventArgs e) protected override void OnClose(CloseEventArgs e)
{ {
base.OnClose(e); base.OnClose(e);
Debug.LogInformation<DebugClient>("WebSocket UiClient Closing: {Code} Reason: {Reason} Total Time: {Time}", e.Code, e.Reason, ConnectedDuration);
Debug.Console(0, Debug.ErrorLogLevel.Notice, "WebSocket UiClient Closing: {0} reason: {1}", e.Code, e.Reason);
} }
protected override void OnError(WebSocketSharp.ErrorEventArgs e) protected override void OnError(ErrorEventArgs e)
{ {
base.OnError(e); base.OnError(e);
Debug.LogError<DebugClient>(e.Exception, "WebSocket UiClient Error");
Debug.Console(2, Debug.ErrorLogLevel.Notice, "WebSocket UiClient Error: {0} message: {1}", e.Exception, e.Message);
} }
} }
} }
#endif
#endif

View File

@@ -6,7 +6,6 @@ using Crestron.SimplSharp;
using Newtonsoft.Json; using Newtonsoft.Json;
using Serilog; using Serilog;
using Serilog.Events; using Serilog.Events;
using WebSocketSharp;
namespace PepperDash.Core.Logging namespace PepperDash.Core.Logging
{ {
@@ -18,8 +17,8 @@ namespace PepperDash.Core.Logging
private static readonly CTimer SaveTimer; private static readonly CTimer SaveTimer;
private static readonly Dictionary<string, DebugContextData> CurrentData; private static readonly Dictionary<string, DebugContextData> CurrentData;
public static readonly string ApplianceFilePath = Path.Combine("user", "debug", $"app-{InitialParametersClass.ApplicationNumber}-Debug.json"); public static readonly string ApplianceFilePath = Path.Combine("/", "user", "debug", $"app{InitialParametersClass.ApplicationNumber.ToString().PadLeft(2, '0')}-debug.json");
public static readonly string ServerFilePath = Path.Combine("User", "debug", $"app-{InitialParametersClass.RoomId}-Debug.json"); public static readonly string ServerFilePath = Path.Combine("/", "User", "debug", $"{InitialParametersClass.RoomId}-debug.json");
/// <summary> /// <summary>
/// The name of the file containing the current debug settings. /// The name of the file containing the current debug settings.
@@ -79,6 +78,10 @@ namespace PepperDash.Core.Logging
try try
{ {
var debugDirectory = Path.GetDirectoryName(FileName) ??
throw new Exception("File directory is root");
Directory.CreateDirectory(debugDirectory);
var json = JsonConvert.SerializeObject(CurrentData); var json = JsonConvert.SerializeObject(CurrentData);
File.WriteAllText(FileName, json); File.WriteAllText(FileName, json);
} }
@@ -104,4 +107,4 @@ namespace PepperDash.Core.Logging
/// ///
/// </summary> /// </summary>
public record DebugContextData(LogEventLevel Level, string[] Devices = null); public record DebugContextData(LogEventLevel Level, string[] Devices = null);
} }

View File

@@ -20,10 +20,5 @@ namespace PepperDash.Core.Logging
CrestronLogger.WriteToLog(message, (uint)logEvent.Level); CrestronLogger.WriteToLog(message, (uint)logEvent.Level);
} }
public DebugCrestronLoggerSink()
{
CrestronLogger.Initialize(1, LoggerModeEnum.RM);
}
} }
} }

View File

@@ -1,7 +1,9 @@
#if NET472 using System;
using System.Security.Authentication; using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using Crestron.SimplSharp;
#if NET472
using WebSocketSharp.Net; using WebSocketSharp.Net;
using WebSocketSharp.Server; using WebSocketSharp.Server;
@@ -11,6 +13,9 @@ namespace PepperDash.Core.Logging
{ {
private const string Path = "/debug/join/"; private const string Path = "/debug/join/";
public string Url =>
$"wss://{CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS, 0)}:{server.Port}{server.WebSocketServices[Path].Path}";
private readonly WebSocketServer server; private readonly WebSocketServer server;
public DebugNet472WebSocket(string certPath = "") : base(certPath) public DebugNet472WebSocket(string certPath = "") : base(certPath)
@@ -41,14 +46,8 @@ namespace PepperDash.Core.Logging
public override void Broadcast(string message) => server.WebSocketServices.Broadcast(message); public override void Broadcast(string message) => server.WebSocketServices.Broadcast(message);
} }
}
#else
using System; //TODO: NETCORE version
using System.Net;
namespace PepperDash.Core.Logging
{
internal class DebugNetWebSocket : DebugWebSocket internal class DebugNetWebSocket : DebugWebSocket
{ {
private const string Path = "/debug/join/"; private const string Path = "/debug/join/";
@@ -57,7 +56,6 @@ namespace PepperDash.Core.Logging
public DebugNetWebSocket(int port, string certPath = "") : base(certPath) public DebugNetWebSocket(int port, string certPath = "") : base(certPath)
{ {
server.AuthenticationSchemeSelectorDelegate = (request) => AuthenticationSchemes.Anonymous;
server.Prefixes.Add("wss://*:" + port + Path); server.Prefixes.Add("wss://*:" + port + Path);
} }
@@ -66,7 +64,4 @@ namespace PepperDash.Core.Logging
public override void Broadcast(string message) => throw new NotImplementedException(); public override void Broadcast(string message) => throw new NotImplementedException();
} }
} }
#endif #endif

View File

@@ -1,7 +1,10 @@
using System; using System;
using System.IO; using System.IO;
using Crestron.SimplSharp; using Crestron.SimplSharp;
#if NET472
using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Asn1.X509;
#endif
namespace PepperDash.Core.Logging namespace PepperDash.Core.Logging
{ {
@@ -29,6 +32,7 @@ namespace PepperDash.Core.Logging
private static void CreateCert(string filePath) private static void CreateCert(string filePath)
{ {
#if NET472
try try
{ {
var utility = new BouncyCertificate(); var utility = new BouncyCertificate();
@@ -44,6 +48,7 @@ namespace PepperDash.Core.Logging
{ {
Debug.LogError(ex, "WSS failed to create cert"); Debug.LogError(ex, "WSS failed to create cert");
} }
#endif
} }
public abstract bool IsListening { get; } public abstract bool IsListening { get; }

View File

@@ -1,6 +1,4 @@
using System.IO; using System.IO;
using Serilog;
using Serilog.Configuration;
using Serilog.Core; using Serilog.Core;
using Serilog.Events; using Serilog.Events;
using Serilog.Formatting; using Serilog.Formatting;
@@ -29,12 +27,4 @@ namespace PepperDash.Core.Logging
webSocket.Broadcast(sw.ToString()); webSocket.Broadcast(sw.ToString());
} }
} }
public class NoopSink : ILogEventSink
{
public static readonly NoopSink Instance = new NoopSink();
public void Emit(LogEvent logEvent)
{
}
}
} }

View File

@@ -29,17 +29,17 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="BouncyCastle" Version="1.8.9" /> <PackageReference Include="Crestron.SimplSharp.SDK.Library" Version="2.21.65" />
<PackageReference Include="Crestron.SimplSharp.SDK.Library" Version="2.21.65" /> <PackageReference Include="Serilog" Version="4.1.0" />
<PackageReference Include="Serilog" Version="4.1.0" /> <PackageReference Include="Serilog.Expressions" Version="5.0.0" />
<PackageReference Include="Serilog.Expressions" Version="5.0.0" /> <PackageReference Include="Serilog.Formatting.Compact" Version="3.0.0" />
<PackageReference Include="Serilog.Formatting.Compact" Version="3.0.0" /> <PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" /> <PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" /> </ItemGroup>
<PackageReference Include="WebSocketSharp" Version="1.0.3-rc11" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net472'"> <ItemGroup Condition="'$(TargetFramework)' == 'net472'">
<PackageReference Include="WebSocketSharp" Version="1.0.3-rc11" />
<PackageReference Include="BouncyCastle" Version="1.8.9" />
<PackageReference Include="Microsoft.Net.Http" Version="2.2.29" /> <PackageReference Include="Microsoft.Net.Http" Version="2.2.29" />
<PackageReference Include="PolySharp" Version="1.14.1"> <PackageReference Include="PolySharp" Version="1.14.1">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>

View File

@@ -1,5 +1,6 @@
using Crestron.SimplSharp; using Crestron.SimplSharp;
#if NET472
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
@@ -357,4 +358,5 @@ namespace PepperDash.Core
return bRet; return bRet;
} }
} }
} }
#endif