Backend Architecture & Telemetry Engine
This page details the architectural design of the C# backend powering LocalTelemetry.Core and LocalTelemetry.App.
Core Architecture (LocalTelemetry.Core)
LocalTelemetry.Core is built as a pure C# .NET 10 class library with zero UI dependencies, allowing hardware monitoring logic to remain completely decoupled, fast, and testable.
AppSettings (Configuration Engine)
- Manages user preferences saved in
settings.json. - Uses
InitPaths(exeDir)to inspect for anapp.modemarker file:- If
app.modeexists (installed mode), data directories point to%LOCALAPPDATA%\LocalTelemetry. - If absent (portable mode), configuration and log files are stored directly alongside
LocalTelemetry.exe.
- If
- Implements schema migration (
MigrateConfig) to cleanly upgrade older settings schemas without losing user preferences. - Persists configuration to
settings.json, protecting against corruption via automatic.corruptbackup creation and graceful fallback to defaults on load failure.
HardwareMonitor (Telemetry Polling Coordinator)
- The central engine coordinating all sensor polling loops on a background worker timer (
100 msto10000 ms, configured viaAppSettings.Monitoring.PollIntervalMs). - Subscribes to
HardwareLifecycleManagerevents for power transitions, display changes, and network topology shifts. - Queries specialized hardware readers on each tick:
IntelMsrReader.cs&AmdMsrReader.cs(viaPawnIokernel driver for temperature, clock frequency, and RAPL package power).IntelPowerGadget.cs(fallback driver for Intel core temperature and package wattage).NvGpuMonitor.cs(NVIDIA NVML P/Invoke bindings).AmdGpuMonitor.cs(AMD ADL P/Invoke bindings).IntelGpuMonitor.cs(Intel IGCL / ControlLib bindings).WddmGpuMonitor.cs(Windows WDDM GPU performance counters viaD3DKMTQueryStatistics).System.Diagnostics.PerformanceCounter(WindowsPhysicalDiskread/write bytes per second).NetworkInterface.GetIPv4Statistics()(Per-tick throughput delta calculation on the active physical network adapter).- Battery charge & discharge wattage via WMI
root\wmi:BatteryStatusandGetSystemPowerStatus.
- Produces immutable
TelemetrySnapshotrecords dispatched viaSnapshotReadyon every refresh tick.
HardwareLifecycleManager (Dynamic OS & Hardware Lifecycle)
- Implemented in
HardwareLifecycleManager.cs. - Listens to native Windows system events (
SystemEvents) and network availability (NetworkChange):- Display & Graphics Resets (
DisplaySettingsChanged/WM_DISPLAYCHANGE): Debounced (3000 ms) and triggers dynamic refresh of WDDM GPU adapter state. - System Sleep (
PowerModes.Suspend): Immediately pauses the background polling timer to eliminate wakeups during standby. - System Resume (
PowerModes.Resume): Waits 3 seconds for hardware warm-up, executesResetGpuMonitors()across NVML, WDDM, ADL, and IGCL backends, re-initializes network adapter counters, and resumes polling. - Network Topology Changes (
NetworkAddressChanged/NetworkAvailabilityChanged): Automatically detects adapter connections, disconnections, and IP address renewals. - PnP Device Changes (
WM_DEVICECHANGE): Refreshes storage drive mappings upon USB or NVMe disk hotplugging.
- Display & Graphics Resets (
MetricSnapshot & TelemetrySnapshot (State Models)
- Represents the complete, immutable point-in-time state of all polled hardware sensors.
- Contains normalized properties for CPU, GPU, RAM, Disk, Network, and Battery telemetry, ensuring UI consumers receive thread-safe, consistent snapshots with zero race conditions.
- See the C# Core API & Models Reference for complete property definitions.
HardwareInventory (Component Fingerprinting & Cache)
- Implemented in
HardwareInventory.cs. - On application launch, generates an SHA-256 system hardware fingerprint (combining motherboard serial, processor ID, GPU device IDs, RAM module serials, and disk hardware IDs).
- Compares the fingerprint against
%LOCALAPPDATA%\LocalTelemetry\hardware_state.json:- If identical, emits a concise single-line confirmation in diagnostic logs, minimizing disk I/O and startup delay.
- If changed or on first launch, executes a comprehensive hardware discovery audit and updates the cached state file.
DiskQuery & PhysicalDisk Performance Counters
- Rather than relying on fragile kernel drivers for storage, LocalTelemetry uses a hybrid approach:
- I/O Rates: Queried using high-performance Windows
PhysicalDiskPerformance Counters (\PhysicalDisk(*)\Disk Read Bytes/secandDisk Write Bytes/sec), tracking both per-disk and system total throughput. - Drive Metadata: Queried via
DiskQuery.csusing Win32 storage IOCTLs (IOCTL_STORAGE_QUERY_PROPERTY,IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS) and WMI to resolve commercial drive capacities, vendor names, boot drive flags, and bus architectures (NVMe,SATA,SCSI).
- I/O Rates: Queried using high-performance Windows
WindowsNetworkUsageProvider & TrafficHistoryStore
- Reads active network adapter traffic statistics and calculates bandwidth deltas.
- Logs daily download, upload, and total usage to
internet_usage.jsonlviaNetUsageLogger.cs,TrafficHistoryFile.cs, andTrafficHistoryStore.cs. - Backfills historical bandwidth records from the Windows System Resource Usage Monitor (
SRUDB.dat) database using the Extensible Storage Engine (ESE /esent.dll) viaWindowsNetworkUsageProvider.csandEseNetworkUsageReader.cs. Restores backups viaJsonlTrafficImporter.csandDatImporter.cs.
BrandColorDefaults (Hardware Palette Mapper)
- Maintains canonical brand color definitions and alias maps for hardware vendors across CPUs (Intel, AMD), GPUs (NVIDIA, AMD, Intel), RAM, Disks, Network Adapters, and Battery OEMs.
- Automatically maps discovered system components to official brand hex palettes.
Log (Structured Diagnostics & Rotation Engine)
- Zero-external-dependency static logging architecture located in
LocalTelemetry.Core.Diagnostics:- System Diagnostics Stream (
logs/lt_system.log): Always active. Captures application lifecycle sessions (SessionStart,SessionEndwith elapsed uptime), driver detection, and system exceptions. - Automatic Size Rotation: Automatically rolls
lt_system.logwhen it reaches 5 MB (MaxSystemLogBytes = 5MB), retaining up to 3 numbered archive files (.1.log,.2.log,.3.log). - Midnight Rollover: Automatically inserts visual calendar separators at midnight (
-- DD-MM-YYYY --) and smoothly rotates daily metric files. - Daily Metrics Stream (
logs/lt_DD-MM-YYYY.log): Gated by user configuration (EnableFileLoggingand per-category modes). Emits periodic sensor readings on each tick without blocking the UI. - Thread Safety: Fully synchronized using non-reentrant private stream locks with automatic flushing (
AutoFlush = true).
- System Diagnostics Stream (
Application Host (LocalTelemetry.App)
LocalTelemetry.App is a WPF application targeting .NET 10 Windows x64.
Application Lifecycle & Dependency Injection
- Application entry point implemented in
App.xaml.cs. Handles UAC elevation checks (IsAdministrator()), relaunching withVerb = "runas"and--elevatedif unelevated. - Configures the Microsoft Dependency Injection container (
IServiceCollection). - Subscribes to
HardwareMonitor.SnapshotReadyto dispatch immutable snapshots toTaskbarOverlay,TrayIconManager,AlertService, andNetUsageLogger. - Manages the process lifecycle of
HardwareMonitor,TaskbarOverlay,TrayIconManager,NotificationClient, and child daemonLocalTelemetry.Notifier.exe.
AlertService (Threshold Evaluation & Notifications)
- Evaluates live
TelemetrySnapshotvalues against threshold limits defined inAppSettings.Alerts. - Dispatches visual text flashing commands to
TaskbarOverlay. - Sends toast notification commands to
NotificationClient.csto triggerLocalTelemetry.Notifier.exeover Named Pipe IPC.
SettingsShell (WebView2 Host Window)
- WPF host window managing the Microsoft WebView2 control (
Microsoft.Web.WebView2.Wpf). - Binds Svelte 5 frontend build assets (
wwwroot/index.html) using local virtual folder mapping (localtelemetry.settings). - Implements bidirectional JSON messaging between C# and Svelte via
WebMessageReceivedhandlers. - See the WebView2 IPC Protocol Reference for full message catalogs.
UpdateCheckService (GitHub Releases Client)
- Implemented in
UpdateCheckService.cs. - Periodically checks the GitHub Releases API based on configured frequency (
weekly,monthly, ormanual). - Parses semantic version strings using a SemVer 2.0 parser that compares major, minor, patch, and pre-release identifiers (
-rc,-beta,-alpha). - Dispatches
updateCheckResultWebMessages to the Svelte 5 frontend with changelogs and direct download URLs.
Polling Interval Dynamics & Zero-Allocation Pipeline
LocalTelemetry maintains a low CPU and memory footprint (~35-50 MB RAM) by employing a zero-allocation polling strategy:
- Fixed-size reusable byte and string buffers for register and IOCTL reading.
- Double-buffered GDI+ drawing cached directly in unmanaged memory.
- Telemetry timer ticks run on background worker threads without dispatching to the UI thread unless an overlay render tick is due.