-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBatteryMonitor.cs
More file actions
executable file
·1370 lines (1171 loc) · 51.1 KB
/
BatteryMonitor.cs
File metadata and controls
executable file
·1370 lines (1171 loc) · 51.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Win32;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Enumeration;
using Windows.Storage.Streams;
using System.Runtime.InteropServices;
namespace BluetoothBatteryMonitor
{
public class BatteryMonitor : ApplicationContext, IDisposable
{
#region Private Fields
private readonly Dictionary<string, DeviceInfo> _devices;
private readonly Dictionary<string, NotifyIcon> _trayIcons;
private readonly Dictionary<string, Icon> _deviceCurrentIcons;
private readonly Dictionary<string, ToolStripItem> _deviceMenuItems;
private readonly Dictionary<string, ToolStripItem> _deviceLastUpdateMenuItems;
private readonly System.Windows.Forms.Timer _uiRefreshTimer;
private readonly System.Threading.Timer _reconnectTimer;
private readonly System.Threading.Timer _stateVerificationTimer;
private readonly SemaphoreSlim _deviceLock;
private readonly SynchronizationContext _syncContext;
private readonly CancellationTokenSource _disposeCts;
private DeviceWatcher? _deviceWatcher;
private DeviceWatcher? _classicDeviceWatcher;
private readonly TimeSpan _stateVerificationInterval = TimeSpan.FromSeconds(60);
private int _stateVerificationRunning;
private int _sessionRefreshPending;
private readonly TimeSpan _sessionRefreshDebounce = TimeSpan.FromSeconds(1);
private readonly TimeSpan _uiRefreshInterval = TimeSpan.FromSeconds(1);
// Cache for HFP device instance IDs (device name -> instance ID)
private readonly Dictionary<string, string> _hfpInstanceIdCache = new(StringComparer.OrdinalIgnoreCase);
// Sentinel icon shown when no device icons are visible
private NotifyIcon? _sentinelIcon;
private int _lastScreenWidth;
private int _lastScreenHeight;
private float _lastDpiX;
private float _lastDpiY;
private Icon? _iconFull;
private Icon? _iconGood;
private Icon? _iconMedium;
private Icon? _iconLow;
private Icon? _iconEmpty;
private const string RegistryKeyPath = @"SOFTWARE\JPIT\BluetoothBatteryMonitor";
private const string RegistryDevicesValue = "Devices";
private static readonly Guid BatteryServiceUuid = new("0000180f-0000-1000-8000-00805f9b34fb");
private static readonly Guid BatteryLevelUuid = new("00002a19-0000-1000-8000-00805f9b34fb");
private const int NotifyIconMaxTextLength = 63;
private static readonly string[] BatteryPropertyKeys =
{
"System.Devices.Aep.Bluetooth.Le.BatteryLevel",
"System.Devices.Aep.BatteryLevel",
"System.Devices.Aep.BatteryLifePercent",
"System.Devices.BatteryLifePercent",
"System.Devices.BatteryLevel"
};
// P/Invoke for proper DPI detection
[DllImport("user32.dll")]
private static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("user32.dll")]
private static extern int ReleaseDC(IntPtr hwnd, IntPtr hdc);
[DllImport("gdi32.dll")]
private static extern int GetDeviceCaps(IntPtr hdc, int nIndex);
private const int LOGPIXELSX = 88;
private const int LOGPIXELSY = 90;
// CfgMgr32 API for reading PnP device properties (like PowerShell's Get-PnpDeviceProperty)
[DllImport("CfgMgr32.dll", CharSet = CharSet.Unicode)]
private static extern int CM_Locate_DevNodeW(out int pdnDevInst, string pDeviceID, int ulFlags);
[DllImport("CfgMgr32.dll", CharSet = CharSet.Unicode)]
private static extern int CM_Get_DevNode_PropertyW(
int dnDevInst,
ref DEVPROPKEY propertyKey,
out int propertyType,
IntPtr propertyBuffer,
ref int propertyBufferSize,
int ulFlags);
[StructLayout(LayoutKind.Sequential)]
private struct DEVPROPKEY
{
public Guid fmtid;
public int pid;
}
private const int CR_SUCCESS = 0;
private const int CR_BUFFER_SMALL = 0x1A;
private const int CM_LOCATE_DEVNODE_NORMAL = 0;
private const int DEVPROP_TYPE_BYTE = 0x00000003;
private const int DEVPROP_TYPE_INT32 = 0x00000006;
private const int DEVPROP_TYPE_UINT32 = 0x00000007;
// HFP Battery property key: {104EA319-6EE2-4701-BD47-8DDBF425BBE5} pid 2
private static readonly DEVPROPKEY DEVPKEY_Bluetooth_HfpBattery = new()
{
fmtid = new Guid("104EA319-6EE2-4701-BD47-8DDBF425BBE5"),
pid = 2
};
// For detecting session changes (RDP connect/disconnect)
private const int WM_WTSSESSION_CHANGE = 0x02B1;
private const int WTS_CONSOLE_CONNECT = 0x1;
private const int WTS_REMOTE_DISCONNECT = 0x4;
private const int WTS_SESSION_UNLOCK = 0x8;
[DllImport("wtsapi32.dll")]
private static extern bool WTSRegisterSessionNotification(IntPtr hWnd, int dwFlags);
[DllImport("wtsapi32.dll")]
private static extern bool WTSUnRegisterSessionNotification(IntPtr hWnd);
private const int NOTIFY_FOR_THIS_SESSION = 0;
// Hidden window for receiving session notifications
private SessionNotificationWindow? _notificationWindow;
#endregion
#region Constructor and Initialization
public BatteryMonitor()
{
_syncContext = SynchronizationContext.Current ?? new WindowsFormsSynchronizationContext();
_disposeCts = new CancellationTokenSource();
_devices = new Dictionary<string, DeviceInfo>();
_trayIcons = new Dictionary<string, NotifyIcon>();
_deviceCurrentIcons = new Dictionary<string, Icon>();
_deviceMenuItems = new Dictionary<string, ToolStripItem>();
_deviceLastUpdateMenuItems = new Dictionary<string, ToolStripItem>();
_deviceLock = new SemaphoreSlim(1, 1);
CaptureCurrentDisplaySettings();
SystemEvents.DisplaySettingsChanged += OnDisplaySettingsChanged;
SystemEvents.SessionSwitch += OnSessionSwitch;
LoadBatteryIcons();
InitializeDevices();
CreateTrayIcons();
CreateSentinelIcon();
UpdateSentinelVisibility();
_uiRefreshTimer = new System.Windows.Forms.Timer
{
Interval = (int)_uiRefreshInterval.TotalMilliseconds
};
_uiRefreshTimer.Tick += OnUiRefreshTimerTick;
_uiRefreshTimer.Start();
_notificationWindow = new SessionNotificationWindow(this);
InitializeDeviceWatcher();
_reconnectTimer = new System.Threading.Timer(
async _ => await RetryDisconnectedDevicesAsync(),
null,
TimeSpan.FromSeconds(30),
TimeSpan.FromSeconds(30)
);
_stateVerificationTimer = new System.Threading.Timer(
async _ => await VerifyDeviceStatesAsync(),
null,
Timeout.InfiniteTimeSpan,
Timeout.InfiniteTimeSpan
);
ScheduleStateVerification();
}
#endregion
#region Session Change Handling
private void OnSessionSwitch(object sender, SessionSwitchEventArgs e)
{
switch (e.Reason)
{
case SessionSwitchReason.ConsoleConnect:
case SessionSwitchReason.RemoteDisconnect:
case SessionSwitchReason.SessionUnlock:
ScheduleSessionReconnect();
break;
case SessionSwitchReason.RemoteConnect:
_ = Task.Run(async () =>
{
await Task.Delay(500);
CaptureCurrentDisplaySettings();
});
break;
}
}
internal void OnWtsSessionChange(int reason)
{
if (reason == WTS_CONSOLE_CONNECT || reason == WTS_REMOTE_DISCONNECT || reason == WTS_SESSION_UNLOCK)
{
ScheduleSessionReconnect();
}
}
private void ScheduleSessionReconnect()
{
if (Interlocked.Exchange(ref _sessionRefreshPending, 1) == 1)
return;
_ = Task.Run(async () =>
{
await Task.Delay(_sessionRefreshDebounce);
Interlocked.Exchange(ref _sessionRefreshPending, 0);
await HandleSessionReconnectAsync();
});
}
private async Task HandleSessionReconnectAsync()
{
_syncContext.Post(_ =>
{
try
{
RefreshTrayIconsForDpiChange();
CaptureCurrentDisplaySettings();
}
catch { }
}, null);
await Task.CompletedTask.ConfigureAwait(false);
}
private void RefreshTrayIconsForDpiChange()
{
var oldIconFull = _iconFull;
var oldIconGood = _iconGood;
var oldIconMedium = _iconMedium;
var oldIconLow = _iconLow;
var oldIconEmpty = _iconEmpty;
LoadBatteryIcons();
foreach (var deviceName in _devices.Keys.ToArray())
{
if (!_trayIcons.TryGetValue(deviceName, out var notifyIcon))
continue;
if (!_devices.TryGetValue(deviceName, out var deviceInfo))
continue;
try
{
var batteryIcon = GetBatteryIcon(deviceInfo.BatteryLevel);
_deviceCurrentIcons[deviceName] = batteryIcon;
notifyIcon.Icon = batteryIcon;
}
catch { }
}
try
{
oldIconFull?.Dispose();
oldIconGood?.Dispose();
oldIconMedium?.Dispose();
oldIconLow?.Dispose();
oldIconEmpty?.Dispose();
}
catch { }
}
private ContextMenuStrip CreateContextMenuForDevice(string deviceName, DeviceInfo deviceInfo)
{
var contextMenu = new ContextMenuStrip { AutoSize = true };
var deviceMenuItem = contextMenu.Items.Add(deviceName, null, null);
deviceMenuItem.Enabled = false;
string statusText = GetStatusText(deviceInfo);
var statusMenuItem = contextMenu.Items.Add(statusText, null, null);
statusMenuItem.Enabled = false;
_deviceMenuItems[deviceName] = statusMenuItem;
var lastUpdatedItem = contextMenu.Items.Add(FormatLastUpdateText(deviceInfo), null, null);
lastUpdatedItem.Enabled = false;
_deviceLastUpdateMenuItems[deviceName] = lastUpdatedItem;
contextMenu.Opening += (_, _) => UpdateContextMenuItems(deviceName);
contextMenu.Closed += (_, _) => UpdateDeviceIcon(deviceName);
contextMenu.Items.Add("-");
contextMenu.Items.Add("Open Bluetooth Settings", null, OnOpenBluetoothSettings);
contextMenu.Items.Add("Configuration", null, OnConfigureClick);
contextMenu.Items.Add("-");
contextMenu.Items.Add("Exit", null, OnExitClick);
return contextMenu;
}
#endregion
#region Display Settings Management
private void CaptureCurrentDisplaySettings()
{
try
{
_lastScreenWidth = Screen.PrimaryScreen?.Bounds.Width ?? 0;
_lastScreenHeight = Screen.PrimaryScreen?.Bounds.Height ?? 0;
IntPtr hdc = GetDC(IntPtr.Zero);
_lastDpiX = GetDeviceCaps(hdc, LOGPIXELSX);
_lastDpiY = GetDeviceCaps(hdc, LOGPIXELSY);
ReleaseDC(IntPtr.Zero, hdc);
}
catch { }
}
private bool HasDisplaySettingsChanged()
{
try
{
int currentWidth = Screen.PrimaryScreen?.Bounds.Width ?? 0;
int currentHeight = Screen.PrimaryScreen?.Bounds.Height ?? 0;
IntPtr hdc = GetDC(IntPtr.Zero);
float currentDpiX = GetDeviceCaps(hdc, LOGPIXELSX);
float currentDpiY = GetDeviceCaps(hdc, LOGPIXELSY);
ReleaseDC(IntPtr.Zero, hdc);
return currentWidth != _lastScreenWidth ||
currentHeight != _lastScreenHeight ||
Math.Abs(currentDpiX - _lastDpiX) > 0.1f ||
Math.Abs(currentDpiY - _lastDpiY) > 0.1f;
}
catch
{
return false;
}
}
private void OnDisplaySettingsChanged(object? sender, EventArgs e)
{
_ = Task.Run(async () =>
{
await Task.Delay(1000);
if (HasDisplaySettingsChanged())
{
await HandleSessionReconnectAsync();
}
});
}
#endregion
#region Icon Management
private void LoadBatteryIcons()
{
try
{
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
_iconFull = LoadIconFromResource(assembly, "icon_battery_full.ico") ?? CreateFallbackIcon();
_iconGood = LoadIconFromResource(assembly, "icon_battery_good.ico") ?? CreateFallbackIcon();
_iconMedium = LoadIconFromResource(assembly, "icon_battery_medium.ico") ?? CreateFallbackIcon();
_iconLow = LoadIconFromResource(assembly, "icon_battery_low.ico") ?? CreateFallbackIcon();
_iconEmpty = LoadIconFromResource(assembly, "icon_battery_empty.ico") ?? CreateFallbackIcon();
}
catch
{
_iconEmpty = CreateFallbackIcon();
}
}
private static Icon? LoadIconFromResource(System.Reflection.Assembly assembly, string resourceName)
{
try
{
var stream = assembly.GetManifestResourceStream($"BluetoothBatteryMonitor.{resourceName}")
?? assembly.GetManifestResourceStream(resourceName);
if (stream != null)
return new Icon(stream);
}
catch { }
return null;
}
private Icon CreateFallbackIcon()
{
using var bitmap = new Bitmap(16, 16);
using var g = Graphics.FromImage(bitmap);
g.Clear(Color.Gray);
using var pen = new Pen(Color.Red, 2);
g.DrawRectangle(pen, 0, 0, 15, 15);
return Icon.FromHandle(bitmap.GetHicon());
}
private Icon GetBatteryIcon(int? percentage)
{
return percentage switch
{
null => _iconEmpty ?? CreateFallbackIcon(),
>= 75 => _iconFull ?? CreateFallbackIcon(),
>= 50 => _iconGood ?? CreateFallbackIcon(),
>= 25 => _iconMedium ?? CreateFallbackIcon(),
>= 10 => _iconLow ?? CreateFallbackIcon(),
_ => _iconEmpty ?? CreateFallbackIcon()
};
}
#endregion
#region Device Management
private void InitializeDevices()
{
foreach (var name in LoadDeviceNamesFromRegistry())
{
_devices[name] = new DeviceInfo { Name = name };
}
}
public static string[] LoadDeviceNamesFromRegistry()
{
try
{
using var key = Registry.CurrentUser.OpenSubKey(RegistryKeyPath);
if (key?.GetValue(RegistryDevicesValue) is string[] names)
return names.Where(n => !string.IsNullOrWhiteSpace(n)).ToArray();
}
catch { }
return Array.Empty<string>();
}
public static void SaveDevicesToRegistry(IEnumerable<string> names)
{
using var key = Registry.CurrentUser.CreateSubKey(RegistryKeyPath);
key.SetValue(RegistryDevicesValue, names.ToArray(), RegistryValueKind.MultiString);
}
#endregion
#region Tray Icon Management
private void CreateTrayIcons()
{
foreach (var deviceName in _devices.Keys)
{
var deviceInfo = _devices[deviceName];
var notifyIcon = new NotifyIcon
{
Icon = GetBatteryIcon(null),
Visible = true,
Text = $"{deviceName}\nScanning..."
};
notifyIcon.DoubleClick += OnOpenBluetoothSettings;
notifyIcon.ContextMenuStrip = CreateContextMenuForDevice(deviceName, deviceInfo);
_trayIcons[deviceName] = notifyIcon;
_deviceCurrentIcons[deviceName] = notifyIcon.Icon;
}
}
private void CreateSentinelIcon()
{
_sentinelIcon = new NotifyIcon
{
Icon = _iconEmpty ?? CreateFallbackIcon(),
Text = "Bluetooth Battery Monitor\nNo devices"
};
_sentinelIcon.DoubleClick += OnConfigureClick;
var contextMenu = new ContextMenuStrip { AutoSize = true };
contextMenu.Items.Add("Configuration", null, OnConfigureClick);
contextMenu.Items.Add("-");
contextMenu.Items.Add("Exit", null, OnExitClick);
_sentinelIcon.ContextMenuStrip = contextMenu;
}
private void UpdateSentinelVisibility()
{
if (_sentinelIcon == null) return;
_sentinelIcon.Visible = _trayIcons.Count == 0;
}
private void OnOpenBluetoothSettings(object? sender, EventArgs e)
{
try
{
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
{
FileName = "ms-settings:bluetooth",
UseShellExecute = true
});
}
catch { }
}
private void OnConfigureClick(object? sender, EventArgs e)
{
using var dialog = new ConfigurationDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
ReloadConfiguration();
}
}
private void ReloadConfiguration()
{
StopDeviceWatchers();
foreach (var icon in _trayIcons.Values.ToArray())
{
try
{
icon.Visible = false;
icon.ContextMenuStrip?.Dispose();
icon.Dispose();
}
catch { }
}
_trayIcons.Clear();
_deviceCurrentIcons.Clear();
_deviceMenuItems.Clear();
_deviceLastUpdateMenuItems.Clear();
foreach (var device in _devices.Values)
{
try { device.BluetoothDevice?.Dispose(); } catch { }
}
_devices.Clear();
_hfpInstanceIdCache.Clear();
InitializeDevices();
CreateTrayIcons();
UpdateSentinelVisibility();
InitializeDeviceWatcher();
}
private void OnExitClick(object? sender, EventArgs e)
{
Application.Exit();
}
#endregion
#region Device Watcher
private void InitializeDeviceWatcher()
{
try
{
string selector = BluetoothLEDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Connected);
_deviceWatcher = DeviceInformation.CreateWatcher(
selector,
new[] { "System.Devices.Aep.IsConnected" },
DeviceInformationKind.AssociationEndpoint
);
_deviceWatcher.Added += OnDeviceAdded;
_deviceWatcher.Updated += OnDeviceUpdated;
_deviceWatcher.Removed += OnDeviceRemoved;
_deviceWatcher.EnumerationCompleted += OnEnumerationCompleted;
_deviceWatcher.Stopped += OnWatcherStopped;
_deviceWatcher.Start();
string classicSelector = BluetoothDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Connected);
_classicDeviceWatcher = DeviceInformation.CreateWatcher(
classicSelector,
new[] { "System.Devices.Aep.IsConnected" },
DeviceInformationKind.AssociationEndpoint
);
_classicDeviceWatcher.Added += OnDeviceAdded;
_classicDeviceWatcher.Updated += OnDeviceUpdated;
_classicDeviceWatcher.Removed += OnDeviceRemoved;
_classicDeviceWatcher.EnumerationCompleted += OnEnumerationCompleted;
_classicDeviceWatcher.Stopped += OnWatcherStopped;
_classicDeviceWatcher.Start();
}
catch { }
}
private async void OnDeviceAdded(DeviceWatcher sender, DeviceInformation args)
{
await ProcessDeviceAsync(args);
}
private async void OnDeviceUpdated(DeviceWatcher sender, DeviceInformationUpdate args)
{
var deviceName = FindDeviceNameById(args.Id);
if (deviceName == null)
return;
foreach (var key in BatteryPropertyKeys)
{
if (args.Properties.TryGetValue(key, out var batteryValue))
{
TryUpdateBatteryLevelFromValue(deviceName, batteryValue);
return;
}
}
if (_devices.TryGetValue(deviceName, out var deviceInfo) &&
deviceInfo.ConnectionType == DeviceConnectionType.BluetoothClassic)
{
await TryReadHfpBatteryViaCfgMgrAsync(deviceName).ConfigureAwait(false);
}
}
private void OnDeviceRemoved(DeviceWatcher sender, DeviceInformationUpdate args)
{
var deviceName = FindDeviceNameById(args.Id);
if (deviceName != null)
{
HandleDeviceDisconnected(deviceName);
}
}
private void OnEnumerationCompleted(DeviceWatcher sender, object args) { }
private void OnWatcherStopped(DeviceWatcher sender, object args) { }
private async Task ProcessDeviceAsync(DeviceInformation deviceInfo)
{
try
{
var deviceName = deviceInfo.Name;
if (string.IsNullOrEmpty(deviceName) || !_devices.ContainsKey(deviceName))
return;
await _deviceLock.WaitAsync(_disposeCts.Token).ConfigureAwait(false);
try
{
var entry = _devices[deviceName];
entry.DeviceId = deviceInfo.Id;
entry.IsConnected = true;
TryUpdateBatteryFromProperties(deviceInfo, deviceName);
ScheduleStateVerification();
_syncContext.Post(_ => UpdateDeviceIcon(deviceName), null);
// Check if this looks like a classic Bluetooth device ID
bool looksLikeClassic = deviceInfo.Id.StartsWith("Bluetooth#", StringComparison.OrdinalIgnoreCase) &&
!deviceInfo.Id.Contains("BluetoothLE", StringComparison.OrdinalIgnoreCase);
// For classic-looking devices, try CfgMgr32 (it's fast!)
if (looksLikeClassic)
{
if (await TryReadHfpBatteryViaCfgMgrAsync(deviceName).ConfigureAwait(false))
{
entry.ConnectionType = DeviceConnectionType.BluetoothClassic;
return;
}
}
// Try BLE device creation
BluetoothLEDevice? leDevice = null;
try
{
leDevice = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id);
}
catch { }
if (leDevice != null)
{
entry.BluetoothDevice = leDevice;
entry.ConnectionType = DeviceConnectionType.BluetoothLe;
await ConnectToBatteryServiceAsync(leDevice, deviceName).ConfigureAwait(false);
return;
}
// It's classic Bluetooth
entry.ConnectionType = DeviceConnectionType.BluetoothClassic;
// If we didn't get battery from CfgMgr32 earlier, try again
if (!entry.BatteryLevel.HasValue)
{
await TryReadHfpBatteryViaCfgMgrAsync(deviceName).ConfigureAwait(false);
}
}
finally
{
_deviceLock.Release();
}
}
catch { }
}
private async Task ConnectToBatteryServiceAsync(BluetoothLEDevice device, string deviceName)
{
try
{
var gattResult = await device.GetGattServicesForUuidAsync(BatteryServiceUuid).AsTask().ConfigureAwait(false);
if (gattResult.Status != GattCommunicationStatus.Success || gattResult.Services.Count == 0)
return;
var batteryService = gattResult.Services[0];
var charResult = await batteryService.GetCharacteristicsForUuidAsync(BatteryLevelUuid).AsTask().ConfigureAwait(false);
if (charResult.Status != GattCommunicationStatus.Success || charResult.Characteristics.Count == 0)
return;
var characteristic = charResult.Characteristics[0];
_devices[deviceName].BatteryCharacteristic = characteristic;
await ReadBatteryLevelAsync(characteristic, deviceName).ConfigureAwait(false);
await SubscribeToBatteryNotificationsAsync(characteristic, deviceName).ConfigureAwait(false);
}
catch { }
}
private async Task SubscribeToBatteryNotificationsAsync(GattCharacteristic characteristic, string deviceName)
{
try
{
var notifyResult = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
GattClientCharacteristicConfigurationDescriptorValue.Notify
).AsTask().ConfigureAwait(false);
if (notifyResult == GattCommunicationStatus.Success)
{
characteristic.ValueChanged += (sender, args) => OnBatteryLevelChanged(sender, args, deviceName);
}
}
catch { }
}
private async Task ReadBatteryLevelAsync(GattCharacteristic characteristic, string deviceName)
{
try
{
var readResult = await characteristic.ReadValueAsync().AsTask(_disposeCts.Token).ConfigureAwait(false);
if (readResult.Status == GattCommunicationStatus.Success)
{
var reader = DataReader.FromBuffer(readResult.Value);
byte batteryLevel = reader.ReadByte();
UpdateBatteryLevel(deviceName, batteryLevel);
}
}
catch { }
}
private void OnBatteryLevelChanged(GattCharacteristic sender, GattValueChangedEventArgs args, string deviceName)
{
try
{
var reader = DataReader.FromBuffer(args.CharacteristicValue);
byte batteryLevel = reader.ReadByte();
UpdateBatteryLevel(deviceName, batteryLevel);
}
catch { }
}
private bool TryUpdateBatteryFromProperties(DeviceInformation deviceInfo, string deviceName)
{
foreach (var key in BatteryPropertyKeys)
{
if (deviceInfo.Properties.TryGetValue(key, out var batteryValue) &&
TryParseBatteryLevel(batteryValue, out var batteryLevel))
{
UpdateBatteryLevel(deviceName, batteryLevel);
return true;
}
}
return false;
}
private void TryUpdateBatteryLevelFromValue(string deviceName, object? batteryValue)
{
if (batteryValue != null && TryConvertBatteryLevel(batteryValue, out var batteryLevel))
{
UpdateBatteryLevel(deviceName, batteryLevel);
}
}
private static bool TryConvertBatteryLevel(object value, out byte batteryLevel)
{
batteryLevel = 0;
try
{
int level = value switch
{
byte b => b,
sbyte sb => sb,
short s => s,
ushort us => us,
int i => i,
uint ui => (int)ui,
long l => (int)l,
ulong ul => (int)ul,
float f => (int)f,
double d => (int)d,
string s => int.Parse(s.Replace("%", string.Empty).Trim(), CultureInfo.InvariantCulture),
_ => Convert.ToInt32(value, CultureInfo.InvariantCulture)
};
if (level is < 0 or > 100)
return false;
batteryLevel = (byte)level;
return true;
}
catch
{
return false;
}
}
private async Task<bool> TryReadHfpBatteryViaCfgMgrAsync(string deviceName)
{
return await Task.Run(() =>
{
try
{
// Check cache first for fast path
if (_hfpInstanceIdCache.TryGetValue(deviceName, out var cachedInstanceId))
{
var battery = GetHfpBatteryLevel(cachedInstanceId);
if (battery.HasValue)
{
UpdateBatteryLevel(deviceName, battery.Value);
return true;
}
// Cache miss - device may have reconnected with new instance, clear and re-scan
_hfpInstanceIdCache.Remove(deviceName);
}
using var enumKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Enum\BTHENUM");
if (enumKey == null)
return false;
foreach (var subKeyName in enumKey.GetSubKeyNames())
{
if (!subKeyName.Contains("111e", StringComparison.OrdinalIgnoreCase) &&
!subKeyName.Contains("111E", StringComparison.OrdinalIgnoreCase))
continue;
using var serviceKey = enumKey.OpenSubKey(subKeyName);
if (serviceKey == null) continue;
foreach (var instanceName in serviceKey.GetSubKeyNames())
{
using var instanceKey = serviceKey.OpenSubKey(instanceName);
if (instanceKey == null) continue;
var friendlyName = instanceKey.GetValue("FriendlyName") as string;
if (string.IsNullOrEmpty(friendlyName) ||
!friendlyName.Contains(deviceName, StringComparison.OrdinalIgnoreCase))
continue;
var instanceId = $"BTHENUM\\{subKeyName}\\{instanceName}";
var battery = GetHfpBatteryLevel(instanceId);
if (battery.HasValue)
{
// Cache for future lookups
_hfpInstanceIdCache[deviceName] = instanceId;
UpdateBatteryLevel(deviceName, battery.Value);
return true;
}
}
}
return false;
}
catch
{
return false;
}
}).ConfigureAwait(false);
}
private byte? GetHfpBatteryLevel(string instanceId)
{
try
{
int result = CM_Locate_DevNodeW(out int devInst, instanceId, CM_LOCATE_DEVNODE_NORMAL);
if (result != CR_SUCCESS)
return null;
int bufferSize = 0;
var propKey = DEVPKEY_Bluetooth_HfpBattery;
result = CM_Get_DevNode_PropertyW(devInst, ref propKey, out int propertyType, IntPtr.Zero, ref bufferSize, 0);
if (result != CR_BUFFER_SMALL && result != CR_SUCCESS)
return null;
if (bufferSize == 0)
return null;
IntPtr buffer = Marshal.AllocHGlobal(bufferSize);
try
{
result = CM_Get_DevNode_PropertyW(devInst, ref propKey, out propertyType, buffer, ref bufferSize, 0);
if (result != CR_SUCCESS)
return null;
if (propertyType == DEVPROP_TYPE_BYTE && bufferSize >= 1)
return Marshal.ReadByte(buffer);
if ((propertyType == DEVPROP_TYPE_INT32 || propertyType == DEVPROP_TYPE_UINT32) && bufferSize >= 4)
{
int value = Marshal.ReadInt32(buffer);
if (value >= 0 && value <= 100)
return (byte)value;
}
if (bufferSize >= 1)
{
byte rawValue = Marshal.ReadByte(buffer);
if (rawValue <= 100)
return rawValue;
}
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
catch { }
return null;
}
private static bool TryParseBatteryLevel(object? batteryValue, out byte batteryLevel)
{
batteryLevel = 0;
return batteryValue != null && TryConvertBatteryLevel(batteryValue, out batteryLevel);
}
private void UpdateBatteryLevel(string deviceName, byte batteryLevel)
{
if (_devices.TryGetValue(deviceName, out var device))
{
device.BatteryLevel = batteryLevel;
device.LastUpdate = DateTime.Now;
ScheduleStateVerification();
_syncContext.Post(_ => UpdateDeviceIcon(deviceName), null);
}
}
private void UpdateDeviceIcon(string deviceName)
{
if (!_devices.TryGetValue(deviceName, out var deviceInfo)) return;
if (!_trayIcons.TryGetValue(deviceName, out var icon)) return;
try
{
var batteryIcon = GetBatteryIcon(deviceInfo.IsConnected ? deviceInfo.BatteryLevel : null);
_deviceCurrentIcons[deviceName] = batteryIcon;
if (icon.Icon != batteryIcon)
icon.Icon = batteryIcon;
UpdateTrayIconText(deviceName, deviceInfo);
UpdateContextMenuItems(deviceName);
UpdateSentinelVisibility();
}
catch (ObjectDisposedException) { }
catch { }
}
private void UpdateContextMenuItems(string deviceName)
{
if (!_devices.TryGetValue(deviceName, out var deviceInfo))
return;
try
{
if (_deviceMenuItems.TryGetValue(deviceName, out var statusItem) &&
!statusItem.IsDisposed &&
(statusItem.Owner == null || !statusItem.Owner.IsDisposed))
{
statusItem.Text = GetStatusText(deviceInfo);
}
if (_deviceLastUpdateMenuItems.TryGetValue(deviceName, out var lastUpdateItem) &&
!lastUpdateItem.IsDisposed &&
(lastUpdateItem.Owner == null || !lastUpdateItem.Owner.IsDisposed))
{
lastUpdateItem.Text = FormatLastUpdateText(deviceInfo);
}
}
catch (ObjectDisposedException) { }
catch (InvalidOperationException) { }
}
private void OnUiRefreshTimerTick(object? sender, EventArgs e)
{
if (_disposeCts.IsCancellationRequested)
return;
foreach (var deviceName in _devices.Keys.ToArray())
{
if (!_devices.TryGetValue(deviceName, out var deviceInfo))
continue;