diff --git a/src/Applications/ACATApp/Program.cs b/src/Applications/ACATApp/Program.cs
index fe08c339..52ddca7c 100644
--- a/src/Applications/ACATApp/Program.cs
+++ b/src/Applications/ACATApp/Program.cs
@@ -22,10 +22,10 @@
using ACAT.Extension;
using ACAT.Extension.CommandHandlers;
using ACATResources;
+using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Windows.Forms;
-using System.Windows.Navigation;
namespace ACATApp
{
@@ -36,8 +36,9 @@ namespace ACATApp
internal static class Program
{
private static Splash splash = null;
- private static Microsoft.Extensions.Logging.ILoggerFactory modernLoggingFactory = null;
+ private static ILoggerFactory modernLoggingFactory = null;
private static ILogger _logger;
+ private static IServiceProvider _serviceProvider;
///
/// The main entry point for the application.
@@ -56,6 +57,7 @@ public static void Main(string[] args)
InitializeGlobals();
InitializeUser();
InitializeLogging();
+ InitializeDependencyInjection();
InitializeContext();
if (!PerformOnboarding())
@@ -101,14 +103,31 @@ private static void InitializeLogging()
{
// Initialize legacy logging
Log.SetupListeners();
-
- // Initialize modern logging infrastructure (ticket #3)
+
+ // Initialize modern logging infrastructure
modernLoggingFactory = LoggingConfiguration.CreateLoggerFactory();
_logger = modernLoggingFactory.CreateLogger(typeof(Program));
_logger.LogDebug("ACAT Dashboard Application Launch");
}
+ private static void InitializeDependencyInjection()
+ {
+ // Set up dependency injection for extension instantiation
+ var services = new ServiceCollection();
+
+ // Add logging (reuse existing factory)
+ services.AddSingleton(modernLoggingFactory);
+ services.AddLogging();
+
+ _serviceProvider = services.BuildServiceProvider();
+
+ // Make service provider available to Context for extension loading
+ Context.ServiceProvider = _serviceProvider;
+
+ _logger.LogDebug("Dependency injection initialized");
+ }
+
private static void InitializeUser()
{
AppCommon.SetUserName();
@@ -213,7 +232,7 @@ private static void ShutdownApplication()
Context.Dispose();
Common.Uninit();
CloseSplashScreen();
- _logger.LogDebug("ACATTalk Application shutdown");
+ _logger.LogDebug("ACAT Dashboard Application shutdown");
Log.Close();
modernLoggingFactory?.Dispose();
AppCommon.OnExit();
diff --git a/src/Applications/ACATConfigNext/Forms/SettingsForm.cs b/src/Applications/ACATConfigNext/Forms/SettingsForm.cs
index fc33658f..3faec7d2 100644
--- a/src/Applications/ACATConfigNext/Forms/SettingsForm.cs
+++ b/src/Applications/ACATConfigNext/Forms/SettingsForm.cs
@@ -6,6 +6,7 @@
using ACAT.Core.WidgetManagement;
using ACAT.Extension;
using ACATConfigNext.UserControls;
+using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
@@ -20,6 +21,7 @@ namespace ACATConfigNext.Forms
public class SettingsForm : Form
{
private readonly ILogger _logger;
+ private readonly IServiceProvider _serviceProvider;
private TableLayoutPanel basePanel;
private FlowLayoutPanel leftPanel;
private TableLayoutPanel navPanel;
@@ -42,13 +44,13 @@ public class SettingsForm : Form
private bool _isDirty = false;
- public SettingsForm(ILogger logger)
+ public SettingsForm(ILogger logger, IServiceProvider serviceProvider)
{
_logger = logger;
+ _serviceProvider = serviceProvider;
WpfInitializationHelper.EnsureApplicationResources();
InitializeComponent();
-
}
private FlowLayoutPanel CreateLeftPanel()
@@ -159,7 +161,7 @@ private void ButtonClicked_Save(object sender, EventArgs e)
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, "Error occurred while saving settings");
MessageBox.Show("An error occurred while saving settings.", "Save Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
@@ -410,6 +412,12 @@ private void CopyPreferencesValues(IPreferences source, IPreferences target)
}
}
+ private object CreateExtensionInstance(Type type)
+ {
+ // Use shared helper method for consistent extension instantiation across all applications
+ return ExtensionHelper.CreateExtensionInstance(_serviceProvider, type, _logger);
+ }
+
private IEnumerable LoadSettings(string category)
{
@@ -431,7 +439,7 @@ private IEnumerable LoadSettings(string category)
{
var wordPredictorTypes = Context.AppWordPredictionManager.WordPredictorExtensions;
var wordPredictorExtensions = wordPredictorTypes
- .Select(type => Activator.CreateInstance(type) as IExtension)
+ .Select(type => CreateExtensionInstance(type) as IExtension)
.Where(instance => instance != null);
return wordPredictorExtensions;
@@ -443,7 +451,7 @@ private IEnumerable LoadSettings(string category)
{
var ttsEngineTypes = Context.AppTTSManager.GetExtensions();
var ttsExtensions = ttsEngineTypes
- .Select(type => Activator.CreateInstance(type) as IExtension)
+ .Select(type => CreateExtensionInstance(type) as IExtension)
.Where(instance => instance != null);
return ttsExtensions;
}
diff --git a/src/Applications/ACATConfigNext/Program.cs b/src/Applications/ACATConfigNext/Program.cs
index 0675da92..96b4487a 100644
--- a/src/Applications/ACATConfigNext/Program.cs
+++ b/src/Applications/ACATConfigNext/Program.cs
@@ -1,4 +1,6 @@
using ACATConfigNext.Forms;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
using System;
using System.Windows.Forms;
@@ -15,7 +17,27 @@ static void Main()
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
- Application.Run(new SettingsForm());
+ // Set up dependency injection
+ var services = new ServiceCollection();
+ ConfigureServices(services);
+ var serviceProvider = services.BuildServiceProvider();
+
+ // Get SettingsForm from DI container
+ var settingsForm = serviceProvider.GetRequiredService();
+ Application.Run(settingsForm);
+ }
+
+ private static void ConfigureServices(IServiceCollection services)
+ {
+ // Configure logging
+ services.AddLogging(builder =>
+ {
+ builder.AddConsole();
+ builder.SetMinimumLevel(LogLevel.Information);
+ });
+
+ // Register SettingsForm - IServiceProvider will be injected automatically
+ services.AddTransient();
}
}
}
\ No newline at end of file
diff --git a/src/Applications/ACATTalk/Program.cs b/src/Applications/ACATTalk/Program.cs
index 9aa8a71e..bc4e29d0 100644
--- a/src/Applications/ACATTalk/Program.cs
+++ b/src/Applications/ACATTalk/Program.cs
@@ -22,6 +22,7 @@
using ACAT.Extension;
using ACAT.Extension.CommandHandlers;
using ACATResources;
+using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Windows.Forms;
@@ -34,7 +35,9 @@ namespace ACATTalk
internal static class Program
{
private static Splash splash = null;
+ private static ILoggerFactory modernLoggingFactory = null;
private static ILogger _logger;
+ private static IServiceProvider _serviceProvider;
///
/// The main entry point for the application.
@@ -50,11 +53,6 @@ public static void Main(string[] args)
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
- //if (!AppCommon.CheckFontsInstalled())
- //{
- // return;
- //}
-
CoreGlobals.AppId = "ACATTalk";
CoreGlobals.ACATUserGuideFileName = "ACAT User Guide.pdf";
FatalErrorHandler.EvtFatalError += CoreGlobals_EvtFatalError;
@@ -66,8 +64,6 @@ public static void Main(string[] args)
AppCommon.SetUserName();
AppCommon.SetProfileName();
- bool freshInstallForUser = !UserManager.UserExists(UserManager.CurrentUser);
-
if (!AppCommon.CreateUserAndProfile())
{
return;
@@ -91,12 +87,17 @@ public static void Main(string[] args)
// Initialize legacy logging system
Log.SetupListeners();
- // Initialize modern logging infrastructure (ticket #3)
- var modernLoggingFactory = LoggingConfiguration.CreateLoggerFactory();
+ // Initialize modern logging infrastructure FIRST - before anything else needs it
+ modernLoggingFactory = LoggingConfiguration.CreateLoggerFactory();
+ LogManager.Initialize(modernLoggingFactory); // Initialize global logger manager
+
_logger = modernLoggingFactory.CreateLogger(typeof(Program));
_logger.LogDebug("ACAT Talk Application Launch");
+ // Set up dependency injection for extension instantiation
+ InitializeDependencyInjection();
+
AuditLog.Audit(new AuditEvent("Application", "start"));
CommandDescriptors.Init();
@@ -193,7 +194,6 @@ public static void Main(string[] args)
Common.Uninit();
-
splash?.Close();
splash = null;
@@ -211,6 +211,23 @@ public static void Main(string[] args)
AppCommon.OnExit();
}
+ private static void InitializeDependencyInjection()
+ {
+ // Set up dependency injection for extension instantiation
+ var services = new ServiceCollection();
+
+ // Add logging (reuse existing factory)
+ services.AddSingleton(modernLoggingFactory);
+ services.AddLogging();
+
+ _serviceProvider = services.BuildServiceProvider();
+
+ // Make service provider available to Context for extension loading
+ Context.ServiceProvider = _serviceProvider;
+
+ _logger.LogDebug("Dependency injection initialized");
+ }
+
///
/// A fatal error has occurred. Try and gracefully exit ACAT
///
@@ -219,7 +236,6 @@ private static void CoreGlobals_EvtFatalError(string reason)
{
splash?.Close();
-
if (Context.AppPanelManager != null && Context.AppPanelManager.GetCurrentForm() != null &&
Context.AppPanelManager.GetCurrentForm().PanelCommon != null && Context.AppPanelManager.GetCurrentForm().PanelCommon.RootWidget != null)
{
diff --git a/src/Applications/AppCommon/ExtensionHelper.cs b/src/Applications/AppCommon/ExtensionHelper.cs
new file mode 100644
index 00000000..936f4000
--- /dev/null
+++ b/src/Applications/AppCommon/ExtensionHelper.cs
@@ -0,0 +1,46 @@
+using ACAT.Core.Extensions;
+using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
+using System;
+using System.Collections.Generic;
+
+namespace ACAT.Applications
+{
+ ///
+ /// Helper class for creating extension instances with proper dependency injection
+ /// Wrapper around ExtensionInstantiator from ACAT.Core for backward compatibility
+ ///
+ public static class ExtensionHelper
+ {
+ ///
+ /// Creates instances of extension types using dependency injection.
+ /// This ensures extensions receive proper logger instances and other registered services.
+ ///
+ /// The service provider for dependency resolution
+ /// Collection of extension types to instantiate
+ /// Optional logger for diagnostics
+ /// Collection of successfully created extension instances
+ public static IEnumerable CreateExtensionInstances(
+ IServiceProvider serviceProvider,
+ IEnumerable extensionTypes,
+ ILogger logger = null)
+ {
+ return ExtensionInstantiator.CreateExtensionInstances(serviceProvider, extensionTypes, logger);
+ }
+
+ ///
+ /// Creates a single extension instance using dependency injection
+ ///
+ /// The service provider for dependency resolution
+ /// The extension type to instantiate
+ /// Optional logger for diagnostics
+ /// The created extension instance, or null if creation fails
+ public static IExtension CreateExtensionInstance(
+ IServiceProvider serviceProvider,
+ Type extensionType,
+ ILogger logger = null)
+ {
+ return ExtensionInstantiator.CreateExtensionInstance(serviceProvider, extensionType, logger) as IExtension;
+ }
+ }
+}
diff --git a/src/Applications/AppCommon/Onboarding.cs b/src/Applications/AppCommon/Onboarding.cs
index 15bba16f..f455dc25 100644
--- a/src/Applications/AppCommon/Onboarding.cs
+++ b/src/Applications/AppCommon/Onboarding.cs
@@ -50,7 +50,7 @@ public static bool DoOnboarding()
public static bool ResetAllPreferences(List currentCategory)
{
- var logger = LoggingConfiguration.CreateLogger(typeof(AppCommon));
+ var logger = LoggingConfiguration.CreateLogger();
try
{
// Reset general preferences
@@ -91,7 +91,7 @@ public static bool ResetAllPreferences(List currentCategory
private static void CopyPreferencesValues(IPreferences source, IPreferences target)
{
- var logger = LoggingConfiguration.CreateLogger(typeof(AppCommon));
+ var logger = LoggingConfiguration.CreateLogger();
var sourceType = source.GetType();
var targetType = target.GetType();
diff --git a/src/Extensions/ACAT.Extensions.Onboarding/Onboarding/OnboardingLanguageSelect.cs b/src/Extensions/ACAT.Extensions.Onboarding/Onboarding/OnboardingLanguageSelect.cs
index 030ede7e..9e28a146 100644
--- a/src/Extensions/ACAT.Extensions.Onboarding/Onboarding/OnboardingLanguageSelect.cs
+++ b/src/Extensions/ACAT.Extensions.Onboarding/Onboarding/OnboardingLanguageSelect.cs
@@ -9,6 +9,7 @@
using ACAT.Extensions.Onboarding.UI.UserControls;
using ACAT.Extensions.Onboarding.UI;
using ACAT.Core.CoreInterfaces;
+using Microsoft.Extensions.Logging;
using System.Globalization;
namespace ACAT.Extensions.Onboarding.Onboarding
@@ -25,8 +26,14 @@ public class OnboardingLanguageSelect : OnboardingExtensionBase
// TODO - Localize Me
private const string Step1 = "STEP 1";
+ private readonly ILogger _logger;
private IOnboardingWizard _wizard;
+ public OnboardingLanguageSelect()
+ {
+ _logger = LoggingConfiguration.CreateLogger();
+ }
+
public override ClassDescriptorAttribute Descriptor
{
get { return ClassDescriptorAttribute.GetDescriptor(GetType()); }
@@ -85,7 +92,7 @@ public override void OnEndStep(IOnboardingUserControl userControl, Reason reason
{
case Step1:
var cultureInfo = userControlLang.currentCulture;
- Log.Debug ("User selected language: " + cultureInfo.DisplayName);
+ _logger.LogDebug("User selected language: {LanguageName}", cultureInfo.DisplayName);
CoreGlobals.AppPreferences.Language = cultureInfo.TwoLetterISOLanguageName;
CoreGlobals.AppPreferences.Save();
diff --git a/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchSetup.cs b/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchSetup.cs
index 9608c041..ba664330 100644
--- a/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchSetup.cs
+++ b/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchSetup.cs
@@ -481,7 +481,7 @@ private void UserControlHardwareSwitchSetup_Load(object sender, EventArgs e)
}
String html = String.Format(_htmlTemplate, headStyle, bodyStyle, textStyle, "Click here for help");
- Log.Debug(html);
+ _logger.LogDebug("Generated HTML: {Html}", html);
webBrowser.DocumentText = html;
//webBrowser.DocumentText =
diff --git a/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchTest.cs b/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchTest.cs
index 72046ee3..23a0a191 100644
--- a/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchTest.cs
+++ b/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchTest.cs
@@ -334,7 +334,7 @@ private void WebBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs
{
var str = e.Url.ToString();
- Log.Debug("Url is [" + str + "]");
+ _logger.LogDebug("Url is [{Url}]", str);
if (str.ToLower().Contains("blank"))
{
diff --git a/src/Extensions/ACAT.Extensions.UI/Scanners/CursorNavigationScanner.cs b/src/Extensions/ACAT.Extensions.UI/Scanners/CursorNavigationScanner.cs
index 82e5277b..f0d87793 100644
--- a/src/Extensions/ACAT.Extensions.UI/Scanners/CursorNavigationScanner.cs
+++ b/src/Extensions/ACAT.Extensions.UI/Scanners/CursorNavigationScanner.cs
@@ -179,7 +179,7 @@ public bool Initialize(StartupArg startupArg)
if (!_scannerCommon.Initialize(startupArg))
{
- Log.Warn("Could not initialize form " + Name);
+ _logger.LogWarning("Could not initialize form {Name}", Name);
return false;
}
diff --git a/src/Extensions/ACAT.Extensions.UI/Scanners/WordPredictionSetModeScanner.cs b/src/Extensions/ACAT.Extensions.UI/Scanners/WordPredictionSetModeScanner.cs
index a8fb706b..1639755f 100644
--- a/src/Extensions/ACAT.Extensions.UI/Scanners/WordPredictionSetModeScanner.cs
+++ b/src/Extensions/ACAT.Extensions.UI/Scanners/WordPredictionSetModeScanner.cs
@@ -52,7 +52,7 @@ public partial class WordPredictionSetModeScanner : HorizontalStripScanner
///
/// Scanner class
/// Title of the scanner
- public WordPredictionSetModeScanner(String panelClass, String title) : base(panelClass, title)
+ public WordPredictionSetModeScanner(String panelClass, String title) : base(panelClass, title, null)
{
InitializeComponent();
_dispatcher = new Dispatcher(this);
diff --git a/src/Extensions/ACAT.Extensions.UI/Scanners/YesNoResponseScanner.cs b/src/Extensions/ACAT.Extensions.UI/Scanners/YesNoResponseScanner.cs
index b0488b21..38129f3d 100644
--- a/src/Extensions/ACAT.Extensions.UI/Scanners/YesNoResponseScanner.cs
+++ b/src/Extensions/ACAT.Extensions.UI/Scanners/YesNoResponseScanner.cs
@@ -218,7 +218,7 @@ public bool Initialize(StartupArg startupArg)
if (!scannerCommon.Initialize(startupArg))
{
- Log.Warn("Could not initialize form " + Name);
+ _logger.LogWarning("Could not initialize form {Name}", Name);
return false;
}
@@ -354,8 +354,6 @@ private void YesNoResponseScanner_FormClosing(object sender, FormClosingEventArg
///
private void YesNoResponseScanner_Load(object sender, EventArgs e)
{
- Log.Verbose();
-
scannerCommon.OnLoad();
if (!String.IsNullOrEmpty(_title))
diff --git a/src/Extensions/ACAT.Extensions.UI/Scanners/YesNoScanner.cs b/src/Extensions/ACAT.Extensions.UI/Scanners/YesNoScanner.cs
index 95a48612..d4cc3a1b 100644
--- a/src/Extensions/ACAT.Extensions.UI/Scanners/YesNoScanner.cs
+++ b/src/Extensions/ACAT.Extensions.UI/Scanners/YesNoScanner.cs
@@ -199,7 +199,7 @@ protected override CreateParams CreateParams
{
get
{
- _logger.LogTrace("CreateParams");
+ _logger?.LogTrace("CreateParams");
return Windows.SetFormStyles(base.CreateParams);
}
}
@@ -238,7 +238,7 @@ public ExtensionInvoker GetInvoker()
/// true on success
public bool Initialize(StartupArg startupArg)
{
- _logger.LogTrace("Initialize");
+ _logger?.LogTrace("Initialize");
PanelClass = startupArg.PanelClass;
startupCommandArg = startupArg.Arg;
this.startupArg = startupArg;
@@ -247,7 +247,7 @@ public bool Initialize(StartupArg startupArg)
if (!scannerCommon.Initialize(startupArg))
{
- Log.Warn("Could not initialize form " + Name);
+ _logger.LogWarning("Could not initialize form {Name}", Name);
return false;
}
@@ -270,7 +270,7 @@ public void OnFocusChanged(WindowActivityMonitorInfo monitorInfo)
///
public virtual void OnPause()
{
- _logger.LogTrace("OnPause");
+ _logger?.LogTrace("OnPause");
scannerCommon.OnPause();
}
@@ -290,7 +290,7 @@ public bool OnQueryPanelChange(PanelRequestEventArgs arg)
///
public virtual void OnResume()
{
- _logger.LogTrace("OnResume");
+ _logger?.LogTrace("OnResume");
scannerCommon.OnResume();
}
@@ -432,8 +432,6 @@ private void YesNoScanner_FormClosing(object sender, FormClosingEventArgs e)
///
private void YesNoScanner_Load(object sender, EventArgs e)
{
- Log.Verbose();
-
scannerCommon.OnLoad();
var widget = PanelCommon.RootWidget.Finder.FindChild("Prompt");
diff --git a/src/Extensions/ACAT.Extensions.UI/UserControls/SentencePredictionUserControl.cs b/src/Extensions/ACAT.Extensions.UI/UserControls/SentencePredictionUserControl.cs
index 412608bd..80d0669c 100644
--- a/src/Extensions/ACAT.Extensions.UI/UserControls/SentencePredictionUserControl.cs
+++ b/src/Extensions/ACAT.Extensions.UI/UserControls/SentencePredictionUserControl.cs
@@ -31,18 +31,16 @@ namespace ACAT.Extensions.UI.UserControls
"User Control for Sentence Prediction")]
public partial class SentencePredictionUserControl : KeyboardUserControl
{
- private readonly ILogger _logger;
private UserControlWordPredictionCommon _userControlWordPredictionCommon;
public SentencePredictionUserControl()
{
- _logger = LoggingConfiguration.CreateLogger();
InitializeComponent();
}
protected override bool HandleInitialize()
{
- _userControlWordPredictionCommon = new UserControlWordPredictionCommon(this, _keybordUserControlCommon.TextController, _keybordUserControlCommon.ScannerPanel, new PredictionTypes[] { PredictionTypes.Sentences });
+ _userControlWordPredictionCommon = new UserControlWordPredictionCommon(this, _keybordUserControlCommon.TextController, _keybordUserControlCommon.ScannerPanel, new PredictionTypes[] { PredictionTypes.Sentences }, null);
bool retVal = _userControlWordPredictionCommon.Initialize(_keybordUserControlCommon.RootWidget);
return retVal;
diff --git a/src/Extensions/ACAT.Extensions.UI/UserControls/Toolbars/LargeToolbarUserControl.cs b/src/Extensions/ACAT.Extensions.UI/UserControls/Toolbars/LargeToolbarUserControl.cs
index 6379b534..27ce45ff 100644
--- a/src/Extensions/ACAT.Extensions.UI/UserControls/Toolbars/LargeToolbarUserControl.cs
+++ b/src/Extensions/ACAT.Extensions.UI/UserControls/Toolbars/LargeToolbarUserControl.cs
@@ -1,6 +1,7 @@
using ACAT.Core.Utility;
using ACAT.Core.WidgetManagement;
using ACAT.Extension.UI.UserControls;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@@ -55,6 +56,7 @@ protected class ButtonSpec
}
public LargeToolbarUserControl(string name)
{
+ _logger = LoggingConfiguration.CreateLogger();
Name = name;
InitializeButtonsList();
InitializeComponent();
@@ -154,7 +156,7 @@ protected virtual void InitializeComponent()
protected override void OnPaint(PaintEventArgs e)
{
- Log.Debug($"{e.Graphics.DpiX} x {e.Graphics.DpiY}");
+ _logger.LogDebug("{DpiX} x {DpiY}", e.Graphics.DpiX, e.Graphics.DpiY);
e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
base.OnPaint(e);
diff --git a/src/Extensions/ACAT.Extensions.UI/UserControls/Toolbars/LaunchAppUserControl.cs b/src/Extensions/ACAT.Extensions.UI/UserControls/Toolbars/LaunchAppUserControl.cs
index 561412f9..3c2e72cd 100644
--- a/src/Extensions/ACAT.Extensions.UI/UserControls/Toolbars/LaunchAppUserControl.cs
+++ b/src/Extensions/ACAT.Extensions.UI/UserControls/Toolbars/LaunchAppUserControl.cs
@@ -1,6 +1,7 @@
using ACAT.Core.PanelManagement;
using ACAT.Core.Utility;
using ACAT.Core.WidgetManagement;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@@ -14,6 +15,8 @@ namespace ACAT.Extensions.UI.UserControls.Toolbars
[DesignerCategory("code")]
public class LaunchAppUserControl : LargeToolbarUserControl
{
+ private static readonly ILogger _logger = LoggingConfiguration.CreateLogger();
+
private class LaunchButtonSpec : ButtonSpec
{
public AppInfo AppInfo { get; set; }
@@ -51,7 +54,7 @@ public LaunchAppUserControl() : base("LaunchAppUserControl")
public override void OnButtonClicked(object s, EventArgs e)
{
string buttonName = e.ToString();
- Log.Info($"Button clicked: {buttonName}");
+ _logger.LogInformation("Button clicked: {ButtonName}", buttonName);
var dict = Buttons.ToDictionary(x => x.Name);
diff --git a/src/Extensions/ACAT.Extensions.UI/UserControls/WordPredictionUserControl.cs b/src/Extensions/ACAT.Extensions.UI/UserControls/WordPredictionUserControl.cs
index 96959718..ac9a1b3b 100644
--- a/src/Extensions/ACAT.Extensions.UI/UserControls/WordPredictionUserControl.cs
+++ b/src/Extensions/ACAT.Extensions.UI/UserControls/WordPredictionUserControl.cs
@@ -37,7 +37,7 @@ public override bool Initialize(UserControlConfigMapEntry mapEntry, TextControll
{
base.Initialize(mapEntry, textController, scanner);
- _userControlWordPredictionCommon = new UserControlWordPredictionCommon(this, textController, scanner, new PredictionTypes[] { PredictionTypes.Words });
+ _userControlWordPredictionCommon = new UserControlWordPredictionCommon(this, textController, scanner, new PredictionTypes[] { PredictionTypes.Words }, null);
bool retVal = _userControlWordPredictionCommon.Initialize(_keybordUserControlCommon.RootWidget);
return retVal;
}
diff --git a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/Scanners/TalkApplicationBCIScanner.cs b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/Scanners/TalkApplicationBCIScanner.cs
index 4913dfa5..76959dd2 100644
--- a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/Scanners/TalkApplicationBCIScanner.cs
+++ b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/Scanners/TalkApplicationBCIScanner.cs
@@ -34,6 +34,7 @@
using ACAT.Extensions.BCI.Common.BCIInterfaceUtilities;
using ACAT.Extensions.BCI.UI.UserControls;
using ACATResources;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -65,6 +66,11 @@ public partial class TalkApplicationBCIScanner : Form, IScannerPanel, ISupportsS
///
private readonly Dispatcher _dispatcher;
+ ///
+ /// Logger instance for this class
+ ///
+ private readonly ILogger _logger;
+
///
/// The AlphabetScannerCommon object. Has a number of
/// helper functions
@@ -187,8 +193,9 @@ public partial class TalkApplicationBCIScanner : Form, IScannerPanel, ISupportsS
///
/// Initializes a new instance of the class.
///
- public TalkApplicationBCIScanner()
+ public TalkApplicationBCIScanner(ILogger logger = null)
{
+ _logger = logger;
_scannerCommon = new ScannerCommon(this);
InitializeComponent();
this.DoubleBuffered = true;
@@ -737,7 +744,7 @@ private void BciActuator_EvtIoctlResponse(int opcode, object response)
{
if (!_RequestCalibration)//have a delay before start typing so the user can see the options and suggestions and start looking where is desired
{
- Log.Debug("BCI LOG | Delay before Typing ");//Run the delay in another therad to avoid blocking the UI
+ _logger?.LogDebug("BCI LOG | Delay before Typing ");//Run the delay in another therad to avoid blocking the UI
_ = ShowTimedMessageBoxAsync().ConfigureAwait(false);
}
else
@@ -752,14 +759,14 @@ private void BciActuator_EvtIoctlResponse(int opcode, object response)
if (_BCIState == BCIState.BCIStartSession)
{
_BCIState = BCIState.BCIInitDone;
- Log.Debug("BCI LOG | BCI Init state: " + BCIState.BCIInitDone);
+ _logger?.LogDebug("BCI LOG | BCI Init state: {State}", BCIState.BCIInitDone);
}
break;
case (int)OpCodes.SendCalibrationStatus:
//STEP - 1
var bciCalibrationStatus = response as BCICalibrationStatus;
- Log.Debug("BCI LOG | bciCalibrationStatus.OkToGoToTyping: " + bciCalibrationStatus.OkToGoToTyping);
+ _logger?.LogDebug("BCI LOG | bciCalibrationStatus.OkToGoToTyping: {OkToGoToTyping}", bciCalibrationStatus.OkToGoToTyping);
if (_ShowMainOptions)//This window should only display once
{
_ShowMainOptions = false;
@@ -988,7 +995,7 @@ private void BCIShowRecalibrationWindowMessage()
}
catch (Exception es)
{
- Log.Exception("BCI LOG | " + es.Message.ToString());
+ _logger?.LogError("BCI LOG | {Message}", es.Message.ToString());
}
}
@@ -1006,32 +1013,32 @@ private void BCIUpdateBCI(BCIState bCIState)
break;
case BCIState.UIRefresh://1 Init state
- Log.Debug("BCI LOG | BCI Init state: " + BCIState.UIRefresh);
+ _logger?.LogDebug("BCI LOG | BCI Init state: {State}", BCIState.UIRefresh);
_BCIState = BCIState.UIRefresh;
_ = ControlsUIAdjustment().ConfigureAwait(false);
break;
case BCIState.Initializing://2 Init state
- Log.Debug("BCI LOG | BCI Init state: " + BCIState.Initializing);
+ _logger?.LogDebug("BCI LOG | BCI Init state: {State}", BCIState.Initializing);
_BCIState = BCIState.Initializing;
_ = InitializeBCI().ConfigureAwait(false);
break;
case BCIState.ReqCalibrationStatus://3 Init state
_BCIState = BCIState.ReqCalibrationStatus;
- Log.Debug("BCI LOG | BCI Init state: " + BCIState.ReqCalibrationStatus);
+ _logger?.LogDebug("BCI LOG | BCI Init state: {State}", BCIState.ReqCalibrationStatus);
_ = BCIRequestCalibrationStatus().ConfigureAwait(false);
break;
case BCIState.StartBCIReqParams://4 Init state
//STEP - 4
- Log.Debug("BCI LOG | BCI Init state: " + BCIState.StartBCIReqParams);
+ _logger?.LogDebug("BCI LOG | BCI Init state: {State}", BCIState.StartBCIReqParams);
_BCIState = BCIState.StartBCIReqParams;
_ = BCIStartBCIReqParams().ConfigureAwait(false);
break;
case BCIState.BCIStartSession://5 Init state
- Log.Debug("BCI LOG | BCI Init state: " + BCIState.BCIStartSession);
+ _logger?.LogDebug("BCI LOG | BCI Init state: {State}", BCIState.BCIStartSession);
_BCIState = BCIState.BCIStartSession;
_ = BCIStartSession().ConfigureAwait(false);
break;
@@ -1039,7 +1046,7 @@ private void BCIUpdateBCI(BCIState bCIState)
}
catch (Exception ex)
{
- Log.Exception("BCI LOG | Error in BCI Init state: " + bCIState + " Messagge: " + ex.Message);
+ _logger?.LogError("BCI LOG | Error in BCI Init state: {State} Message: {Message}", bCIState, ex.Message);
}
}
@@ -1129,7 +1136,7 @@ private void ExitApplication()
}
catch (Exception e)
{
- Log.Exception("BCI LOG | Error in ExitApplication() BCI: " + e.Message);
+ _logger?.LogError("BCI LOG | Error in ExitApplication() BCI: {Message}", e.Message);
}
}
@@ -1250,8 +1257,8 @@ private void LearnCannedPhrases(string textToLearn)
private void LogAssemblyVersion()
{
var version = ACATPreferences.ApplicationAssembly.GetName().Version.Major + "." + ACATPreferences.ApplicationAssembly.GetName().Version.Minor;
- Log.Debug("BCI LOG | ACAT - Assembly version info");
- Log.Debug("BCI LOG | AssemblyVersion: " + version);
+ _logger?.LogDebug("BCI LOG | ACAT - Assembly version info");
+ _logger?.LogDebug("BCI LOG | AssemblyVersion: {Version}", version);
}
///
@@ -1348,7 +1355,7 @@ private void SetCaretPositionForTextBoxUC(UserControl userControl, Control panel
if (BCIInterfaceUtils.GetCaretPositionOfTextBoxUC() != currentCaretPosition)
{
Windows.SetCaretPosition(_textBoxTalkWindow, BCIInterfaceUtils.GetCaretPositionOfTextBoxUC());
- Log.Debug("BCI LOG | Caret position reestablish | Textbox user control changed");
+ _logger?.LogDebug("BCI LOG | Caret position reestablish | Textbox user control changed");
}
}
}
@@ -1359,14 +1366,14 @@ private void SetCaretPositionForTextBoxUC(UserControl userControl, Control panel
if (BCIInterfaceUtils.GetCaretPhrasePositionOfTextBoxUC() != currentCaretPosition)
{
Windows.SetCaretPosition(_textBoxTalkWindow, BCIInterfaceUtils.GetCaretPhrasePositionOfTextBoxUC());
- Log.Debug("BCI LOG | Caret position reestablish | Textbox user control changed");
+ _logger?.LogDebug("BCI LOG | Caret position reestablish | Textbox user control changed");
}
}
}
}
catch (Exception ex)
{
- Log.Debug("BCI LOG | Error | SetCaretPositionForTextBoxUC: " + ex.Message);
+ _logger?.LogDebug("BCI LOG | Error | SetCaretPositionForTextBoxUC: {Message}", ex.Message);
}
}
@@ -1540,7 +1547,7 @@ private void TextBoxTalkWindowOnKeyPress(object sender, KeyPressEventArgs keyPre
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger?.LogError(ex, ex.Message);
}
}
@@ -1552,9 +1559,9 @@ private void TextToSpeech(String text)
{
if (!String.IsNullOrEmpty(text))
{
- Log.Debug("*** TTS *** : " + text);
+ _logger?.LogDebug("*** TTS *** : {Text}", text);
TTSManager.Instance.ActiveEngine.Speak(text);
- Log.Debug("*** TTS *** : sent text!");
+ _logger?.LogDebug("*** TTS *** : sent text!");
AuditLog.Audit(new AuditEventTextToSpeech(TTSManager.Instance.ActiveEngine.Descriptor.Name));
}
@@ -1639,6 +1646,8 @@ private void UpdatetextBoxEvt(string message)
///
private class CommandHandler : RunCommandHandler
{
+ private static ILogger _logger;
+
///
/// Initializes a new instance of the class.
///
@@ -1648,6 +1657,15 @@ public CommandHandler(String cmd)
{
}
+ ///
+ /// Sets the logger instance for the command handler
+ ///
+ /// logger instance
+ public static void SetLogger(ILogger logger)
+ {
+ _logger = logger;
+ }
+
///
/// Executes the command
///
@@ -1660,7 +1678,7 @@ public override bool Execute(ref bool handled)
{
handled = true;
List[] widgets;
- Log.Debug("BCI LOG | Command | selected | Pressed | " + Command.ToString());
+ _logger?.LogDebug("BCI LOG | Command | selected | Pressed | {Command}", Command.ToString());
switch (Command)
{
case "CmdEditScanner":
@@ -1871,7 +1889,7 @@ public override bool Execute(ref bool handled)
}
}
else
- Log.Debug("BCI LOG | Command | selected | Pressed in calibration | No action | " + Command.ToString());
+ _logger?.LogDebug("BCI LOG | Command | selected | Pressed in calibration | No action | {Command}", Command.ToString());
return true;
}
}
@@ -1888,6 +1906,13 @@ private class Dispatcher : DefaultCommandDispatcher
public Dispatcher(IScannerPanel panel)
: base(panel)
{
+ // Set the logger for CommandHandler
+ var form = panel.Form as TalkApplicationBCIScanner;
+ if (form != null)
+ {
+ CommandHandler.SetLogger(form._logger);
+ }
+
Commands.Add(new CommandHandler("CmdEditScanner"));
Commands.Add(new CommandHandler("CmdEntryModeSelect"));
Commands.Add(new CommandHandler("CmdMenuScanner"));
diff --git a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/PhrasesUserControlBCI.cs b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/PhrasesUserControlBCI.cs
index 95fb1e47..dd16a226 100644
--- a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/PhrasesUserControlBCI.cs
+++ b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/PhrasesUserControlBCI.cs
@@ -44,7 +44,7 @@ public partial class PhrasesUserControlBCI : UserControl, IUserControl
private UserControlWordPredictionCommon _sentencePredictionCommon;
public PhrasesUserControlBCI(ILogger logger = null)
{
- _logger = logger ?? LoggerFactory.GetLogger();
+ _logger = logger ?? LoggingConfiguration.CreateLogger();
InitializeComponent();
}
@@ -95,7 +95,7 @@ public bool Initialize(UserControlConfigMapEntry mapEntry, TextController textCo
_keyboardCommon = new UserControlKeyboardCommon(this, mapEntry, textController, scanner);
- _sentencePredictionCommon = new UserControlWordPredictionCommon(this, textController, scanner, new PredictionTypes[] { PredictionTypes.Sentences});
+ _sentencePredictionCommon = new UserControlWordPredictionCommon(this, textController, scanner, new PredictionTypes[] { PredictionTypes.Sentences}, null);
_scanner = scanner;
diff --git a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/TTSYesNoUserControlBCI.cs b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/TTSYesNoUserControlBCI.cs
index a71971dc..c202069a 100644
--- a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/TTSYesNoUserControlBCI.cs
+++ b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/TTSYesNoUserControlBCI.cs
@@ -37,7 +37,7 @@ public partial class TTSYesNoUserControlBCI : UserControl, IUserControl
public TTSYesNoUserControlBCI(ILogger logger = null)
{
- _logger = logger ?? LoggerFactory.GetLogger();
+ _logger = logger ?? LoggingConfiguration.CreateLogger();
InitializeComponent();
}
diff --git a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/TTSYesNoUserControlBCI2.cs b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/TTSYesNoUserControlBCI2.cs
index a560f504..3cc9e443 100644
--- a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/TTSYesNoUserControlBCI2.cs
+++ b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/TTSYesNoUserControlBCI2.cs
@@ -37,7 +37,7 @@ public partial class TTSYesNoUserControlBCI2 : UserControl, IUserControl
public TTSYesNoUserControlBCI2(ILogger logger = null)
{
- _logger = logger ?? LoggerFactory.GetLogger();
+ _logger = logger ?? LoggingConfiguration.CreateLogger();
InitializeComponent();
}
diff --git a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/WordPredictionUserControlBCI.cs b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/WordPredictionUserControlBCI.cs
index a55dce13..c863b7e2 100644
--- a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/WordPredictionUserControlBCI.cs
+++ b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/WordPredictionUserControlBCI.cs
@@ -88,7 +88,7 @@ public bool Initialize(UserControlConfigMapEntry mapEntry, TextController textCo
_keyboardCommon = new UserControlKeyboardCommon(this, mapEntry, textController, scanner);
- _wordPredictionCommon = new UserControlWordPredictionCommon(this, textController, scanner, new PredictionTypes[] { PredictionTypes.Words });
+ _wordPredictionCommon = new UserControlWordPredictionCommon(this, textController, scanner, new PredictionTypes[] { PredictionTypes.Words }, null);
_scanner = scanner;
diff --git a/src/Extensions/BCI/Actuators/BCIActuator/BCIActuator.cs b/src/Extensions/BCI/Actuators/BCIActuator/BCIActuator.cs
index dea1f592..db6f9b8d 100644
--- a/src/Extensions/BCI/Actuators/BCIActuator/BCIActuator.cs
+++ b/src/Extensions/BCI/Actuators/BCIActuator/BCIActuator.cs
@@ -1,4 +1,4 @@
-////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////
//
// Copyright 2013-2019; 2023 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
@@ -29,6 +29,7 @@
using ACAT.Extensions.BCI.Actuators.openBCISensorUI;
using ACAT.Extensions.BCI.Common.BCIControl;
using ACATResources;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
@@ -45,6 +46,8 @@ namespace ACAT.Extensions.BCI.Actuators.BCIActuator
"BCI Actuator")]
internal class BCIActuator : ActuatorBase, ISupportsPreferences
{
+ private readonly ILogger _logger;
+
///
/// The setting object for the box calibration
///
@@ -214,6 +217,7 @@ internal class BCIActuator : ActuatorBase, ISupportsPreferences
///
public BCIActuator()
{
+ _logger = LoggingConfiguration.CreateLogger();
try
{
// Load settings
@@ -249,7 +253,7 @@ public BCIActuator()
}
catch (Exception e)
{
- Log.Exception(e.Message);
+ _logger.LogError(e, "Failed to initialize BCIActuator");
}
}
@@ -273,7 +277,7 @@ private bool AreChannelsEqual(bool[] currentChannels, int[] classifierChannels)
}
catch (Exception e)
{
- Log.Exception("Exception: " + e.Message);
+ _logger.LogError(e, "Failed to compare channels");
}
return equalChannels;
}
@@ -290,7 +294,7 @@ private Dictionary GetAvailableClassifiers()
//If recheck needed, all classifiers need to be recalibrated
if (BCISettingsFixed.SignalControl_RecheckNeeded)
{
- Log.Debug("Signal recheck needed.No available classifiers");
+ _logger.LogDebug("Signal recheck needed.No available classifiers");
return availableClassifiers;
}
@@ -323,7 +327,7 @@ private Dictionary GetAvailableClassifiers()
// NOTE: Status set to Expired, in a future release a new status should be created for this condition
if (!AreChannelsEqual(currentChannels, tmpDecisionMaker.TrainedClassifiersObj.channelSubset))
{
- Log.Debug("Classifier: " + scanSection + " - Different channels than calibration. Current channels will be used in calibration.");
+ _logger.LogDebug("Classifier: " + scanSection + " - Different channels than calibration. Current channels will be used in calibration.");
classifierStatus = BCIClassifierStatus.Mismatch;
}
// Check if classifier expired
@@ -338,14 +342,14 @@ private Dictionary GetAvailableClassifiers()
// Add classifier to dictionary
BCIClassifierInfo classifierInfo = new(isRequired, scanSection, classifierStatus, auc);
availableClassifiers.Add(scanSection, classifierInfo);
- Log.Debug("Classifier: " + scanSection + " found | AUC:" + availableClassifiers[scanSection].Auc + " isRequired:" + isRequired + " Status:" + classifierStatus);
+ _logger.LogDebug("Classifier: " + scanSection + " found | AUC:" + availableClassifiers[scanSection].Auc + " isRequired:" + isRequired + " Status:" + classifierStatus);
}
}
}
}
catch (Exception e)
{
- Log.Exception(e.Message);
+ _logger.LogError(e, "Failed to get available classifiers");
}
return availableClassifiers;
}
@@ -370,11 +374,11 @@ private void LoadTypingMappings()
};
foreach (KeyValuePair mapping in DictTypingCalibrationMappings)
- Log.Debug("Typing section:" + mapping.Key + " Using classifier:" + mapping.Value);
+ _logger.LogDebug("Typing section:" + mapping.Key + " Using classifier:" + mapping.Value);
}
catch (Exception e)
{
- Log.Exception(e.Message);
+ _logger.LogError(e, "Failed to load typing mappings");
}
}
@@ -416,7 +420,7 @@ private bool LoadClassifiers()
if (File.Exists(classifierFilePath))
{
- Log.Debug("Section: " + typingMapping.Key + " | Loading classifier:" + typingMapping.Value + " from:" + classifierFilePath);
+ _logger.LogDebug("Section: " + typingMapping.Key + " | Loading classifier:" + typingMapping.Value + " from:" + classifierFilePath);
DecisionMaker tmpDecisionMaker = new(classifierFilePath);
if (tmpDecisionMaker != null && tmpDecisionMaker.TrainedClassifiersObj != null)
@@ -430,7 +434,7 @@ private bool LoadClassifiers()
{
EEGProcessingGlobals.DecisionMakerDict.Add(typingMapping.Key, tmpDecisionMaker);
- Log.Debug(typingMapping.Key.ToString() + " typing section - Using " + typingMapping.Value.ToString() + " classifier. Status: loaded");
+ _logger.LogDebug(typingMapping.Key.ToString() + " typing section - Using " + typingMapping.Value.ToString() + " classifier. Status: loaded");
var bciLogEntry = new BCILogEntryClassifierLoaded()
{
@@ -451,19 +455,19 @@ private bool LoadClassifiers()
else
{
missingClassifier = true;
- Log.Warn(typingMapping.Key.ToString() + " typing section - Using " + typingMapping.Value.ToString() + " classifier. Status: missing!!");
+ _logger.LogWarning(typingMapping.Key.ToString() + " typing section - Using " + typingMapping.Value.ToString() + " classifier. Status: missing!!");
}
}
else
{
missingClassifier = true;
- Log.Warn(typingMapping.Key.ToString() + " typing section. Classifier file not found. - Using " + typingMapping.Value.ToString() + " classifier. Status: missing!!");
+ _logger.LogWarning(typingMapping.Key.ToString() + " typing section. Classifier file not found. - Using " + typingMapping.Value.ToString() + " classifier. Status: missing!!");
}
}
}
catch (Exception e)
{
- Log.Exception(e.Message);
+ _logger.LogError(e, "Failed to load classifiers");
return false;
}
return !missingClassifier;
@@ -556,12 +560,12 @@ public override bool PostInit()
if (_daqInstance.GetType() == typeof(DAQ_gTecBCI))
{
- Log.Debug("startgTecUnicornTesting");
+ _logger.LogDebug("startgTecUnicornTesting");
TestGtecDevice();
}
else
{
- Log.Debug("startOpenBCITesting");
+ _logger.LogDebug("startOpenBCITesting");
TestBCIDevices();
}
@@ -584,7 +588,7 @@ public override bool IoctlRequest(int opcode, object request)
{
bool retVal = false;
- Log.Debug("IoctRequest received: " + (OpCodes)opcode + " | Request: " + request);
+ _logger.LogDebug("IoctRequest received: " + (OpCodes)opcode + " | Request: " + request);
switch (opcode)
{
@@ -716,7 +720,7 @@ protected override void Dispose(bool disposing)
{
try
{
- Log.Verbose();
+ _logger.LogTrace("Disposing BCIActuator resources");
if (disposing)
{
@@ -754,10 +758,10 @@ private void bciDeviceTestingCompleted()
actuatorState = (GTecDeviceTester.ExitOnboardingEarly) ? State.Stopped : State.Running;
}
- Log.Debug("\nbciDeviceTestingCompleted | actuatorState: " + actuatorState.ToString());
+ _logger.LogDebug("\nbciDeviceTestingCompleted | actuatorState: " + actuatorState.ToString());
SendIoctlResponse((int)OpCodes.CalibrationWindowClose, String.Empty);
- Log.Debug("IoctRequest " + OpCodes.CalibrationWindowClose + " sent. Message: empty");
+ _logger.LogDebug("IoctRequest " + OpCodes.CalibrationWindowClose + " sent. Message: empty");
}
///
@@ -788,13 +792,13 @@ private IActuatorSwitch find(String switchSource)
///
private void OnTriggerTestRequestParameters(object request)
{
- Log.Debug("TriggerTest parameters requested");
+ _logger.LogDebug("TriggerTest parameters requested");
// Send parameters to ACAT
var bciTriggerTestParameters = new BCITriggerTestParameters(BCIActuatorSettings.Settings.TriggerTest_NumRepetitions, BCIActuatorSettings.Settings.TriggerTest_ScanTime);
- Log.Debug(" Sending parameters. Scan time: " + bciTriggerTestParameters.ScanTime + " | Num repetitions: " + bciTriggerTestParameters.NumRepetitions);
+ _logger.LogDebug(" Sending parameters. Scan time: " + bciTriggerTestParameters.ScanTime + " | Num repetitions: " + bciTriggerTestParameters.NumRepetitions);
SendIoctlResponse((int)OpCodes.TriggerTestSendParameters, bciTriggerTestParameters);
- Log.Debug("IoctRequest " + OpCodes.TriggerTestSendParameters + " sent. Message: empty");
+ _logger.LogDebug("IoctRequest " + OpCodes.TriggerTestSendParameters + " sent. Message: empty");
}
///
@@ -803,7 +807,7 @@ private void OnTriggerTestRequestParameters(object request)
///
private void OnRequestCalibrationStatus(object request)
{
- Log.Debug("Request Calibration Status received");
+ _logger.LogDebug("Request Calibration Status received");
BCIError error;
BCIClassifierStatus overallStatus = BCIClassifierStatus.NotFound;
@@ -840,7 +844,7 @@ private void OnRequestCalibrationStatus(object request)
// Add classifier to dictionary
DictClassifierInfo.Add(calibrationSection, classifierInfo);
- Log.Warn("Calibration:" + calibrationSection + " isRequired:" + classifierInfo.IsRequired + " Status:" + classifierInfo.ClassifierStatus.ToString() + " Auc:" + classifierInfo.Auc);
+ _logger.LogDebug("Calibration:" + calibrationSection + " isRequired:" + classifierInfo.IsRequired + " Status:" + classifierInfo.ClassifierStatus.ToString() + " Auc:" + classifierInfo.Auc);
// Set overall status
if (classifierInfo.IsRequired && classifierInfo.ClassifierStatus != BCIClassifierStatus.Ok)
@@ -863,7 +867,7 @@ private void OnRequestCalibrationStatus(object request)
showOnlyDefaults = false;
}
- Log.Debug("Additional classifier:" + calibrationSection + "Set showOnlyDefaults to:" + showOnlyDefaults);
+ _logger.LogDebug("Additional classifier:" + calibrationSection + "Set showOnlyDefaults to:" + showOnlyDefaults);
}
}
error = new BCIError(BCIErrorCodes.Status_Ok, BCIMessages.Status_Ok);
@@ -871,7 +875,7 @@ private void OnRequestCalibrationStatus(object request)
catch (Exception e)
{
error = new BCIError(BCIErrorCodes.CalibrationError_LoadingClassifiers, StringResources.ClassifiersNotLoadedError);
- Log.Exception("Error " + BCIErrorCodes.CalibrationError_LoadingClassifiers.ToString() + " " + "Excepction: " + e.Message);
+ _logger.LogError(e, "Error " + BCIErrorCodes.CalibrationError_LoadingClassifiers.ToString());
}
// Set oKToGoToTyping status
@@ -879,9 +883,9 @@ private void OnRequestCalibrationStatus(object request)
// Send parameters to ACAT
var bciCalibrationStatus = new BCICalibrationStatus(showOnlyDefaults, areMoreClassifiersThanMapping, okToGoToTyping, overallStatus, DictClassifierInfo, error);
- Log.Debug("Sending Calibration Status. ShowOnlyDefaults:" + showOnlyDefaults + " | areMoreClassifiersThanMappings:" + areMoreClassifiersThanMapping + " | okToGoToTyping:" + okToGoToTyping + " | OverallStatus:" + overallStatus.ToString());
+ _logger.LogDebug("Sending Calibration Status. ShowOnlyDefaults:" + showOnlyDefaults + " | areMoreClassifiersThanMappings:" + areMoreClassifiersThanMapping + " | okToGoToTyping:" + okToGoToTyping + " | OverallStatus:" + overallStatus.ToString());
SendIoctlResponse((int)OpCodes.SendCalibrationStatus, bciCalibrationStatus);
- Log.Debug("IoctRequest: " + OpCodes.SendCalibrationStatus + " sent. Message: " + bciCalibrationStatus.ToString());
+ _logger.LogDebug("IoctRequest: " + OpCodes.SendCalibrationStatus + " sent. Message: " + bciCalibrationStatus.ToString());
}
///
@@ -890,7 +894,7 @@ private void OnRequestCalibrationStatus(object request)
///
private void OnRequestMapOptions(object request)
{
- Log.Debug("Request Map options received");
+ _logger.LogDebug("Request Map options received");
BCIError error;
@@ -946,10 +950,10 @@ private void OnRequestMapOptions(object request)
if (availableClassifiers.ContainsKey(availableClassifierForSection) && availableClassifiers[availableClassifierForSection].ClassifierStatus == BCIClassifierStatus.Ok)
{
availableClassifiersForSection.Add(availableClassifiers[availableClassifierForSection]);
- Log.Debug("Section:" + typingSection + " Available classifier:" + availableClassifierForSection + " Auc:" + availableClassifiers[availableClassifierForSection].Auc);
+ _logger.LogDebug("Section:" + typingSection + " Available classifier:" + availableClassifierForSection + " Auc:" + availableClassifiers[availableClassifierForSection].Auc);
}
else
- Log.Debug("Section:" + typingSection + " Classsifier:" + DictAllowedMappings[typingSection] + " is not available");
+ _logger.LogDebug("Section:" + typingSection + " Classsifier:" + DictAllowedMappings[typingSection] + " is not available");
}
// Add classifier found in dictionary
DictClassifierInfoForAvailableMappings.Add(typingSection, availableClassifiersForSection);
@@ -959,14 +963,14 @@ private void OnRequestMapOptions(object request)
catch (Exception e)
{
error = new BCIError(BCIErrorCodes.CalibrationError_LoadingClassifiers, StringResources.ClassifiersNotLoadedError);
- Log.Exception("Error " + BCIErrorCodes.CalibrationError_LoadingClassifiers.ToString() + " " + "Excepction: " + e.Message);
+ _logger.LogError(e, "Error " + BCIErrorCodes.CalibrationError_LoadingClassifiers.ToString());
}
// Send response to ACAT
var bciMapOptions = new BCIMapOptions(BCIActuatorSettings.Settings.Calibration_UseAdvanceModeForTypingMappings, DictClassifierInfoForAvailableMappings, DictTypingCalibrationMappings, error);
- Log.Debug("Sending map options. Is advanced: " + bciMapOptions.IsAdvanced + " | error: " + (BCIErrorCodes)error.ErrorCode);
+ _logger.LogDebug("Sending map options. Is advanced: " + bciMapOptions.IsAdvanced + " | error: " + (BCIErrorCodes)error.ErrorCode);
SendIoctlResponse((int)OpCodes.SendMapOptions, bciMapOptions);
- Log.Debug("IoctRequest " + OpCodes.SendMapOptions + " sent. Message: " + bciMapOptions.ToString());
+ _logger.LogDebug("IoctRequest " + OpCodes.SendMapOptions + " sent. Message: " + bciMapOptions.ToString());
}
///
@@ -975,7 +979,7 @@ private void OnRequestMapOptions(object request)
///
private void OnSendUpdatedMappings(object request)
{
- Log.Debug("Send Updated mappings called");
+ _logger.LogDebug("Send Updated mappings called");
try
{
var bciUpdatedMappings = request as BCICalibrationUpdatedMappings;
@@ -1008,21 +1012,21 @@ private void OnSendUpdatedMappings(object request)
TypingCalibrationMappings.KeyboardRCalibrationMapping = mappingForTypingSection.Value.ToString();
break;
}
- Log.Debug("Typing section:" + mappingForTypingSection.Key.ToString() + " Classifier used:" + mappingForTypingSection.Value.ToString());
+ _logger.LogDebug("Typing section:" + mappingForTypingSection.Key.ToString() + " Classifier used:" + mappingForTypingSection.Value.ToString());
}
// Save settings
TypingCalibrationMappings.Save();
- Log.Debug("Settings updated and saved");
+ _logger.LogDebug("Settings updated and saved");
// Reload classifiers
LoadClassifiers();
- Log.Debug("Classifiers re-loaded");
+ _logger.LogDebug("Classifiers re-loaded");
}
}
catch (Exception e)
{
- Log.Exception(e.Message);
+ _logger.LogError(e, "Failed to send updated mappings");
}
}
@@ -1032,7 +1036,7 @@ private void OnSendUpdatedMappings(object request)
///
private void OnTriggerTestSaveParameters(object request)
{
- Log.Debug("Received OnTriggerTestSaveParameters");
+ _logger.LogDebug("Received OnTriggerTestSaveParameters");
// Receive parameters from ACAT
var bciTriggerTestParameters = request as BCITriggerTestParameters;
@@ -1042,7 +1046,7 @@ private void OnTriggerTestSaveParameters(object request)
BCIActuatorSettings.Settings.TriggerTest_ScanTime = bciTriggerTestParameters.ScanTime;
BCIActuatorSettings.Settings.Save();
- Log.Debug("Eyes closed parameters (Scan time: " + BCIActuatorSettings.Settings.TriggerTest_ScanTime + " , num repetitions: " + BCIActuatorSettings.Settings.TriggerTest_NumRepetitions + ") received from ACAT and saved to BCISettings file");
+ _logger.LogDebug("Eyes closed parameters (Scan time: " + BCIActuatorSettings.Settings.TriggerTest_ScanTime + " , num repetitions: " + BCIActuatorSettings.Settings.TriggerTest_NumRepetitions + ") received from ACAT and saved to BCISettings file");
}
///
@@ -1051,15 +1055,15 @@ private void OnTriggerTestSaveParameters(object request)
///
private void OnTriggerTestStart(object request)
{
- Log.Debug("Trigger test start");
+ _logger.LogDebug("Trigger test start");
if (_daqInstance.GetType() == typeof(DAQ_OpenBCI))
{
_ = ((DAQ_OpenBCI)_daqInstance).TriggerTestStart();
}
- Log.Debug("Trigger test started");
+ _logger.LogDebug("Trigger test started");
SendIoctlResponse((int)OpCodes.TriggerTestStartReady, null);
- Log.Debug("IoctRequest " + OpCodes.TriggerTestStartReady + " sent. Message:null ");
+ _logger.LogDebug("IoctRequest " + OpCodes.TriggerTestStartReady + " sent. Message:null ");
}
///
@@ -1068,7 +1072,7 @@ private void OnTriggerTestStart(object request)
///
private void OnTriggerTestStop(object request)
{
- Log.Debug("Trigger test stop");
+ _logger.LogDebug("Trigger test stop");
BaseDAQ.ExitCodes exitCode = ((DAQ_OpenBCI)_daqInstance).TriggerTestStop(BCIActuatorSettings.Settings.TriggerTest_NumRepetitions, out _, out List dutyCycleList, out double dutyCycleAvg);
bool triggerTestSuccesful = false;
@@ -1077,9 +1081,9 @@ private void OnTriggerTestStop(object request)
// Send parameters to ACAT
var bciTriggerTest = new BCITriggerTestResult(triggerTestSuccesful, dutyCycleList, dutyCycleAvg);
- Log.Debug("Sending trigger test results. TriggerTestSuccesful: " + triggerTestSuccesful + " | dutyCycleAvg: " + dutyCycleAvg + " | dutyCycle for individual pulses: " + dutyCycleList.ToArray().ToString());
+ _logger.LogDebug("Sending trigger test results. TriggerTestSuccesful: " + triggerTestSuccesful + " | dutyCycleAvg: " + dutyCycleAvg + " | dutyCycle for individual pulses: " + dutyCycleList.ToArray().ToString());
SendIoctlResponse((int)OpCodes.TriggerTestResult, bciTriggerTest);
- Log.Debug("IoctRequest " + OpCodes.TriggerTestResult + " sent. Message: " + bciTriggerTest.ToString());
+ _logger.LogDebug("IoctRequest " + OpCodes.TriggerTestResult + " sent. Message: " + bciTriggerTest.ToString());
}
///
@@ -1088,12 +1092,12 @@ private void OnTriggerTestStop(object request)
///
private void OnCalibrationEyesClosedRequestParameters(object request)
{
- Log.Debug("Requesting calibration for eyes close parameters");
+ _logger.LogDebug("Requesting calibration for eyes close parameters");
// Send parameters to ACAT
var bciCalibrationEyesClosedParameters = new BCICalibrationEyesClosedParameters(BCIActuatorSettings.Settings.EyesClosedCalibration_NumRepetitions, BCIActuatorSettings.Settings.EyesClosedCalibration_IntervalDuration);
- Log.Debug("Sending eyes close parameters. Num repetitions: " + bciCalibrationEyesClosedParameters.NumRepetitions + " | Interval duration: " + bciCalibrationEyesClosedParameters.IntervalDuration);
+ _logger.LogDebug("Sending eyes close parameters. Num repetitions: " + bciCalibrationEyesClosedParameters.NumRepetitions + " | Interval duration: " + bciCalibrationEyesClosedParameters.IntervalDuration);
SendIoctlResponse((int)OpCodes.CalibrationEyesClosedSendParameters, bciCalibrationEyesClosedParameters);
- Log.Debug("IoctRequest " + OpCodes.CalibrationEyesClosedSendParameters + " sent. Message: " + bciCalibrationEyesClosedParameters.ToString());
+ _logger.LogDebug("IoctRequest " + OpCodes.CalibrationEyesClosedSendParameters + " sent. Message: " + bciCalibrationEyesClosedParameters.ToString());
}
///
@@ -1102,7 +1106,7 @@ private void OnCalibrationEyesClosedRequestParameters(object request)
///
private void OnCalibrationEyesClosedSaveParameters(object request)
{
- Log.Debug("Calibration eyes closed save parameters called");
+ _logger.LogDebug("Calibration eyes closed save parameters called");
// Receive parameters from ACAT
var bciCalibrationEyesClosedParameters = request as BCICalibrationEyesClosedParameters;
@@ -1112,7 +1116,7 @@ private void OnCalibrationEyesClosedSaveParameters(object request)
BCIActuatorSettings.Settings.EyesClosedCalibration_NumRepetitions = bciCalibrationEyesClosedParameters.NumRepetitions;
BCIActuatorSettings.Settings.Save();
- Log.Debug("Eyes closed parameters (Interval duration: " + BCIActuatorSettings.Settings.EyesClosedCalibration_IntervalDuration + " , num repetitions: " + BCIActuatorSettings.Settings.EyesClosedCalibration_NumRepetitions + ") received from ACAT and saved to BCISettings file");
+ _logger.LogDebug("Eyes closed parameters (Interval duration: " + BCIActuatorSettings.Settings.EyesClosedCalibration_IntervalDuration + " , num repetitions: " + BCIActuatorSettings.Settings.EyesClosedCalibration_NumRepetitions + ") received from ACAT and saved to BCISettings file");
}
///
@@ -1136,11 +1140,11 @@ private void OnCalibrationEyesClosedIterationEnd(object request)
// var bciLogEntry = new BCILogEntryEyesClosed(BCIActuatorSettings.Settings.EyesClosed_EnableDetection, 0, eyesClosedDetected, alphaValues, betaValues, avgAlpha, avgBeta, bciEyesClosedIterationEnd.BciEyesClosedMode.ToString());
// var jsonString = JsonConvert.SerializeObject(bciLogEntry);
// AuditLog.Audit(new AuditEvent("BCIEyesClosedCalibration", jsonString));
- // Log.Debug("Saved to audit file:" + jsonString);
+ // _logger.LogDebug("Saved to audit file:" + jsonString);
// }
// catch (Exception e)
// {
- // Log.Exception(e.Message);
+ // _logger.LogError(e, "Failed to process eyes closed calibration event");
// }
//}
}
@@ -1152,7 +1156,7 @@ private void OnCalibrationEyesClosedIterationEnd(object request)
private void OnCalibrationEyesClosedEnd(object request)
{
// TODO: We do not use Eyes closed detection
- //Log.Debug("Calibration eyes closed ended");
+ //_logger.LogDebug("Calibration eyes closed ended");
//if (useSensor)
//{
@@ -1167,11 +1171,11 @@ private void OnCalibrationEyesClosedEnd(object request)
// // End the esssion
// DAQ_OpenBCI.EndSession();
- // Log.Debug("Session ended");
+ // _logger.LogDebug("Session ended");
// }
// catch (Exception e)
// {
- // Log.Exception(e.Message);
+ // _logger.LogError(e, "Failed to end eyes closed calibration session");
// }
//}
}
@@ -1184,7 +1188,7 @@ private void OnCalibrationEyesClosedEnd(object request)
///
private void OnCalibrationEnd(object request)
{
- Log.Debug("Calibartion End Received");
+ _logger.LogDebug("Calibration End Received");
var bciCalibrationEnd = request as BCICalibrationEnd;
@@ -1219,18 +1223,18 @@ private void OnCalibrationEnd(object request)
if (auc * 100 >= DictCalibrationParameters[_currentCalibrationMode].MinimumScoreRequired)
calibrationSuccessful = true;
- Log.Debug("Session: " + sessionID + " Calibrated successfully: " + calibrationSuccessful + " - AUC: " + auc);
+ _logger.LogDebug("Session: " + sessionID + " Calibrated successfully: " + calibrationSuccessful + " - AUC: " + auc);
if (auc == -1)// Error when training classifiers
{
- Log.Debug("Error when training classifiers");
+ _logger.LogDebug("Error when training classifiers");
error = new BCIError(BCIErrorCodes.CalibrationError_OnAnalyzingData_TrainingClassifiersError, StringResources.CalibrationError_CalibrationFailed);
}
}
catch (Exception e)
{
auc = -1;
- Log.Exception(e.Message);
+ _logger.LogError(e, "Failed during calibration data analysis");
error = new BCIError(BCIErrorCodes.CalibrationError_OnAnalyzingData_UnknownException, StringResources.CalibrationError_CalibrationFailed);
}
}
@@ -1240,7 +1244,7 @@ private void OnCalibrationEnd(object request)
if (BCIActuatorSettings.Settings.Testing_ForceRecalibrateFromFile && BCIActuatorSettings.Settings.Testing_CalibrationFileId != null)
{
auc = RecalibrateFromFile();
- Log.Debug("Recalibrated from file. AUC: " + auc);
+ _logger.LogDebug("Recalibrated from file. AUC: " + auc);
}
calibrationSuccessful = true;
}
@@ -1249,9 +1253,9 @@ private void OnCalibrationEnd(object request)
// Send auc to ACAT
var bciCalibrationResult = new BCICalibrationResult(auc, calibrationSuccessful, error);
- Log.Debug("Sending response. Calibration result: " + calibrationSuccessful + " | AUC: " + auc);
+ _logger.LogDebug("Sending response. Calibration result: " + calibrationSuccessful + " | AUC: " + auc);
SendIoctlResponse((int)OpCodes.CalibrationResult, bciCalibrationResult);
- Log.Debug("IoctRequest " + OpCodes.CalibrationResult + " sent. Message: " + bciCalibrationResult.ToString());
+ _logger.LogDebug("IoctRequest " + OpCodes.CalibrationResult + " sent. Message: " + bciCalibrationResult.ToString());
}
///
@@ -1261,7 +1265,7 @@ private void OnCalibrationEnd(object request)
///
private void OnCalibrationEndRepetition(object request)
{
- Log.Debug("Calibration end repetition received");
+ _logger.LogDebug("Calibration end repetition received");
BCIError sensorError = new(BCIErrorCodes.Status_Ok, BCIMessages.Status_Ok);
SignalStatus statusSignal = SignalStatus.SIGNAL_KO;
@@ -1302,7 +1306,7 @@ private void OnCalibrationEndRepetition(object request)
numTriggerPulsesExpected = bciCalibrationInput.RowColumnIDs.Count;
if (numTriggerPulsesDetected == 0)
{
- Log.Debug("Optical sensor error. No pulses were detected");
+ _logger.LogDebug("Optical sensor error. No pulses were detected");
sensorError = new BCIError(BCIErrorCodes.OpticalSensorError_NoPulsesDetected, StringResources.OpticalSensorError);
}
// Note: Removed code since we can't guarantee the number of pulses received given bluetooth delays
@@ -1327,7 +1331,7 @@ private void OnCalibrationEndRepetition(object request)
};
var jsonString = bciLogEntry;
AuditLog.Audit(new AuditEvent("BCIEyesClosed", jsonString));
- Log.Debug("Line added to audit file: " + jsonString);
+ _logger.LogDebug("Line added to audit file: " + jsonString);
}
else
{
@@ -1339,7 +1343,7 @@ private void OnCalibrationEndRepetition(object request)
catch (Exception e)
{
sensorError = new BCIError(BCIErrorCodes.CalibrationError_UnknwonException, StringResources.CalibrationError_CalibrationFailed);
- Log.Exception(e.Message);
+ _logger.LogError(e, "Failed to process calibration input");
}
}
}
@@ -1347,14 +1351,14 @@ private void OnCalibrationEndRepetition(object request)
if (sensorError.ErrorCode != BCIErrorCodes.Status_Ok)
{
String txt = "Error on calibration repetition end (Error: " + sensorError.ErrorCode + " Message: " + sensorError.ErrorMessage + ") Expected pulses: " + numTriggerPulsesExpected + " - Detected pulses: " + numTriggerPulsesDetected;
- Log.Debug(txt);
+ _logger.LogDebug(txt);
}
// Send result
var bciCalibrationResult = new BCISensorStatus() { Error = sensorError, StatusSignal = statusSignal };
- Log.Debug("Sending response. SensorError:" + (BCIErrorCodes)bciCalibrationResult.Error.ErrorCode);
+ _logger.LogDebug("Sending response. SensorError:" + (BCIErrorCodes)bciCalibrationResult.Error.ErrorCode);
SendIoctlResponse((int)OpCodes.CalibrationEndRepetitionResult, bciCalibrationResult);
- Log.Debug("IoctRequest " + OpCodes.CalibrationEndRepetitionResult + " sent. Message: " + bciCalibrationResult.ToString());
+ _logger.LogDebug("IoctRequest " + OpCodes.CalibrationEndRepetitionResult + " sent. Message: " + bciCalibrationResult.ToString());
}
///
@@ -1374,7 +1378,7 @@ private void OnHighlightOnOff(object request)
///
private void OnLanguageModelProbabilities(object request)
{
- Log.Debug("Language model probabilities received");
+ _logger.LogDebug("Language model probabilities received");
var bciLanguageModelProbabilities = request as BCILanguageModelProbabilities;
bool enableLanguageModelprobabilities = false;
@@ -1383,7 +1387,7 @@ private void OnLanguageModelProbabilities(object request)
epochIdx++;
// Restart classifiers (nextcharacterprobs = clear talk window, resume after pause, etc)
- Log.Debug("Restarting all probabilities");
+ _logger.LogDebug("Restarting all probabilities");
EEGProcessingGlobals.RestartAllDecisionMakerProbabilities();
// Add next character probabilities (flag will be turn on/off if they shouldn't be
@@ -1414,11 +1418,11 @@ private void OnLanguageModelProbabilities(object request)
{
EEGProcessingGlobals.DecisionMakerDict[currentSection].AddNextCharacterProbabilities(bciLanguageModelProbabilities.LanguageModelProbabilities);
EEGProcessingGlobals.DecisionMakerDict[currentSection].enableLanguageModelProbabilities = enableLanguageModelprobabilities;
- Log.Debug("Probabilities for " + currentSection + " added to. Use LM for section: " + enableLanguageModelprobabilities);
+ _logger.LogDebug("Probabilities for " + currentSection + " added to. Use LM for section: " + enableLanguageModelprobabilities);
}
else
{
- Log.Debug("Probabilities not added");
+ _logger.LogDebug("Probabilities not added");
}
}
@@ -1431,7 +1435,7 @@ private void OnLanguageModelProbabilities(object request)
};
var jsonString = bciLogEntry;
AuditLog.Audit(new AuditEvent("BCILanguageModelProbabilitiesReceived", jsonString));
- Log.Debug("Line added to audit file: " + jsonString);
+ _logger.LogDebug("Line added to audit file: " + jsonString);
}
///
@@ -1472,7 +1476,7 @@ private void OnRequestParameters(object request)
BCIError error = new(BCIErrorCodes.Status_Ok, BCIMessages.Status_Ok);
var bciUserInputParameters = request as BCIUserInputParameters;
- Log.Debug("Request parameters for mode " + bciUserInputParameters.BciMode);
+ _logger.LogDebug("Request parameters for mode " + bciUserInputParameters.BciMode);
switch (bciUserInputParameters.BciMode)
{
@@ -1483,7 +1487,7 @@ private void OnRequestParameters(object request)
break;
case BCIModes.CALIBRATION:
- Log.Debug("Calibration mode: " + bciUserInputParameters.BciCalibrationMode + " Scan time: " + bciUserInputParameters.ScanTime + " | Number of targets: " + bciUserInputParameters.NumTargets + " | Number of iterations per target: " + bciUserInputParameters.NumIterationsPerTarget + " | Minimum score required: " + bciUserInputParameters.MinScoreRequired);
+ _logger.LogDebug("Calibration mode: " + bciUserInputParameters.BciCalibrationMode + " Scan time: " + bciUserInputParameters.ScanTime + " | Number of targets: " + bciUserInputParameters.NumTargets + " | Number of iterations per target: " + bciUserInputParameters.NumIterationsPerTarget + " | Minimum score required: " + bciUserInputParameters.MinScoreRequired);
// Update settings for the corresponding section from parameters sent from ACAT
switch (bciUserInputParameters.BciCalibrationMode)
@@ -1494,7 +1498,7 @@ private void OnRequestParameters(object request)
BoxCalibrationSettings.NumberOfIterationsPerTarget = bciUserInputParameters.NumIterationsPerTarget;
BoxCalibrationSettings.MinimumScoreRequired = bciUserInputParameters.MinScoreRequired;
BoxCalibrationSettings.Save();
- Log.Debug("Parameters saved for box calibration");
+ _logger.LogDebug("Parameters saved for box calibration");
break;
case BCIScanSections.Word:
@@ -1503,7 +1507,7 @@ private void OnRequestParameters(object request)
WordCalibrationSettings.NumberOfIterationsPerTarget = bciUserInputParameters.NumIterationsPerTarget;
WordCalibrationSettings.MinimumScoreRequired = bciUserInputParameters.MinScoreRequired;
WordCalibrationSettings.Save();
- Log.Debug("Parameters saved for calibration");
+ _logger.LogDebug("Parameters saved for calibration");
break;
case BCIScanSections.Sentence:
@@ -1512,7 +1516,7 @@ private void OnRequestParameters(object request)
SentenceCalibrationSettings.NumberOfIterationsPerTarget = bciUserInputParameters.NumIterationsPerTarget;
SentenceCalibrationSettings.MinimumScoreRequired = bciUserInputParameters.MinScoreRequired;
SentenceCalibrationSettings.Save();
- Log.Debug("Parameters saved for sentence calibration");
+ _logger.LogDebug("Parameters saved for sentence calibration");
break;
case BCIScanSections.KeyboardL:
@@ -1521,7 +1525,7 @@ private void OnRequestParameters(object request)
KeyboardLeftCalibrationSettings.NumberOfIterationsPerTarget = bciUserInputParameters.NumIterationsPerTarget;
KeyboardLeftCalibrationSettings.MinimumScoreRequired = bciUserInputParameters.MinScoreRequired;
KeyboardLeftCalibrationSettings.Save();
- Log.Debug("Parameters saved for keyboard Left calibration");
+ _logger.LogDebug("Parameters saved for keyboard Left calibration");
break;
case BCIScanSections.KeyboardR:
@@ -1530,7 +1534,7 @@ private void OnRequestParameters(object request)
KeyboardRightCalibrationSettings.NumberOfIterationsPerTarget = bciUserInputParameters.NumIterationsPerTarget;
KeyboardRightCalibrationSettings.MinimumScoreRequired = bciUserInputParameters.MinScoreRequired;
KeyboardRightCalibrationSettings.Save();
- Log.Debug("Paramters saved for keyboard right calibration");
+ _logger.LogDebug("Parameters saved for keyboard right calibration");
break;
}
@@ -1539,15 +1543,15 @@ private void OnRequestParameters(object request)
DictCalibrationParameters[bciUserInputParameters.BciCalibrationMode].TargetCount = bciUserInputParameters.NumTargets;
DictCalibrationParameters[bciUserInputParameters.BciCalibrationMode].IterationsPerTarget = bciUserInputParameters.NumIterationsPerTarget;
DictCalibrationParameters[bciUserInputParameters.BciCalibrationMode].MinimumScoreRequired = bciUserInputParameters.MinScoreRequired;
- Log.Debug("Parameters updated in the " + bciUserInputParameters.BciCalibrationMode + " dictionary");
+ _logger.LogDebug("Parameters updated in the " + bciUserInputParameters.BciCalibrationMode + " dictionary");
break;
}
// Send parameters to ACAT
var bciParameters = new BCIParameters(DictCalibrationParameters, recalibrationRequired, lastCalibrationAUC, BCIActuatorSettings.Settings.Scanning_PauseTime, BCIActuatorSettings.Settings.Scanning_ShortPauseTime, BCIActuatorSettings.Settings.Scanning_ShowDecisionTime, BCIActuatorSettings.Settings.Scanning_DelayAfterDecision, BCIActuatorSettings.Settings.Scanning_DelayToGetReady, BCIActuatorSettings.Settings.Testing_MinimumProbabiltyToDisplayBarOnTyping, BCIActuatorSettings.Settings.Scanning_FocalCircleColor, BCIActuatorSettings.Settings.Scanning_IsFocalCircleFilled, error);
- Log.Debug("Sending parameters. Error:" + (BCIErrorCodes)bciParameters.Error.ErrorCode + " RecalibrationRequired:" + bciParameters.CalibrationRequiredFlag + " | Pause time:" + bciParameters.Scanning_PauseTime + ", Short pause time:" + bciParameters.Scanning_ShortPauseTime + ", Show decision time: " + bciParameters.Scanning_ShowDecisionTime + ", Delay after decision:" + bciParameters.Scanning_DelayAfterDecision + ", Minimum probability to display bars on typing:" + bciParameters.MinProbablityToDisplayBarOnTyping);
+ _logger.LogDebug("Sending parameters. Error:" + (BCIErrorCodes)bciParameters.Error.ErrorCode + " RecalibrationRequired:" + bciParameters.CalibrationRequiredFlag + " | Pause time:" + bciParameters.Scanning_PauseTime + ", Short pause time:" + bciParameters.Scanning_ShortPauseTime + ", Show decision time: " + bciParameters.Scanning_ShowDecisionTime + ", Delay after decision:" + bciParameters.Scanning_DelayAfterDecision + ", Minimum probability to display bars on typing:" + bciParameters.MinProbablityToDisplayBarOnTyping);
SendIoctlResponse((int)OpCodes.SendParameters, bciParameters);
- Log.Debug("IoctRequest " + OpCodes.SendParameters);
+ _logger.LogDebug("IoctRequest " + OpCodes.SendParameters);
}
///
@@ -1567,7 +1571,7 @@ private void OnSessionStart(object request)
if (bciModeObj != null)
{
- Log.Debug("Start session: " + bciModeObj.BciMode);
+ _logger.LogDebug("Start session: " + bciModeObj.BciMode);
if (useSensor)
{
@@ -1597,9 +1601,9 @@ private void OnSessionStart(object request)
// For Debugging / Testing: calibrate from old file when selected from settings
if (BCIActuatorSettings.Settings.Testing_ForceRecalibrateFromFile && BCIActuatorSettings.Settings.Testing_CalibrationFileId != null)
{
- Log.Debug("Recalibrating from file");
+ _logger.LogDebug("Recalibrating from file");
float auc = RecalibrateFromFile();
- Log.Debug("Recalibrated from file. AUC: " + auc);
+ _logger.LogDebug("Recalibrated from file. AUC: " + auc);
}
if (!LoadClassifiers())
@@ -1617,7 +1621,7 @@ private void OnSessionStart(object request)
}
// Start session
- Log.Debug("Starting session: " + sessionID);
+ _logger.LogDebug("Starting session: " + sessionID);
sensorReady = _daqInstance.StartSession(sessionID, true);
sessionDirectory = _daqInstance.GetSessionDirectory();
_isSessionInProgress = false; // set to true on calibrationEndRepetition and TypingEndRepetition
@@ -1628,11 +1632,11 @@ private void OnSessionStart(object request)
{
filePathCopyTo = Path.Combine(sessionDirectory, fileName);
filePathCopyFrom = UserManager.GetFullPath(fileName);
- Log.Debug("Copying files from: " + filePathCopyFrom + " to " + filePathCopyTo);
+ _logger.LogDebug("Copying files from: " + filePathCopyFrom + " to " + filePathCopyTo);
if (!String.IsNullOrEmpty(filePathCopyTo) && !String.IsNullOrEmpty(filePathCopyFrom) && File.Exists(filePathCopyFrom) && Directory.Exists(sessionDirectory))
{
File.Copy(filePathCopyFrom, filePathCopyTo);
- Log.Debug("FIles copied from: " + filePathCopyFrom + " to " + filePathCopyTo);
+ _logger.LogDebug("Files copied from: " + filePathCopyFrom + " to " + filePathCopyTo);
}
}
}
@@ -1655,13 +1659,13 @@ private void OnSessionStart(object request)
SessionId = sessionID,
Error = error
};
- Log.Debug("Sending response. Error: " + (BCIErrorCodes)error.ErrorCode + " Sensor ready: " + bciStartSessionResults.SensorReady + " | session ID: " + sessionID + " | directory: " + sessionDirectory);
+ _logger.LogDebug("Sending response. Error: " + (BCIErrorCodes)error.ErrorCode + " Sensor ready: " + bciStartSessionResults.SensorReady + " | session ID: " + sessionID + " | directory: " + sessionDirectory);
SendIoctlResponse((int)OpCodes.StartSessionResult, bciStartSessionResults);
- Log.Debug("IoctRequest " + OpCodes.StartSessionResult + " sent. Message: " + bciStartSessionResults.ToString());
+ _logger.LogDebug("IoctRequest " + OpCodes.StartSessionResult + " sent. Message: " + bciStartSessionResults.ToString());
}
catch (Exception e)
{
- Log.Exception(e.Message);
+ _logger.LogError(e, "Failed to start session");
}
}
@@ -1683,7 +1687,7 @@ private float RecalibrateFromFile()
if (idxCalibrationType != -1)
{
string calibrationType = sessionID.Substring(idxCalibrationType + strToFind.Length);
- Log.Debug("Recalibrating from file " + sessionID + " | Test ID: " + BCIActuatorSettings.Settings.Testing_TestID + " | Calibration type:" + calibrationType);
+ _logger.LogDebug("Recalibrating from file " + sessionID + " | Test ID: " + BCIActuatorSettings.Settings.Testing_TestID + " | Calibration type:" + calibrationType);
FeatureExtractionObj = calibrationType.ToLower() switch
{
@@ -1708,14 +1712,14 @@ private float RecalibrateFromFile()
};
}
- Log.Debug(" Recalibrating file " + sessionID);
+ _logger.LogDebug(" Recalibrating file " + sessionID);
// Train classifiers
auc = FeatureExtractionObj.Learn(sessionID); // will return -1 if error when training classifiers
- Log.Debug("Recalibrated with AUC: " + auc);
+ _logger.LogDebug("Recalibrated with AUC: " + auc);
}
catch (Exception e)
{
- Log.Exception(e.Message);
+ _logger.LogError(e, "Failed to recalibrate from file");
}
return auc;
}
@@ -1741,7 +1745,7 @@ private void OnToggleCalibrationWindow()
/*if (!IsSignalFormVisible())
{*/
SendIoctlResponse((int)OpCodes.CalibrationWindowPreShow, String.Empty);
- Log.Debug("IoctRequest " + OpCodes.CalibrationWindowPreShow + " sent. Message: empty");
+ _logger.LogDebug("IoctRequest " + OpCodes.CalibrationWindowPreShow + " sent. Message: empty");
//}
}
@@ -1772,7 +1776,7 @@ private void OnTypingRepetitionEnd(object request)
var bciTypingRepetitionEnd = request as BCITypingRepetitionEnd;
BCIScanSections currentScanSection = bciTypingRepetitionEnd.ScanningSection;
- Log.Debug("On typing Repetition end called for section: " + bciTypingRepetitionEnd.ScanningSection);
+ _logger.LogDebug("On typing Repetition end called for section: " + bciTypingRepetitionEnd.ScanningSection);
if (useSensor)
{
@@ -1850,7 +1854,7 @@ private void OnTypingRepetitionEnd(object request)
if (BCIActuatorSettings.Settings.EyesClosed_EnableDetection)
{
- Log.Debug("Eyes closed detected");
+ _logger.LogDebug("Eyes closed detected");
returnToBoxScanningFlag = eyesClosedDetected;
if (eyesClosedDetected)
{
@@ -1866,7 +1870,7 @@ private void OnTypingRepetitionEnd(object request)
// Reduce and compute posterior probabilities
decidedButtonID = 0;
decidedFlag = false;
- Log.Debug("Calculating posterior probabilities");
+ _logger.LogDebug("Calculating posterior probabilities");
EEGProcessingGlobals.DecisionMakerDict[currentScanSection].ComputePosteriorProbs(allSamples,
bciTypingRepetitionEnd.RowColumnIDs,
bciTypingRepetitionEnd.FlashingSequence,
@@ -1895,15 +1899,15 @@ private void OnTypingRepetitionEnd(object request)
if (posteriorProbs == null || posteriorProbs.Count == 0)
{
//error = new BCIError(BCIErrorCodes.TypingError_OnRepetitionEnd_NoProbabilitiesCalculated, BCIMessages.TypingError); // no probabilities returned. optical sensor dead?
- Log.Debug("Probabilities not returned from DeicisionMaker");
+ _logger.LogDebug("Probabilities not returned from DeicisionMaker");
}
else if (posteriorProbs.Count != buttonIds.Count)
{
// error = new BCIError(BCIErrorCodes.TypingError_OnRepetitionEnd_ProabilitiesMarkersMissmatch, BCIMessages.TypingError);
- Log.Debug("Number of probabilities different than number of highlights. Num buttons: " + buttonIds.Count + " Num Probabilities: " + posteriorProbs.Count);
+ _logger.LogDebug("Number of probabilities different than number of highlights. Num buttons: " + buttonIds.Count + " Num Probabilities: " + posteriorProbs.Count);
}
- Log.Debug("Posterior probabilities calculated. Repetition: " + repetition + " Decided:" + decidedFlag + " DecisionLabel:" + decidedButtonLabel + " DecisionID: " + decidedButtonID + " Probabilities" + eegProbs.ToString());
+ _logger.LogDebug("Posterior probabilities calculated. Repetition: " + repetition + " Decided:" + decidedFlag + " DecisionLabel:" + decidedButtonLabel + " DecisionID: " + decidedButtonID + " Probabilities" + eegProbs.ToString());
}
}
else
@@ -1919,12 +1923,12 @@ private void OnTypingRepetitionEnd(object request)
catch (Exception e)
{
error = new BCIError(BCIErrorCodes.TypingError_OnRepetitionEnd_UnknownException, StringResources.TypingError);// Error when processing data
- Log.Exception("Error: " + error.ErrorCode + " Message" + error.ErrorMessage + " Excepcion: " + e.Message);
+ _logger.LogError(e, "Error: " + error.ErrorCode + " Message" + error.ErrorMessage);
}
// Display error on logs
if (error.ErrorCode != BCIErrorCodes.Status_Ok)
- Log.Exception("Error: " + error.ErrorCode + " Message" + error.ErrorMessage);
+ _logger.LogError("Error: {ErrorCode} Message: {ErrorMessage}", error.ErrorCode, error.ErrorMessage);
}
else
{
@@ -2017,7 +2021,7 @@ private void OnTypingRepetitionEnd(object request)
};
var jsonString = bciLogEntry;
AuditLog.Audit(new AuditEvent("BCIRepetitionEnd", jsonString));
- Log.Debug("Results: " + jsonString);
+ _logger.LogDebug("Results: " + jsonString);
// Send results to application
var bciTypingRepetitionResult = new BCITypingRepetitionResult
@@ -2032,9 +2036,9 @@ private void OnTypingRepetitionEnd(object request)
if (posteriorProbs != null)
bciTypingRepetitionResult.PosteriorProbs = posteriorProbs;
- Log.Debug("Sending response. Error: " + (BCIErrorCodes)error.ErrorCode + " | Decided:" + decidedFlag + "DecidedID:" + decidedButtonID + " ReturnToBoxScanning:" + returnToBoxScanningFlag + " StatusSignal: " + statusSignal);
+ _logger.LogDebug("Sending response. Error: " + (BCIErrorCodes)error.ErrorCode + " | Decided:" + decidedFlag + "DecidedID:" + decidedButtonID + " ReturnToBoxScanning:" + returnToBoxScanningFlag + " StatusSignal: " + statusSignal);
SendIoctlResponse((int)OpCodes.TypingEndRepetitionResult, bciTypingRepetitionResult);
- Log.Debug("IoctRequest " + OpCodes.TypingEndRepetitionResult + " sent. Message: " + bciTypingRepetitionResult.ToString());
+ _logger.LogDebug("IoctRequest " + OpCodes.TypingEndRepetitionResult + " sent. Message: " + bciTypingRepetitionResult.ToString());
}
///
@@ -2103,7 +2107,7 @@ private void TestBCIDevices()
private void TestGtecDevice()
{
- _gtecDeviceTester = new GTecDeviceTester();
+ _gtecDeviceTester = new GTecDeviceTester(null);
_gtecDeviceTester.EvtBCIDeviceTestingCompleted += bciDeviceTestingCompleted;
_gtecDeviceTester.initialize();
}
@@ -2124,7 +2128,7 @@ private void unInit()
}
///
- /// Show disclamer
+ /// Show disclaimer
///
private void showDisclaimer()
{
diff --git a/src/Extensions/BCI/Actuators/BCIActuator/BCIActuatorSwitch.cs b/src/Extensions/BCI/Actuators/BCIActuator/BCIActuatorSwitch.cs
index 9b8c0488..8a3b0e6b 100644
--- a/src/Extensions/BCI/Actuators/BCIActuator/BCIActuatorSwitch.cs
+++ b/src/Extensions/BCI/Actuators/BCIActuator/BCIActuatorSwitch.cs
@@ -64,8 +64,6 @@ protected override void Dispose(bool disposing)
{
try
{
- Log.Verbose();
-
if (disposing)
{
// release managed resources
diff --git a/src/Extensions/BCI/Actuators/EEGDataAcquisition/BaseDAQ.cs b/src/Extensions/BCI/Actuators/EEGDataAcquisition/BaseDAQ.cs
index 53f7fba3..86bf3dfb 100644
--- a/src/Extensions/BCI/Actuators/EEGDataAcquisition/BaseDAQ.cs
+++ b/src/Extensions/BCI/Actuators/EEGDataAcquisition/BaseDAQ.cs
@@ -19,6 +19,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
+using Microsoft.Extensions.Logging;
namespace ACAT.Extensions.BCI.Actuators.EEG.EEGDataAcquisition
{
@@ -27,6 +28,8 @@ namespace ACAT.Extensions.BCI.Actuators.EEG.EEGDataAcquisition
///
public abstract class BaseDAQ
{
+ protected static ILogger _logger;
+
///
/// Settings file name
///
@@ -313,7 +316,7 @@ public virtual bool StartSession(string sessionID, bool forceSavingData)
if (saveDataToFile)
{
- Log.Debug("Creating files for session: " + sessionID);
+ _logger?.LogDebug("Creating files for session: {SessionID}", sessionID);
// Creates new file
if (sessionID == "")
@@ -329,7 +332,7 @@ public virtual bool StartSession(string sessionID, bool forceSavingData)
}
catch (Exception e)
{
- Log.Exception("Exception " + e.Message);
+ _logger?.LogError(e, "Exception starting session");
}
return result;
}
@@ -352,12 +355,12 @@ public virtual bool EndSession()
{
GetData(); // Empty buffer
}
- Log.Debug("Session closed");
+ _logger?.LogDebug("Session closed");
result = true;
}
catch (Exception e)
{
- Log.Exception("Exception " + e.Message);
+ _logger?.LogError(e, "Exception ending session");
}
return result;
@@ -398,7 +401,7 @@ protected virtual bool AppendDataToBuffer(double[,] data, double[,] inBuffer, in
}
catch (Exception e)
{
- Log.Exception(e.Message);
+ _logger?.LogError(e, "Exception appending data to buffer");
}
return result;
}
@@ -413,7 +416,7 @@ protected virtual void CreateFiles(string sessionID)
{
if (FileWriterObj == null)
{
- Log.Debug("Creating files for session: " + sessionID);
+ _logger?.LogDebug("Creating files for session: {SessionID}", sessionID);
if (sessionID == "")
FileWriterObj = new FileWriter();
@@ -433,12 +436,12 @@ public virtual void Config_Board(string cmd)
{
try
{
- Log.Debug("Config board. Command: " + cmd);
+ _logger?.LogDebug("Config board. Command: {Command}", cmd);
DeviceObj.config_board(cmd);
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger?.LogError(ex, "Exception configuring board");
}
}
}
diff --git a/src/Extensions/BCI/Actuators/EEGDataAcquisition/DAQ_OpenBCI.cs b/src/Extensions/BCI/Actuators/EEGDataAcquisition/DAQ_OpenBCI.cs
index 2726d2b3..b2636837 100644
--- a/src/Extensions/BCI/Actuators/EEGDataAcquisition/DAQ_OpenBCI.cs
+++ b/src/Extensions/BCI/Actuators/EEGDataAcquisition/DAQ_OpenBCI.cs
@@ -17,9 +17,11 @@
using ACAT.Extensions.BCI.Common.BCIControl;
using Accord.Math;
using brainflow;
+using Microsoft.Extensions.Logging;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
+using System.Configuration;
using System.IO.Ports;
using System.Linq;
using System.Threading;
@@ -28,6 +30,8 @@ namespace ACAT.Extensions.BCI.Actuators.EEG.EEGDataAcquisition
{
public class DAQ_OpenBCI : BaseDAQ
{
+ private new readonly ILogger _logger;
+
// ********** Params set here (not read from settings)
// private readonly string[] otherChannelsPinsNameList = { "x", "D11", "D12", "D13", "D17", "D18", "x" };
// private readonly int[] otherChannelsPinsIdxList = {12, 13, 14, 15, 16, 17, 18}; this is returnet when DeviceObj.get_other_channels();
@@ -56,17 +60,17 @@ public class DAQ_OpenBCI : BaseDAQ
///
/// Status of the board
///
- private BoardStatus status;
+ private new BoardStatus status;
///
/// Boolean, true if device initialized
///
- public bool deviceInitialized = false;
+ public new bool deviceInitialized = false;
///
/// Buffer to store data and calculate signal stauts
///
- private double[,] _bufferSignalStatus;
+ private new double[,] _bufferSignalStatus;
///
/// Buffer to store data for eyes closed detection
@@ -77,16 +81,16 @@ public class DAQ_OpenBCI : BaseDAQ
/// Index of the EEG channels in data returned from sensor
/// This is directly via from brainflow
///
- public int[] indEegChannels;
+ public new int[] indEegChannels;
- public enum DeviceStatus
+ public new enum DeviceStatus
{
DEVICE_STANDBY,
DEVICE_ERROR,
DEVICE_ACQUIRINGDATA,
};
- public DeviceStatus deviceStatus;
+ public new DeviceStatus deviceStatus;
// BoardStatus enum is now inherited from BaseDAQ
@@ -105,13 +109,21 @@ public enum DaisyBoardStatus
// ExitCodes enum is now inherited from BaseDAQ
+ ///
+ /// Initializes an instance of the class
+ ///
+ public DAQ_OpenBCI()
+ {
+ _logger = LoggingConfiguration.CreateLogger();
+ }
+
///
/// Loads settings from the configuration file
///
public override void LoadSettings()
{
SignalControl_WindowDurationForVrmsMeaseurment = BCIActuatorSettings.Settings.SignalControl_WindowDurationForVrmsMeaseurment;
- Log.Debug("DAQ settings loaded. Window duration for uVrmsMeasurement: " + SignalControl_WindowDurationForVrmsMeaseurment);
+ _logger.LogDebug("DAQ settings loaded. Window duration for uVrmsMeasurement: " + SignalControl_WindowDurationForVrmsMeaseurment);
switch (BCIActuatorSettings.Settings.DAQ_NumEEGChannels)
{
@@ -135,19 +147,19 @@ public override void LoadSettings()
BCISettingsFixed.DataParser_IdxTriggerSignal_Hw = 16;
BCISettingsFixed.DataParser_IdxTriggerSignal_Sw = 24;
BCISettingsFixed.DimReduct_DownsampleRate = 2;
- Log.Debug("Num Channels settings is incorrect. Sensor set to default: 8 channels");
+ _logger.LogDebug("Num Channels settings is incorrect. Sensor set to default: 8 channels");
break;
}
BCIActuatorSettings.Save();
- Log.Debug("Sensor set to " + BCIActuatorSettings.Settings.DAQ_NumEEGChannels + " channels. SensorID: " + BCISettingsFixed.DAQ_SensorId + " , Downsample rate: " + BCISettingsFixed.DimReduct_DownsampleRate +
+ _logger.LogDebug("Sensor set to " + BCIActuatorSettings.Settings.DAQ_NumEEGChannels + " channels. SensorID: " + BCISettingsFixed.DAQ_SensorId + " , Downsample rate: " + BCISettingsFixed.DimReduct_DownsampleRate +
" , Idx hw trigger signal: " + BCISettingsFixed.DataParser_IdxTriggerSignal_Hw + " , Idx sw trigger signal: " + BCISettingsFixed.DataParser_IdxTriggerSignal_Sw);
boardID = BCISettingsFixed.DAQ_SensorId;
saveDataToFile = BCIActuatorSettings.Settings.DAQ_SaveToFileFlag;
frontendFilterIdx = BCIActuatorSettings.Settings.DAQ_FrontendFilterIdx;
notchFilterIdx = BCIActuatorSettings.Settings.DAQ_NotchFilterIdx;
- Log.Debug(" Frontend filter: " + frontendFilterIdx + " Notch filter: " + notchFilterIdx);
+ _logger.LogDebug(" Frontend filter: " + frontendFilterIdx + " Notch filter: " + notchFilterIdx);
eyesClosedDetectionUseFixThreshold = BCIActuatorSettings.Settings.EyesClosed_UseFixThreshold;
if (eyesClosedDetectionUseFixThreshold)
@@ -155,7 +167,7 @@ public override void LoadSettings()
else
eyesClosedDetectionThreshold = BCIActuatorSettings.Settings.EyesClosed_AdaptiveThreshold;
eyesClosed_WindowDuration = BCIActuatorSettings.Settings.EyesClosed_WindowDuration;
- Log.Debug("Eyes closed detection. Use Fix Threshold" + eyesClosedDetectionUseFixThreshold + " Threshold: " + eyesClosedDetectionThreshold + " Window duration: " + eyesClosed_WindowDuration);
+ _logger.LogDebug("Eyes closed detection. Use Fix Threshold" + eyesClosedDetectionUseFixThreshold + " Threshold: " + eyesClosedDetectionThreshold + " Window duration: " + eyesClosed_WindowDuration);
}
#region Get/set
@@ -221,13 +233,13 @@ public String DetectPort()
foreach (String port in SerialPort.GetPortNames())
{
- Log.Debug("Checking port " + port);
+ _logger.LogDebug("Checking port " + port);
serialPort = port;
AddWarning(ExitCodes.IDLE, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " TESTING PORT MESSAGE: Serial port " + serialPort);
if (TestPort(port, out _))
{
- Log.Debug("Detected cytonboard port " + port);
+ _logger.LogDebug("Detected cytonboard port " + port);
return serialPort;
}
}
@@ -298,13 +310,13 @@ public override bool InitDevice(string deviceIdentifier)
{
if (status == BoardStatus.BOARD_OPEN)
{
- Log.Debug("Board was open, closing device");
+ _logger.LogDebug("Board was open, closing device");
CloseDevice();
}
if (status == BoardStatus.BOARD_ACQUIRINGDATA)
{
- Log.Debug("Board already acquiring data, returning");
+ _logger.LogDebug("Board already acquiring data, returning");
return true;
}
else
@@ -314,13 +326,13 @@ public override bool InitDevice(string deviceIdentifier)
// Enable /disable boardlogging
if (boardLoggerEnabled)
{
- Log.Debug("BoardLoggerEnabled: " + boardLoggerEnabled + " Enabling brainflow logging");
+ _logger.LogDebug("BoardLoggerEnabled: " + boardLoggerEnabled + " Enabling brainflow logging");
BoardShim.enable_dev_board_logger();
BoardShim.set_log_file(boardLogFileName);
}
else
{
- Log.Debug("BoardLoggerEnabled: " + boardLoggerEnabled + " Disabling brainflow logging");
+ _logger.LogDebug("BoardLoggerEnabled: " + boardLoggerEnabled + " Disabling brainflow logging");
BoardShim.disable_board_logger();
}
@@ -331,22 +343,22 @@ public override bool InitDevice(string deviceIdentifier)
}
// Test port
- Log.Debug("Testing port: " + port);
+ _logger.LogDebug("Testing port: " + port);
bool sensorConnected = TestPort(port, out _);
if (!sensorConnected)
{
- Log.Debug("Sensor not connected to port " + port + ". Starting port detection");
+ _logger.LogDebug("Sensor not connected to port " + port + ". Starting port detection");
port = DetectPort();
- Log.Debug("Port " + port + " detected. Testing port");
+ _logger.LogDebug("Port " + port + " detected. Testing port");
sensorConnected = TestPort(port, out _);
- Log.Debug("Port " + port + " tested. Result: " + sensorConnected);
+ _logger.LogDebug("Port " + port + " tested. Result: " + sensorConnected);
}
BrainFlowInputParams input_params = new();
if (sensorConnected)
{
- Log.Debug("Sensor connected to port " + port);
+ _logger.LogDebug("Sensor connected to port " + port);
// Save port
serialPort = port;
@@ -354,7 +366,7 @@ public override bool InitDevice(string deviceIdentifier)
// Save port to settings
BCIActuatorSettings.Settings.DAQ_ComPort = serialPort;
BCIActuatorSettings.Save();
- Log.Debug("Port: " + serialPort + " saved to settings");
+ _logger.LogDebug("Port: " + serialPort + " saved to settings");
// Check if Cyton Daisy board attached
// Makes separate COM connection (BrainFlow / BoardShim does not allow parsing of responses from lower level commands
@@ -375,7 +387,7 @@ public override bool InitDevice(string deviceIdentifier)
DeviceObj = new BoardShim(boardID, input_params);
DeviceObj.prepare_session();
- Log.Debug("DAQ_OpenBCI - InitDevice | Board session prepared");
+ _logger.LogDebug("DAQ_OpenBCI - InitDevice | Board session prepared");
indEegChannels = BoardShim.get_eeg_channels(boardID);
sampleRate = BoardShim.get_sampling_rate(boardID);
@@ -385,12 +397,12 @@ public override bool InitDevice(string deviceIdentifier)
FrontendFilter = new Filter(frontendFilterIdx, Filter.FilterTypes.Frontend);
NotchFilter = new Filter(notchFilterIdx, Filter.FilterTypes.Notch);
- Log.Debug("Creating Frontend filter: " + frontendFilterIdx + " | Notch filter: " + notchFilterIdx);
+ _logger.LogDebug("Creating Frontend filter: " + frontendFilterIdx + " | Notch filter: " + notchFilterIdx);
status = BoardStatus.BOARD_OPEN;
deviceInitialized = true;
AddWarning(ExitCodes.IDLE, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " STATUS MESSAGE: Device initialized at serial port: " + serialPort);
- Log.Debug("Board initialized. Status: " + status.ToString());
+ _logger.LogDebug("Board initialized. Status: " + status.ToString());
return true;
}
else
@@ -399,7 +411,7 @@ public override bool InitDevice(string deviceIdentifier)
}
catch (Exception e)
{
- Log.Exception(e.Message);
+ _logger.LogError(e, e.Message);
sensorStatus = getErrorCode(e.Message, ExitCodes.BOARD_NOT_READY_ERROR);
AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus);
return false;
@@ -422,7 +434,7 @@ public override bool Start(string deviceIdentifier = "", bool saveData = false,
{
// Init device
bool initPortSuccess;
- Log.Debug("Initiating device");
+ _logger.LogDebug("Initiating device");
if (status != BoardStatus.BOARD_OPEN)
{
if (!String.IsNullOrWhiteSpace(deviceIdentifier))
@@ -433,15 +445,15 @@ public override bool Start(string deviceIdentifier = "", bool saveData = false,
else
initPortSuccess = true;
- Log.Debug("Starting stream");
+ _logger.LogDebug("Starting stream");
DeviceObj.start_stream();
- Log.Debug("Stream started");
+ _logger.LogDebug("Stream started");
status = BoardStatus.BOARD_ACQUIRINGDATA;
if (saveDataToFile)
{
- Log.Debug("Creating files for session " + sessionID);
+ _logger.LogDebug("Creating files for session " + sessionID);
CreateFiles(sessionID);
}
@@ -455,10 +467,10 @@ public override bool Start(string deviceIdentifier = "", bool saveData = false,
{
sensorStatus = getErrorCode(e.Message, ExitCodes.BOARD_NOT_CREATED_ERROR);
AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus);
- Log.Exception("Exception:" + e.Message + " Error code:" + sensorStatus);
+ _logger.LogError("Exception:" + e.Message + " Error code:" + sensorStatus);
success = false;
}
- Log.Debug("Device started: " + success);
+ _logger.LogDebug("Device started: " + success);
return success;
}
@@ -472,19 +484,19 @@ public override bool Stop()
{
if (status == BoardStatus.BOARD_ACQUIRINGDATA)
{
- Log.Debug("Board acquiring data. Stopping device");
+ _logger.LogDebug("Board acquiring data. Stopping device");
GetData();
DeviceObj.stop_stream();
DeviceObj.release_session();
- Log.Debug("Device stopped");
+ _logger.LogDebug("Device stopped");
}
if (saveDataToFile && FileWriterObj != null && FileWriterObj.isFileOpened)
{
- Log.Debug("Closing files");
+ _logger.LogDebug("Closing files");
FileWriterObj.CloseFiles();
FileWriterObj = null;
- Log.Debug("Files closed");
+ _logger.LogDebug("Files closed");
}
status = BoardStatus.BOARD_STANDBY;
@@ -494,7 +506,7 @@ public override bool Stop()
{
sensorStatus = getErrorCode(e.Message, ExitCodes.SYNC_TIMEOUT_ERROR);
AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus);
- Log.Exception("Exception:" + e.Message + " Error code: " + sensorStatus);
+ _logger.LogError("Exception:" + e.Message + " Error code: " + sensorStatus);
return false;
}
}
@@ -509,7 +521,7 @@ public override bool CloseDevice()
{
if (status == BoardStatus.BOARD_CLOSED)
{
- Log.Debug("Board already closed");
+ _logger.LogDebug("Board already closed");
return true;
}
@@ -518,14 +530,14 @@ public override bool CloseDevice()
DeviceObj.release_session();
status = BoardStatus.BOARD_CLOSED;
- Log.Debug("Device closed");
+ _logger.LogDebug("Device closed");
return true;
}
catch (Exception e)
{
sensorStatus = getErrorCode(e.Message, ExitCodes.UNABLE_TO_CLOSE);
AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus);
- Log.Exception("Exception:" + e.Message + " Error code: " + sensorStatus);
+ _logger.LogError("Exception:" + e.Message + " Error code: " + sensorStatus);
return false;
}
}
@@ -570,7 +582,7 @@ public override bool CloseDevice()
}
catch (Exception e)
{
- Log.Exception("Exception: " + e.Message);
+ _logger.LogError(e, e.Message);
}
if (returnFilteredData)
@@ -715,7 +727,7 @@ public override SignalStatus GetStatus(out SignalStatus[] statusSignals)
}
catch (Exception e)
{
- Log.Exception("Exception: " + e.Message);
+ _logger.LogError(e, e.Message);
}
}
return statusAllSignals;
@@ -738,7 +750,7 @@ public SignalStatus GetStatus2_ReceivedData()
///
///
///
- private bool AppendDataToBuffer(double[,] data, double[,] inBuffer, int numSamplesInBuffer, out double[,] outBuffer)
+ protected override bool AppendDataToBuffer(double[,] data, double[,] inBuffer, int numSamplesInBuffer, out double[,] outBuffer)
{
bool result = false;
outBuffer = null;
@@ -765,7 +777,7 @@ private bool AppendDataToBuffer(double[,] data, double[,] inBuffer, int numSampl
}
catch (Exception e)
{
- Log.Exception(e.Message);
+ _logger.LogError(e, e.Message);
}
return result;
}
@@ -831,7 +843,7 @@ public bool DetectEyesClosed(out double[] alphaValues, out double avgAlpha, out
}
catch (Exception e)
{
- Log.Exception(e.Message);
+ _logger.LogError(e, e.Message);
}
}
avgAlpha /= indEegChannels.Length;
@@ -860,7 +872,7 @@ private bool TestPort(String port, out bool portAlreadyOpen)
portAlreadyOpen = false;
try
{
- Log.Debug("Testing port " + port);
+ _logger.LogDebug("Testing port " + port);
BrainFlowInputParams input_params = new()
{
serial_port = port
@@ -869,7 +881,7 @@ private bool TestPort(String port, out bool portAlreadyOpen)
DeviceObj = new BoardShim(boardID, input_params);
DeviceObj.prepare_session();
DeviceObj.release_session();
- Log.Debug("Sensor detected to port" + port);
+ _logger.LogDebug("Sensor detected to port" + port);
return true;
}
catch (Exception e)
@@ -878,7 +890,7 @@ private bool TestPort(String port, out bool portAlreadyOpen)
if (sensorStatus == ExitCodes.ANOTHER_BOARD_IS_CREATED_ERROR)
portAlreadyOpen = true;
AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus);
- Log.Exception("Exception: " + e.Message);
+ _logger.LogError(e, e.Message);
return false;
}
}
@@ -927,7 +939,7 @@ private UInt32 ReadLatencyTimerValue(String comPort)
}
catch (Exception e)
{
- Log.Exception("Exception: " + e.Message);
+ _logger.LogError(e, e.Message);
}
return 0;
@@ -953,13 +965,13 @@ private ExitCodes getErrorCode(string message, ExitCodes defaultErrorCode)
/// Creates files where data is stored
///
///
- private void CreateFiles(String sessionID)
+ protected override void CreateFiles(String sessionID)
{
if (saveDataToFile)
{
if (FileWriterObj == null)
{
- Log.Debug("Creating files for session: " + sessionID);
+ _logger.LogDebug("Creating files for session: " + sessionID);
if (sessionID == "")
FileWriterObj = new FileWriter();
@@ -993,7 +1005,7 @@ public override bool StartSession(string sessionID, bool forceSavingData)
if (saveDataToFile)
{
- Log.Debug("Creating files for session: " + sessionID);
+ _logger.LogDebug("Creating files for session: " + sessionID);
// Creates new file
if (sessionID == "")
@@ -1010,7 +1022,7 @@ public override bool StartSession(string sessionID, bool forceSavingData)
}
catch (Exception e)
{
- Log.Exception("Exception " + e.Message);
+ _logger.LogError(e.Message);
}
return result;
}
@@ -1033,12 +1045,12 @@ public override bool EndSession()
{
GetData(); // Empty buffer
}
- Log.Debug("Session closed");
+ _logger.LogDebug("Session closed");
result = true;
}
catch (Exception e)
{
- Log.Exception("Exception " + e.Message);
+ _logger.LogError(e.Message);
}
return result;
@@ -1082,7 +1094,7 @@ public Dictionary getWarning()
}
catch (Exception e)
{
- Log.Exception(e.Message);
+ _logger.LogError(e, e.Message);
return info;
}
return info;
@@ -1092,16 +1104,16 @@ public Dictionary getWarning()
/// Send lower level config command to BoardShim device
///
///
- public void Config_Board(string cmd)
+ public override void Config_Board(string cmd)
{
try
{
- Log.Debug("Config board. Command" + cmd);
+ _logger.LogDebug("Config board. Command" + cmd);
DeviceObj.config_board(cmd);
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, ex.Message);
}
}
@@ -1160,14 +1172,14 @@ private bool cytonIsDaisyAttached(String comPort)
NewLine = "$$$"
};
- Log.Debug(String.Format("cytonIsDaisyAttached | Opening serial port with port name: {0}, baud rate: {1}", serialPort.PortName, serialPort.BaudRate));
+ _logger.LogDebug(String.Format("cytonIsDaisyAttached | Opening serial port with port name: {0}, baud rate: {1}", serialPort.PortName, serialPort.BaudRate));
serialPort.Open();
Thread.Sleep(100);
// If the port is open, do something
if (serialPort.IsOpen)
{
- Log.Debug("cytonIsDaisyAttached | serialPort is open");
+ _logger.LogDebug("cytonIsDaisyAttached | serialPort is open");
int max_tries = 3;
while (!receivedResponse && max_tries > 0)
{
@@ -1176,7 +1188,7 @@ private bool cytonIsDaisyAttached(String comPort)
Thread.Sleep(1000);
String response = serialPort.ReadLine().Trim();
- Log.Debug(String.Format("cytonIsDaisyAttached | response: {0}", response));
+ _logger.LogDebug(String.Format("cytonIsDaisyAttached | response: {0}", response));
if (response == "8" || response == "16")
{
@@ -1203,7 +1215,7 @@ private bool cytonIsDaisyAttached(String comPort)
Thread.Sleep(500);
}
- Log.Debug("cytonIsDaisyAttached | End read line / check loop. Sending reset board command");
+ _logger.LogDebug("cytonIsDaisyAttached | End read line / check loop. Sending reset board command");
serialPort.WriteLine("d");
Thread.Sleep(3500);
}
@@ -1221,35 +1233,35 @@ private bool cytonIsDaisyAttached(String comPort)
BCIActuatorSettings.Settings.DAQ_NumEEGChannels = 8;
_daisyBoardStatus = DaisyBoardStatus.NOT_CONNECTED;
}
- Log.Debug("cytonIsDaisyAttached | Received a valid response from cyton board | DAQ_NumEEGChannels: " +
+ _logger.LogDebug("cytonIsDaisyAttached | Received a valid response from cyton board | DAQ_NumEEGChannels: " +
BCIActuatorSettings.Settings.DAQ_NumEEGChannels.ToString());
BCIActuatorSettings.Save();
}
else
{
- Log.Debug("cytonIsDaisyAttached | Did not receive a valid response from cyton board. Setting DAQ_NumEEGChannels to 8");
+ _logger.LogDebug("cytonIsDaisyAttached | Did not receive a valid response from cyton board. Setting DAQ_NumEEGChannels to 8");
BCIActuatorSettings.Settings.DAQ_NumEEGChannels = 16;
}
}
catch (Exception e)
{
- Log.Exception(e.Message);
+ _logger.LogError(e, e.Message);
}
finally
{
- Log.Debug("cytonIsDaisyAttached | closing serialPort from finally");
+ _logger.LogDebug("cytonIsDaisyAttached | closing serialPort from finally");
serialPort.Close();
- Log.Debug("cytonIsDaisyAttached | serialPort closed from finally");
+ _logger.LogDebug("cytonIsDaisyAttached | serialPort closed from finally");
}
if (serialPort != null && serialPort.IsOpen)
{
- Log.Debug("cytonIsDaisyAttached | serialPort not yet closed. calling close() again");
+ _logger.LogDebug("cytonIsDaisyAttached | serialPort not yet closed. calling close() again");
serialPort.Close();
}
- Log.Debug(String.Format("cytonDaisyAttached() done | " +
+ _logger.LogDebug(String.Format("cytonDaisyAttached() done | " +
"receivedResponse: {0}, " +
"daisyBoardAttached: {1}, " +
"BCIActuatorSettings.Settings.DAQ_NumEEGChannels: {2}",
diff --git a/src/Extensions/BCI/Actuators/EEGDataAcquisition/DAQ_gTecBCI.cs b/src/Extensions/BCI/Actuators/EEGDataAcquisition/DAQ_gTecBCI.cs
index 9f48cc7b..24e48f45 100644
--- a/src/Extensions/BCI/Actuators/EEGDataAcquisition/DAQ_gTecBCI.cs
+++ b/src/Extensions/BCI/Actuators/EEGDataAcquisition/DAQ_gTecBCI.cs
@@ -19,6 +19,7 @@
using Gtec.Unicorn;
#endif
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -31,6 +32,8 @@ namespace ACAT.Extensions.BCI.Actuators.EEG.EEGDataAcquisition
///
public class DAQ_gTecBCI : BaseDAQ
{
+ private static new readonly ILogger _logger = LoggingConfiguration.CreateLogger();
+
///
/// MInimum duty cycle required to pass trigger test. Set to 0 for no duty cycle requirement
///
@@ -55,7 +58,7 @@ public override void LoadSettings()
{
SignalControl_WindowDurationForVrmsMeaseurment = BCIActuatorSettings.Settings.SignalControl_WindowDurationForVrmsMeaseurment;
SignalControl_MinDutyCycleToPassTriggerTest = BCIActuatorSettings.Settings.TriggerTest_MinDutyCycleToPassTriggerTest;
- Log.Debug("DAQ settings loaded. Min duty cycle to pass trigger test" + SignalControl_MinDutyCycleToPassTriggerTest + " Window duration for uVrmsMeasurement: " + SignalControl_WindowDurationForVrmsMeaseurment);
+ _logger.LogDebug("DAQ settings loaded. Min duty cycle to pass trigger test" + SignalControl_MinDutyCycleToPassTriggerTest + " Window duration for uVrmsMeasurement: " + SignalControl_WindowDurationForVrmsMeaseurment);
// Gtec Does not have hardware trigger so we will keep both same for ML that support openbci
BCIActuatorSettings.Settings.DAQ_NumEEGChannels = 8;
@@ -80,14 +83,14 @@ public override void LoadSettings()
BCIActuatorSettings.Save();
- Log.Debug("Sensor set to " + BCIActuatorSettings.Settings.DAQ_NumEEGChannels + " channels. SensorID: " + BCISettingsFixed.DAQ_SensorId + " , Downsample rate: " + BCISettingsFixed.DimReduct_DownsampleRate +
+ _logger.LogDebug("Sensor set to " + BCIActuatorSettings.Settings.DAQ_NumEEGChannels + " channels. SensorID: " + BCISettingsFixed.DAQ_SensorId + " , Downsample rate: " + BCISettingsFixed.DimReduct_DownsampleRate +
" , Idx hw trigger signal: " + BCISettingsFixed.DataParser_IdxTriggerSignal_Hw + " , Idx sw trigger signal: " + BCISettingsFixed.DataParser_IdxTriggerSignal_Sw);
saveDataToFile = BCIActuatorSettings.Settings.DAQ_SaveToFileFlag;
frontendFilterIdx = BCIActuatorSettings.Settings.DAQ_FrontendFilterIdx;
notchFilterIdx = BCIActuatorSettings.Settings.DAQ_NotchFilterIdx;
- Log.Debug(" Frontend filter: " + frontendFilterIdx + " Notch filter: " + notchFilterIdx);
+ _logger.LogDebug(" Frontend filter: " + frontendFilterIdx + " Notch filter: " + notchFilterIdx);
}
public static bool IsDeviceAvailable()
@@ -110,7 +113,7 @@ public static bool IsDeviceAvailable()
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, ex.Message);
}
return success;
@@ -139,13 +142,13 @@ public override bool InitDevice(string serial_number = "")
if (status == BoardStatus.BOARD_OPEN)
{
- Log.Debug("Board was open, closing device");
+ _logger.LogDebug("Board was open, closing device");
CloseDevice();
}
if (status == BoardStatus.BOARD_ACQUIRINGDATA)
{
- Log.Debug("Board already acquiring data, returning");
+ _logger.LogDebug("Board already acquiring data, returning");
return true;
}
else
@@ -155,30 +158,30 @@ public override bool InitDevice(string serial_number = "")
// Enable /disable boardlogging
if (boardLoggerEnabled)
{
- Log.Debug("BoardLoggerEnabled: " + boardLoggerEnabled + " Enabling brainflow logging");
+ _logger.LogDebug("BoardLoggerEnabled: " + boardLoggerEnabled + " Enabling brainflow logging");
BoardShim.enable_dev_board_logger();
BoardShim.set_log_file(boardLogFileName);
}
else
{
- Log.Debug("BoardLoggerEnabled: " + boardLoggerEnabled + " Disabling brainflow logging");
+ _logger.LogDebug("BoardLoggerEnabled: " + boardLoggerEnabled + " Disabling brainflow logging");
BoardShim.disable_board_logger();
}
// Test port
- Log.Debug("Testing port: " + serial_number);
+ _logger.LogDebug("Testing port: " + serial_number);
bool sensorConnected = TestPort(serial_number, out _);
BrainFlowInputParams input_params = new();
if (sensorConnected)
{
- Log.Debug("Sensor connected to port " + serial_number);
+ _logger.LogDebug("Sensor connected to port " + serial_number);
// Save port to settings
BCIActuatorSettings.Settings.GTecDeviceName = serial_number;
BCIActuatorSettings.Save();
- Log.Debug("Port: " + serial_number + " saved to settings");
+ _logger.LogDebug("Port: " + serial_number + " saved to settings");
// DAQ_NumEEGChannels may have changed - run LoadSettings() at this point
LoadSettings();
@@ -202,14 +205,14 @@ public override bool InitDevice(string serial_number = "")
FrontendFilter = new Filter(frontendFilterIdx, Filter.FilterTypes.Frontend);
NotchFilter = new Filter(notchFilterIdx, Filter.FilterTypes.Notch);
- Log.Debug("Creating Frontend filter: " + frontendFilterIdx + " | Notch filter: " + notchFilterIdx);
+ _logger.LogDebug("Creating Frontend filter: " + frontendFilterIdx + " | Notch filter: " + notchFilterIdx);
status = BoardStatus.BOARD_OPEN;
deviceInitialized = true;
AddWarning(ExitCodes.IDLE, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " STATUS MESSAGE: Device initialized at serial port: " + serial_number);
- Log.Debug("Board initialized. Status: " + status.ToString());
+ _logger.LogDebug("Board initialized. Status: " + status.ToString());
return true;
}
@@ -219,7 +222,7 @@ public override bool InitDevice(string serial_number = "")
}
catch (Exception e)
{
- Log.Exception(e.Message);
+ _logger.LogError(e.Message);
sensorStatus = getErrorCode(e.Message, ExitCodes.BOARD_NOT_READY_ERROR);
AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus);
return false;
@@ -242,22 +245,22 @@ public override bool Start(string serial_number = "", bool saveData = false, str
{
// Init device
bool initPortSuccess;
- Log.Debug("Initiating device");
+ _logger.LogDebug("Initiating device");
if (status != BoardStatus.BOARD_OPEN)
initPortSuccess = InitDevice(serial_number);
else
initPortSuccess = true;
- Log.Debug("Starting stream");
+ _logger.LogDebug("Starting stream");
Start_Streaming();
- Log.Debug("Stream started");
+ _logger.LogDebug("Stream started");
status = BoardStatus.BOARD_ACQUIRINGDATA;
//triggerTestInProgressFlag = false;
if (saveDataToFile)
{
- Log.Debug("Creating files for session " + sessionID);
+ _logger.LogDebug("Creating files for session " + sessionID);
CreateFiles(sessionID);
}
@@ -271,10 +274,10 @@ public override bool Start(string serial_number = "", bool saveData = false, str
{
sensorStatus = getErrorCode(e.Message, ExitCodes.BOARD_NOT_CREATED_ERROR);
AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus);
- Log.Exception("Exception:" + e.Message + " Error code:" + sensorStatus);
+ _logger.LogError("Exception:" + e.Message + " Error code:" + sensorStatus);
success = false;
}
- Log.Debug("Device started: " + success);
+ _logger.LogDebug("Device started: " + success);
return success;
}
@@ -288,18 +291,18 @@ public override bool Stop()
{
if (status == BoardStatus.BOARD_ACQUIRINGDATA)
{
- Log.Debug("Board acquiring data. Stopping device");
+ _logger.LogDebug("Board acquiring data. Stopping device");
GetData();
Stop_Streaming();
- Log.Debug("Device stopped");
+ _logger.LogDebug("Device stopped");
}
if (saveDataToFile && FileWriterObj != null && FileWriterObj.isFileOpened)
{
- Log.Debug("Closing files");
+ _logger.LogDebug("Closing files");
FileWriterObj.CloseFiles();
FileWriterObj = null;
- Log.Debug("Files closed");
+ _logger.LogDebug("Files closed");
}
status = BoardStatus.BOARD_STANDBY;
@@ -309,7 +312,7 @@ public override bool Stop()
{
sensorStatus = getErrorCode(e.Message, ExitCodes.SYNC_TIMEOUT_ERROR);
AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus);
- Log.Exception("Exception:" + e.Message + " Error code: " + sensorStatus);
+ _logger.LogError("Exception:" + e.Message + " Error code: " + sensorStatus);
return false;
}
}
@@ -324,7 +327,7 @@ public override bool CloseDevice()
{
if (status == BoardStatus.BOARD_CLOSED)
{
- Log.Debug("Board already closed");
+ _logger.LogDebug("Board already closed");
return true;
}
@@ -334,14 +337,14 @@ public override bool CloseDevice()
}
status = BoardStatus.BOARD_CLOSED;
- Log.Debug("Device closed");
+ _logger.LogDebug("Device closed");
return true;
}
catch (Exception e)
{
sensorStatus = getErrorCode(e.Message, ExitCodes.UNABLE_TO_CLOSE);
AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus);
- Log.Exception("Exception:" + e.Message + " Error code: " + sensorStatus);
+ _logger.LogError("Exception:" + e.Message + " Error code: " + sensorStatus);
return false;
}
}
@@ -383,7 +386,7 @@ public override bool CloseDevice()
}
catch (Exception e)
{
- Log.Exception("Exception: " + e.Message);
+ _logger.LogError("Exception: " + e.Message);
}
if (returnFilteredData)
@@ -414,14 +417,14 @@ private bool TestPort(String serial_number, out bool portAlreadyOpen)
portAlreadyOpen = false;
try
{
- Log.Debug("Testing port " + serial_number);
+ _logger.LogDebug("Testing port " + serial_number);
BrainFlowInputParams input_params = new();
//input_params.serial_number = serial_number;
DeviceObj = new BoardShim(boardID, input_params);
DeviceObj.prepare_session();
DeviceObj.release_session();
- Log.Debug("Sensor detected to port" + serial_number);
+ _logger.LogDebug("Sensor detected to port" + serial_number);
return true;
}
catch (Exception e)
@@ -430,7 +433,7 @@ private bool TestPort(String serial_number, out bool portAlreadyOpen)
if (sensorStatus == ExitCodes.ANOTHER_BOARD_IS_CREATED_ERROR)
portAlreadyOpen = true;
AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus);
- Log.Exception("Exception: " + e.Message);
+ _logger.LogError("Exception: " + e.Message);
return false;
}
}
@@ -488,7 +491,7 @@ public Dictionary getWarning()
}
catch (Exception e)
{
- Log.Exception(e.Message);
+ _logger.LogError(e.Message);
return info;
}
return info;
@@ -544,7 +547,7 @@ public async Task> ScanDevicesAsync(bool paired = true)
}
catch (Gtec.Unicorn.DeviceException ex)
{
- Log.Exception($"Error: {ex.Message}");
+ _logger.LogError(ex, ex.Message);
}
return devices;
});
@@ -576,9 +579,9 @@ public async Task connectionTestAsync()
{
#if !SIMULATIONBOARD
- Log.Debug($"Selected device: {BCIActuatorSettings.Settings.GTecDeviceName}, trying to connect...");
+ _logger.LogDebug($"Selected device: {BCIActuatorSettings.Settings.GTecDeviceName}, trying to connect...");
using Unicorn device = new Unicorn(BCIActuatorSettings.Settings.GTecDeviceName);
- Log.Debug($"Device: {device} is connected...");
+ _logger.LogDebug($"Device: {device} is connected...");
device.Dispose();
#endif
EvtBluetoothResult(BluetoothEvent.SUCCESSFUL_CONNECTION, null);
@@ -586,7 +589,7 @@ public async Task connectionTestAsync()
}
catch (Gtec.Unicorn.DeviceException ex)
{
- Log.Exception($"Error: {ex.Message}");
+ _logger.LogError(ex, ex.Message);
Dictionary eventParams = new()
{
["error"] = ex.Message
@@ -596,7 +599,7 @@ public async Task connectionTestAsync()
}
catch (Exception ex)
{
- Log.Exception($"Unexpected error: {ex.Message}");
+ _logger.LogError(ex, ex.Message);
Dictionary eventParams = new()
{
["error"] = ex.Message
@@ -615,7 +618,7 @@ public async Task connectionTestAsync()
/// Any extra params sent with bluetooth event request
public void bluetoothRequestHandler(BluetoothEvent bluetoothEvent, Dictionary eventParams)
{
- Log.Debug("DAQ_gTecBCI | bluetoothRequestHandler | bluetoothEvent: " + bluetoothEvent.ToString());
+ _logger.LogDebug("DAQ_gTecBCI | bluetoothRequestHandler | bluetoothEvent: " + bluetoothEvent.ToString());
switch (bluetoothEvent)
{
@@ -657,7 +660,7 @@ public override SignalStatus GetStatus(out SignalStatus[] statusSignals)
}
catch (Exception e)
{
- Log.Exception("Exception: " + e.Message);
+ _logger.LogError("Exception: " + e.Message);
}
}
return statusAllSignals;
diff --git a/src/Extensions/BCI/Actuators/EEGDataAcquisition/FileManagement/FileWriter.cs b/src/Extensions/BCI/Actuators/EEGDataAcquisition/FileManagement/FileWriter.cs
index e075462a..26cf5ce5 100644
--- a/src/Extensions/BCI/Actuators/EEGDataAcquisition/FileManagement/FileWriter.cs
+++ b/src/Extensions/BCI/Actuators/EEGDataAcquisition/FileManagement/FileWriter.cs
@@ -13,6 +13,7 @@
using ACAT.Core.UserManagement;
using ACAT.Core.Utility;
using ACAT.Extensions.BCI.Actuators.EEG.EEGSettings;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
@@ -24,6 +25,7 @@ namespace ACAT.Extensions.BCI.Actuators.EEG.EEGDataAcquisition.FileManagement
{
public class FileWriter
{
+ private static readonly ILogger _logger = LoggingConfiguration.CreateLogger();
///
/// Directory for session
///
@@ -172,8 +174,7 @@ private void WriteDataToFile(StreamWriter sw, double[,] data)
}
catch (Exception ex)
{
- Log.Exception(data[channelIdx, sampleIdx].ToString());
- Log.Exception(ex.ToString());
+ _logger.LogError(ex, "Error writing data at channel {ChannelIdx}, sample {SampleIdx}, value: {Value}", channelIdx, sampleIdx, data[channelIdx, sampleIdx]);
}
if (channelIdx < numChannels - 1)
stringBuilder.Append(", ");
@@ -188,7 +189,7 @@ private void WriteDataToFile(StreamWriter sw, double[,] data)
}
catch (Exception ex)
{
- Log.Exception(ex.ToString());
+ _logger.LogError(ex, "Error writing data to file");
}
finally
{
diff --git a/src/Extensions/BCI/Actuators/EEGProcessing/DataLoader/DataParser.cs b/src/Extensions/BCI/Actuators/EEGProcessing/DataLoader/DataParser.cs
index a70f5321..9b76827f 100644
--- a/src/Extensions/BCI/Actuators/EEGProcessing/DataLoader/DataParser.cs
+++ b/src/Extensions/BCI/Actuators/EEGProcessing/DataLoader/DataParser.cs
@@ -12,6 +12,7 @@
using ACAT.Core.Utility;
using ACAT.Extensions.BCI.Actuators.EEG.EEGSettings;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -21,6 +22,8 @@ namespace ACAT.Extensions.BCI.Actuators.EEG.EEGProcessing.DataLoader
[Serializable]
public class DataParser
{
+ private static readonly ILogger _logger = LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger();
+
///
/// Offset added to targets
/// (this parameter is typically set in settings)
@@ -264,8 +267,7 @@ public void ParseData(double[,] inputData, int[] triggerData, List markerVa
}
catch (Exception e)
{
- //Log.Exception(e.getClass().getName()); e)
- Log.Debug(e.Message);
+ _logger.LogDebug("{Message}", e.Message);
}
}
@@ -288,7 +290,7 @@ public void ParseData(double[,] inputData, int[] triggerData, List markerVa
remainingData = new double[numColumns, numRemainingSamples];
string txtLog = "Get " + numRemainingSamples + " remaining data. Input data with Num Columns: " + numColumns + " Num Samples: " + numSamples;
- Log.Debug(txtLog);
+ _logger.LogDebug("{Message}", txtLog);
try
{
for (int columnIdx = 0; columnIdx < numColumns; columnIdx++)
@@ -296,11 +298,11 @@ public void ParseData(double[,] inputData, int[] triggerData, List markerVa
remainingData[columnIdx, i] = allData[columnIdx, startingSampleIdx + i];
txtLog = "Remaining dat. Num Columns: " + remainingData.GetLength(0) + " Num samples: " + remainingData.GetLength(1);
- Log.Debug(txtLog);
+ _logger.LogDebug("{Message}", txtLog);
}
catch (Exception e)
{
- Log.Exception(e.Message);
+ _logger.LogError(e, "{Message}", e.Message);
}
}
diff --git a/src/Extensions/BCI/Actuators/EEGProcessing/DecisionMaker.cs b/src/Extensions/BCI/Actuators/EEGProcessing/DecisionMaker.cs
index 950995f3..d126b42b 100644
--- a/src/Extensions/BCI/Actuators/EEGProcessing/DecisionMaker.cs
+++ b/src/Extensions/BCI/Actuators/EEGProcessing/DecisionMaker.cs
@@ -16,6 +16,8 @@
using ACAT.Core.Utility;
using ACAT.Extensions.BCI.Actuators.EEG.EEGProcessing.Utilities;
using ACAT.Extensions.BCI.Actuators.EEG.EEGSettings;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Logging.Abstractions;
using System;
using System.Collections.Generic;
using System.IO;
@@ -24,6 +26,9 @@ namespace ACAT.Extensions.BCI.Actuators.EEG.EEGProcessing
{
public class DecisionMaker
{
+ private static readonly ILogger _nullLogger = NullLogger.Instance;
+ private readonly ILogger _logger;
+
// ************ Params and objects loaded at init
///
@@ -91,8 +96,9 @@ public class DecisionMaker
///
/// Constructor (Params read from settings)
///
- public DecisionMaker(string TrainedClassifiersFilePath)
+ public DecisionMaker(string TrainedClassifiersFilePath, ILogger logger = null)
{
+ _logger = logger ?? _nullLogger;
enableLanguageModelProbabilities = false; // by default (actuator will set flag for different type of LM probabilities)
maxNumberOfSequences = BCIActuatorSettings.Settings.Classifier_MaxDecisionSequences;
confidenceThreshold = BCIActuatorSettings.Settings.Classifier_ConfidenceThreshold;
@@ -110,23 +116,24 @@ public DecisionMaker(string TrainedClassifiersFilePath)
{
TrainedClassifiersObj = BinaryUtils.ReadFromBinaryFile(TrainedClassifiersFilePath);
- string logTxt = "Decision maker created with calibration file " + TrainedClassifiersObj.trainedClassifiersSessionID + ". AUC: " + TrainedClassifiersObj.meanAUC + " Max number of sequences: " + maxNumberOfSequences + ". Confidence threshold: " + confidenceThreshold;
- Log.Debug(logTxt);
+ _logger.LogDebug("Decision maker created with calibration file {SessionID}. AUC: {MeanAUC} Max number of sequences: {MaxSequences}. Confidence threshold: {ConfidenceThreshold}",
+ TrainedClassifiersObj.trainedClassifiersSessionID, TrainedClassifiersObj.meanAUC, maxNumberOfSequences, confidenceThreshold);
}
else
- Log.Debug("Calibration file does not exist");
+ _logger.LogDebug("Calibration file does not exist");
}
catch (Exception e)
{
- Log.Exception(e.Message);
+ _logger.LogError(e, "Exception in DecisionMaker constructor");
}
}
///
/// Constructor (Params as input)
///
- public DecisionMaker(int maxNumberOfSeqs, float confThreshold)
+ public DecisionMaker(int maxNumberOfSeqs, float confThreshold, ILogger logger = null)
{
+ _logger = logger ?? _nullLogger;
maxNumberOfSequences = maxNumberOfSeqs;
confidenceThreshold = confThreshold;
@@ -135,7 +142,7 @@ public DecisionMaker(int maxNumberOfSeqs, float confThreshold)
if (File.Exists(filePath))
TrainedClassifiersObj = BinaryUtils.ReadFromBinaryFile(filePath);
else
- Log.Debug("Calibration file does not exist");
+ _logger.LogDebug("Calibration file does not exist");
_likelihoodsTarget = new Dictionary>();
_likelihoodsNontarget = new Dictionary>();
@@ -193,7 +200,7 @@ public void ComputePosteriorProbs(double[,] data2parse, List markerValues,
TrainedClassifiersObj.UpdateChannelSubset(availableChannels);
List markerValuesString = markerValues.ConvertAll(x => x.ToString());
- Log.Debug("Reduce data w/ " + data2parse.Length + " samples and " + String.Join(", ", markerValuesString) + " markers");
+ _logger.LogDebug("Reduce data w/ {SampleCount} samples and {Markers} markers", data2parse.Length, String.Join(", ", markerValuesString));
// Append incomplete data and markers
double[,] allDataToParse;
@@ -203,7 +210,7 @@ public void ComputePosteriorProbs(double[,] data2parse, List markerValues,
// Concatenate markers
allMarkersToParse = incompleteMarkers;
allMarkersToParse.AddRange(markerValues);
- Log.Debug("Markers concatenated. Total markers: " + allMarkersToParse.Count);
+ _logger.LogDebug("Markers concatenated. Total markers: {TotalMarkers}", allMarkersToParse.Count);
// Concatenate data
int numColumns = data2parse.GetLength(0);
@@ -217,7 +224,8 @@ public void ComputePosteriorProbs(double[,] data2parse, List markerValues,
for (int sampleIdx = 0; sampleIdx < data2parse.GetLength(1); sampleIdx++)
allDataToParse[columnIdx, sampleIdx + incompleteData.GetLength(1)] = data2parse[columnIdx, sampleIdx];
}
- Log.Debug("Data concatenated. Total data: " + allDataToParse.GetLength(1) + " containing " + incompleteData.GetLength(1) + " from previous iterations and " + data2parse.GetLength(1) + " from current iteration");
+ _logger.LogDebug("Data concatenated. Total data: {TotalData} containing {PreviousData} from previous iterations and {CurrentData} from current iteration",
+ allDataToParse.GetLength(1), incompleteData.GetLength(1), data2parse.GetLength(1));
}
else
{
@@ -229,14 +237,14 @@ public void ComputePosteriorProbs(double[,] data2parse, List markerValues,
List trialScores = TrainedClassifiersObj.Reduce(allDataToParse, allMarkersToParse, flashingSequence, out incompleteData, out incompleteMarkers);
if (trialScores != null)
- Log.Debug("Data reduced " + trialScores.Count + " trial scores found");
+ _logger.LogDebug("Data reduced {TrialScoreCount} trial scores found", trialScores.Count);
else
- Log.Debug("Data not reduced. Scores returned null. Will reduce in new iteration");
+ _logger.LogDebug("Data not reduced. Scores returned null. Will reduce in new iteration");
List appendedTrialScores = new();
if (incompleteTrialScores != null)
{
- Log.Debug("Creating appended list with " + incompleteTrialScores.Count + " scores");
+ _logger.LogDebug("Creating appended list with {IncompleteScoreCount} scores", incompleteTrialScores.Count);
appendedTrialScores = new List(incompleteTrialScores);
}
if (trialScores != null && trialScores.Count > 0)
@@ -244,18 +252,20 @@ public void ComputePosteriorProbs(double[,] data2parse, List markerValues,
// Append trial scores
if (appendedTrialScores != null && appendedTrialScores.Count > 0)
{
- Log.Debug("Adding current " + trialScores.Count + " scores to appended trialscores");
+ _logger.LogDebug("Adding current {CurrentScoreCount} scores to appended trialscores", trialScores.Count);
appendedTrialScores.AddRange(trialScores);
if (incompleteTrialScores != null)
- Log.Debug("Appended trialScores. Total scores: " + appendedTrialScores.Count + " with " + incompleteTrialScores.Count + " from previous iteration and " + trialScores.Count + " from current iteration");
+ _logger.LogDebug("Appended trialScores. Total scores: {TotalScores} with {PreviousScores} from previous iteration and {CurrentScores} from current iteration",
+ appendedTrialScores.Count, incompleteTrialScores.Count, trialScores.Count);
else
- Log.Debug("Appended trialScores. Total scores: " + appendedTrialScores.Count + " with 0 from previous iteration and " + trialScores.Count + " from current iteration");
+ _logger.LogDebug("Appended trialScores. Total scores: {TotalScores} with 0 from previous iteration and {CurrentScores} from current iteration",
+ appendedTrialScores.Count, trialScores.Count);
}
else
{
appendedTrialScores = trialScores;
- Log.Debug("No trial scores from previous iterations. Current " + trialScores.Count + " will be used");
+ _logger.LogDebug("No trial scores from previous iterations. Current {CurrentScoreCount} will be used", trialScores.Count);
}
}
@@ -268,22 +278,22 @@ public void ComputePosteriorProbs(double[,] data2parse, List markerValues,
// List completeTrialScores = new List(appendedTrialScores);
List completeTrialScores = new(appendedTrialScores.GetRange(0, flashingSequence.Count));
- Log.Debug("Calculating probabilities for " + completeTrialScores.Count + " scores corresponding to " + flashingSequence.Count + " trials");
+ _logger.LogDebug("Calculating probabilities for {CompleteScoreCount} scores corresponding to {TrialCount} trials", completeTrialScores.Count, flashingSequence.Count);
ComputePosteriorProbs(completeTrialScores.ToArray(), flashingSequence, out decided, out decidedButtonID, out repetition, out posteriorProbs, out eegProbs, out nextCharacterProbs);
- Log.Debug("Posterior probabilities calculated. Repetition: " + repetition + " , Decided: " + decided + " , Decided button ID: " + decidedButtonID);
+ _logger.LogDebug("Posterior probabilities calculated. Repetition: {Repetition} , Decided: {Decided} , Decided button ID: {DecidedButtonID}", repetition, decided, decidedButtonID);
if (appendedTrialScores.Count > flashingSequence.Count)
{
incompleteTrialScores = new List(appendedTrialScores.GetRange(flashingSequence.Count, appendedTrialScores.Count - flashingSequence.Count));
- Log.Debug("Incomplete Trial scores " + incompleteTrialScores.Count + " saved for next iteration");
+ _logger.LogDebug("Incomplete Trial scores {IncompleteScoreCount} saved for next iteration", incompleteTrialScores.Count);
}
}
else
{
if (trialScores != null)
- Log.Debug("Incomplete trial scores. Expected: " + flashingSequence.Count + " Calculated: " + trialScores.Count + " Waiting for new repetition");
+ _logger.LogDebug("Incomplete trial scores. Expected: {ExpectedCount} Calculated: {CalculatedCount} Waiting for new repetition", flashingSequence.Count, trialScores.Count);
else
- Log.Debug("Incomplete trial scores. Expected: " + flashingSequence.Count + " Calculated: 0 Waiting for new repetition");
+ _logger.LogDebug("Incomplete trial scores. Expected: {ExpectedCount} Calculated: 0 Waiting for new repetition", flashingSequence.Count);
if (incompleteTrialScores == null)
incompleteTrialScores = appendedTrialScores;
@@ -294,7 +304,7 @@ public void ComputePosteriorProbs(double[,] data2parse, List markerValues,
}
catch (Exception e)
{
- Log.Exception(e.Message);
+ _logger.LogError(e, "Exception in ComputePosteriorProbs");
}
}
@@ -371,7 +381,7 @@ public void ComputePosteriorProbs(double[] trialScores, Dictionary t
// Add next character probabilities
if (enableLanguageModelProbabilities && _languageModelProbabilities != null)
{
- Log.Debug("Adding language model probabilities");
+ _logger.LogDebug("Adding language model probabilities");
if (_languageModelProbabilities.ContainsKey(buttonID))
{
buttonLogPosterior += Math.Log(Math.Sqrt(_languageModelProbabilities[buttonID]));
@@ -427,8 +437,7 @@ public void ComputePosteriorProbs(double[] trialScores, Dictionary t
decided = false;
if (maxProb > confidenceThreshold || _sequenceCount == maxNumberOfSequences)
{
- string txtLog = "Decision made. Repetition: " + _sequenceCount + " Probability: " + maxProb;
- Log.Debug(txtLog);
+ _logger.LogDebug("Decision made. Repetition: {SequenceCount} Probability: {MaxProb}", _sequenceCount, maxProb);
decided = true;
_sequenceCount = 0;
_likelihoodsTarget = new Dictionary>();
@@ -440,14 +449,14 @@ public void ComputePosteriorProbs(double[] trialScores, Dictionary t
}
if (posteriorProbs == null || posteriorProbs.Count == 0)
- Log.Debug("Zero posteriorProbs");
+ _logger.LogDebug("Zero posteriorProbs");
}
else
- Log.Debug("Error when computing probabilities, trialScore is null or 0, returning null and restarting algorithm");
+ _logger.LogDebug("Error when computing probabilities, trialScore is null or 0, returning null and restarting algorithm");
}
catch (Exception e)
{
- Log.Exception(e.Message);
+ _logger.LogError(e, "Exception in ComputePosteriorProbs");
}
}
@@ -456,7 +465,7 @@ public void ComputePosteriorProbs(double[] trialScores, Dictionary t
///
public void RestartProbabilities()
{
- Log.Debug("Restarting probabilities");
+ _logger.LogDebug("Restarting probabilities");
_sequenceCount = 0;
_likelihoodsTarget = new Dictionary>();
_likelihoodsNontarget = new Dictionary>();
diff --git a/src/Extensions/BCI/Actuators/EEGProcessing/DimReduction/DimReductChanSel.cs b/src/Extensions/BCI/Actuators/EEGProcessing/DimReduction/DimReductChanSel.cs
index 4811b03d..143e692a 100644
--- a/src/Extensions/BCI/Actuators/EEGProcessing/DimReduction/DimReductChanSel.cs
+++ b/src/Extensions/BCI/Actuators/EEGProcessing/DimReduction/DimReductChanSel.cs
@@ -12,6 +12,7 @@
using ACAT.Core.Utility;
using Accord.Math;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -21,11 +22,14 @@ namespace ACAT.Extensions.BCI.Actuators.EEG.EEGProcessing.DimReduction
[Serializable]
public class DimReductChanSel
{
+ [NonSerialized]
+ private readonly ILogger _logger;
// Subset of channels
public int[] channelSubset;
public DimReductChanSel(int[] pChannelSubset)
{
+ _logger = LoggingConfiguration.CreateLogger();
channelSubset = pChannelSubset;
}
@@ -85,7 +89,7 @@ public bool Reduce(List inputData, out List outputData)
}
catch (Exception e)
{
- Log.Exception(e.Message);
+ _logger?.LogError(e, "Error during dimension reduction processing");
}
return true;
}
diff --git a/src/Extensions/BCI/Actuators/EEGProcessing/FeatureExtraction.cs b/src/Extensions/BCI/Actuators/EEGProcessing/FeatureExtraction.cs
index 3a0b89c9..2daf1ddd 100644
--- a/src/Extensions/BCI/Actuators/EEGProcessing/FeatureExtraction.cs
+++ b/src/Extensions/BCI/Actuators/EEGProcessing/FeatureExtraction.cs
@@ -23,6 +23,7 @@
using ACAT.Extensions.BCI.Actuators.EEG.EEGSettings;
using ACAT.Extensions.BCI.Common.BCIControl;
using Accord.Math;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
@@ -33,6 +34,8 @@ namespace ACAT.Extensions.BCI.Actuators.EEG.EEGProcessing
[Serializable]
public class FeatureExtraction
{
+ private readonly ILogger _logger;
+
///
/// Path of the trained classifiers
///
@@ -161,8 +164,9 @@ public class FeatureExtraction
///
///
///
- public FeatureExtraction(Dictionary pSymbolsInGroups, CalibrationParametersForSection pCalibrationParameters, int numRows = 6, int numCols = 6, bool isRowCol = true)
+ public FeatureExtraction(Dictionary pSymbolsInGroups, CalibrationParametersForSection pCalibrationParameters, int numRows = 6, int numCols = 6, bool isRowCol = true, ILogger logger = null)
{
+ _logger = logger;
// Get parameters from settings
offsetTarget = BCIActuatorSettings.Settings.Calibration_OffsetTarget;
windowDuration = BCIActuatorSettings.Settings.FeatureExtraction_WindowDurationInMs / 1000f;
@@ -357,8 +361,7 @@ public float Learn(String sessionID)
// Train classifiers
trainedClassifiersSessionID = sessionID;
- string txtLog = "Read data " + sessionID;
- Log.Debug(txtLog);
+ _logger?.LogDebug("Read data {SessionID}", sessionID);
FileReader fileReaderObj = new();
fileReaderObj.ReadDataAndMarkersFromFiles(sessionID, out rawData, out triggerSignal, out markerValues, out sessionDirectory);
//fileReaderObj.ReadDataAndMarkersFromTestFiles(out rawData, out triggerSignal, out markerValues, out sessionDirectory,
@@ -366,20 +369,19 @@ public float Learn(String sessionID)
int numSamples = rawData.GetLength(1);
int numColumns = rawData.GetLength(0);
- txtLog = "Raw data read " + sessionID + " Num samples: " + numSamples + " Num channels: " + numColumns;
- Log.Debug(txtLog);
+ _logger?.LogDebug("Raw data read {SessionID} Num samples: {NumSamples} Num channels: {NumColumns}", sessionID, numSamples, numColumns);
//Plots.plotTriggerSignal(triggerSignal);
// 1.2 Filter
- Log.Debug("Filtering data");
+ _logger?.LogDebug("Filtering data");
_BandPassFilter.FilterData(rawData, triggerSignal, out double[,] filteredData, out int[] delayedTriggerSignal);
- Log.Debug("Data filtered");
+ _logger?.LogDebug("Data filtered");
//Plots.plotSignal(filteredData, 1);
// 1.2 Parse file
- Log.Debug("Parsing data");
+ _logger?.LogDebug("Parsing data");
_DataParserObj.ParseData(filteredData, delayedTriggerSignal, markerValues, _symbolsInGroups, out inputData, out trialTargetness, out trialLabels, out List trialGroups, out List targetLabels, out _, out _, true);
// ===================== 2. Preprocessing ==========================
@@ -387,8 +389,7 @@ public float Learn(String sessionID)
{
int[] trialTargetnessArray = trialTargetness.ToArray();
- txtLog = "Data parsed. Num trials: " + inputData.Count;
- Log.Debug(txtLog);
+ _logger?.LogDebug("Data parsed. Num trials: {Count}", inputData.Count);
// 2.1 Select subset of channels (if applicable)
_DimReductChannelSelectionObj.Reduce(inputData, out inputData);
@@ -400,21 +401,18 @@ public float Learn(String sessionID)
// ===================== 3. Feature selection ==========================
// 3.1 PCA (reduce dimensions)
- Log.Debug("Applying PCA");
+ _logger?.LogDebug("Applying PCA");
_DimReductPCAObj.Learn(inputData);
_DimReductPCAObj.Reduce(inputData, out trialData);
// 3.2 RDA (transform to scores using crossValidation)
- txtLog = "Crossvalidation with " + trialData.Count + " trials";
- Log.Debug(txtLog);
+ _logger?.LogDebug("Crossvalidation with {Count} trials", trialData.Count);
scores = _CrossValidationObj.CrossValidate(_DimReductRDAObj, trialData, trialTargetness);
// Calculate performance
- txtLog = "Calculating AUC for " + scores.Count + " trials";
- Log.Debug(txtLog);
+ _logger?.LogDebug("Calculating AUC for {Count} trials", scores.Count);
meanAUC = ClassifierUtils.CalculateAUC(scores, trialTargetnessArray, out double[] TPrate, out double[] FPrate);
- txtLog = "AUC " + meanAUC;
- Log.Debug(txtLog);
+ _logger?.LogDebug("AUC {MeanAUC}", meanAUC);
// 3.3 Train RDA with all data (scores for target/nontarget class distributions are calculated with crossV)
_DimReductRDAObj.Learn(trialData, trialTargetness.ToList());
@@ -452,7 +450,7 @@ public float Learn(String sessionID)
}
catch (Exception e)
{
- Log.Exception(e.Message);
+ _logger?.LogError(e, e.Message);
meanAUC = -1;
// Save Error in file
@@ -475,26 +473,26 @@ public List Reduce(List inputData)
{
// ===================== 2. Preprocessing ==========================
// 2.1 Select subset of channels (if applicable)
- Log.Debug("Reducing number of channels for " + inputData.Count + " trials");
+ _logger?.LogDebug("Reducing number of channels for {Count} trials", inputData.Count);
_DimReductChannelSelectionObj.Reduce(inputData, out inputData);
- Log.Debug("Number of channels reduced to " + _DimReductChannelSelectionObj.channelSubset.Length);
+ _logger?.LogDebug("Number of channels reduced to {Length}", _DimReductChannelSelectionObj.channelSubset.Length);
// 2.2 Downsample
- Log.Debug("Downsampling");
+ _logger?.LogDebug("Downsampling");
_DimReductDownSampleObj.Reduce(inputData, out inputData);
- Log.Debug("Data downsampled by " + _DimReductDownSampleObj.downsampleRate + " for " + inputData.Count + " trials");
+ _logger?.LogDebug("Data downsampled by {Rate} for {Count} trials", _DimReductDownSampleObj.downsampleRate, inputData.Count);
// ===================== 3. Feature selection ==========================
// PCA (reduce dimensions)"
- Log.Debug("Starting PCA.reduce for " + inputData.Count + " trials");
+ _logger?.LogDebug("Starting PCA.reduce for {Count} trials", inputData.Count);
_DimReductPCAObj.Reduce(inputData, out List trialData);
- Log.Debug("PCA reduced for " + trialData.Count);
+ _logger?.LogDebug("PCA reduced for {Count}", trialData.Count);
// RDA (obtain 1-dimensional scores)
- Log.Debug("Starting RDA.reduce for " + trialData.Count + " trials");
+ _logger?.LogDebug("Starting RDA.reduce for {Count} trials", trialData.Count);
_DimReductRDAObj.Reduce(trialData, out List scores);
- Log.Debug("RDA reduced " + scores.Count + " scores");
+ _logger?.LogDebug("RDA reduced {Count} scores", scores.Count);
return scores;
}
@@ -514,18 +512,18 @@ public List Reduce(double[,] allData, List markerValues, Dictionary
int numSamples = allData.GetLength(1);
int numColumns = allData.GetLength(0);
incompleteData = null;
- Log.Debug("Parsing data from brainflow " + numSamples + " samples and " + numColumns + " columns");
+ _logger?.LogDebug("Parsing data from brainflow {NumSamples} samples and {NumColumns} columns", numSamples, numColumns);
_DataParserObj.ParseDataFromBrainflow(allData, out double[,] rawData, out int[] triggerSignal, out _);
numSamples = rawData.GetLength(1);
- Log.Debug("Data parsed " + numSamples + " samples.");
+ _logger?.LogDebug("Data parsed {NumSamples} samples.", numSamples);
_BandPassFilter.FilterData(rawData, triggerSignal, out double[,] filteredData, out int[] delayedTriggerSignal);
// 1.2 Parse file
- Log.Debug("Parsing data");
+ _logger?.LogDebug("Parsing data");
_DataParserObj.ParseData(filteredData, delayedTriggerSignal, markerValues, symbolsInGroups, out List trialData, out _, out _, out List trialMarkers, out _, out int incompleteSampleIdx, out incompleteMarkerValues);
- Log.Debug("Data parsed for " + trialMarkers.Count + " markers and" + trialData.Count + " trials");
+ _logger?.LogDebug("Data parsed for {MarkersCount} markers and {TrialsCount} trials", trialMarkers.Count, trialData.Count);
// trialLabels: if singleBox paradigm: trialLabels[trial1][boxID]
// if RC paradigm: trialLabels[trial1][box1 box2 box3] containing all highlighted boxes
@@ -534,13 +532,13 @@ public List Reduce(double[,] allData, List markerValues, Dictionary
{
int startSampleIdx = incompleteSampleIdx - _BandPassFilter.GetGroupDelay();
incompleteData = _DataParserObj.GetRemaining(allData, startSampleIdx);
- Log.Debug("Incomplete data remaining with " + incompleteData.GetLength(1) + " columns and " + incompleteData.GetLength(0) + " samples for " + trialMarkers.Count + " markers");
+ _logger?.LogDebug("Incomplete data remaining with {Columns} columns and {Samples} samples for {MarkersCount} markers", incompleteData.GetLength(1), incompleteData.GetLength(0), trialMarkers.Count);
}
if (trialData.Count > 0 && trialData.Count == trialMarkers.Count)
{
trialScores = Reduce(trialData);
- Log.Debug("Reduced " + trialScores.Count + " trials found");
+ _logger?.LogDebug("Reduced {Count} trials found", trialScores.Count);
}
return trialScores; // will return null if can't be computed
}
diff --git a/src/Extensions/BCI/Actuators/EEGProcessing/Utilities/FileReader.cs b/src/Extensions/BCI/Actuators/EEGProcessing/Utilities/FileReader.cs
index e09fdccb..f768e215 100644
--- a/src/Extensions/BCI/Actuators/EEGProcessing/Utilities/FileReader.cs
+++ b/src/Extensions/BCI/Actuators/EEGProcessing/Utilities/FileReader.cs
@@ -30,7 +30,7 @@ internal class FileReader
///
public FileReader(ILogger logger = null)
{
- _logger = logger ?? LoggerFactory.GetLogger();
+ _logger = logger ?? LoggingConfiguration.CreateLogger();
}
///
diff --git a/src/Extensions/BCI/Actuators/EEGUtilities/SerialComm.cs b/src/Extensions/BCI/Actuators/EEGUtilities/SerialComm.cs
index a8b7ca69..e6eb455e 100644
--- a/src/Extensions/BCI/Actuators/EEGUtilities/SerialComm.cs
+++ b/src/Extensions/BCI/Actuators/EEGUtilities/SerialComm.cs
@@ -30,7 +30,7 @@ internal class SerialComm
public SerialComm(String portName, ILogger logger = null)
{
- _logger = logger ?? LoggerFactory.GetLogger();
+ _logger = logger ?? LoggingConfiguration.CreateLogger();
_portName = portName;
}
diff --git a/src/Extensions/BCI/Actuators/gTec_SensorUI/SensorForm.cs b/src/Extensions/BCI/Actuators/gTec_SensorUI/SensorForm.cs
index 0b3449ea..d18ba71d 100644
--- a/src/Extensions/BCI/Actuators/gTec_SensorUI/SensorForm.cs
+++ b/src/Extensions/BCI/Actuators/gTec_SensorUI/SensorForm.cs
@@ -134,7 +134,7 @@ public SensorForm(DAQ_gTecBCI gTecBCI, ILogger logger)
_userControlBCIErrorgTecBoard.buttonRetry_userControlBCIErrorgTecBoard.Click += new EventHandler(this.buttonRetest_Click);
_userControlBCIErrorgTecBoard.Dock = DockStyle.Fill;
- _userControlErrorBluetoothDisconnected = new UserControlErrorBluetoothDisconnected();
+ _userControlErrorBluetoothDisconnected = new UserControlErrorBluetoothDisconnected(null);
_userControlErrorBluetoothDisconnected.buttonExit_userControlErrorBluetoothDisconnected.Click += new EventHandler(this.buttonExit_Click);
_userControlErrorBluetoothDisconnected.buttonNext_userControlErrorBluetoothDisconnected.Click += new EventHandler(this.buttonNext_Click);
_userControlErrorBluetoothDisconnected.Dock = DockStyle.Fill;
@@ -154,7 +154,7 @@ public SensorForm(DAQ_gTecBCI gTecBCI, ILogger logger)
_userControlPromptBCIFIlterSettings.buttonNext_userControlPromptBCIFIlterSettings.Click += new EventHandler(this.buttonNext_Click);
_userControlPromptBCIFIlterSettings.Dock = DockStyle.Fill;
- _userControlBCISignalCheck = new UserControlBCISignalCheck();
+ _userControlBCISignalCheck = new UserControlBCISignalCheck(null);
_userControlBCISignalCheck.buttonExit_userControlBCISignalCheck.Click += new EventHandler(this.buttonExit_Click);
_userControlBCISignalCheck.buttonNext_userControlBCISignalCheck.Click += new EventHandler(this.buttonNext_Click);
_userControlBCISignalCheck.Dock = DockStyle.Fill;
@@ -362,8 +362,8 @@ public void TaskStartStopDataProcessing(OnboardingUserState state)
///
private void startStopProcessDataTimer(bool startProcessDataTimer, OnboardingUserState state)
{
- Log.Debug("startStopProcessDataTimer | startProcessDataTimer: " + startProcessDataTimer.ToString() +
- " | state: " + state.ToString());
+ _logger.LogDebug("startStopProcessDataTimer | startProcessDataTimer: {StartProcessDataTimer} | state: {State}",
+ startProcessDataTimer, state);
if (startProcessDataTimer)
{
diff --git a/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlBCISignalCheck.cs b/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlBCISignalCheck.cs
index 6a82ceb6..d59965dd 100644
--- a/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlBCISignalCheck.cs
+++ b/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlBCISignalCheck.cs
@@ -318,9 +318,9 @@ public void updateSignalStatus(double[,] latestUnfilteredData, double[,] latestF
public void initializeBCISignalCheck(DAQ_gTecBCI gtecbci, bool maxTimeHasElapsed, double maxTimeMins, double minElapsedPrevSignalQualityCheck, bool userPassedLastSignalQualityCheck)
{
gTecBCI = gtecbci;
- Log.Debug(String.Format("initializeBCISignalCheck | maxTimeHasElapsed: {0}, " +
- "minElapsedPrevSignalQualityCheck: {1}, userPassedLastSignalQualityCheck: {2}",
- maxTimeHasElapsed.ToString(), minElapsedPrevSignalQualityCheck.ToString(), userPassedLastSignalQualityCheck.ToString()));
+ _logger?.LogDebug("initializeBCISignalCheck | maxTimeHasElapsed: {MaxTimeHasElapsed}, " +
+ "minElapsedPrevSignalQualityCheck: {MinElapsedPrevSignalQualityCheck}, userPassedLastSignalQualityCheck: {UserPassedLastSignalQualityCheck}",
+ maxTimeHasElapsed, minElapsedPrevSignalQualityCheck, userPassedLastSignalQualityCheck);
// Get / inititalize variables related to board config used in data processing
_indEegChannels = gTecBCI.indEegChannels;
@@ -338,10 +338,10 @@ public void initializeBCISignalCheck(DAQ_gTecBCI gtecbci, bool maxTimeHasElapsed
for (int i = 0; i < _indEegChannels.Length; i++)
_indEegChannels_str += (_indEegChannels[i].ToString() + ", ");
- Log.Debug(String.Format("initializeBCISignalCheck | _numChannels: {0}, " + "_samplingRate: {1}, " +
- "_scaleIdx: {2}, _bufSize: {3}\n" +
- "_indEegChannels_str: {4}",
- _numChannels.ToString(), _samplingRate.ToString(), _scaleIdx.ToString(), _bufSize.ToString(), _indEegChannels_str));
+ _logger?.LogDebug("initializeBCISignalCheck | _numChannels: {NumChannels}, " + "_samplingRate: {SamplingRate}, " +
+ "_scaleIdx: {ScaleIdx}, _bufSize: {BufSize}\n" +
+ "_indEegChannels_str: {IndEegChannelsStr}",
+ _numChannels, _samplingRate, _scaleIdx, _bufSize, _indEegChannels_str);
// Set some text fields to smaller font size for 125 scaling (100 scaling is default)
var tuple = DualMonitor.GetDisplayWidthAndScaling();
@@ -623,9 +623,9 @@ private static bool AppendDataToBuffer2(double[,] data, double[,] inBuffer, int
result = true;
}
- catch (Exception e)
+ catch (Exception)
{
- _logger.LogError(e, "Exception in removeColumnsFromChan: {Message}", e.Message);
+ // Exception will propagate to calling method for proper logging
}
return result;
}
@@ -643,7 +643,7 @@ private void tabControlElectrodeQuality_SelectedIndexChanged(object sender, Even
highlightSelectedTab(0);
}
- Log.Debug("tabControlElectrodeQuality_SelectedIndexChanged" + " | _currentBCISignalCheckMode: " + _currentBCISignalCheckMode.ToString());
+ _logger?.LogDebug("tabControlElectrodeQuality_SelectedIndexChanged | _currentBCISignalCheckMode: {CurrentBCISignalCheckMode}", _currentBCISignalCheckMode);
}
///
@@ -696,7 +696,7 @@ private void GetGraphYLims(int scaleIdx, out int yLimMin, out int yLimMax)
}
catch (Exception e)
{
- Log.Exception(e.Message);
+ _logger?.LogError(e, "Exception in GetGraphYLims");
}
yLimMax = scale;
@@ -774,7 +774,7 @@ public void handle125Scaling()
}
catch (Exception ex)
{
- _logger.LogError(e, "Exception in ProcessDataSignalCheck: {Message}", e.Message);
+ _logger.LogError(ex, "Exception in ProcessDataSignalCheck: {Message}", ex.Message);
}
}
}
diff --git a/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlErrorBluetoothDisconnected.cs b/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlErrorBluetoothDisconnected.cs
index ab0f015a..95a5282c 100644
--- a/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlErrorBluetoothDisconnected.cs
+++ b/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlErrorBluetoothDisconnected.cs
@@ -190,7 +190,7 @@ public void bluetoothResultHandler(DAQ_gTecBCI.BluetoothEvent bluetoothEvent, Di
}
catch (Exception ex)
{
- Log.Exception("UserControlErrorBluetoothDisconnected | bluetoothResultHandler | Exception: " + ex.Message);
+ _logger.LogError(ex, "UserControlErrorBluetoothDisconnected | bluetoothResultHandler | Exception");
}
}));
diff --git a/src/Extensions/BCI/Actuators/gTec_SensorUI/Utils.cs b/src/Extensions/BCI/Actuators/gTec_SensorUI/Utils.cs
index db86bac5..3ed57db4 100644
--- a/src/Extensions/BCI/Actuators/gTec_SensorUI/Utils.cs
+++ b/src/Extensions/BCI/Actuators/gTec_SensorUI/Utils.cs
@@ -9,7 +9,7 @@ namespace ACAT.Extensions.BCI.Actuators.gTecSensorUI
{
internal class Utils
{
- private static readonly ILogger _logger = LoggerFactory.GetLogger();
+ private static readonly ILogger _logger = LoggingConfiguration.CreateLogger();
internal static void HandleHelpNavigaion(WebBrowserNavigatingEventArgs e)
{
diff --git a/src/Extensions/BCI/Actuators/gTec_SensorUI/gTecDeviceTester.cs b/src/Extensions/BCI/Actuators/gTec_SensorUI/gTecDeviceTester.cs
index 75d56ebd..600b1f58 100644
--- a/src/Extensions/BCI/Actuators/gTec_SensorUI/gTecDeviceTester.cs
+++ b/src/Extensions/BCI/Actuators/gTec_SensorUI/gTecDeviceTester.cs
@@ -173,7 +173,7 @@ public void initialize()
_endSignalCheckTimer = false;
// Create main form
- _mainForm = new SensorForm(gTecBCI);
+ _mainForm = new SensorForm(gTecBCI, null);
// Set handlers for main events
if (_Testing_useSensor)
@@ -459,7 +459,7 @@ private void buttonNextHandler(String buttonNextName)
if (!userPassedLastSignalQualityCheck)
{
// Exit anyways regardless of signal quality result
- Log.Debug("User did not pass signal quality check but set testing parameter to ignore result. Exiting as if user did pass the check");
+ _logger.LogDebug("User did not pass signal quality check but set testing parameter to ignore result. Exiting as if user did pass the check");
}
}
@@ -494,7 +494,7 @@ private void buttonNextHandler(String buttonNextName)
else
{
// Display message to user prompting them to improve signal quality before moving on
- Log.Debug("Not exiting | Did not pass signal quality criteria");
+ _logger.LogDebug("Not exiting | Did not pass signal quality criteria");
bool confirmed = ConfirmBoxOneOption.ShowDialog(StringResources.SignalQualityChecksFailed +
"\n" + StringResources.Youneedtocompleteboth + "\n“ +Impedance” tests and get good signals to" + "\n" + "proceed" +
"\n" + StringResources.Pleaserefertotheuserguideforhelp, "", StringResources.OK, _mainForm, false);
@@ -512,7 +512,7 @@ private void buttonNextHandler(String buttonNextName)
///
private void runSignalCheckIfRequired()
{
- Log.Debug("gTecDeviceTester | runSignalCheckIfRequired");
+ _logger.LogDebug("gTecDeviceTester | runSignalCheckIfRequired");
// Always check time last impedance test was run (all electrodes tested) and update UI accordingly
long timestampPrevImpedanceTest = BCIActuatorSettings.Settings.SignalQuality_TimeOfLastImpedanceCheck;
@@ -523,8 +523,8 @@ private void runSignalCheckIfRequired()
bool maxTimeHasElapsed = false;
if (minElapsedPrevSignalQualityCheck >= maxTimeMins)
maxTimeHasElapsed = true;
- Log.Debug(String.Format("runSignalCheckIfRequired | timestampPrevImpedanceTest: {0}, timestampNow: {1}, secDiff: {2}", timestampPrevImpedanceTest.ToString(), timestampNow.ToString(), secDiff.ToString()));
- Log.Debug(String.Format("minElapsedPrevSignalQualityCheck: {0}, maxTimeMins: {1}, maxTimeHasElapsed: {2}", minElapsedPrevSignalQualityCheck.ToString(), maxTimeMins.ToString(), maxTimeHasElapsed.ToString()));
+ _logger.LogDebug("runSignalCheckIfRequired | timestampPrevImpedanceTest: {TimestampPrevImpedanceTest}, timestampNow: {TimestampNow}, secDiff: {SecDiff}", timestampPrevImpedanceTest, timestampNow, secDiff);
+ _logger.LogDebug("minElapsedPrevSignalQualityCheck: {MinElapsedPrevSignalQualityCheck}, maxTimeMins: {MaxTimeMins}, maxTimeHasElapsed: {MaxTimeHasElapsed}", minElapsedPrevSignalQualityCheck, maxTimeMins, maxTimeHasElapsed);
// Always check if user passed the last overall signal quality check that was executed
// If max time has not passed, but user did not pass their most recent overall signal quality check,
diff --git a/src/Extensions/BCI/Actuators/openBCI_SensorUI/OpenBCIDeviceTester.cs b/src/Extensions/BCI/Actuators/openBCI_SensorUI/OpenBCIDeviceTester.cs
index 539e8e63..f7b1b1b0 100644
--- a/src/Extensions/BCI/Actuators/openBCI_SensorUI/OpenBCIDeviceTester.cs
+++ b/src/Extensions/BCI/Actuators/openBCI_SensorUI/OpenBCIDeviceTester.cs
@@ -33,7 +33,7 @@ namespace ACAT.Extensions.BCI.Actuators.openBCISensorUI
///
public class OpenBCIDeviceTester
{
- private readonly ILogger _logger;
+ private readonly ILogger _logger = LogManager.GetLogger();
///
/// Variables representing all the different states in testing process (state machine)
@@ -202,12 +202,12 @@ public OpenBCIDeviceTester()
///
public void initialize()
{
- Log.Debug("OpenBCIDeviceTester | initialize");
+ _logger.LogDebug("Initializing OpenBCIDeviceTester");
// Close main form if for some reason it's opened at this point
if (_mainForm != null && _mainForm.IsDisposed == false)
{
- Log.Debug("OpenBCIDeviceTester | _mainForm != null && _mainForm.IsDisposed == false");
+ _logger.LogDebug("Main form is open and not disposed, closing it");
_mainForm.Close();
_mainForm.Dispose();
}
@@ -219,7 +219,7 @@ public void initialize()
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, "Exception during initialization");
}
if (ExitOnboardingEarly)
@@ -317,7 +317,7 @@ public void Exit(bool lostConnection)
///
private void _mainForm_EvtFormClosed(object sender, FormClosedEventArgs e)
{
- Log.Debug("OpenBCIDeviceTester | _mainForm_EvtFormClosed | _deviceTestingState: " + _deviceTestingState.ToString());
+ _logger.LogDebug("Main form closed with DeviceTestingState: {DeviceTestingState}", _deviceTestingState);
if (_deviceTestingState == DeviceTestingState.ReceivedBCIError_LostDataConnection)
{
@@ -375,9 +375,10 @@ private void startSignalQualityTestingState(DeviceTestingState newDeviceTestingS
bool maxTimeHasElapsed = false;
if (minElapsedPrevSignalQualityCheck >= maxTimeMins)
maxTimeHasElapsed = true;
- Log.Debug(String.Format("startSignalQualityTestingState | newDeviceTestingState == DeviceTestingState.BCISignalCheckStartRequired" +
- "\ntimestampPrevImpedanceTest: {0}, timestampNow: {1}, secDiff: {2}", timestampPrevImpedanceTest.ToString(), timestampNow.ToString(), secDiff.ToString()));
- Log.Debug(String.Format("minElapsedPrevSignalQualityCheck: {0}, maxTimeMins: {1}, maxTimeHasElapsed: {2}", minElapsedPrevSignalQualityCheck.ToString(), maxTimeMins.ToString(), maxTimeHasElapsed.ToString()));
+ _logger.LogDebug("Signal quality test timing - PrevTest: {PrevTestTimestamp}, Now: {NowTimestamp}, SecDiff: {SecDiff}",
+ timestampPrevImpedanceTest, timestampNow, secDiff);
+ _logger.LogDebug("Signal quality elapsed check - MinElapsed: {MinElapsed}min, MaxTime: {MaxTime}min, HasElapsed: {HasElapsed}",
+ minElapsedPrevSignalQualityCheck, maxTimeMins, maxTimeHasElapsed);
// Always check if user passed the last overall signal quality check that was executed
// If max time has not passed, but user did not pass their most recent overall signal quality check,
@@ -457,7 +458,7 @@ private void startSignalQualityTestingState(DeviceTestingState newDeviceTestingS
///
private void finishSignalQualityTestingState(DeviceTestingState currentDeviceTestingState)
{
- Log.Debug("OpenBCIDeviceTester | finishSignalQualityTestingState | currentDeviceTestingState: " + currentDeviceTestingState.ToString());
+ _logger.LogDebug("Finishing signal quality testing with state: {DeviceTestingState}", currentDeviceTestingState);
// Next button selected from BCI signal check start required screen
if (currentDeviceTestingState == DeviceTestingState.BCISignalCheckStartRequired)
@@ -533,20 +534,20 @@ private void finishSignalQualityTestingState(DeviceTestingState currentDeviceTes
bool userPassedLastSignalQualityCheck = BCIActuatorSettings.Settings.SignalQuality_PassedLastOverallQualityCheck;
if (userPassedLastSignalQualityCheck)
{
- Log.Debug("User passed most recent signal quality check");
+ _logger.LogDebug("User passed most recent signal quality check");
exitBCIOnboarding = true;
}
// Check if testing parameter set to ignore signal quality check result
if (BCIActuatorSettings.Settings.Testing_IgnoreSignalTestResultDuringOnboarding)
{
- Log.Debug("BCIActuatorSettings.Testing_IgnoreSignalTestResultDuringOnboarding = true");
+ _logger.LogDebug("Ignoring signal test result during onboarding (Testing_IgnoreSignalTestResultDuringOnboarding enabled)");
exitBCIOnboarding = true;
if (!userPassedLastSignalQualityCheck)
{
// Exit anyways regardless of signal quality result
- Log.Debug("User did not pass signal quality check but set testing parameter to ignore result. Exiting as if user did pass the check");
+ _logger.LogDebug("User did not pass signal quality check but testing parameter is set to ignore - exiting anyway");
}
}
@@ -584,7 +585,7 @@ private void finishSignalQualityTestingState(DeviceTestingState currentDeviceTes
else
{
// Display message to user prompting them to improve signal quality before moving on
- Log.Debug("Not exiting | Did not pass signal quality criteria");
+ _logger.LogDebug("Not exiting - user did not pass signal quality criteria");
_ = ConfirmBoxOneOption.ShowDialog("Signal Quality Checks Failed or Incomplete" +
"\nYou need to complete both “Railing” and\n“Impedance” tests and get good signals to\nproceed" +
"\nPlease refer to the user guide for help", "", StringResources.OK, _mainForm, false);
@@ -617,7 +618,7 @@ private void _mainForm_EvtButtonRetestClicked(object sender)
///
private void retestBCIConnections()
{
- Log.Debug("retestBCIConnections(). deviceTestingState: " + _deviceTestingState);
+ _logger.LogDebug("Retesting BCI connections with state: {DeviceTestingState}", _deviceTestingState);
// If already on Optical sensor error screen -> retest button does not check all BCI connections from the beginning, tests optical sensor right away
// _requestTestTriggerBox goes to correct user control when test completed
@@ -666,7 +667,7 @@ private void _mainForm_EvtButtonExitClicked_DEBUG(object sender)
try
{
_Testing_useSensor_TestIndex += 1;
- Log.Debug("OpenBCIDeviceTester | _mainForm_EvtButtonExitClicked_DEBUG | _Testing_useSensor_TestIndex: " + _Testing_useSensor_TestIndex.ToString());
+ _logger.LogDebug("DEBUG Exit button clicked, test index: {TestIndex}", _Testing_useSensor_TestIndex);
if (_Testing_useSensor_TestIndex < _DebugStates.Length)
{
DeviceTestingState newState = _DebugStates[_Testing_useSensor_TestIndex];
@@ -698,7 +699,7 @@ private void _mainForm_EvtButtonExitClicked_DEBUG(object sender)
}
catch (Exception e)
{
- Log.Exception("_mainForm_EvtButtonExitClicked_DEBUG exception: " + e.ToString());
+ _logger.LogError(e, "Exception in DEBUG exit button handler");
}
}
@@ -745,7 +746,7 @@ public async Task startBCIDeviceTesting(int initialDelaySec = 0)
}
}
- Log.Debug("startBCIDeviceTesting | Calling InitDAQ()");
+ _logger.LogDebug("Starting BCI device testing - calling InitDAQ()");
// Call async function which connects to BCI sensor + starts task that controls TriggerBox flashing and tests optical sensor by request
if (_Testing_useSensor == true)
@@ -790,7 +791,7 @@ private void changeTriggerBoxColor(Color color)
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, "Exception in changeTriggerBoxColor");
}
}
@@ -809,7 +810,7 @@ private void changeDeviceTestingState(DeviceTestingState state)
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, "Exception in changeDeviceTestingState");
}
}
@@ -820,7 +821,7 @@ private void changeDeviceTestingState(DeviceTestingState state)
///
public async Task InitDAQ() // Original function
{
- Log.Debug("InitDAQ()");
+ _logger.LogDebug("Initializing DAQ");
_initDAQTaskStopped = false;
while (!_endTasks)
@@ -834,31 +835,31 @@ public async Task InitDAQ() // Original function
BaseDAQ.ExitCodes exitCode = ((DAQ_OpenBCI)_daqInstance).getUsbDongleConnected();
if (exitCode == BaseDAQ.ExitCodes.UNABLE_TO_OPEN_PORT_ERROR)
{
- Log.Debug("OpenBCIDeviceTester | _deviceTestingState = DeviceTestingState.ReceivedBCIError_UsbDongle");
+ _logger.LogDebug("USB dongle connection error detected, state: ReceivedBCIError_UsbDongle");
_deviceTestingState = DeviceTestingState.ReceivedBCIError_UsbDongle;
changeDeviceTestingState(DeviceTestingState.ReceivedBCIError_UsbDongle);
}
else
{
- Log.Debug("InitDAQ | exitCode: " + exitCode.ToString());
+ _logger.LogDebug("InitDAQ exit code: {ExitCode}", exitCode);
bool success = _daqInstance.Start("");
if (success)
{
- Log.Debug("DAQ_OpenBCI.Start() | true");
+ _logger.LogDebug("DAQ_OpenBCI started successfully");
// Check latency setting of port is set correctly
bool latencyPortOk = ((DAQ_OpenBCI)_daqInstance).CheckLatencyPort();
if (latencyPortOk)
{
- Log.Debug("DAQ_OpenBCI.CheckLatencyPort() | true");
+ _logger.LogDebug("DAQ_OpenBCI latency port check passed");
if (_daqInstance.deviceInitialized)
{
- Log.Debug("DAQ_OpenBCI.deviceInitialized | true");
+ _logger.LogDebug("DAQ_OpenBCI device initialized successfully");
// BCI impedence / railing integration - debugging option, go straight to signal check screens without checking optical sensor
- Log.Debug("_Testing_BCIOnboardingIgnoreOpticalSensorChecks == true");
+ _logger.LogDebug("Testing mode enabled - ignoring optical sensor checks during onboarding");
// Go to first stage of signal quality checking process
startSignalQualityTestingState(DeviceTestingState.BCISignalCheckStartRequired);
@@ -866,12 +867,12 @@ public async Task InitDAQ() // Original function
}
else
{
- Log.Debug("DAQ_OpenBCI.deviceInitialized | false");
+ _logger.LogDebug("DAQ_OpenBCI device initialization failed");
}
}
else
{
- Log.Debug("DAQ_OpenBCI.CheckLatencyPort() | false | _deviceTestingState = DeviceTestingState.ReceivedBCIError_PortConfig");
+ _logger.LogDebug("DAQ_OpenBCI latency port check failed, state: ReceivedBCIError_PortConfig");
_daqInstance.Stop();
_deviceTestingState = DeviceTestingState.ReceivedBCIError_PortConfig;
changeDeviceTestingState(DeviceTestingState.ReceivedBCIError_PortConfig);
@@ -879,7 +880,7 @@ public async Task InitDAQ() // Original function
}
else
{
- Log.Debug("OpenBCIDeviceTester | _deviceTestingState = DeviceTestingState.ReceivedBCIError_CytonBoard");
+ _logger.LogDebug("Cyton board connection error detected, state: ReceivedBCIError_CytonBoard");
_deviceTestingState = DeviceTestingState.ReceivedBCIError_CytonBoard;
changeDeviceTestingState(DeviceTestingState.ReceivedBCIError_CytonBoard);
}
@@ -890,7 +891,7 @@ public async Task InitDAQ() // Original function
}
_initDAQTaskStopped = true;
- Log.Debug("InitDAQ | hole | _initDAQ_TaskStopped = true");
+ _logger.LogDebug("InitDAQ task stopped");
// return;
}
diff --git a/src/Extensions/BCI/Actuators/openBCI_SensorUI/SensorForm.cs b/src/Extensions/BCI/Actuators/openBCI_SensorUI/SensorForm.cs
index a67084fe..3ea87f13 100644
--- a/src/Extensions/BCI/Actuators/openBCI_SensorUI/SensorForm.cs
+++ b/src/Extensions/BCI/Actuators/openBCI_SensorUI/SensorForm.cs
@@ -20,6 +20,7 @@
using System.Windows.Forms;
using static ACAT.Extensions.BCI.Actuators.openBCISensorUI.OpenBCIDeviceTester;
using static ACAT.Extensions.BCI.Actuators.openBCISensorUI.UserControlBCISignalCheck;
+using Microsoft.Extensions.Logging;
namespace ACAT.Extensions.BCI.Actuators.openBCISensorUI
{
@@ -28,6 +29,8 @@ namespace ACAT.Extensions.BCI.Actuators.openBCISensorUI
///
public partial class SensorForm : Form
{
+ private static ILogger _logger => LogManager.GetLogger();
+
///
/// User control displayed while trying to connect to sensor
///
@@ -210,7 +213,7 @@ public SensorForm(DeviceTestingState initialState)
///
public void changeDeviceTestingState(DeviceTestingState state)
{
- Log.Debug("SensorForm | changeDeviceTestingState | state: " + state.ToString());
+ _logger?.LogDebug("SensorForm | changeDeviceTestingState | state: {State}", state);
DeviceTestingState prevDeviceTestingState = _mainFormDeviceTestingState;
UserControl newUserControl = null;
@@ -339,8 +342,8 @@ public void changeDeviceTestingState(DeviceTestingState state)
///
private void startStopProcessDataTimer(bool startProcessDataTimer, DeviceTestingState state)
{
- Log.Debug("startStopProcessDataTimer | startProcessDataTimer: " + startProcessDataTimer.ToString() +
- " | state: " + state.ToString());
+ _logger?.LogDebug("startStopProcessDataTimer | startProcessDataTimer: {StartTimer} | state: {State}",
+ startProcessDataTimer, state);
if (startProcessDataTimer)
{
@@ -367,11 +370,11 @@ private void startStopProcessDataTimer(bool startProcessDataTimer, DeviceTesting
}
timerProcessData.Start();
- Log.Debug("startStopProcessDataTimer | Started timerProcessData");
+ _logger?.LogDebug("startStopProcessDataTimer | Started timerProcessData");
}
catch (Exception e)
{
- Log.Exception("startStopProcessDataTimer | Exception: " + e.ToString());
+ _logger?.LogError(e, "startStopProcessDataTimer | Exception");
}
}
else
@@ -388,7 +391,7 @@ private void startStopProcessDataTimer(bool startProcessDataTimer, DeviceTesting
}
catch (Exception e)
{
- Log.Exception("startStopProcessDataTimer | Exception: " + e.ToString());
+ _logger?.LogError(e, "startStopProcessDataTimer | Exception");
}
}
}
@@ -430,7 +433,7 @@ private void ProcessDataSignalCheck_Tick(object sender, EventArgs e)
// Check flag to stop this particular timer
if (_stopTimers || OpenBCIDeviceTester._endSignalCheckTimer)
{
- Log.Debug("ProcessDataSignalCheck_Tick | _stopTimers | OpenBCIDeviceTester._endSignalCheckTimer");
+ _logger?.LogDebug("ProcessDataSignalCheck_Tick | _stopTimers | OpenBCIDeviceTester._endSignalCheckTimer");
startStopProcessDataTimer(false, DeviceTestingState.ExitBCITesting);
return;
}
@@ -465,7 +468,7 @@ private void Handle_FormCLosing(object sender, FormClosingEventArgs e)
// Only exit if ExitOnboardingEarly flag has been set (user selected Exit button)
if (!ExitOnboardingEarly)
{
- Log.Debug("User has requested to close form (Alt + F4) - ignore");
+ _logger?.LogDebug("User has requested to close form (Alt + F4) - ignore");
e.Cancel = true;
closeReasonIsUserClosing = true;
}
@@ -543,7 +546,7 @@ private void buttonRetest_Click(object sender, EventArgs e)
///
private void modifyUserControlsForDebugMode()
{
- Log.Debug("SensorForm | modifyUserControlsForDebugMode");
+ _logger?.LogDebug("SensorForm | modifyUserControlsForDebugMode");
_userControlTestBCIConnections.buttonExit.AutoSize = true;
_userControlTestBCIConnections.buttonExit.Font = new Font("Montserrat Medium", 13F);
diff --git a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorCytonBoard.cs b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorCytonBoard.cs
index 2f108960..e7913979 100644
--- a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorCytonBoard.cs
+++ b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorCytonBoard.cs
@@ -69,7 +69,7 @@ private void WebBrowserDesc_DocumentCompleted(object sender, WebBrowserDocumentC
private void WebBrowserDesc_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
- Utils.HandleHelpNavigaion(e);
+ Utils.HandleHelpNavigation(e);
}
}
}
\ No newline at end of file
diff --git a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorOpticalSensor.cs b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorOpticalSensor.cs
index 08dc6c4f..d83c2043 100644
--- a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorOpticalSensor.cs
+++ b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorOpticalSensor.cs
@@ -62,7 +62,7 @@ public partial class UserControlBCIErrorOpticalSensor : UserControl
///
public UserControlBCIErrorOpticalSensor(String stepId, ILogger logger = null)
{
- _logger = logger ?? LoggerFactory.GetLogger();
+ _logger = logger ?? LoggingConfiguration.CreateLogger();
InitializeComponent();
_stepId = stepId;
@@ -116,7 +116,7 @@ private void WebBrowserDesc_DocumentCompleted(object sender, WebBrowserDocumentC
private void WebBrowserDesc_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
- Utils.HandleHelpNavigaion(e);
+ Utils.HandleHelpNavigation(e);
}
////
diff --git a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorOpticalSensorDetect.cs b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorOpticalSensorDetect.cs
index 9606e688..19558a48 100644
--- a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorOpticalSensorDetect.cs
+++ b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorOpticalSensorDetect.cs
@@ -69,7 +69,7 @@ private void WebBrowserDesc_DocumentCompleted(object sender, WebBrowserDocumentC
private void WebBrowserDesc_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
- Utils.HandleHelpNavigaion(e);
+ Utils.HandleHelpNavigation(e);
}
}
}
\ No newline at end of file
diff --git a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorPortConfig.cs b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorPortConfig.cs
index c398a14d..08205e4e 100644
--- a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorPortConfig.cs
+++ b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorPortConfig.cs
@@ -78,7 +78,7 @@ private void WebBrowserDesc_DocumentCompleted(object sender, WebBrowserDocumentC
private void WebBrowserDesc_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
- Utils.HandleHelpNavigaion(e);
+ Utils.HandleHelpNavigation(e);
}
}
}
\ No newline at end of file
diff --git a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorUsbDongle.cs b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorUsbDongle.cs
index d7dd5058..8d20f3e7 100644
--- a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorUsbDongle.cs
+++ b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorUsbDongle.cs
@@ -56,7 +56,7 @@ private void WebBrowserDesc_DocumentCompleted(object sender, WebBrowserDocumentC
private void WebBrowserDesc_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
- Utils.HandleHelpNavigaion(e);
+ Utils.HandleHelpNavigation(e);
}
}
}
\ No newline at end of file
diff --git a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCISignalCheck.cs b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCISignalCheck.cs
index 3bf3f971..ea256d9c 100644
--- a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCISignalCheck.cs
+++ b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCISignalCheck.cs
@@ -23,6 +23,7 @@
using ACAT.Extensions.BCI.Common.BCIControl;
using Accord.Math;
using brainflow;
+using Microsoft.Extensions.Logging;
//using SharpDX.Direct2D1;
using System;
using System.Collections.Generic;
@@ -39,6 +40,11 @@ namespace ACAT.Extensions.BCI.Actuators.openBCISensorUI
///
public partial class UserControlBCISignalCheck : UserControl
{
+ ///
+ /// Logger instance for this class
+ ///
+ private readonly ILogger _logger;
+
///
/// The DAQ instance for OpenBCI
///
@@ -278,6 +284,9 @@ public UserControlBCISignalCheck(String stepId)
{
InitializeComponent();
+ // Initialize logger
+ _logger = LoggingConfiguration.CreateLogger();
+
// Initialize the DAQ instance
_daqInstance = DAQFactory.CreateDAQ(DAQDeviceType.OpenBCI);
@@ -614,7 +623,7 @@ public void changeSignalCheckMode(BCISignalCheckMode mode)
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, ex.Message);
}
}
@@ -627,7 +636,7 @@ public void changeSignalCheckMode(BCISignalCheckMode mode)
public void initializeBCISignalCheck(bool maxTimeHasElapsed, double maxTimeMins, double minElapsedPrevSignalQualityCheck,
bool userPassedLastSignalQualityCheck)
{
- Log.Debug(String.Format("initializeBCISignalCheck | maxTimeHasElapsed: {0}, " +
+ _logger.LogDebug(String.Format("initializeBCISignalCheck | maxTimeHasElapsed: {0}, " +
"minElapsedPrevSignalQualityCheck: {1}, userPassedLastSignalQualityCheck: {2}",
maxTimeHasElapsed.ToString(), minElapsedPrevSignalQualityCheck.ToString(), userPassedLastSignalQualityCheck.ToString()));
@@ -669,7 +678,7 @@ public void initializeBCISignalCheck(bool maxTimeHasElapsed, double maxTimeMins,
for (int i = 0; i < _indEegChannels.Length; i++)
_indEegChannels_str += (_indEegChannels[i].ToString() + ", ");
- Log.Debug(String.Format("initializeBCISignalCheck | _numChannels: {0}, " + "_samplingRate: {1}, " +
+ _logger.LogDebug(String.Format("initializeBCISignalCheck | _numChannels: {0}, " + "_samplingRate: {1}, " +
"_scaleIdx: {2}, _bufSize: {3}\n" +
"_indEegChannels_str: {4}",
_numChannels.ToString(), _samplingRate.ToString(), _scaleIdx.ToString(), _bufSize.ToString(), _indEegChannels_str));
@@ -845,7 +854,7 @@ public void initializeBCISignalCheck(bool maxTimeHasElapsed, double maxTimeMins,
//private async Task StartImpedanceTesting()
private void StartImpedanceTesting()
{
- Log.Debug("StartImpedanceTesting");
+ _logger.LogDebug("StartImpedanceTesting");
if (!_runImpedanceTestingCycle && _daqInstance.deviceInitialized)
{
@@ -855,7 +864,7 @@ private void StartImpedanceTesting()
////// Before running impedance tests ///////
//// Stop streaming on board, does not consistently register commands while streaming
- Log.Debug("Stop streaming");
+ _logger.LogDebug("Stop streaming");
((DAQ_OpenBCI)_daqInstance).Stop_Streaming();
Thread.Sleep(50);
@@ -866,7 +875,7 @@ private void StartImpedanceTesting()
EEGChannel currentEegChannel = _eegChannels[_currentImpedanceTestElectrodeIndex];
String electrodeName = currentEegChannel._electrodeName;
- Log.Debug("StartImpedanceTesting loop | _currentImpedanceTestElectrodeIndex: " + _currentImpedanceTestElectrodeIndex.ToString() +
+ _logger.LogDebug("StartImpedanceTesting loop | _currentImpedanceTestElectrodeIndex: " + _currentImpedanceTestElectrodeIndex.ToString() +
" | electrodeName: " + electrodeName.ToString());
String cmdStartElectrodeImpedanceTest = currentEegChannel.ImpedanceTestingEnableCmd;
@@ -884,7 +893,7 @@ private void StartImpedanceTesting()
_daqInstance.GetData(); // Clear buffer
//// Send enable electrode Impedance testing commands
- Log.Debug(String.Format("Sending enable electrode {0} Impedance testing command: {1}", electrodeName, cmdStartElectrodeImpedanceTest));
+ _logger.LogDebug(String.Format("Sending enable electrode {0} Impedance testing command: {1}", electrodeName, cmdStartElectrodeImpedanceTest));
((DAQ_OpenBCI)_daqInstance).Config_Board(cmdStartElectrodeImpedanceTest);
Thread.Sleep(750);
@@ -892,7 +901,7 @@ private void StartImpedanceTesting()
_daqInstance.deviceInitialized = true;
//// Send start streaming
- Log.Debug("Start streaming");
+ _logger.LogDebug("Start streaming");
((DAQ_OpenBCI)_daqInstance).Start_Streaming();
Thread.Sleep(50);
@@ -910,15 +919,15 @@ private void StartImpedanceTesting()
_daqInstance.deviceInitialized = false;
//// Stop streaming
- Log.Debug("Stop streaming");
+ _logger.LogDebug("Stop streaming");
((DAQ_OpenBCI)_daqInstance).Stop_Streaming();
Thread.Sleep(50);
// Send command to disable impedance testing for specific electrode
- Log.Debug(String.Format("Sending disable electrode {0} impedance testing command: {1}", electrodeName, cmdEndElectrodeImpedanceTest));
+ _logger.LogDebug(String.Format("Sending disable electrode {0} impedance testing command: {1}", electrodeName, cmdEndElectrodeImpedanceTest));
((DAQ_OpenBCI)_daqInstance).Config_Board(cmdEndElectrodeImpedanceTest);
Thread.Sleep(750);
- Log.Debug("Completed impedance testing electrode: " + _currentImpedanceTestElectrodeIndex.ToString());
+ _logger.LogDebug("Completed impedance testing electrode: " + _currentImpedanceTestElectrodeIndex.ToString());
// Reset back color of impedance result button in Impedance testing page to transparent
Invoke(new Action(() =>
@@ -933,7 +942,7 @@ private void StartImpedanceTesting()
_currentImpedanceTestElectrodeIndex = 0;
if (BCIActuatorSettings.Settings.SignalQuality_StopImpedanceTestAfterOneCycle)
{
- Log.Debug("SignalQuality_StopImpedanceTestAfterOneCycle = true | Stopping impedance testing");
+ _logger.LogDebug("SignalQuality_StopImpedanceTestAfterOneCycle = true | Stopping impedance testing");
try
{
Invoke(new Action(() =>
@@ -948,7 +957,7 @@ private void StartImpedanceTesting()
}
catch (Exception ex)
{
- Log.Exception(ex.Message);
+ _logger.LogError(ex, ex.Message);
}
}
}
@@ -958,18 +967,18 @@ private void StartImpedanceTesting()
//// Do opposite of what was done at the beginning on this function to bring board back to default state
// Reset board to default parameters
- Log.Debug("Send command to reset board");
+ _logger.LogDebug("Send command to reset board");
((DAQ_OpenBCI)_daqInstance).Reset_Board(); // Run multiple times?
Thread.Sleep(750); // Tested 750 - is ok
- Log.Debug("Send command to reset board");
+ _logger.LogDebug("Send command to reset board");
((DAQ_OpenBCI)_daqInstance).Reset_Board();
Thread.Sleep(4500);
- Log.Debug("Calling Stop()");
+ _logger.LogDebug("Calling Stop()");
_daqInstance.Stop();
Thread.Sleep(250); // Tested 250 - is ok
- Log.Debug("Calling Start()");
+ _logger.LogDebug("Calling Start()");
_daqInstance.Start(); // Also starts streaming
// Stopped Impedance testing cycle, update UI accordingly
@@ -990,7 +999,7 @@ private void StartImpedanceTesting()
// save this time as time of last signal quality check completed
if (_AllElectrodesOverallSignalQualityResult.allElectrodesUpdatedWithinSession == true)
{
- Log.Debug("Saving current time as SignalQuality_TimeOfLastImpedanceCheck");
+ _logger.LogDebug("Saving current time as SignalQuality_TimeOfLastImpedanceCheck");
BCIActuatorSettings.Settings.SignalQuality_TimeOfLastImpedanceCheck = DateTimeOffset.Now.ToUnixTimeSeconds();
BCIActuatorSettings.Save(); // Save settings
}
@@ -1029,7 +1038,7 @@ public void ProcessDataSignalCheck(double[,] data, double[,] filteredData)
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, ex.Message);
}
// Removed automatic optical sensor checks below for now - it's likely the optical sensor is still
@@ -1100,7 +1109,7 @@ private void updateRailingTestResult(int chIdx, int railingResultPercentage, boo
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, ex.Message);
}
}
@@ -1161,7 +1170,7 @@ private void updateImpedanceResult(int chIdx, int impedanceResult, bool update_u
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, ex.Message);
}
}
@@ -1213,7 +1222,7 @@ public bool updateSignalQualityResult(int chIdx)
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, ex.Message);
}
return ret;
@@ -1260,7 +1269,7 @@ private void updateSignalChart(int channelIndex, double[] samples, bool scale_pl
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, ex.Message);
}
}
@@ -1294,9 +1303,9 @@ private static bool AppendDataToBuffer2(double[,] data, double[,] inBuffer, int
result = true;
}
- catch (Exception e)
+ catch (Exception)
{
- Log.Exception(e.Message);
+ // Exception will propagate to calling method for proper logging
}
return result;
}
@@ -1339,7 +1348,7 @@ private void tabControlElectrodeQuality_SelectedIndexChanged(object sender, Even
}
}
- Log.Debug("tabControlElectrodeQuality_SelectedIndexChanged" +
+ _logger.LogDebug("tabControlElectrodeQuality_SelectedIndexChanged" +
" | _impedanceTestingRunning: " + _impedanceTestingRunning.ToString() +
" | _currentBCISignalCheckMode: " + _currentBCISignalCheckMode.ToString());
}
@@ -1375,7 +1384,7 @@ private void highlightSelectedTab(int tabControlIndex)
}
catch (Exception e)
{
- Log.Exception(e.Message);
+ _logger.LogError(e, e.Message);
}
}
@@ -1420,7 +1429,7 @@ private void GetGraphYLimits(int scaleIdx, out int yLimMin, out int yLimMax)
}
catch (Exception e)
{
- Log.Exception(e.Message);
+ _logger.LogError(e, e.Message);
}
yLimMax = scale;
@@ -1434,13 +1443,13 @@ private void GetGraphYLimits(int scaleIdx, out int yLimMin, out int yLimMax)
///
private void buttonTestImpedance_Click(object sender, EventArgs e)
{
- Log.Debug("buttonTestImpedance_Click | _currentImpedanceTestElectrodeIndex: " + _currentImpedanceTestElectrodeIndex.ToString());
+ _logger.LogDebug("buttonTestImpedance_Click | _currentImpedanceTestElectrodeIndex: " + _currentImpedanceTestElectrodeIndex.ToString());
if (_runImpedanceTestingCycle)
{
try
{
- Log.Debug("Impedance cyclical testing running. Stopping process...");
+ _logger.LogDebug("Impedance cyclical testing running. Stopping process...");
buttonTestImpedance.Enabled = false;
buttonTestImpedance.BackColor = Color.Gray;
updateImpedanceTestingStateLabels(ImpedanceTestingState.STOP_IN_PROGRESS);
@@ -1450,7 +1459,7 @@ private void buttonTestImpedance_Click(object sender, EventArgs e)
}
catch (Exception ex)
{
- Log.Exception(ex.Message);
+ _logger.LogError(ex, ex.Message);
}
}
else if (!_runImpedanceTestingCycle)
@@ -1458,7 +1467,7 @@ private void buttonTestImpedance_Click(object sender, EventArgs e)
// Start impedance testing
try
{
- Log.Debug("Impedances testing not running. Starting process...");
+ _logger.LogDebug("Impedances testing not running. Starting process...");
buttonTestImpedance.Text = "Stop";
buttonNext.Enabled = false;
buttonNext.BackColor = Color.Gray;
@@ -1468,7 +1477,7 @@ private void buttonTestImpedance_Click(object sender, EventArgs e)
}
catch (Exception ex)
{
- Log.Exception(ex.Message);
+ _logger.LogError(ex, ex.Message);
}
// Start thread doing impedance testing
@@ -1566,7 +1575,7 @@ private void updateImpedanceTestingStateLabels(ImpedanceTestingState impedanceTe
}
catch (Exception ex)
{
- Log.Exception(ex.Message);
+ _logger.LogError(ex, ex.Message);
}
}
@@ -1607,7 +1616,7 @@ private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompl
private void WebBrowserDesc_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
- Utils.HandleHelpNavigaion(e);
+ Utils.HandleHelpNavigation(e);
}
///
@@ -1641,7 +1650,7 @@ public void handle125Scaling()
}
catch (Exception ex)
{
- Log.Exception(ex.Message);
+ _logger.LogError(ex, ex.Message);
}
}
}
diff --git a/src/Extensions/BCI/Actuators/openBCI_SensorUI/Utils.cs b/src/Extensions/BCI/Actuators/openBCI_SensorUI/Utils.cs
index 9ab1872a..cb9484cd 100644
--- a/src/Extensions/BCI/Actuators/openBCI_SensorUI/Utils.cs
+++ b/src/Extensions/BCI/Actuators/openBCI_SensorUI/Utils.cs
@@ -9,9 +9,9 @@ namespace ACAT.Extensions.BCI.Actuators.openBCISensorUI
{
internal class Utils
{
- private static readonly ILogger _logger = LoggerFactory.GetLogger();
+ private static readonly ILogger _logger = LoggingConfiguration.CreateLogger();
- internal static void HandleHelpNavigaion(WebBrowserNavigatingEventArgs e)
+ internal static void HandleHelpNavigation(WebBrowserNavigatingEventArgs e)
{
var str = e.Url.ToString();
diff --git a/src/Extensions/BCI/Common/AnimationSharp/AnimationSharpManagerV2.cs b/src/Extensions/BCI/Common/AnimationSharp/AnimationSharpManagerV2.cs
index d703bedc..1323ecae 100644
--- a/src/Extensions/BCI/Common/AnimationSharp/AnimationSharpManagerV2.cs
+++ b/src/Extensions/BCI/Common/AnimationSharp/AnimationSharpManagerV2.cs
@@ -41,7 +41,7 @@ namespace ACAT.Extensions.BCI.Common.AnimationSharp
///
public class AnimationSharpManagerV2
{
- private readonly ILogger _logger;
+ private readonly ILogger _logger = LogManager.GetLogger();
///
/// Current active Keyboard Layout
///
diff --git a/src/Extensions/BCI/Common/AnimationSharp/Utility/AnimationManagerUtils.cs b/src/Extensions/BCI/Common/AnimationSharp/Utility/AnimationManagerUtils.cs
index 139c08b4..cacd0fbe 100644
--- a/src/Extensions/BCI/Common/AnimationSharp/Utility/AnimationManagerUtils.cs
+++ b/src/Extensions/BCI/Common/AnimationSharp/Utility/AnimationManagerUtils.cs
@@ -27,7 +27,7 @@ namespace ACAT.Extensions.BCI.Common.AnimationSharp.Utility
///
public class AnimationManagerUtils
{
- private static readonly ILogger _logger = LoggerFactory.GetLogger();
+ private static readonly ILogger _logger = LoggingConfiguration.CreateLogger();
///
/// String messages for BCI
///
diff --git a/src/Extensions/BCI/Common/AnimationSharp/Utility/BCIUtils.cs b/src/Extensions/BCI/Common/AnimationSharp/Utility/BCIUtils.cs
index 8d3379ca..92db816e 100644
--- a/src/Extensions/BCI/Common/AnimationSharp/Utility/BCIUtils.cs
+++ b/src/Extensions/BCI/Common/AnimationSharp/Utility/BCIUtils.cs
@@ -18,11 +18,10 @@ namespace ACAT.Extensions.BCI.Common.AnimationSharp.Utility
public class BCIUtils
{
private readonly ILogger _logger;
- private readonly ILogger _logger;
public BCIUtils(ILogger logger = null)
{
- _logger = logger ?? LoggerFactory.GetLogger();
+ _logger = logger ?? LoggingConfiguration.CreateLogger();
}
///
diff --git a/src/Extensions/BCI/Common/AnimationSharp/Utility/CachedLogBCI.cs b/src/Extensions/BCI/Common/AnimationSharp/Utility/CachedLogBCI.cs
index 56bd830a..32fa6ef2 100644
--- a/src/Extensions/BCI/Common/AnimationSharp/Utility/CachedLogBCI.cs
+++ b/src/Extensions/BCI/Common/AnimationSharp/Utility/CachedLogBCI.cs
@@ -39,7 +39,7 @@ public class CachedLogBCI
public CachedLogBCI(string baseFileName, string baseDirPath = null, ILogger logger = null)
{
- _logger = logger ?? LoggerFactory.GetLogger();
+ _logger = logger ?? LoggingConfiguration.CreateLogger();
if (!string.IsNullOrEmpty(baseFileName))
{
LogFileName = baseFileName + ".csv";
diff --git a/src/Extensions/BCI/Common/AnimationSharp/Utility/SharpDXUtils.cs b/src/Extensions/BCI/Common/AnimationSharp/Utility/SharpDXUtils.cs
index 7ed4ff2f..b4af1cb9 100644
--- a/src/Extensions/BCI/Common/AnimationSharp/Utility/SharpDXUtils.cs
+++ b/src/Extensions/BCI/Common/AnimationSharp/Utility/SharpDXUtils.cs
@@ -24,7 +24,7 @@ namespace ACAT.Extensions.BCI.Common.AnimationSharp.Utility
{
public class SharpDXUtils
{
- private static readonly ILogger _logger = LoggerFactory.GetLogger();
+ private static readonly ILogger _logger = LoggingConfiguration.CreateLogger();
///
/// Get the border color from the Theme xml file
///
diff --git a/src/Extensions/BCI/Common/BCIInterfaceUtilities/CalibrationEyesForm.cs b/src/Extensions/BCI/Common/BCIInterfaceUtilities/CalibrationEyesForm.cs
index 68dee729..e145438f 100644
--- a/src/Extensions/BCI/Common/BCIInterfaceUtilities/CalibrationEyesForm.cs
+++ b/src/Extensions/BCI/Common/BCIInterfaceUtilities/CalibrationEyesForm.cs
@@ -309,7 +309,7 @@ private void SetEnableStateButtons(bool enable)
///
private void ShowCalibrationEyesSettingsForm()
{
- CalibrationEyesSettingsForm calibrationEyesSettingsForm = new();
+ CalibrationEyesSettingsForm calibrationEyesSettingsForm = new(null);
calibrationEyesSettingsForm.ShowDialog();
var parameters = calibrationEyesSettingsForm.ResultParameters;
calibrationEyesSettingsForm.Dispose();
diff --git a/src/Extensions/BCI/Common/BCIInterfaceUtilities/CalibrationEyesSettingsForm.cs b/src/Extensions/BCI/Common/BCIInterfaceUtilities/CalibrationEyesSettingsForm.cs
index fd8b6127..84f9aa27 100644
--- a/src/Extensions/BCI/Common/BCIInterfaceUtilities/CalibrationEyesSettingsForm.cs
+++ b/src/Extensions/BCI/Common/BCIInterfaceUtilities/CalibrationEyesSettingsForm.cs
@@ -79,7 +79,7 @@ public CalibrationEyesSettingsForm(ILogger logger)
public static ResultParams ShowDialog(string label, Form parent = null, bool setTopMost = false)
{
- var confirmBox = new CalibrationEyesSettingsForm();
+ var confirmBox = new CalibrationEyesSettingsForm(null);
confirmBox.ShowDialog(parent);
ResultParams retVal = confirmBox.ResultParameters;
confirmBox.Dispose();
diff --git a/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxCalibrationModes.cs b/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxCalibrationModes.cs
index 6f913e18..d62582c6 100644
--- a/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxCalibrationModes.cs
+++ b/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxCalibrationModes.cs
@@ -92,7 +92,7 @@ public ConfirmBoxCalibrationModes(ILogger logger)
public static Tuple ShowDialog(BCICalibrationStatus actuatorResponse, bool enableBeginBtn, Form parent = null, bool setTopMost = false)
{
- var confirmBox = new ConfirmBoxCalibrationModes();
+ var confirmBox = new ConfirmBoxCalibrationModes(null);
//To always display the form in the main screen
confirmBox.StartPosition = FormStartPosition.Manual;
confirmBox.Location = confirmBox.primaryScreen.WorkingArea.Location;
diff --git a/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxTriggerBoxSettings.cs b/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxTriggerBoxSettings.cs
index ea79754b..dee4b22e 100644
--- a/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxTriggerBoxSettings.cs
+++ b/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxTriggerBoxSettings.cs
@@ -60,7 +60,7 @@ public partial class ConfirmBoxTriggerBoxSettings : Form
///
public ConfirmBoxTriggerBoxSettings(ILogger logger = null)
{
- _logger = logger ?? LoggerFactory.GetLogger();
+ _logger = logger ?? LoggingConfiguration.CreateLogger();
InitializeComponent();
label1.Text = StringResources.CalibrationIsEssential;
Load += ConfirmBox_Load;
diff --git a/src/Extensions/BCI/Common/BCIInterfaceUtilities/OtherTestForm.cs b/src/Extensions/BCI/Common/BCIInterfaceUtilities/OtherTestForm.cs
index cb0fcf88..7e8e0393 100644
--- a/src/Extensions/BCI/Common/BCIInterfaceUtilities/OtherTestForm.cs
+++ b/src/Extensions/BCI/Common/BCIInterfaceUtilities/OtherTestForm.cs
@@ -41,7 +41,7 @@ public partial class OtherTestForm : Form
///
public OtherTestForm(ILogger logger = null)
{
- _logger = logger ?? LoggerFactory.GetLogger();
+ _logger = logger ?? LoggingConfiguration.CreateLogger();
InitializeComponent();
Load += ConfirmBox_Load;
}
diff --git a/src/Extensions/BCI/Common/BCIInterfaceUtilities/RemapCalibrationForm.cs b/src/Extensions/BCI/Common/BCIInterfaceUtilities/RemapCalibrationForm.cs
index 6dfd39ad..a343512b 100644
--- a/src/Extensions/BCI/Common/BCIInterfaceUtilities/RemapCalibrationForm.cs
+++ b/src/Extensions/BCI/Common/BCIInterfaceUtilities/RemapCalibrationForm.cs
@@ -74,7 +74,7 @@ public RemapCalibrationForm(ILogger logger)
public static bool ShowFormDialog(Form parent = null, bool setTopMost = false)
{
- var confirmBox = new RemapCalibrationForm();
+ var confirmBox = new RemapCalibrationForm(null);
//To always display the form in the main screen
confirmBox.StartPosition = FormStartPosition.Manual;
confirmBox.Location = confirmBox.primaryScreen.WorkingArea.Location;
diff --git a/src/Extensions/Default/Actuators/CameraActuator/AutoCalibrateForm.cs b/src/Extensions/Default/Actuators/CameraActuator/AutoCalibrateForm.cs
index 01be5ae6..efb679a2 100644
--- a/src/Extensions/Default/Actuators/CameraActuator/AutoCalibrateForm.cs
+++ b/src/Extensions/Default/Actuators/CameraActuator/AutoCalibrateForm.cs
@@ -13,6 +13,7 @@
using ACAT.Core.PanelManagement.Utils;
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Windows.Forms;
@@ -20,6 +21,7 @@ namespace ACAT.Extensions.Actuators.CameraActuator
{
internal partial class AutoCalibrateForm : Form
{
+ private static readonly ILogger _logger = LoggingConfiguration.CreateLogger();
private VideoWindowFinder _videoWindowFinder;
private readonly CameraActuator _visionActuator;
@@ -63,7 +65,7 @@ private void AutoCalibrateForm_Resize(object sender, EventArgs e)
private void AutoCalibrateForm_Shown(object sender, EventArgs e)
{
- _videoWindowFinder = new VideoWindowFinder();
+ _videoWindowFinder = new VideoWindowFinder(null);
_videoWindowFinder.EvtVideoWindowDisplayed += _videoWindowFinder_EvtVideoWindowDisplayed;
_videoWindowFinder.Start();
}
@@ -92,11 +94,11 @@ private void EndCalibration()
_videoWindowFinder.Dispose();
}
- Log.Debug("Hiding video window");
+ _logger.LogDebug("Hiding video window");
CameraSensor.hideVideoWindow();
- Log.Debug("Closing calibform");
+ _logger.LogDebug("Closing calibform");
Windows.CloseForm(this);
}
diff --git a/src/Extensions/Default/Actuators/CameraActuator/CameraActuator.cs b/src/Extensions/Default/Actuators/CameraActuator/CameraActuator.cs
index 2146f3c3..71169306 100644
--- a/src/Extensions/Default/Actuators/CameraActuator/CameraActuator.cs
+++ b/src/Extensions/Default/Actuators/CameraActuator/CameraActuator.cs
@@ -227,6 +227,11 @@ public override bool Init()
return true;
}
+ public CameraActuator()
+ {
+ _logger = LoggingConfiguration.CreateLogger();
+ }
+
///
/// Pause the actuator
///
@@ -297,7 +302,7 @@ public override void StartCalibration(RequestCalibrationReason reason)
{
try
{
- Log.Debug("Calling UpdateCalibrationstatus");
+ _logger.LogDebug("Calling UpdateCalibrationstatus");
if (_autoCalibrateForm != null)
{
@@ -305,16 +310,16 @@ public override void StartCalibration(RequestCalibrationReason reason)
_autoCalibrateForm = null;
}
- Log.Debug("Calling NotifyStartCalibration");
+ _logger.LogDebug("Calling NotifyStartCalibration");
Context.AppActuatorManager.NotifyStartCalibration(new CalibrationNotifyEventArgs(true, false));
if (reason == RequestCalibrationReason.SensorInitiated)
{
- Log.Debug("Calling new Calibform");
+ _logger.LogDebug("Calling new Calibform");
_autoCalibrateForm = new AutoCalibrateForm(this);
- Log.Debug("Calling new Calibform show dialog");
+ _logger.LogDebug("Calling new Calibform show dialog");
var form = Context.AppPanelManager.GetCurrentForm() as Form;
if (form != null)
@@ -328,7 +333,7 @@ public override void StartCalibration(RequestCalibrationReason reason)
{
_autoCalibrateForm.ShowDialog();
}
- Log.Debug("Returned from Calibform show dialog");
+ _logger.LogDebug("Returned from Calibform show dialog");
_autoCalibrateForm = null;
}
@@ -342,10 +347,10 @@ public override void StartCalibration(RequestCalibrationReason reason)
}
}
- Log.Debug("Calling NotifyEndCalibration");
+ _logger.LogDebug("Calling NotifyEndCalibration");
Context.AppActuatorManager.NotifyEndCalibration();
- Log.Debug("Calling OnEndCalibration");
+ _logger.LogDebug("Calling OnEndCalibration");
OnEndCalibration();
if (_cameraActuatorInitInProgress)
@@ -357,7 +362,7 @@ public override void StartCalibration(RequestCalibrationReason reason)
}
catch (Exception ex)
{
- Log.Exception(ex.ToString());
+ _logger.LogError(ex, ex.Message);
}
}
@@ -453,21 +458,21 @@ internal void setHeadMovementSensitivity(int value)
internal void setVisionSettings()
{
- Log.Debug("Setting vision parameters...");
+ _logger.LogDebug("Setting vision parameters...");
- Log.Debug("HeadMovementSensitivity: " + CameraActuatorSettings.HeadMovementSensitivity);
+ _logger.LogDebug("HeadMovementSensitivity: {HeadMovementSensitivity}", CameraActuatorSettings.HeadMovementSensitivity);
setHeadMovementSensitivity(CameraActuatorSettings.HeadMovementSensitivity);
- Log.Debug("CheekTwitchSensitivity: " + CameraActuatorSettings.CheekTwitchSensitivity);
+ _logger.LogDebug("CheekTwitchSensitivity: {CheekTwitchSensitivity}", CameraActuatorSettings.CheekTwitchSensitivity);
setCheekTwitchSensitivity(CameraActuatorSettings.CheekTwitchSensitivity);
- Log.Debug("EyebrowRaiseSensitivity: " + CameraActuatorSettings.EyebrowRaiseSensitivity);
+ _logger.LogDebug("EyebrowRaiseSensitivity: {EyebrowRaiseSensitivity}", CameraActuatorSettings.EyebrowRaiseSensitivity);
setEyebrowRaiseSensitivity(CameraActuatorSettings.EyebrowRaiseSensitivity);
- Log.Debug("CheekTwitchHoldTime: " + CameraActuatorSettings.CheekTwitchHoldTime);
+ _logger.LogDebug("CheekTwitchHoldTime: {CheekTwitchHoldTime}", CameraActuatorSettings.CheekTwitchHoldTime);
setCheekTwitchHoldTime(CameraActuatorSettings.CheekTwitchHoldTime);
- Log.Debug("EyebrowRaiseHoldTime: " + CameraActuatorSettings.EyebrowRaiseHoldTime);
+ _logger.LogDebug("EyebrowRaiseHoldTime: {EyebrowRaiseHoldTime}", CameraActuatorSettings.EyebrowRaiseHoldTime);
setEyebrowRaiseHoldTime(CameraActuatorSettings.EyebrowRaiseHoldTime);
}
@@ -481,7 +486,7 @@ protected override void Dispose(bool disposing)
{
try
{
- Log.Verbose();
+ _logger.LogTrace("Dispose");
if (disposing)
{
@@ -562,7 +567,7 @@ private void callbackFromVision(string text)
{
var gesture = String.Empty;
- Log.Debug("Received msg: " + text);
+ _logger.LogDebug("Received msg: {Message}", text);
IActuatorSwitch actuatorSwitch = parseActuatorMsgAndGetSwitch(text, ref gesture);
@@ -593,27 +598,27 @@ private void callbackFromVision(string text)
{
IsCalibrating = true;
- Log.Debug("Received CALIB_START");
+ _logger.LogDebug("Received CALIB_START");
EvtCalibrationStart?.Invoke(this, new EventArgs());
if (!_cameraActuatorInitInProgress && !_calibrateAndTestInProgress)
{
- Log.Debug("Calling RequestCalibration");
+ _logger.LogDebug("Calling RequestCalibration");
RequestCalibration(_calibrateAndTestInProgress ?
RequestCalibrationReason.AppRequested :
RequestCalibrationReason.SensorInitiated);
- Log.Debug("Returned from RequestCalibration");
+ _logger.LogDebug("Returned from RequestCalibration");
}
}
catch (Exception ex)
{
- Log.Exception("Exception " + ex);
+ _logger.LogError(ex, ex.Message);
}
}
else if (gesture == "CALIB_END") // end camera calibration
{
- Log.Debug("CALIB_END");
+ _logger.LogDebug("CALIB_END");
IsCalibrating = false;
@@ -708,7 +713,7 @@ private void showCalibrationAndTestForm()
_calibrateAndTestInProgress = true;
- _configureActuatorForm = new ConfigureActuatorForm(this);
+ _configureActuatorForm = new ConfigureActuatorForm(this, null);
CameraSensor.showVideoWindow();
@@ -785,21 +790,18 @@ private void visionThread()
}
catch (SEHException seh)
{
- Log.Exception("acatVision threw a SEHException: " + seh.ToString());
- Log.Exception(seh);
+ _logger.LogError(seh, "acatVision threw a SEHException");
}
catch (AccessViolationException ave)
{
- Log.Exception("acatVision threw an AccessViolationException: " + ave.ToString());
- Log.Exception(ave);
+ _logger.LogError(ave, "acatVision threw an AccessViolationException");
}
catch (Exception ex)
{
- Log.Exception("acatVision threw an exception: " + ex.ToString());
- Log.Exception(ex);
+ _logger.LogError(ex, "acatVision threw an exception");
}
- Log.Debug("ACATvision quit");
+ _logger.LogDebug("ACATvision quit");
}
public bool CalibrationDoneAtleastOnce
diff --git a/src/Extensions/Default/Actuators/CameraActuator/ConfigureActuatorForm.cs b/src/Extensions/Default/Actuators/CameraActuator/ConfigureActuatorForm.cs
index baf65862..0276bb5a 100644
--- a/src/Extensions/Default/Actuators/CameraActuator/ConfigureActuatorForm.cs
+++ b/src/Extensions/Default/Actuators/CameraActuator/ConfigureActuatorForm.cs
@@ -312,7 +312,7 @@ private void CameraActuator_EvtChangeCameraStart(String camera)
form.Invoke(new MethodInvoker(delegate
{
labelPrompt.Text = String.Empty;
- Log.Debug("Calling startTimer()");
+ _logger.LogDebug("Calling startTimer()");
startTimer(_switchingCamera);
}));
}
@@ -348,7 +348,7 @@ private void ConfigureActuatorForm_Load(object sender, EventArgs e)
Resize += CalibrateForm_Resize;
- _webcamGestureSelectUserControl = new WebcamGestureSelectUserControl(_cameraActuator);
+ _webcamGestureSelectUserControl = new WebcamGestureSelectUserControl(_cameraActuator, null);
_webcamGestureSettingsUserControl = new WebcamGestureSettingsUserControl(_cameraActuator);
_webcamGestureSettingsUserControl.EvtPause += _webcamGestureSettingsUserControl_EvtPause;
@@ -372,7 +372,7 @@ private void ConfigureActuatorForm_Shown(object sender, EventArgs e)
};
_textTimer.Tick += _textTimer_Tick;
- _videoWindowFinder = new VideoWindowFinder();
+ _videoWindowFinder = new VideoWindowFinder(null);
_videoWindowFinder.EvtVideoWindowDisplayed += _videoWindowFinder_EvtVideoWindowDisplayed;
_videoWindowFinder.EvtVideoWindowFindStart += _videoWindowFinder_EvtVideoWindowFindStart;
diff --git a/src/Extensions/Default/AppAgents/ACATAgent/ACATAgent.cs b/src/Extensions/Default/AppAgents/ACATAgent/ACATAgent.cs
index 4eb5f313..64513f68 100644
--- a/src/Extensions/Default/AppAgents/ACATAgent/ACATAgent.cs
+++ b/src/Extensions/Default/AppAgents/ACATAgent/ACATAgent.cs
@@ -20,5 +20,8 @@ namespace ACAT.Extensions.AppAgents.AcatAgent
"Application Agent for the executing assembly")]
internal class ACATAgent : ACATAgentBase
{
+ public ACATAgent() : base(null)
+ {
+ }
}
}
\ No newline at end of file
diff --git a/src/Extensions/Default/AppAgents/TalkApplicationScannerAgent/TalkApplicationScannerAgent.cs b/src/Extensions/Default/AppAgents/TalkApplicationScannerAgent/TalkApplicationScannerAgent.cs
index bc285394..d2f304f9 100644
--- a/src/Extensions/Default/AppAgents/TalkApplicationScannerAgent/TalkApplicationScannerAgent.cs
+++ b/src/Extensions/Default/AppAgents/TalkApplicationScannerAgent/TalkApplicationScannerAgent.cs
@@ -28,17 +28,7 @@ namespace ACAT.Extensions.AppAgents.TalkApplicationScannerAgent
internal class TalkApplicationScannerAgent : AgentBase
{
///
- /// Logger instance
- ///
- private readonly ILogger _logger;
-
- ///
- /// Logger factory for creating loggers
- ///
- private readonly ILoggerFactory _loggerFactory;
-
- ///
- /// The text control agent responsbile for handling
+ /// The text control agent responsible for handling
/// editing and caret movement functions
///
private TextControlAgentBase _textInterface;
@@ -56,12 +46,10 @@ internal class TalkApplicationScannerAgent : AgentBase
///
/// Initializes a new instance of the TalkApplicationScannerAgent class
///
- public TalkApplicationScannerAgent(ILogger logger, ILoggerFactory loggerFactory)
+ public TalkApplicationScannerAgent(ILogger logger) : base(logger)
{
- _logger = logger ?? throw new ArgumentNullException(nameof(logger));
- _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
}
- private Control textBoxControl;
+ //private Control textBoxControl;
///
/// Gets the list of process supported by this agent
@@ -189,7 +177,7 @@ private void createTalkWindowTextInterface(IntPtr handle, AutomationElement auto
bool handled = false;
//_textInterface = new EditTextControlAgent(handle, automationElement, ref handled);
- var textControlLogger = _loggerFactory.CreateLogger();
+ var textControlLogger = LoggingConfiguration.CreateLogger();
_textInterface = new TalkApplicationTextControlAgent(textControlLogger, textBoxControl, handle, automationElement, ref handled);
_textInterface.EvtTextChanged += _textInterface_EvtTextChanged;
setTextInterface(_textInterface);
diff --git a/src/Extensions/Default/FunctionalAgents/LaunchAppAgent/LaunchAppAgent.cs b/src/Extensions/Default/FunctionalAgents/LaunchAppAgent/LaunchAppAgent.cs
index 3af60ecd..2038fbfc 100644
--- a/src/Extensions/Default/FunctionalAgents/LaunchAppAgent/LaunchAppAgent.cs
+++ b/src/Extensions/Default/FunctionalAgents/LaunchAppAgent/LaunchAppAgent.cs
@@ -64,8 +64,6 @@ internal class LaunchAppAgent : FunctionalAgentBase
///
private const string SettingsFileName = "LaunchAppSettings.xml";
- private readonly ILogger _logger;
-
///
/// The usercontrol that displays the list of applications
///
@@ -89,9 +87,8 @@ internal class LaunchAppAgent : FunctionalAgentBase
///
/// Initializes a new instance of the class.
///
- public LaunchAppAgent(ILogger logger)
+ public LaunchAppAgent(ILogger logger = null) : base(logger)
{
- _logger = logger;
LaunchAppSettings.PreferencesFilePath = UserManager.GetFullPath(SettingsFileName);
Settings = LaunchAppSettings.Load();
}
diff --git a/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsAgent.cs b/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsAgent.cs
index 927c2438..eb10dac6 100644
--- a/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsAgent.cs
+++ b/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsAgent.cs
@@ -50,8 +50,6 @@ internal class SwitchWindowsAgent : FunctionalAgentBase
///
private static SwitchWindowsScanner _switchWindowsScanner;
- private readonly ILogger _logger;
-
///
/// Meta data for window selected
///
@@ -60,9 +58,8 @@ internal class SwitchWindowsAgent : FunctionalAgentBase
///
/// Initializes a new instance of the class.
///
- public SwitchWindowsAgent(ILogger logger)
+ public SwitchWindowsAgent(ILogger logger = null) : base(logger)
{
- _logger = logger;
Name = ClassDescriptorAttribute.GetDescriptor(GetType()).Name;
}
diff --git a/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsScanner.cs b/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsScanner.cs
index b5d82058..2f0fb65b 100644
--- a/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsScanner.cs
+++ b/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsScanner.cs
@@ -49,7 +49,8 @@ namespace ACAT.Extensions.FunctionalAgents.SwitchWindowsAgent
"SwitchWindowsScanner",
"Switch Windows Scanner")]
public partial class SwitchWindowsScanner : GenericScannerForm
- { private readonly ILogger _logger;
+ {
+ private readonly ILogger _logger;
///
/// Enables invoking methods and properties in this form
///
@@ -121,6 +122,7 @@ public partial class SwitchWindowsScanner : GenericScannerForm
///
public SwitchWindowsScanner() : base()
{
+ _logger = LoggingConfiguration.CreateLogger();
InitializeComponent();
}
diff --git a/src/Extensions/Default/TTSEngines/SAPIEngine/SAPIEngine.cs b/src/Extensions/Default/TTSEngines/SAPIEngine/SAPIEngine.cs
index d0d7ec9a..7c349ae3 100644
--- a/src/Extensions/Default/TTSEngines/SAPIEngine/SAPIEngine.cs
+++ b/src/Extensions/Default/TTSEngines/SAPIEngine/SAPIEngine.cs
@@ -96,7 +96,7 @@ public class SAPIEngine : ExtensionInvoker, ITTSEngine, ISupportsPreferences
///
/// Initializes a new instance of the class.
///
- public SAPIEngine(ILogger logger)
+ public SAPIEngine(ILogger logger = null)
{
_logger = logger;
SAPISettings.PreferencesFilePath = UserManager.GetFullPath(SettingsFileName);
diff --git a/src/Extensions/Default/TTSEngines/TTSClient/TTSClient.cs b/src/Extensions/Default/TTSEngines/TTSClient/TTSClient.cs
index c2e4f0c4..79800e4d 100644
--- a/src/Extensions/Default/TTSEngines/TTSClient/TTSClient.cs
+++ b/src/Extensions/Default/TTSEngines/TTSClient/TTSClient.cs
@@ -629,7 +629,7 @@ private String getTempFileName(String extension)
catch (Exception ex)
{
_logger.LogError(ex, "Could not create temp directory for TTSClient. {Exception}", ex);
- path = ".\\\
+ path = ".\\";
}
path = path + "\\TTS_" + Guid.NewGuid() + extension;
diff --git a/src/Extensions/Default/TTSEngines/TTSClient/Transport.cs b/src/Extensions/Default/TTSEngines/TTSClient/Transport.cs
index 2cbe8319..6fd0442e 100644
--- a/src/Extensions/Default/TTSEngines/TTSClient/Transport.cs
+++ b/src/Extensions/Default/TTSEngines/TTSClient/Transport.cs
@@ -27,7 +27,7 @@ public class Transport : ITTSTransport
public Transport()
{
_settings = TTSClientSettings.Load();
- _transportHttp = new TransportHttp();
+ _transportHttp = new TransportHttp(null);
}
public TTSFormat Format
diff --git a/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistUtils.cs b/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistUtils.cs
index 1f715f07..8a31efef 100644
--- a/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistUtils.cs
+++ b/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistUtils.cs
@@ -128,7 +128,7 @@ public static List> ToList(List predictions
}
newList = sentences.ToList();
}
- catch (Exception es)
+ catch
{
// Log exception but continue - return empty list
// Note: Static method cannot use injected logger
diff --git a/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistWordPredictor.cs b/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistWordPredictor.cs
index 8fee7da0..7230a25e 100644
--- a/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistWordPredictor.cs
+++ b/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistWordPredictor.cs
@@ -11,6 +11,7 @@
////////////////////////////////////////////////////////////////////////////
//#define DEBUG_CONVASSIST
+using ACAT.Core.PanelManagement;
using ACAT.Core.PreferencesManagement;
using ACAT.Core.PreferencesManagement.Interfaces;
using ACAT.Core.UserManagement;
@@ -92,20 +93,28 @@ public class ConvAssistWordPredictor : ConvAssistWordPredictorBase
private bool pipeCreated;
private Task wordPredictionTask;
+ ///
+ /// Initializes an instance of the class with default logger
+ ///
+ public ConvAssistWordPredictor() : this(Context.ServiceProvider?.GetService(typeof(ILogger)) as ILogger
+ ?? LoggingConfiguration.CreateLogger())
+ {
+ }
+
///
/// Initializes and instance of the class
///
public ConvAssistWordPredictor(ILogger logger)
{
- _logger = logger;
+ _logger = logger ?? throw new ArgumentNullException(nameof(logger));
Settings.PreferencesFilePath = getUserRelativePath(CultureInfo.CurrentCulture.TwoLetterISOLanguageName, SettingsFileName, true);
settings = Settings.Load();
convAssistSettings = settings;
- _wordPredictionsRequestHandler = new WordPredictionsRequestHandler(this);
- _sentencePredictionsRequestHandler = new SentencePredictionsRequestHandler(this);
+ _wordPredictionsRequestHandler = new WordPredictionsRequestHandler(this, null);
+ _sentencePredictionsRequestHandler = new SentencePredictionsRequestHandler(this, null);
wpStack = new Stack