forked from mann1x/BSManager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBSManagerMain.cs
1740 lines (1460 loc) · 64.3 KB
/
BSManagerMain.cs
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.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Management;
using System.Diagnostics;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Bluetooth.Advertisement;
using Windows.Storage.Streams;
using System.Reflection;
using System.Threading;
using Microsoft.Win32;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using IWshRuntimeLibrary;
using AutoUpdaterDotNET;
using System.Runtime.Serialization;
using System.Timers;
using System.ServiceProcess;
using File = System.IO.File;
using System.Text;
using Microsoft.Toolkit.Uwp.Notifications;
using System.IO.Packaging;
using NUnit.Framework;
using System.Globalization;
namespace BSManager
{
public enum MsgSeverity
{
INFO,
WARNING,
ERROR
}
public partial class Form1 : Form
{
readonly ComponentResourceManager resources = new ComponentResourceManager(typeof(Form1));
static int bsCount = 0;
static List<string> bsSerials = new List<string>();
static List<string> sbsSerials = new List<string>();
static List<string> pbsSerials = new List<string>();
static IEnumerable<JToken> bsTokens;
// Current data format
static DataFormat _dataFormat = DataFormat.Hex;
static string _versionInfo;
static TimeSpan _timeout = TimeSpan.FromSeconds(5);
static string steamvr_lhjson;
static string pimax_lhjson;
static bool slhfound = false;
static bool plhfound = false;
private HashSet<Lighthouse> _lighthouses = new HashSet<Lighthouse>();
private BluetoothLEAdvertisementWatcher watcher;
private ManagementEventWatcher insertWatcher;
private ManagementEventWatcher removeWatcher;
private int _delayCmd = 500;
private const string v2_ON = "01";
private const string v2_OFF = "00";
private readonly Guid v2_powerGuid = Guid.Parse("00001523-1212-efde-1523-785feabcd124");
private readonly Guid v2_powerCharacteristic = Guid.Parse("00001525-1212-efde-1523-785feabcd124");
private const string v1_ON = "12 00 00 28 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00";
private const string v1_OFF = "12 01 00 28 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00";
private readonly Guid v1_powerGuid = Guid.Parse("0000cb00-0000-1000-8000-00805f9b34fb");
private readonly Guid v1_powerCharacteristic = Guid.Parse("0000cb01-0000-1000-8000-00805f9b34fb");
private int _V2DoubleCheckMin = 5;
private bool V2BaseStations = false;
private bool V2BaseStationsVive = false;
public bool HeadSetState = false;
private static int processingCmdSync = 0;
private static int processingLHSync = 0;
private int ProcessLHtimerCycle = 1000;
public Thread thrUSBDiscovery;
public Thread thrProcessLH;
private DateTime LastCmdStamp;
private LastCmd LastCmdSent;
System.Timers.Timer ProcessLHtimer = new System.Timers.Timer();
private static TextWriterTraceListener traceEx = new TextWriterTraceListener("BSManager_exceptions.log", "BSManagerEx");
private static TextWriterTraceListener traceDbg = new TextWriterTraceListener("BSManager.log", "BSManagerDbg");
private readonly string fnKillList = "BSManager.kill.txt";
private readonly string fnGraceList = "BSManager.grace.txt";
private string[] kill_list = new string[] { };
private string[] graceful_list = new string[] { "vrmonitor", "vrdashboard", "ReviveOverlay", "vrmonitor" };
private string[] cleanup_pilist = new string[] { "pi_server", "piservice", "pimaxclient" };
private static bool debugLog = false;
private static bool ManageRuntime = false;
private static string RuntimePath = "";
private static bool LastManage = false;
private static bool ShowProgressToast = true;
private static bool SetProgressToast = true;
protected List<Windows.UI.Notifications.ToastNotification> ptoastNotificationList = new List<Windows.UI.Notifications.ToastNotification>();
[System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
public static extern bool PostMessage(IntPtr handleWnd, UInt32 Msg, Int32 wParam, UInt32 lParam);
const int WM_QUERYENDSESSION = 0x0011,
WM_ENDSESSION = 0x0016,
WM_TRUE = 0x1,
WM_FALSE = 0x0;
[System.Runtime.InteropServices.DllImportAttribute("user32.dll", EntryPoint = "FindWindowEx")]
public static extern int FindWindowEx(int hwndParent, int hwndEnfant, int lpClasse, string lpTitre);
[System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
static extern int GetWindowThreadProcessId(IntPtr hWnd, out int processId);
[System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
public static extern IntPtr FindWindowEx(IntPtr parentWindow, IntPtr previousChildWindow, string windowClass, string windowTitle);
public Form1()
{
LogLine($"[BSMANAGER] FORM INIT ");
InitializeComponent();
Application.ApplicationExit += delegate { notifyIcon1.Dispose(); };
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
Trace.AutoFlush = true;
this.Hide();
var name = Assembly.GetExecutingAssembly().GetName();
_versionInfo = string.Format($"{name.Version.Major:0}.{name.Version.Minor:0}.{name.Version.Build:0}");
LogLine($"[BSMANAGER] STARTED ");
LogLine($"[BSMANAGER] Version: {_versionInfo}");
FindRuntime();
using (RegistryKey registrySettingsCheck = Registry.CurrentUser.OpenSubKey("SOFTWARE\\ManniX\\BSManager", true))
{
RegistryKey registrySettings;
if (registrySettingsCheck == null)
{
registrySettings = Registry.CurrentUser.CreateSubKey
("SOFTWARE\\ManniX\\BSManager");
}
registrySettings = Registry.CurrentUser.OpenSubKey("SOFTWARE\\ManniX\\BSManager", true);
if (registrySettings.GetValue("DebugLog") == null)
{
toolStripDebugLog.Checked = false;
debugLog = false;
LogLine($"[BSMANAGER] Debug Log disabled");
}
else
{
toolStripDebugLog.Checked = true;
debugLog = true;
LogLine($"[BSMANAGER] Debug Log enabled");
}
if (registrySettings.GetValue("ManageRuntime") == null)
{
RuntimeToolStripMenuItem.Checked = false;
ManageRuntime = false;
LogLine($"[BSMANAGER] Manage Runtime disabled");
}
else
{
RuntimeToolStripMenuItem.Checked = true;
ManageRuntime = true;
LogLine($"[BSMANAGER] Manage Runtime enabled");
}
if (registrySettings.GetValue("ShowProgressToast") == null)
{
disableProgressToastToolStripMenuItem.Checked = true;
SetProgressToast = false;
ShowProgressToast = false;
LogLine($"[BSMANAGER] Progress Toast disabled");
}
else
{
disableProgressToastToolStripMenuItem.Checked = false;
SetProgressToast = true;
ShowProgressToast = true;
LogLine($"[BSMANAGER] Progress Toast enabled");
}
}
AutoUpdater.ReportErrors = false;
AutoUpdater.InstalledVersion = new Version(_versionInfo);
AutoUpdater.DownloadPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
AutoUpdater.RunUpdateAsAdmin = false;
AutoUpdater.Synchronous = true;
AutoUpdater.ParseUpdateInfoEvent += AutoUpdaterOnParseUpdateInfoEvent;
AutoUpdater.Start("https://raw.githubusercontent.com/mann1x/BSManager/master/BSManager/AutoUpdaterBSManager.json");
bSManagerVersionToolStripMenuItem.Text = "BSManager Version " + _versionInfo;
using (RegistryKey registryStart = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
{
if (registryStart.GetValue("BSManager") != null)
{
string _curpath = registryStart?.GetValue("BSManager")?.ToString();
if (_curpath == null)
{
toolStripRunAtStartup.Checked = false;
}
else
{
if (_curpath != MyExecutableWithPath) registryStart.SetValue("BSManager", MyExecutableWithPath);
toolStripRunAtStartup.Checked = true;
}
}
else
{
registryStart.SetValue("BSManager", "");
}
}
string[] _glist = null;
string[] _klist = null;
_glist = ProcListLoad(fnGraceList, "graceful");
_klist = ProcListLoad(fnKillList, "immediate");
if (_glist != null) graceful_list = _glist;
if (_klist != null) kill_list = _klist;
_glist = null; _klist = null;
slhfound = Read_SteamVR_config();
if (!slhfound)
{
SteamVR_DB_ToolStripMenuItem.Text = "SteamVR DB not found in registry";
}
else
{
slhfound = Load_LH_DB("SteamVR");
if (!slhfound) { SteamVR_DB_ToolStripMenuItem.Text = "SteamVR DB file parse error"; }
else
{
SteamVR_DB_ToolStripMenuItem.Text = "Serials:";
foreach (string bs in sbsSerials)
{
SteamVR_LH_ToolStripMenuItem.DropDownItems.Add(bs);
}
}
}
plhfound = Read_Pimax_config();
if (!plhfound)
{
Pimax_DB_ToolStripMenuItem.Text = "Pimax DB not found";
}
else
{
plhfound = Load_LH_DB("Pimax");
if (!plhfound) { Pimax_DB_ToolStripMenuItem.Text = "Pimax DB file parse error"; }
else
{
Pimax_DB_ToolStripMenuItem.Text = "Serials:";
foreach (string bs in pbsSerials)
{
Pimax_LH_ToolStripMenuItem.DropDownItems.Add(bs);
}
}
}
WqlEventQuery insertQuery = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'");
insertWatcher = new ManagementEventWatcher(insertQuery);
insertWatcher.EventArrived += new EventArrivedEventHandler(DeviceInsertedEvent);
insertWatcher.Start();
WqlEventQuery removeQuery = new WqlEventQuery("SELECT * FROM __InstanceDeletionEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'");
removeWatcher = new ManagementEventWatcher(removeQuery);
removeWatcher.EventArrived += new EventArrivedEventHandler(DeviceRemovedEvent);
removeWatcher.Start();
watcher = new BluetoothLEAdvertisementWatcher();
watcher.Received += AdvertisementWatcher_Received;
thrUSBDiscovery = new Thread(RunUSBDiscovery);
thrUSBDiscovery.Start();
thrProcessLH = new Thread(RunProcessLH);
while (true)
{
if (!thrUSBDiscovery.IsAlive)
{
LogLine("[LightHouse] Starting LightHouse Thread");
thrProcessLH.Start();
break;
}
}
const string scheme = "pack";
if (!UriParser.IsKnownScheme(scheme))
{
Assert.That(PackUriHelper.UriSchemePack, Is.EqualTo(scheme));
}
// Listen to notification activation
ToastNotificationManagerCompat.OnActivated += toastArgs =>
{
// Obtain the arguments from the notification
ToastArguments args = ToastArguments.Parse(toastArgs.Argument);
// Clear the Toast Progress List
if (args["conversationId"] == "9113") ptoastNotificationList.Clear();
};
}
catch (Exception ex)
{
HandleEx(ex);
}
}
private void HandleEx(Exception ex)
{
try
{
string _msg = ex.Message;
if (ex.Source != string.Empty && ex.Source != null) _msg = $"{_msg} Source: {ex.Source}";
new ToastContentBuilder()
.AddHeader("6789", "Exception raised", "")
.AddText(_msg)
.AddText(ex.StackTrace)
.Show(toast =>
{
toast.ExpirationTime = DateTime.Now.AddSeconds(360);
});
LogLine($"{ex}");
traceEx.WriteLine($"[{DateTime.Now}] {ex}");
traceEx.Flush();
}
catch (Exception e)
{
LogLine($"[HANDLEEX] Exception: {e}");
}
}
public static void LogLine(string msg)
{
Trace.WriteLine($"{msg}");
if (debugLog)
{
traceDbg.WriteLine($"[{DateTime.Now}] {msg}");
traceDbg.Flush();
}
}
public void BalloonMsg(string msg, string header = "BSManager")
{
try
{
new ToastContentBuilder()
.AddText(header)
.AddText(msg)
.Show(toast =>
{
toast.ExpirationTime = DateTime.Now.AddSeconds(120);
});
Trace.WriteLine($"{msg}");
if (debugLog)
{
traceDbg.WriteLine($"[{DateTime.Now}] {msg}");
traceDbg.Flush();
}
}
catch (Exception e)
{
LogLine($"[BALLOONMSG] Exception: {e}");
}
}
private void timerManageRuntime()
{
Task.Delay(TimeSpan.FromMilliseconds(2500))
.ContinueWith(task => doManageRuntime());
}
private IntPtr[] GetProcessWindows(int process)
{
IntPtr[] apRet = (new IntPtr[256]);
int iCount = 0;
IntPtr pLast = IntPtr.Zero;
do
{
pLast = FindWindowEx(IntPtr.Zero, pLast, null, null);
int iProcess_;
GetWindowThreadProcessId(pLast, out iProcess_);
if (iProcess_ == process) apRet[iCount++] = pLast;
} while (pLast != IntPtr.Zero);
System.Array.Resize(ref apRet, iCount);
return apRet;
}
private void doManageRuntime()
{
try
{
void _pKill(Process _p2kill)
{
try
{
_p2kill.Kill();
}
catch (InvalidOperationException)
{
LogLine($"[Manage Runtime] {_p2kill.ProcessName} has probably already exited");
}
catch (AggregateException)
{
LogLine($"[Manage Runtime] {_p2kill.ProcessName} can't be killed: not all processes in the tree can be killed");
}
catch (NotSupportedException)
{
LogLine($"[Manage Runtime] {_p2kill.ProcessName} can't be killed: operation not supported");
}
catch (Win32Exception)
{
LogLine($"[Manage Runtime] {_p2kill.ProcessName} can't be killed: not enogh privileges or already exiting");
}
}
void _pClose(Process _p2close)
{
try
{
_p2close.CloseMainWindow();
}
catch (InvalidOperationException)
{
string ProcessName = _p2close.ProcessName;
LogLine($"[Manage Runtime] {ProcessName} has probably already exited");
}
}
void loopKill(string[] procnames, bool graceful)
{
foreach (string procname in procnames)
{
Process[] ProcsArray = Process.GetProcessesByName(procname);
if (ProcsArray.Count() > 0)
{
foreach (Process Proc2Kill in ProcsArray)
{
string ProcessName = Proc2Kill.ProcessName;
LogLine($"[Manage Runtime] Closing {ProcessName} with PID={Proc2Kill.Id}");
if (graceful)
{
_pClose(Proc2Kill);
}
else
{
_pKill(Proc2Kill);
}
for (int i = 0; i < 20; i++)
{
if (!Proc2Kill.HasExited)
{
Thread.Sleep(250);
Proc2Kill.Refresh();
Thread.Sleep(250);
}
else
{
break;
}
}
if (!Proc2Kill.HasExited)
{
_pKill(Proc2Kill);
Thread.Sleep(250);
Proc2Kill.Refresh();
Thread.Sleep(250);
if (!Proc2Kill.HasExited)
{
IntPtr[] wnd = GetProcessWindows(Int32.Parse((Proc2Kill.Id).ToString()));
var wm_ret = PostMessage(wnd[0], WM_ENDSESSION, WM_TRUE, 0x80000000);
Thread.Sleep(1000);
if (!Proc2Kill.HasExited)
{
LogLine($"[Manage Runtime] {ProcessName} can't be killed, still running");
}
}
else
{
LogLine($"[Manage Runtime] {ProcessName} killed");
Proc2Kill.Close();
Proc2Kill.Dispose();
}
}
else
{
LogLine($"[Manage Runtime] {ProcessName} killed");
Proc2Kill.Close();
Proc2Kill.Dispose();
}
}
}
else
{
LogLine($"[Manage Runtime] {procname} can't be killed: not found");
}
ProcsArray = null;
}
}
if (ManageRuntime)
{
if (!HeadSetState && LastManage)
{
#if DEBUG
Process[] localAll = Process.GetProcesses();
foreach (Process processo in localAll)
{
LogLine($"[PROCESSES] Active: {processo.ProcessName} PID={processo.Id}");
}
#endif
ServiceController sc = new ServiceController("PiServiceLauncher");
LogLine($"[Manage Runtime] PiService is currently: {sc.Status}");
if ((sc.Status.Equals(ServiceControllerStatus.Running)) ||
(sc.Status.Equals(ServiceControllerStatus.StartPending)))
{
LogLine($"[Manage Runtime] Stopping PiService");
sc.Stop();
sc.Refresh();
LogLine($"[Manage Runtime] PiService is now: {sc.Status}");
}
loopKill(cleanup_pilist, false);
if (graceful_list.Length > 0)
loopKill(graceful_list, true);
if (kill_list.Length > 0)
loopKill(kill_list, false);
LastManage = false;
}
else if (HeadSetState && !LastManage)
{
Process[] PimaxClientArray = Process.GetProcessesByName("PimaxClient");
LogLine($"[Manage Runtime] Found {PimaxClientArray.Count()} PimaxClient running");
if (PimaxClientArray.Count() == 0)
{
ProcessStartInfo startInfo = new ProcessStartInfo("C:\\Program Files\\Pimax\\PimaxClient\\pimaxui\\PimaxClient.exe", "hide");
startInfo.WindowStyle = ProcessWindowStyle.Minimized;
Process PimaxClient = Process.Start(startInfo);
LogLine($"[Manage Runtime] Started PimaxClient ({"C:\\Program Files\\Pimax\\PimaxClient\\pimaxui\\PimaxClient.exe"}) with PID={PimaxClient.Id}");
}
LastManage = true;
}
}
}
catch (Exception e) when (e is Win32Exception || e is FileNotFoundException)
{
LogLine($"[Manage Runtime] The following exception was raised: {e}");
}
}
private void USBDiscovery()
{
try
{
ManagementObjectCollection collection;
using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub"))
collection = searcher.Get();
foreach (var device in collection)
{
string did = (string)device.GetPropertyValue("DeviceID");
LogLine($"[USB Discovery] DID={did}");
CheckHMDOn(did);
}
collection.Dispose();
return;
}
catch (Exception ex)
{
HandleEx(ex);
}
}
private void CheckHMDOn(string did)
{
try
{
string _hmd = "";
string action = "ON";
if (did.Contains("VID_0483&PID_0101")) _hmd = "PIMAX HMD";
if (did.Contains("VID_2996&PID_0309")) _hmd = "VIVE PRO HMD";
if (did.Contains("VID_34A4&PID_0012")) _hmd = "Crystal HMD";
if (_hmd.Length > 0)
{
if (SetProgressToast) ShowProgressToast = true;
LogLine($"[HMD] ## {_hmd} {action} ");
ChangeHMDStrip($" {_hmd} {action} ", true);
this.notifyIcon1.Icon = BSManagerRes.bsmanager_on;
HeadSetState = true;
Task.Delay(TimeSpan.FromMilliseconds(500))
.ContinueWith(task => checkLHState(lh => !lh.PoweredOn, true));
LogLine($"[HMD] Runtime {action}: ManageRuntime is {ManageRuntime}");
timerManageRuntime();
}
}
catch (Exception ex)
{
HandleEx(ex);
}
}
private void checkLHState(Func<Lighthouse, bool> lighthousePredicate, bool hs_state)
{
if (HeadSetState == hs_state)
{
var results = _lighthouses.Where(lighthousePredicate);
if (results.Any())
{
foreach (Lighthouse lh in _lighthouses)
{
lh.ProcessDone = false;
}
}
}
}
private void CheckHMDOff(string did)
{
try
{
string _hmd = "";
string action = "OFF";
if (did.Contains("VID_0483&PID_0101")) _hmd = "PIMAX HMD";
if (did.Contains("VID_2996&PID_0309")) _hmd = "VIVE PRO HMD";
if (did.Contains("VID_34A4&PID_0012")) _hmd = "Crystal HMD";
if (_hmd.Length > 0)
{
if (SetProgressToast) ShowProgressToast = true;
LogLine($"[HMD] ## {_hmd} {action} ");
ChangeHMDStrip($" {_hmd} {action} ", false);
this.notifyIcon1.Icon = BSManagerRes.bsmanager_off;
HeadSetState = false;
Task.Delay(TimeSpan.FromMilliseconds(500))
.ContinueWith(task => checkLHState(lh => lh.PoweredOn, false));
LogLine($"[HMD] Runtime {action}: ManageRuntime is {ManageRuntime}");
timerManageRuntime();
}
}
catch (Exception ex)
{
HandleEx(ex);
}
}
private void DeviceInsertedEvent(object sender, EventArrivedEventArgs e)
{
try
{
ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
foreach (var property in instance.Properties)
{
if (property.Name == "PNPDeviceID")
{
CheckHMDOn(property.Value.ToString());
}
//LogLine($" INSERTED " + property.Name + " = " + property.Value);
}
e.NewEvent.Dispose();
}
catch (Exception ex)
{
HandleEx(ex);
}
}
private void DeviceRemovedEvent(object sender, EventArrivedEventArgs e)
{
try
{
ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
foreach (var property in instance.Properties)
{
if (property.Name == "PNPDeviceID")
{
CheckHMDOff(property.Value.ToString());
}
//LogLine($" REMOVED " + property.Name + " = " + property.Value);
}
e.NewEvent.Dispose();
}
catch (Exception ex)
{
HandleEx(ex);
}
}
private void ProcessLH_ElapsedEventHandler(object sender, ElapsedEventArgs e)
{
int sync = Interlocked.CompareExchange(ref processingLHSync, 1, 0);
if (sync == 0)
{
OnProcessLH(sender, e);
processingLHSync = 0;
}
}
public void ProcessWatcher(bool start)
{
if (start)
{
if (watcher.Status == BluetoothLEAdvertisementWatcherStatus.Stopped || watcher.Status == BluetoothLEAdvertisementWatcherStatus.Created)
{
ptoastNotificationList.Clear();
LogLine($"[LightHouse] Starting BLE Watcher Status: {watcher.Status}");
watcher.Start();
Thread.Sleep(250);
LogLine($"[LightHouse] Started BLE Watcher Status: {watcher.Status}");
}
}
else
{
if (watcher.Status == BluetoothLEAdvertisementWatcherStatus.Started && watcher.Status != BluetoothLEAdvertisementWatcherStatus.Stopping)
{
LogLine($"[LightHouse] Stopping BLE Watcher Status: {watcher.Status}");
watcher.Stop();
Thread.Sleep(250);
LogLine($"[LightHouse] Stopped BLE Watcher Status: {watcher.Status}");
ptoastNotificationList.Clear();
}
}
}
public void OnProcessLH(object sender, ElapsedEventArgs args)
{
try
{
bool _done = true;
if (V2BaseStationsVive && LastCmdSent == LastCmd.SLEEP && !HeadSetState)
{
TimeSpan _delta = DateTime.Now - LastCmdStamp;
//LogLine($"LastCmdSent {LastCmdSent} _delta {_delta}");
if (_delta.Minutes >= _V2DoubleCheckMin)
{
ShowProgressToast = false;
foreach (Lighthouse lh in _lighthouses)
{
lh.ProcessDone = false;
}
}
}
foreach (Lighthouse _lh in _lighthouses)
{
if (_lh.ProcessDone == false) _done = false;
}
if (_lighthouses.Count == 0 || _lighthouses.Count < bsCount)
{
ProcessWatcher(true);
}
else if (_done)
{
ProcessWatcher(false);
}
else
{
ProcessWatcher(true);
}
Thread.Sleep(ProcessLHtimerCycle);
}
catch (Exception ex)
{
HandleEx(ex);
}
}
void RunUSBDiscovery()
{
USBDiscovery();
}
void RunProcessLH()
{
ProcessLHtimer.Interval = ProcessLHtimerCycle;
ProcessLHtimer.Elapsed += new ElapsedEventHandler(ProcessLH_ElapsedEventHandler);
ProcessLHtimer.Start();
}
private void AutoUpdaterOnParseUpdateInfoEvent(ParseUpdateInfoEventArgs args)
{
dynamic json = JsonConvert.DeserializeObject(args.RemoteData);
args.UpdateInfo = new UpdateInfoEventArgs
{
CurrentVersion = json.version,
ChangelogURL = json.changelog,
DownloadURL = json.url,
Mandatory = new Mandatory
{
Value = json.mandatory.value,
UpdateMode = json.mandatory.mode,
MinimumVersion = json.mandatory.minVersion
},
CheckSum = new CheckSum
{
Value = json.checksum.value,
HashingAlgorithm = json.checksum.hashingAlgorithm
}
};
}
private void ChangeHMDStrip(string label, bool _checked)
{
try
{
BeginInvoke((MethodInvoker)delegate {
ToolStripMenuItemHmd.Text = label;
ToolStripMenuItemHmd.Checked = _checked;
});
}
catch (Exception ex)
{
HandleEx(ex);
}
}
private void ChangeDiscoMsg(string count, string nameBS)
{
try
{
BeginInvoke((MethodInvoker)delegate {
ToolStripMenuItemDisco.Text = $"Discovered: {count}/{bsCount}";
toolStripMenuItemBS.DropDownItems.Add(nameBS);
});
}
catch (Exception ex)
{
HandleEx(ex);
}
}
private void ChangeBSMsg(string _name, bool _poweredOn, LastCmd _lastCmd, Action _action)
{
try
{
string _cmdStatus = "";
string _actionStatus = "";
switch (_lastCmd)
{
case LastCmd.ERROR:
_cmdStatus = "[ERROR] ";
break;
default:
_cmdStatus = "";
break;
}
switch (_action)
{
case Action.WAKEUP:
_actionStatus = " - Going to Wakeup";
break;
case Action.SLEEP:
_actionStatus = " - Going to Standby";
break;
default:
_actionStatus = "";
break;
}
BeginInvoke((MethodInvoker)delegate {
foreach (ToolStripMenuItem item in toolStripMenuItemBS.DropDownItems)
{
if (item.Text.StartsWith(_name))
{
if (_poweredOn) item.Image = BSManagerRes.bsmanager_on.ToBitmap();
if (!_poweredOn) item.Image = null;
item.Text = $"{_name} {_cmdStatus}{_actionStatus}";
}
}
});
}
catch (Exception ex)
{
HandleEx(ex);
}
}
private bool Read_SteamVR_config()
{
try
{
steamvr_lhjson = string.Empty;
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\WOW6432Node\\Valve\\Steam"))
{
if (key != null)
{
Object o = key.GetValue("InstallPath");
if (o != null)
{
steamvr_lhjson = o.ToString() + "\\config\\lighthouse\\lighthousedb.json";
if (File.Exists(steamvr_lhjson))
{
LogLine($"[CONFIG] Found SteamVR LH DB at Path={steamvr_lhjson}");
return true;
}
else
{
LogLine($"[CONFIG] Not found SteamVR LH DB at Path={steamvr_lhjson}");
return false;
}
}
}
return false;
}
}
catch (Exception ex)
{
HandleEx(ex);
return false;
}
}
private bool Read_Pimax_config()
{
try
{
pimax_lhjson = string.Empty;
string ProgramDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
pimax_lhjson = ProgramDataFolder + "\\pimax\\runtime\\config\\lighthouse\\lighthousedb.json";