Skip to content

Commit

Permalink
fix: only build the bouncy cert and use the websocket if 472
Browse files Browse the repository at this point in the history
  • Loading branch information
ngenovese11 committed Nov 4, 2024
1 parent f86d9d5 commit ba89ea2
Show file tree
Hide file tree
Showing 9 changed files with 68 additions and 84 deletions.
56 changes: 27 additions & 29 deletions src/Pepperdash.Core/Debug.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,12 @@ public static class Debug
/// </summary>
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;

Expand All @@ -69,10 +74,11 @@ public static class Debug
static Debug()
{
CrestronDataStoreStatic.InitCrestronDataStore();
var directorySeparator = Path.DirectorySeparatorChar.ToString();

var logFilePath = CrestronEnvironment.DevicePlatform == eDevicePlatform.Appliance ?
$@"{Directory.GetCurrentDirectory()}{Path.DirectorySeparatorChar}user{Path.DirectorySeparatorChar}debug{Path.DirectorySeparatorChar}app{InitialParametersClass.ApplicationNumber}{Path.DirectorySeparatorChar}global-log.log" :
$@"{Directory.GetCurrentDirectory()}{Path.DirectorySeparatorChar}user{Path.DirectorySeparatorChar}debug{Path.DirectorySeparatorChar}room{InitialParametersClass.RoomId}{Path.DirectorySeparatorChar}global-log.log";
var logFilePath = CrestronEnvironment.DevicePlatform == eDevicePlatform.Appliance
? Path.Combine(directorySeparator, "user", "program" + InitialParametersClass.ApplicationNumber, "logs", "global-log.log")
: Path.Combine(directorySeparator, "User", "logs", "global-log.log");

CrestronConsole.PrintLine($"Saving log files to {logFilePath}");

Expand All @@ -97,51 +103,41 @@ static Debug()
);

#if NET472

const string certFilename = "cert.pfx";
var certPath = IsRunningOnAppliance ? Path.Combine(Path.DirectorySeparatorChar.ToString(), "user", certFilename) : Path.Combine("User", certFilename);
var certPath = IsRunningOnAppliance ? Path.Combine("/", "user") : Path.Combine("/", "User");
var websocket = new DebugNet472WebSocket(certPath);
WebsocketPort = websocket.Port;
WebsocketUrl = websocket.Url;
DefaultLoggerConfiguration.WriteTo.Sink(new DebugWebsocketSink(websocket, new JsonFormatter(renderMessage: true)), levelSwitch: WebsocketLoggingLevelSwitch);
#endif

var supportsRemovableDrive = false;
try
{
if (InitialParametersClass.NumberOfRemovableDrives > 0)
{
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");
CrestronLogger.Initialize(1, LoggerModeEnum.RM);
supportsRemovableDrive = true;
}
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);
ConsoleLoggingLevelSwitch.MinimumLevel = storedConsoleLevel.Level;
CrestronConsole.PrintLine("Beginning console logging with level:{0}", storedConsoleLevel.Level);

Log.Logger = DefaultLoggerConfiguration.CreateLogger();
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)
{
CrestronConsole.AddNewConsoleCommand(SetDoNotLoadOnNextBootFromConsole, "donotloadonnextboot",
"donotloadonnextboot:P [true/false]: Should the application load on next boot", ConsoleAccessLevelEnum.AccessOperator);

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);

CrestronConsole.AddNewConsoleCommand(ShowDebugLog, "appdebuglog",
Expand Down Expand Up @@ -213,8 +209,10 @@ private static void SetDebugFromConsole(string levelString)
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");
}
}
catch
{
Expand Down
20 changes: 8 additions & 12 deletions src/Pepperdash.Core/Logging/DebugClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,39 +24,35 @@ public TimeSpan ConnectedDuration

public DebugClient()
{
Debug.Console(0, "DebugClient Created");
Debug.LogInformation<DebugClient>("DebugClient Created");
}

protected override void OnOpen()
{
base.OnOpen();

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;
}

protected override void OnMessage(MessageEventArgs e)
{
base.OnMessage(e);

Debug.Console(0, "WebSocket UiClient Message: {0}", e.Data);
Debug.LogVerbose<DebugClient>("WebSocket UiClient Message: {Data}", e.Data);
}

protected override void OnClose(CloseEventArgs e)
{
base.OnClose(e);

Debug.Console(0, Debug.ErrorLogLevel.Notice, "WebSocket UiClient Closing: {0} reason: {1}", e.Code, e.Reason);
Debug.LogInformation<DebugClient>("WebSocket UiClient Closing: {Code} Reason: {Reason} Total Time: {Time}", e.Code, e.Reason, ConnectedDuration);
}

protected override void OnError(WebSocketSharp.ErrorEventArgs e)
protected override void OnError(ErrorEventArgs e)
{
base.OnError(e);

Debug.Console(2, Debug.ErrorLogLevel.Notice, "WebSocket UiClient Error: {0} message: {1}", e.Exception, e.Message);
Debug.LogError<DebugClient>(e.Exception, "WebSocket UiClient Error");
}
}
}
#endif

#endif
11 changes: 7 additions & 4 deletions src/Pepperdash.Core/Logging/DebugContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
using Newtonsoft.Json;
using Serilog;
using Serilog.Events;
using WebSocketSharp;

