-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
977 lines (883 loc) · 42.2 KB
/
Program.cs
File metadata and controls
977 lines (883 loc) · 42.2 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
using Microsoft.Win32;
using MultiDisplayVCPServer.Properties;
using System.Diagnostics;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace MultiDisplayVCPServer
{
/// <summary>
/// Main application class. Handles server lifecycle, client connections, and command execution.
/// </summary>
public static partial class Program
{
/// <summary>
/// A unique GUID to ensure only one instance of the application can run.
/// </summary>
private const string AppGuid = "MultiDisplayVCPServer.0D77BA1D-F890-48F0-975F-5E8A91F2681E";
/// <summary>
/// Mutex to enforce the single-instance-only rule.
/// </summary>
private static Mutex appMutex = null;
/// <summary>
/// The main TCP listener for incoming client connections.
/// </summary>
private static TcpListener listener;
/// <summary>
/// CancellationTokenSource to gracefully shut down the server.
/// </summary>
private static CancellationTokenSource cts;
/// <summary>
/// The background task that runs the server's listener loop.
/// </summary>
private static Task listenerTask;
/// <summary>
/// Event that fires when the server's state (Stopped, Running, Restarting) changes.
/// </summary>
public static event EventHandler<int> ServerStateChanged;
/// <summary>
/// Event that fires to send a log message to the UI.
/// </summary>
public static event EventHandler<string> LogMessageReceived;
/// <summary>
/// Logs a message to the console and to the main UI form if it's open.
/// </summary>
/// <param name="message">The message to log.</param>
private static void Log(string message)
{
string logEntry = $"[{DateTime.Now:HH:mm:ss}] {message}";
Debug.WriteLine(logEntry);
if (Application.OpenForms.Cast<Form>().Any(f => f is MainForm))
{
LogMessageReceived?.Invoke(null, logEntry);
}
}
private static ServerStatus _monitorCache = new();
private static readonly object _cacheLock = new();
private static readonly char[] _pipeDelimiter = new[] { '|' };
private static readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions { WriteIndented = true };
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
public static void Main(string[] _)
{
Log("Main() started.");
bool createdNew = false;
try
{
// Ensure only one instance of the app is running
Log("Checking for existing application instance (Mutex)...");
appMutex = new Mutex(true, $"Global\\{AppGuid}", out createdNew);
}
catch (Exception)
{
createdNew = false;
}
if (!createdNew)
{
Log("Another instance is already running. Showing message box.");
MessageBox.Show("Another instance of Multi-Connection Monitor Server is already running.", "Application Already Running", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log("Main() exiting.");
return;
}
Log("Mutex check passed. Starting application.");
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// --- THIS IS THE NEW LOGIC ---
// 1. Run the SplashForm.
// This makes the SplashForm the main UI thread.
Log("Running SplashForm.");
Application.Run(new SplashForm());
// --- END NEW LOGIC ---
Log("SplashForm closed. Releasing mutex.");
appMutex.ReleaseMutex();
Log("Main() finished.");
}
/// <summary>
/// Starts the TCP listener background task.
/// </summary>
public static void StartServerLoop()
{
Log("StartServerLoop() started.");
if (listenerTask != null && !listenerTask.IsCompleted)
{
Log("Attempted to start server, but it is already running or busy.");
return;
}
Log("Creating new CancellationTokenSource and starting ListenerLoopAsync task.");
cts = new CancellationTokenSource();
listenerTask = Task.Run(() => ListenerLoopAsync(cts.Token));
Log("Server startup initiated...");
}
/// <summary>
/// Signals the TCP listener to stop and cancels the background task.
/// </summary>
public static void ShutdownServer()
{
Log("ShutdownServer() started.");
cts?.Cancel();
Log("CancellationTokenSource cancel requested.");
listener?.Stop();
Log("TCP listener stop requested.");
Log("ShutdownServer() finished.");
}
/// <summary>
/// Shuts down the server, waits, and then starts it again.
/// </summary>
public static void RestartServer()
{
Log("RestartServer() started.");
Settings.Default.ServerState = 2; // Set state to "Restarting"
Settings.Default.Save();
ServerStateChanged?.Invoke(null, 2);
Log("Server state set to 2 (Restarting).");
Log("Calling ShutdownServer().");
ShutdownServer();
Log("Waiting for 150ms...");
Thread.Sleep(150);
Log("Calling StartServerLoop().");
StartServerLoop();
Log("Server restart sequence completed.");
}
/// <summary>
/// The main server loop that runs on a background thread.
/// </summary>
/// <param name="token">The cancellation token to signal shutdown.</param>
private static async Task ListenerLoopAsync(CancellationToken token)
{
Log("ListenerLoopAsync() started on background thread.");
bool serverStartedSuccessfully = false;
try
{
SetServerState(2); // "Busy/Restarting"
int port = Settings.Default.Port;
listener = new TcpListener(IPAddress.Any, port);
listener.Start();
serverStartedSuccessfully = true;
// --- THIS LOG IS MOVED UP ---
Log($"Server listener started on port {port}.");
// --- Build the cache on startup FIRST ---
Log("Building initial monitor cache... (This may take a few seconds)");
await BuildMonitorCacheAsync();
Log("Cache built. Server is ready and waiting for connections.");
Log("Setting server state to 1 (Running).");
SetServerState(1);
while (!token.IsCancellationRequested)
{
// ...
TcpClient client = await listener.AcceptTcpClientAsync(token);
if (client != null)
{
Log($"Client connected: {client.Client.RemoteEndPoint}");
}
// --- FIX for CS4014: Assign task to discard '_' ---
// This tells the compiler we are *intentionally* not awaiting
_ = Task.Run(() => HandleClientAsync(client, token), token);
}
}
catch (OperationCanceledException)
{
Log("Server listener stopped gracefully via token cancellation.");
}
catch (SocketException ex) when (ex.ErrorCode == 10004)
{
Log("Server listener stopped gracefully (SocketException 10004).");
}
catch (Exception ex)
{
Log($"Server failed to start or crashed: {ex.Message}");
if (!serverStartedSuccessfully)
{
Log("Server failed during initial startup.");
throw;
}
}
finally
{
Log("ListenerLoopAsync() cleaning up...");
listener?.Stop();
Settings.Default.ServerState = 0; // "Stopped"
Settings.Default.Save();
Log("Server state set to 0 (Stopped).");
if (!token.IsCancellationRequested)
{
Log("Firing ServerStateChanged event (0).");
ServerStateChanged?.Invoke(null, 0);
}
Log("ListenerLoopAsync() finished.");
}
}
/// <summary>
/// Runs the slow, brute-force scan to discover all monitors and capabilities
/// and stores the result in the static _monitorCache.
/// </summary>
public static async Task BuildMonitorCacheAsync()
{
Log("BuildMonitorCacheAsync() started.");
Log("Starting monitor capability scan...");
var sw = Stopwatch.StartNew();
// Run the synchronous, slow scan on a background thread
Log("Awaiting Task.Run(GetMonitorCapabilities)...");
var newStatus = await Task.Run(() => GetMonitorCapabilities());
Log("GetMonitorCapabilities task completed.");
sw.Stop();
// Safely replace the old cache with the new one
Log("Safely replacing old cache with new cache...");
lock (_cacheLock)
{
Log("Cache lock acquired.");
_monitorCache = newStatus;
Log("Cache lock released.");
}
Log($"Monitor scan complete in {sw.ElapsedMilliseconds}ms. Found {_monitorCache.Monitors.Count} monitors.");
Log("BuildMonitorCacheAsync() finished.");
}
/// <summary>
/// Updates a single value in the cache after a successful SET command.
/// </summary>
private static void UpdateCache(string pnpId, byte vcpCode, uint newValue)
{
Log($"UpdateCache() started for {pnpId}: 0x{vcpCode:X2} = {newValue}");
lock (_cacheLock)
{
Log("Cache lock acquired.");
var monitor = _monitorCache.Monitors.FirstOrDefault(m => m.DeviceID == pnpId);
if (monitor != null)
{
var feature = monitor.Capabilities.FirstOrDefault(f => f.Code == vcpCode);
if (feature != null)
{
feature.CurrentValue = newValue;
Log($"Cache updated for {pnpId}: 0x{vcpCode:X2} set to {newValue}");
}
else
{
Log($"Cache update warning: Feature 0x{vcpCode:X2} not found for monitor {pnpId}.");
}
}
else
{
Log($"Cache update warning: Monitor {pnpId} not found in cache.");
}
}
Log("Cache lock released.");
Log("UpdateCache() finished.");
}
/// <summary>
/// Handles a single connected client.
/// </summary>
/// <param name="client">The connected TcpClient.</param>
/// <param name="token">The cancellation token.</param>
private static async Task HandleClientAsync(TcpClient client, CancellationToken token)
{
string remoteEndPoint = client.Client.RemoteEndPoint?.ToString() ?? "Unknown Client";
Log($"HandleClientAsync() started for {remoteEndPoint}.");
using (client)
using (NetworkStream stream = client.GetStream())
{
try
{
Log($"Reading from stream for {remoteEndPoint}...");
byte[] buffer = new byte[1024];
int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, token);
string receivedData = Encoding.ASCII.GetString(buffer, 0, bytesRead).Trim();
// Log the command part of the request, which is safer than logging the whole string
string loggableData = receivedData;
if (receivedData.Contains('|'))
{
// --- FIX for CA1861: Use the cached delimiter ---
var partsForLog = receivedData.Split(_pipeDelimiter, 3);
loggableData = partsForLog.Length == 3 ? partsForLog[2] : receivedData;
}
Log($"Received request from {remoteEndPoint}: '{loggableData}'");
if (string.IsNullOrEmpty(receivedData))
{
Log($"Empty request from {remoteEndPoint}. Closing connection.");
return;
}
// Protocol: timestamp|hash_base64|command
string[] parts = receivedData.Split(_pipeDelimiter, 3);
string responseMessage;
bool isJson = false;
if (parts.Length == 3)
{
Log($"Request from {remoteEndPoint} has 3 parts. Validating hash...");
string timestampStr = parts[0];
string hashBase64 = parts[1];
string command = parts[2];
string requiredPassword = Settings.Default.Password;
if (ValidateHash(timestampStr, hashBase64, command, requiredPassword))
{
Log("Hash validated. Executing command.");
responseMessage = ExecuteDdcCiCommand(command, out isJson);
}
else
{
responseMessage = "ERROR: Invalid Hash.";
Log($"Authentication failed for {remoteEndPoint}. Hash mismatch or stale timestamp.");
}
}
else
{
responseMessage = "ERROR: Invalid request format.";
Log($"Authentication failed for {remoteEndPoint}. Invalid format (expected 3 parts, got {parts.Length}).");
}
Log($"Sending response to {remoteEndPoint}...");
await SendResponseAsync(stream, responseMessage, isJson, token);
}
catch (OperationCanceledException) { }
catch (IOException ex) when (ex.InnerException is SocketException se && se.ErrorCode == 10054)
{
Log($"Client {remoteEndPoint} disconnected abruptly (SocketError 10054).");
}
catch (Exception ex)
{
Log($"Client handling error for {remoteEndPoint}: {ex.Message}");
if (stream.CanWrite)
{
Log("Attempting to send server error message to client.");
await SendResponseAsync(stream, "SERVER ERROR: An unexpected server error occurred.", false, token);
}
}
finally
{
Log($"Client connection closed: {remoteEndPoint}.");
Log($"HandleClientAsync() finished for {remoteEndPoint}.");
}
}
}
/// <summary>
/// Validates an incoming request's HMAC hash and timestamp.
/// </summary>
/// <param name="timestampStr">The client-provided Unix timestamp string.</param>
/// <param name="hashBase64">The client-provided HMAC-SHA256 hash.</param>
/// <param name="command">The command being executed.</param>
/// <param name="password">The shared secret (password) used to generate the hash.</param>
/// <returns>True if the hash and timestamp are valid, otherwise false.</returns>
private static bool ValidateHash(string timestampStr, string hashBase64, string command, string password)
{
Log("ValidateHash() started.");
try
{
// 1. Check timestamp
Log("Checking timestamp...");
if (!long.TryParse(timestampStr, NumberStyles.None, CultureInfo.InvariantCulture, out long timestamp))
{
Log("Timestamp parse failed.");
return false;
}
var requestTime = DateTimeOffset.FromUnixTimeSeconds(timestamp).UtcDateTime;
var now = DateTime.UtcNow;
// Allow a 30-second window
if (requestTime < now.AddSeconds(-30) || requestTime > now.AddSeconds(30))
{
Log($"Hash validation failed: Stale timestamp. Request: {requestTime}, Server: {now}");
return false;
}
Log("Timestamp is valid.");
// 2. Check hash
Log("Checking hash...");
using (var hmac = new HMACSHA256(Encoding.ASCII.GetBytes(password)))
{
string messageToHash = command + timestampStr;
byte[] computedHashBytes = hmac.ComputeHash(Encoding.ASCII.GetBytes(messageToHash));
string computedHashBase64 = Convert.ToBase64String(computedHashBytes);
if (computedHashBase64 != hashBase64)
{
Log($"Hash validation failed: Hash mismatch. Expected: {computedHashBase64}, Got: {hashBase64}");
return false;
}
}
Log("Hash is valid.");
Log("ValidateHash() finished successfully.");
return true;
}
catch (Exception ex)
{
Log($"Error during hash validation: {ex.Message}");
return false;
}
}
/// <summary>
/// Parses and executes a validated command from a client.
/// </summary>
/// <param name="command">The command to execute (e.g., "GET_CAPS" or "SET:ID:CODE:VALUE").</param>
/// <param name="isJson">Output parameter; set to true if the response is JSON.</param>
/// <returns>A string response for the client.</returns>
private static string ExecuteDdcCiCommand(string command, out bool isJson)
{
Log($"ExecuteDdcCiCommand() started. Command: {command}");
isJson = false;
if (command.Equals("GET_CAPS", StringComparison.OrdinalIgnoreCase))
{
isJson = true;
Log("Executing GET_CAPS from cache.");
lock (_cacheLock)
{
Log("Cache lock acquired for GET_CAPS.");
// --- FIX for CA1869: Use the cached JSON options ---
string jsonResponse = JsonSerializer.Serialize(_monitorCache, _jsonOptions);
Log("Cache lock released for GET_CAPS.");
// ...
return jsonResponse;
}
}
else if (command.StartsWith("SET:", StringComparison.OrdinalIgnoreCase))
{
Log("Command is SET. Parsing...");
string[] parts = command.Split(':');
if (parts.Length == 4 &&
uint.TryParse(parts[2], out uint vcpCode) &&
uint.TryParse(parts[3], out uint vcpValue))
{
string targetPnP_ID = parts[1]; // This is the stable Model ID
Log($"Parsed SET: ID={targetPnP_ID}, Code={vcpCode}, Value={vcpValue}");
Log($"Finding handle for PnP_ID: {targetPnP_ID}");
IntPtr targetHandle = FindMonitorHandle(targetPnP_ID);
if (targetHandle != (IntPtr)(-1))
{
Log($"Found handle {targetHandle}. Attempting to set VCP feature...");
try
{
bool success = MonitorController.SetVCPFeature(targetHandle, (byte)vcpCode, vcpValue);
Log($"SetVCPFeature returned: {success}");
if (success)
{
Log("SET successful. Updating cache.");
UpdateCache(targetPnP_ID, (byte)vcpCode, vcpValue);
}
string response = success
? $"OK: VCP Code 0x{vcpCode:X2} set to {vcpValue} on {targetPnP_ID}."
: "ERROR: DDC/CI command failed.";
Log($"ExecuteDdcCiCommand() finished. Response: {response}");
return response;
}
finally
{
Log($"Destroying handle {targetHandle}.");
MonitorController.DestroyPhysicalMonitor(targetHandle);
}
}
else
{
Log($"Error: Monitor ID {targetPnP_ID} not found.");
Log("ExecuteDdcCiCommand() finished.");
return $"ERROR: Monitor ID {targetPnP_ID} not found.";
}
}
else
{
Log("Error: Invalid SET command format.");
Log("ExecuteDdcCiCommand() finished.");
return "ERROR: Invalid SET command format. Use SET:ID:CODE:VALUE.";
}
}
else if (command.Equals("REFRESH_CACHE", StringComparison.OrdinalIgnoreCase))
{
Log("Manual REFRESH_CACHE command received. Rebuilding cache in background.");
_ = BuildMonitorCacheAsync();
Log("ExecuteDdcCiCommand() finished.");
return "OK: Cache refresh initiated.";
}
else
{
Log($"Error: Invalid command '{command}'.");
Log("ExecuteDdcCiCommand() finished.");
return "ERROR: Invalid Command. Send GET_CAPS or SET:ID:CODE:VALUE.";
}
}
#region Monitor_DDC/CI_Helpers
/// <summary>
/// Finds the DDC/CI handle (hMonitor) for a monitor based on its stable PnP Model ID.
/// </summary>
/// <param name="targetPnP_ID">The stable Model ID (e.g., "ACR0D1D").</param>
/// <returns>A handle to the physical monitor, or -1 if not found.</returns>
static IntPtr FindMonitorHandle(string targetPnP_ID)
{
Log($"FindMonitorHandle() started for PnP_ID: {targetPnP_ID}");
if (string.IsNullOrEmpty(targetPnP_ID))
{
Log("Error: targetPnP_ID is null or empty.");
return (IntPtr)(-1);
}
// 1. Get the WMI map of PnP_ID -> DDC/CI Description
Log("Getting WMI map (from cache or new query)...");
var pnpMap = MonitorWmiHelper.GetPnPMonitorMap();
if (!pnpMap.TryGetValue(targetPnP_ID, out string targetDescription))
{
Log($"Error: Could not find PnP_ID {targetPnP_ID} in WMI map.");
return (IntPtr)(-1);
}
Log($"Target DDC/CI Description is: {targetDescription}");
// 2. Enumerate all monitors
Log("Enumerating all physical monitors...");
var monitors = MonitorController.EnumeratePhysicalMonitors(new Dictionary<string, string>());
Log($"Found {monitors.Count} physical monitors.");
IntPtr foundHandle = (IntPtr)(-1);
// 3. Find the monitor with the matching DDC/CI Description
Log("Searching for monitor with matching description...");
foreach (var monitor in monitors)
{
if (monitor.Description.Equals(targetDescription, StringComparison.OrdinalIgnoreCase))
{
// Test if this is the real monitor by checking for Input Select (0x60)
uint current = 0, max = 0;
MonitorController.MONITOR_CAPABILITIES_REQUEST_TYPE type = 0;
if (MonitorController.GetVCPFeatureAndVCPFeatureReply(monitor.Handle, 0x60, ref type, ref current, ref max))
{
foundHandle = monitor.Handle;
Log($"Found REAL handle {foundHandle} for {targetDescription}");
break;
}
else
{
Log($"Found dummy/capture card handle for {targetDescription}. Ignoring.");
}
}
}
// 4. Clean up other handles
Log("Cleaning up other monitor handles...");
foreach (var monitor in monitors)
{
if (monitor.Handle != foundHandle)
{
MonitorController.DestroyPhysicalMonitor(monitor.Handle);
}
}
Log($"FindMonitorHandle() finished. Returning handle: {foundHandle}");
return foundHandle;
}
/// <summary>
/// Gathers capabilities from all DDC/CI-compliant monitors and returns them as a JSON string.
/// </summary>
/// <returns>A JSON string representing the ServerStatus object.</returns>
static ServerStatus GetMonitorCapabilities()
{
Log("GetMonitorCapabilities() started.");
// 1. Get the map of DDC/CI Description -> PnP Model ID
Log("Getting WMI map (from cache or new query)...");
var pnpMap = MonitorWmiHelper.GetMonitorPnPMap();
Log($"Found {pnpMap.Count} monitors in WMI.");
List<MonitorInfo> monitorList = new();
// 2. Enumerate all physical monitors
Log("Enumerating all physical monitors...");
var physicalMonitors = MonitorController.EnumeratePhysicalMonitors(pnpMap);
Log($"Found {physicalMonitors.Count} DDC/CI monitors.");
foreach (var pMon in physicalMonitors)
{
Log($"Processing monitor: {pMon.Description} (PnP: {pMon.PnP_ID})");
IntPtr hMonitor = pMon.Handle;
// 3. Check for stable PnP_ID (if it's missing, we can't use this monitor)
if (string.IsNullOrEmpty(pMon.PnP_ID))
{
Log($"Skipping monitor {pMon.Description}: Could not find matching PnP_ID in WMI.");
MonitorController.DestroyPhysicalMonitor(hMonitor);
continue;
}
// 4. Get capabilities string
Log($"Getting capabilities string length for {pMon.Description}...");
uint length = 0;
if (!MonitorController.GetCapabilitiesStringLength(hMonitor, ref length))
{
Log($"Skipping monitor {pMon.Description}: Failed to get capabilities string length.");
MonitorController.DestroyPhysicalMonitor(hMonitor);
continue;
}
Log($"Capabilities string length: {length}");
StringBuilder sb = new StringBuilder((int)length);
if (!MonitorController.CapabilitiesRequestAndCapabilitiesReply(hMonitor, sb, length))
{
Log($"Skipping monitor {pMon.Description}: Failed to get capabilities string.");
MonitorController.DestroyPhysicalMonitor(hMonitor);
continue;
}
Log($"Capabilities string: {sb.ToString()}");
// 5. Discover all VCP features
Log($"Discovering VCP features for {pMon.Description}...");
List<VcpFeature> features = DiscoverAllVcpFeatures(hMonitor, sb.ToString());
// The Dummy Filter: If it has less than 10 features, it's a capture card.
if (features.Count < 10)
{
Log($"Skipping {pMon.Description}: Only found {features.Count} features. Likely a capture card.");
MonitorController.DestroyPhysicalMonitor(hMonitor);
continue;
}
Log($"Discovered {features.Count} features. Adding to cache.");
monitorList.Add(new MonitorInfo
{
DeviceID = pMon.PnP_ID, // The stable Model ID
Description = pMon.Description, // The DDC/CI Name
Capabilities = features
});
Log($"Destroying handle for {pMon.Description}.");
MonitorController.DestroyPhysicalMonitor(hMonitor);
}
ServerStatus status = new()
{
Monitors = monitorList,
Message = $"OK: Found {monitorList.Count} DDC/CI compliant monitors."
};
Log("GetMonitorCapabilities() finished.");
return status;
}
/// <summary>
/// Helper to parse a hex string to a uint.
/// </summary>
static bool TryParseVcpHex(string hex, out uint result)
{
// --- Skipped logging for this small, noisy utility ---
return uint.TryParse(hex, System.Globalization.NumberStyles.HexNumber,
System.Globalization.CultureInfo.InvariantCulture, out result);
}
[GeneratedRegex(@"vcp\((.*?)\)", RegexOptions.IgnoreCase | RegexOptions.Singleline)]
private static partial Regex VcpCapabilityRegex();
/// <summary>
/// Iterates through all possible VCP codes (0-255) to discover a monitor's features.
/// </summary>
/// <param name="hMonitor">The monitor's handle.</param>
/// <param name="capString">The monitor's capabilities string (for parsing non-continuous values).</param>
/// <returns>A list of VcpFeature objects.</returns>
static List<VcpFeature> DiscoverAllVcpFeatures(IntPtr hMonitor, string capString)
{
Log($"DiscoverAllVcpFeatures() started for handle {hMonitor}.");
List<VcpFeature> features = new();
// List of VCP codes to ignore (reserved, table, or buggy)
var exclusionList = new HashSet<byte>
{
0x04, 0x05, 0x08, 0xAC, 0xAE, 0xB6, 0xC0, 0xC8, 0xC9, 0xDF, 0x02, 0x52, 0x82,
0xB2, 0xC6, 0xCA, 0xCC, 0xDC,
};
for (int i = 224; i <= 255; i++) { exclusionList.Add((byte)i); } // 0xE0-0xFF
// Known non-continuous VCP codes
var nonContinuousList = new HashSet<byte> { 0x14, 0x60, 0x8D, 0xD6, };
// Parse non-continuous value maps from the capability string (e.g., "60(01 02 0F)")
Log("Parsing capability string for non-continuous values...");
Dictionary<byte, string> nonContinuousMap = new Dictionary<byte, string>();
Match vcpMatch = VcpCapabilityRegex().Match(capString);
if (vcpMatch.Success)
{
string vcpContent = vcpMatch.Groups[1].Value.Trim();
string[] vcpTokens = vcpContent.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string token in vcpTokens)
{
int nonContStart = token.IndexOf('(');
if (nonContStart != -1)
{
if (TryParseVcpHex(token.Substring(0, nonContStart), out uint vcpCode))
{
nonContinuousMap[(byte)vcpCode] = token.Substring(nonContStart + 1).TrimEnd(')');
}
}
}
}
Log($"Found {nonContinuousMap.Count} non-continuous value maps.");
// Brute-force check all 256 VCP codes
Log("Starting brute-force scan for VCP codes 0-255...");
for (int vcpCode = 0; vcpCode <= 255; vcpCode++)
{
uint currentValue = 0;
uint maximumValue = 0;
MonitorController.MONITOR_CAPABILITIES_REQUEST_TYPE type = 0;
if (MonitorController.GetVCPFeatureAndVCPFeatureReply(hMonitor, (byte)vcpCode, ref type, ref currentValue, ref maximumValue))
{
if (exclusionList.Contains((byte)vcpCode))
{
continue;
}
VcpFeature feature = new VcpFeature
{
Code = (byte)vcpCode,
Name = GetVcpFeatureName((byte)vcpCode),
ReadWrite = true, // We assume Read/Write if GetVCPFeature succeeded
CurrentValue = currentValue,
MaximumValue = maximumValue,
};
if (nonContinuousList.Contains((byte)vcpCode))
{
feature.Type = "Non-Continuous";
if (nonContinuousMap.TryGetValue((byte)vcpCode, out string valuesStr))
{
string[] values = valuesStr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string valHex in values)
{
if (TryParseVcpHex(valHex, out uint val))
{
if (feature.NonContinuousValues == null) feature.NonContinuousValues = new Dictionary<uint, string>();
feature.NonContinuousValues[val] = val.ToString(); // TODO: Add friendly names if available
}
}
}
}
else
{
feature.Type = "Continuous";
}
features.Add(feature);
}
}
Log($"Brute-force scan complete. Found {features.Count} features.");
Log("DiscoverAllVcpFeatures() finished.");
return features;
}
/// <summary>
/// Provides a friendly name for a known VCP code.
/// </summary>
static string GetVcpFeatureName(byte code)
{
// --- Skipped logging for this simple, high-frequency utility ---
return code switch
{
0x02 => "New Control Value",
0x04 => "Restore Factory Defaults",
0x05 => "Restore Factory Luminance/Contrast",
0x08 => "Restore Factory Color Defaults",
0x0B => "Color Temperature Increment",
0x0C => "Color Temperature Request",
0x10 => "Brightness",
0x12 => "Contrast",
0x14 => "Select Color Preset",
0x16 => "Video Gain (Drive): Red",
0x18 => "Video Gain (Drive): Green",
0x1A => "Video Gain (Drive): Blue",
0x59 => "6 Axis Saturation Control: Red",
0x5A => "6 Axis Saturation Control: Yellow",
0x5B => "6 Axis Saturation Control: Green",
0x5C => "6 Axis Saturation Control: Cyan",
0x5D => "6 Axis Saturation Control: Blue",
0x5E => "6 Axis Saturation Control: Magenta",
0x60 => "Input Select",
0x62 => "Audio: Speaker Volume",
0x6C => "Video Black Level: Red",
0x6E => "Video Black Level: Green",
0x70 => "Video Black Level: Blue",
0x8D => "Audio Mute / Screen Blank",
0x9B => "6 Axis Color Control: Red",
0x9C => "6 Axis Color Control: Yellow",
0x9D => "6 Axis Color Control: Green",
0x9E => "6 Axis Color Control: Cyan",
0x9F => "6 Axis Color Control: Blue",
0xA0 => "6 Axis Color Control: Magenta",
0xAC => "Horizontal Frequency",
0xAE => "Vertical Frequency",
0xB6 => "Display Technology Type",
0xC0 => "Display Usage Time",
0xC6 => "Application Enable Key",
0xC8 => "Display Controller ID",
0xC9 => "Display Firmware Level",
0xCC => "OSD Language",
0xD6 => "Power Mode",
0xDF => "VCP Version",
_ => $"VCP Code 0x{code:X2}",
};
}
#endregion
/// <summary>
/// Sends a response back to the client over the network stream.
/// </summary>
private static async Task SendResponseAsync(NetworkStream stream, string message, bool isJson, CancellationToken token)
{
string logMessage = isJson ? "JSON Data" : message;
Log($"SendResponseAsync() started. Sending: {logMessage}");
byte[] response = Encoding.ASCII.GetBytes(message);
await stream.WriteAsync(response, 0, response.Length, token);
Log("SendResponseAsync() finished.");
}
/// <summary>
/// Saves the current application settings to disk.
/// </summary>
public static void SaveSettings()
{
Log("SaveSettings() started.");
try
{
Settings.Default.Save();
Log("Application settings saved successfully.");
}
catch (Exception ex)
{
Log($"Error saving settings: {ex.Message}");
}
}
/// <summary>
/// Enables or disables the application's automatic startup via the Windows Registry.
/// </summary>
/// <param name="enable">If true, adds to startup; otherwise, removes it.</param>
public static void SetStartup(bool enable)
{
Log($"SetStartup() started. Enable: {enable}");
const string runKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
const string appName = "MultiDisplayVCPServer";
try
{
Log("Opening registry key HKCU\\" + runKey);
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(runKey, true))
{
if (key == null)
{
Log("Error: Registry key not found.");
return;
}
if (enable)
{
string executablePath = Environment.ProcessPath;
if (string.IsNullOrEmpty(executablePath))
{
Log("Error: Could not determine executable path for startup.");
return;
}
string registryValue = $"\"{executablePath}\"";
Log($"Setting registry value '{appName}' to '{registryValue}'");
key.SetValue(appName, registryValue);
Log("Application added to Windows startup.");
}
else
{
if (key.GetValue(appName) != null)
{
Log($"Deleting registry value '{appName}'.");
key.DeleteValue(appName);
Log("Application removed from Windows startup.");
}
else
{
Log("Registry value not found, no action needed.");
}
}
}
}
catch (Exception ex)
{
Log($"Error modifying registry for startup: {ex.Message}");
}
Log("SetStartup() finished.");
}
/// <summary>
/// Allows external classes (like MainForm) to report a change in the server's busy state.
/// </summary>
/// <param name="state">The new state (0=Stopped, 1=Running, 2=Busy/Restarting).</param>
public static void SetServerState(int state)
{
Log($"SetServerState() called. New state: {state}");
// Only update if the state is actually changing
if (Settings.Default.ServerState != state)
{
Log($"State is different from current ({Settings.Default.ServerState}). Updating...");
Settings.Default.ServerState = state;
Settings.Default.Save();
Log($"Server state manually set to {state} and saved.");
ServerStateChanged?.Invoke(null, state);
Log("ServerStateChanged event fired.");
}
else
{
Log("State is the same as current. No change.");
}
Log("SetServerState() finished.");
}
}
}