forked from AaronKelley/PowerMode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSetPowerMode.cs
More file actions
475 lines (433 loc) · 19.3 KB
/
Copy pathSetPowerMode.cs
File metadata and controls
475 lines (433 loc) · 19.3 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
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text.Json;
using PowerMode.Oem;
namespace PowerMode
{
/// <summary>
/// This program allows for setting the Windows "power mode" or "power slider" value from the command line.
/// The Windows overlay access lives in <see cref="PowerOverlay"/>; OEM power-mode backends live under Oem/.
/// When an OEM backend is detected, setting the Windows slider also drives the matching OEM mode (bound at
/// set-time). See docs/OEM-Power-Backends.md.
/// </summary>
class SetPowerMode
{
/// <summary>
/// Execution starts here.
/// </summary>
/// <param name="args">Command line parameters.</param>
/// <returns>Error status; 0 = success, non-zero = failure.</returns>
static int Main(string[] args)
{
try
{
// Read from App.config.
ReadConfig();
// The --json flag switches the report to machine-readable output; --no-oem suppresses the
// OEM binding (set the Windows slider only). Strip both; everything else is positional.
bool jsonOutput = false;
bool suppressOem = false;
List<string> positional = new List<string>();
foreach (string arg in args)
{
string lower = arg.ToLower();
if (lower == "--json" || lower == "-json" || lower == "/json")
{
jsonOutput = true;
}
else if (lower == "--no-oem" || lower == "-no-oem" || lower == "/no-oem")
{
suppressOem = true;
}
else
{
positional.Add(arg);
}
}
// OEM subcommands: PowerMode /oem list | /oem <mode>.
if (positional.Count >= 1 && IsOemFlag(positional[0]))
{
return HandleOemVerb(positional);
}
if (positional.Count == 0)
{
// Report the current power modes.
return Report(jsonOutput);
}
else if (positional.Count == 1)
{
// Attempt to set the power mode (both AC and DC).
string parameter = positional[0].ToLower();
if (parameter == "/?" || parameter == "-?")
{
Usage();
return 1;
}
Guid powerMode = PowerOverlay.ParseMode(parameter);
uint result = PowerOverlay.SetActiveOverlay(powerMode);
if (result == 0)
{
Console.WriteLine("Set power mode to {0}.", powerMode);
ApplyOemForOverlay(powerMode, suppressOem);
}
else
{
Console.Error.WriteLine("Failed to set power mode.\n");
Usage();
}
return (int)result;
}
else
{
// Parse /ac and /dc arguments.
Guid? acMode = null;
Guid? dcMode = null;
for (int i = 0; i < positional.Count; i++)
{
string flag = positional[i].ToLower();
if ((flag == "/ac" || flag == "-ac" || flag == "--ac") && i + 1 < positional.Count)
{
acMode = PowerOverlay.ParseMode(positional[++i].ToLower());
}
else if ((flag == "/dc" || flag == "-dc" || flag == "--dc") && i + 1 < positional.Count)
{
dcMode = PowerOverlay.ParseMode(positional[++i].ToLower());
}
else
{
Console.Error.WriteLine("Unrecognized argument: {0}\n", positional[i]);
Usage();
return 1;
}
}
if (acMode == null && dcMode == null)
{
Usage();
return 1;
}
if (acMode != null)
{
Guid acGuid = acMode.Value;
uint result = PowerOverlay.SetUserConfiguredAcMode(ref acGuid);
if (result == 0)
{
Console.WriteLine("Set AC power mode to {0}.", acGuid);
}
else
{
Console.Error.WriteLine("Failed to set AC power mode (error {0}).\n", result);
return (int)result;
}
}
if (dcMode != null)
{
Guid dcGuid = dcMode.Value;
uint result = PowerOverlay.SetUserConfiguredDcMode(ref dcGuid);
if (result == 0)
{
Console.WriteLine("Set DC power mode to {0}.", dcGuid);
}
else
{
Console.Error.WriteLine("Failed to set DC power mode (error {0}).\n", result);
return (int)result;
}
}
// Bind the OEM mode to whichever slider position is currently effective (AC vs DC).
if (PowerOverlay.GetEffectiveOverlay(out Guid effective) == 0)
{
ApplyOemForOverlay(effective, suppressOem);
}
}
}
catch (Exception exception)
{
// Print error information to the console.
Console.Error.WriteLine("{0}: {1}\n{2}", exception.GetType(), exception.Message, exception.StackTrace);
Console.WriteLine();
Usage();
return 1;
}
return 0;
}
/// <summary>
/// Drive the OEM power mode to match a Windows overlay position (slider-bound). No-op when the OEM
/// binding is suppressed, the overlay is a custom GUID with no normalized mapping, or no OEM backend is
/// present. OEM failures are reported but never fail the overall command (the slider was already set).
/// </summary>
private static void ApplyOemForOverlay(Guid overlay, bool suppressOem)
{
if (suppressOem)
{
return;
}
NormalizedMode? normalized = PowerOverlay.ToNormalized(overlay);
if (!normalized.HasValue)
{
return; // custom/unknown overlay GUID — leave the OEM mode alone
}
IOemBackend backend;
try
{
backend = OemDetection.Detect();
}
catch (Exception)
{
return;
}
if (backend == null)
{
return;
}
try
{
OemMode applied = backend.SetForNormalized(normalized.Value);
Console.WriteLine("Set {0} OEM mode to {1}.", backend.Vendor, applied.Token);
}
catch (Exception exception)
{
Console.Error.WriteLine("OEM mode set failed: {0}", exception.Message);
}
}
/// <summary>
/// Report the current power mode. As human-readable text this lists the
/// effective, AC, and DC modes (plus any detected OEM mode); as JSON it emits a
/// single flat object for the currently-effective mode, with an additive "oem" member.
/// </summary>
/// <param name="json">When true, emit machine-readable JSON instead of text.</param>
/// <returns>Zero on success; the non-zero API error from reading the effective mode otherwise.</returns>
private static int Report(bool json)
{
uint result = PowerOverlay.GetEffectiveOverlay(out Guid effectiveMode);
if (result != 0)
{
return (int)result;
}
Dictionary<string, object> oem = BuildOemReport(effectiveMode);
if (json)
{
// Flat, single-mode shape for automated consumers (e.g. QuasarBenchRunner):
// {"name":"Balanced","guid":"...","oem":{...}|null}
// "name"/"guid" are unchanged from earlier versions; "oem" is additive (null on non-OEM machines).
var report = new Dictionary<string, object>
{
["name"] = PowerOverlay.ModeToken(effectiveMode),
["guid"] = effectiveMode.ToString(),
["oem"] = oem,
};
Console.WriteLine(JsonSerializer.Serialize(report));
return 0;
}
// Human-readable text path: also report the user-configured AC and DC modes.
Console.WriteLine("Effective: {0} ({1})", PowerOverlay.FormatMode(effectiveMode), effectiveMode);
if (PowerOverlay.GetUserConfiguredAcMode(out Guid acMode) == 0)
{
Console.WriteLine("AC: {0} ({1})", PowerOverlay.FormatMode(acMode), acMode);
}
if (PowerOverlay.GetUserConfiguredDcMode(out Guid dcMode) == 0)
{
Console.WriteLine("DC: {0} ({1})", PowerOverlay.FormatMode(dcMode), dcMode);
}
if (oem != null)
{
string expected = oem.TryGetValue("expectedForSlider", out object exp) && exp != null
? string.Format(", expected {0}", exp) : string.Empty;
Console.WriteLine("OEM: {0} mode {1} [control model {2}]{3} (supported: {4})",
oem["vendor"], oem["currentMode"], oem["controlModel"], expected,
string.Join(", ", (List<string>)oem["supportedModes"]));
}
return 0;
}
/// <summary>
/// Detect an OEM backend and read its current state for the report. Returns null when no OEM backend
/// applies (non-OEM machine, disabled, or a query failure) — never throws out of the report path.
/// </summary>
private static Dictionary<string, object> BuildOemReport(Guid effectiveOverlay)
{
IOemBackend backend;
try
{
backend = OemDetection.Detect();
}
catch (Exception)
{
return null;
}
if (backend == null)
{
return null;
}
try
{
OemControlInfo info = backend.GetControlInfo();
OemMode current = backend.GetCurrentMode();
var supported = new List<string>();
foreach (OemMode m in backend.SupportedModes())
{
supported.Add(m.Token);
}
// The native mode the current slider position would resolve to (drift is current vs expected).
object expectedForSlider = null;
NormalizedMode? normalized = PowerOverlay.ToNormalized(effectiveOverlay);
if (normalized.HasValue)
{
expectedForSlider = backend.ResolveForNormalized(normalized.Value).Token;
}
return new Dictionary<string, object>
{
["vendor"] = info.Vendor,
["controlModel"] = info.Model.ToString(),
["biDirectional"] = info.BiDirectional,
["durableLever"] = info.DurableLever.ToString(),
["currentMode"] = current.Token,
["currentModeCode"] = current.Code,
["expectedForSlider"] = expectedForSlider,
["supportedModes"] = supported,
};
}
catch (Exception exception)
{
// OEM telemetry is best-effort; never break the core report.
Console.Error.WriteLine("OEM query failed: {0}", exception.Message);
return null;
}
}
private static bool IsOemFlag(string arg)
{
string lower = arg.ToLower();
return lower == "/oem" || lower == "-oem" || lower == "--oem";
}
/// <summary>
/// Handle the /oem verb: "/oem list" enumerates modes; "/oem <mode>" sets one directly. The mode may be
/// a normalized token (MaxPerformance/Balanced/PowerSaver — model- and power-aware), a native OEM token,
/// or a numeric code.
/// </summary>
private static int HandleOemVerb(List<string> positional)
{
IOemBackend backend = OemDetection.Detect();
if (backend == null)
{
Console.Error.WriteLine("No OEM power-mode backend detected (manufacturer: {0}).",
OemDetection.GetManufacturer());
return 1;
}
string sub = positional.Count >= 2 ? positional[1] : null;
if (sub == null || string.Equals(sub, "list", StringComparison.OrdinalIgnoreCase))
{
OemControlInfo info = backend.GetControlInfo();
OemMode current = backend.GetCurrentMode();
Console.WriteLine("{0} OEM power modes (control model {1}, durable lever {2}); current: {3}",
backend.Vendor, info.Model, info.DurableLever, current.Token);
foreach (OemMode m in backend.SupportedModes())
{
string norm = m.Normalized.HasValue ? m.Normalized.Value.ToString() : "-";
string marker = m.Code == current.Code ? "*" : " ";
Console.WriteLine(" {0} {1,-12} code={2} normalized={3}", marker, m.Token, m.Code, norm);
}
return 0;
}
try
{
OemMode applied;
NormalizedMode? normalized = ParseNormalized(sub);
if (normalized.HasValue)
{
applied = backend.SetForNormalized(normalized.Value);
}
else
{
OemMode? native = FindNativeMode(backend, sub);
if (native == null)
{
Console.Error.WriteLine("Unknown or unsupported OEM mode '{0}'. Use '/oem list'.", sub);
return 1;
}
applied = backend.SetMode(native.Value);
if (backend.GetControlInfo().Model == ControlModel.V2 && !applied.Normalized.HasValue)
{
Console.Error.WriteLine(
"Note: '{0}' has no Windows-slider equivalent; on this (V2) unit it may be overridden by the OEM app.",
applied.Token);
}
}
Console.WriteLine("Set {0} OEM mode to {1}.", backend.Vendor, applied.Token);
return 0;
}
catch (Exception exception)
{
Console.Error.WriteLine("OEM mode set failed: {0}", exception.Message);
return 1;
}
}
/// <summary>Parse a vendor-neutral normalized token, or null if not one.</summary>
private static NormalizedMode? ParseNormalized(string token)
{
switch (token.ToLower())
{
case "maxperformance": return NormalizedMode.MaxPerformance;
case "balanced": return NormalizedMode.Balanced;
case "powersaver": return NormalizedMode.PowerSaver;
default: return null;
}
}
/// <summary>Match a native OEM token or numeric code against the unit's supported modes.</summary>
private static OemMode? FindNativeMode(IOemBackend backend, string token)
{
foreach (OemMode m in backend.SupportedModes())
{
if (string.Equals(m.Token, token, StringComparison.OrdinalIgnoreCase)
|| m.Code.ToString() == token)
{
return m;
}
}
return null;
}
/// <summary>
/// Print a usage message to the console.
/// </summary>
private static void Usage()
{
Console.WriteLine(
"PowerMode (GPLv3); used to set the active power mode on Windows 10, version 1709 or later\n" +
"https://github.com/AaronKelley/PowerMode\n" +
"\n" +
" PowerMode Report the current power mode\n" +
" PowerMode --json Report the current power mode as JSON\n" +
" PowerMode <mode> Set the power mode (both AC and DC)\n" +
" PowerMode /ac <mode> Set the AC (plugged in) power mode\n" +
" PowerMode /dc <mode> Set the DC (battery) power mode\n" +
" PowerMode /ac <mode> /dc <mode> Set AC and DC power modes independently\n" +
" PowerMode /oem list List the detected OEM power modes\n" +
" PowerMode /oem <mode> Set the OEM power mode directly\n" +
"\n" +
" Modes: BestPowerEfficiency, Balanced, BestPerformance, or a GUID\n" +
" On OEM machines, setting the slider also drives the matching OEM mode; --no-oem opts out."
);
}
private static void ReadConfig()
{
if (ConfigurationManager.AppSettings["BestPowerEfficiencyGuid"] != null)
{
PowerOverlay.BestPowerEfficiency = new Guid(ConfigurationManager.AppSettings["BestPowerEfficiencyGuid"]);
}
if (ConfigurationManager.AppSettings["BalancedGuid"] != null)
{
PowerOverlay.Balanced = new Guid(ConfigurationManager.AppSettings["BalancedGuid"]);
}
if (ConfigurationManager.AppSettings["BestPerformanceGuid"] != null)
{
PowerOverlay.BestPerformance = new Guid(ConfigurationManager.AppSettings["BestPerformanceGuid"]);
}
if (ConfigurationManager.AppSettings["OemVendor"] != null)
{
OemDetection.VendorPin = ConfigurationManager.AppSettings["OemVendor"];
}
if (ConfigurationManager.AppSettings["OemControlModel"] != null)
{
OemDetection.ControlModelPin = ConfigurationManager.AppSettings["OemControlModel"];
}
}
}
}