namespace PepperDash.Core.Logging
{
Expand All @@ -18,8 +17,8 @@ public static class DebugContext
private static readonly CTimer SaveTimer;
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 ServerFilePath = Path.Combine("User", "debug", $"app-{InitialParametersClass.RoomId}-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", $"{InitialParametersClass.RoomId}-debug.json");

/// <summary>
/// The name of the file containing the current debug settings.
Expand Down Expand Up @@ -79,6 +78,10 @@ private static void SaveData()

try
{
var debugDirectory = Path.GetDirectoryName(FileName) ??
throw new Exception("File directory is root");

Directory.CreateDirectory(debugDirectory);
var json = JsonConvert.SerializeObject(CurrentData);
File.WriteAllText(FileName, json);
}
Expand All @@ -104,4 +107,4 @@ private static Dictionary<string, DebugContextData> LoadData()
///
/// </summary>
public record DebugContextData(LogEventLevel Level, string[] Devices = null);
}
}
5 changes: 0 additions & 5 deletions src/Pepperdash.Core/Logging/DebugCrestronLoggerSink.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,5 @@ public void Emit(LogEvent logEvent)

CrestronLogger.WriteToLog(message, (uint)logEvent.Level);
}

public DebugCrestronLoggerSink()
{
CrestronLogger.Initialize(1, LoggerModeEnum.RM);
}
}
}
21 changes: 8 additions & 13 deletions src/Pepperdash.Core/Logging/DebugNet472WebSocket.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
#if NET472

using System;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using Crestron.SimplSharp;

#if NET472
using WebSocketSharp.Net;
using WebSocketSharp.Server;

Expand All @@ -11,6 +13,9 @@ internal class DebugNet472WebSocket : DebugWebSocket
{
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;

public DebugNet472WebSocket(string certPath = "") : base(certPath)
Expand Down Expand Up @@ -41,14 +46,8 @@ public DebugNet472WebSocket(string certPath = "") : base(certPath)

public override void Broadcast(string message) => server.WebSocketServices.Broadcast(message);
}
}
#else

using System;
using System.Net;

namespace PepperDash.Core.Logging
{
//TODO: NETCORE version
internal class DebugNetWebSocket : DebugWebSocket
{
private const string Path = "/debug/join/";
Expand All @@ -57,7 +56,6 @@ internal class DebugNetWebSocket : DebugWebSocket

public DebugNetWebSocket(int port, string certPath = "") : base(certPath)
{
server.AuthenticationSchemeSelectorDelegate = (request) => AuthenticationSchemes.Anonymous;
server.Prefixes.Add("wss://*:" + port + Path);
}

Expand All @@ -66,7 +64,4 @@ public DebugNetWebSocket(int port, string certPath = "") : base(certPath)
public override void Broadcast(string message) => throw new NotImplementedException();
}
}

#endif


5 changes: 5 additions & 0 deletions src/Pepperdash.Core/Logging/DebugWebSocket.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
using System;
using System.IO;
using Crestron.SimplSharp;

#if NET472
using Org.BouncyCastle.Asn1.X509;
#endif

namespace PepperDash.Core.Logging
{
Expand Down Expand Up @@ -29,6 +32,7 @@ protected DebugWebSocket(string certPath = "")

private static void CreateCert(string filePath)
{
#if NET472
try
{
var utility = new BouncyCertificate();
Expand All @@ -44,6 +48,7 @@ private static void CreateCert(string filePath)
{
Debug.LogError(ex, "WSS failed to create cert");
}
#endif
}

public abstract bool IsListening { get; }
Expand Down
10 changes: 0 additions & 10 deletions src/Pepperdash.Core/Logging/DebugWebsocketSink.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using System.IO;
using Serilog;
using Serilog.Configuration;
using Serilog.Core;
using Serilog.Events;
using Serilog.Formatting;
Expand Down Expand Up @@ -29,12 +27,4 @@ public void Emit(LogEvent logEvent)
webSocket.Broadcast(sw.ToString());
}
}

public class NoopSink : ILogEventSink
{
public static readonly NoopSink Instance = new NoopSink();
public void Emit(LogEvent logEvent)
{
}
}
}
20 changes: 10 additions & 10 deletions src/Pepperdash.Core/PepperDash.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,17 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="BouncyCastle" Version="1.8.9" />
<PackageReference Include="Crestron.SimplSharp.SDK.Library" Version="2.21.65" />
<PackageReference Include="Serilog" Version="4.1.0" />
<PackageReference Include="Serilog.Expressions" Version="5.0.0" />
<PackageReference Include="Serilog.Formatting.Compact" Version="3.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="WebSocketSharp" Version="1.0.3-rc11" />
</ItemGroup>
<PackageReference Include="Crestron.SimplSharp.SDK.Library" Version="2.21.65" />
<PackageReference Include="Serilog" Version="4.1.0" />
<PackageReference Include="Serilog.Expressions" Version="5.0.0" />
<PackageReference Include="Serilog.Formatting.Compact" Version="3.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
</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="PolySharp" Version="1.14.1">
<PrivateAssets>all</PrivateAssets>
Expand Down
4 changes: 3 additions & 1 deletion src/Pepperdash.Core/Web/BouncyCertificate.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Crestron.SimplSharp;

#if NET472
using System;
using System.Collections.Generic;
using System.IO;
Expand Down Expand Up @@ -357,4 +358,5 @@ public bool AddCertToStore(X509Certificate2 cert, System.Security.Cryptography.X
return bRet;
}
}
}
}
#endif

0 comments on commit ba89ea2

Please sign in to comment.