-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTemperatureSensorHelper.cs
More file actions
137 lines (125 loc) · 6.05 KB
/
Copy pathTemperatureSensorHelper.cs
File metadata and controls
137 lines (125 loc) · 6.05 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
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Security.Cryptography;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text.Json;
using LibreHardwareMonitor.Hardware;
namespace TaskbarInfo;
public static class TemperatureSensorHelper
{
public static bool TryRun(string[] args)
{
if (!args.Contains("--temperature-helper", StringComparer.Ordinal)) return false;
string? pipe = args.FirstOrDefault(value => value.StartsWith("--pipe=", StringComparison.Ordinal))?[7..];
string? token = args.FirstOrDefault(value => value.StartsWith("--token=", StringComparison.Ordinal))?[8..];
string? parentText = args.FirstOrDefault(value => value.StartsWith("--parent-pid=", StringComparison.Ordinal))?[13..];
if (string.IsNullOrWhiteSpace(pipe) || string.IsNullOrWhiteSpace(token) || !int.TryParse(parentText, out int parentPid)) return true;
Run(pipe, token, parentPid);
return true;
}
private static void Run(string pipeName, string token, int parentPid)
{
var computer = new Computer { IsCpuEnabled = true, IsGpuEnabled = true, IsStorageEnabled = true, IsControllerEnabled = true };
computer.Open();
try
{
while (IsParentAlive(parentPid))
{
using var server = CreateServer(pipeName);
try { server.WaitForConnectionAsync().Wait(TimeSpan.FromSeconds(15)); } catch { return; }
if (!server.IsConnected) return;
using var reader = new StreamReader(server, leaveOpen: true);
using var writer = new StreamWriter(server) { AutoFlush = true };
try
{
string? requestJson = reader.ReadLine();
var request = requestJson == null ? null : JsonSerializer.Deserialize<TemperatureHelperRequest>(requestJson);
if (request == null || !TemperatureHelperProtocol.HasValidToken(token, request.Token)) return;
writer.WriteLine(JsonSerializer.Serialize(ReadSnapshot(computer)));
}
catch { return; }
}
}
finally { computer.Close(); }
}
private static TemperatureHelperResponse ReadSnapshot(Computer computer)
{
double? cpu = null, gpu = null, disk = null;
foreach (IHardware hardware in computer.Hardware) ReadHardware(hardware, ref cpu, ref gpu, ref disk);
return new TemperatureHelperResponse(cpu, gpu, disk);
}
private static void ReadHardware(IHardware hardware, ref double? cpu, ref double? gpu, ref double? disk)
{
hardware.Update();
foreach (ISensor sensor in hardware.Sensors)
{
float? value = sensor.Value;
if (sensor.SensorType != SensorType.Temperature || !value.HasValue || !float.IsFinite(value.Value) || value.Value < 0 || value.Value > 150) continue;
if (hardware.HardwareType == HardwareType.Cpu) cpu = Math.Max(cpu ?? value.Value, value.Value);
else if (hardware.HardwareType is HardwareType.GpuAmd or HardwareType.GpuIntel or HardwareType.GpuNvidia) gpu = Math.Max(gpu ?? value.Value, value.Value);
else if (hardware.HardwareType == HardwareType.Storage) disk = Math.Max(disk ?? value.Value, value.Value);
}
foreach (IHardware child in hardware.SubHardware) ReadHardware(child, ref cpu, ref gpu, ref disk);
}
private static bool IsParentAlive(int processId)
{
try { return !Process.GetProcessById(processId).HasExited; } catch { return false; }
}
private static NamedPipeServerStream CreateServer(string pipeName)
{
var security = new PipeSecurity();
SecurityIdentifier user = WindowsIdentity.GetCurrent().User
?? throw new InvalidOperationException("Current user SID is unavailable.");
security.AddAccessRule(new PipeAccessRule(user, PipeAccessRights.ReadWrite, AccessControlType.Allow));
return NamedPipeServerStreamAcl.Create(
pipeName,
PipeDirection.InOut,
1,
PipeTransmissionMode.Byte,
PipeOptions.None,
0,
0,
security);
}
}
public sealed class TemperatureSensorHelperClient : IDisposable
{
private readonly string _pipeName = $"TinyBar.Temperature.{Environment.ProcessId}.{Guid.NewGuid():N}";
private readonly string _token = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32));
private bool _started;
public TaskbarTemperatureSnapshot Read(bool enabled)
{
if (!enabled || !OperatingSystem.IsWindows()) return TaskbarTemperatureSnapshot.Empty;
if (!_started && !Start()) return TaskbarTemperatureSnapshot.Empty;
try
{
using var client = new NamedPipeClientStream(".", _pipeName, PipeDirection.InOut);
client.Connect(300);
using var writer = new StreamWriter(client, leaveOpen: true) { AutoFlush = true };
using var reader = new StreamReader(client, leaveOpen: true);
writer.WriteLine(JsonSerializer.Serialize(new TemperatureHelperRequest(_token)));
string? responseJson = reader.ReadLine();
var response = responseJson == null ? null : JsonSerializer.Deserialize<TemperatureHelperResponse>(responseJson);
return response == null ? TaskbarTemperatureSnapshot.Empty : new(response.CpuTemperatureCelsius, response.GpuTemperatureCelsius, response.DiskTemperatureCelsius);
}
catch { return TaskbarTemperatureSnapshot.Empty; }
}
private bool Start()
{
try
{
Process.Start(new ProcessStartInfo(Environment.ProcessPath!)
{
UseShellExecute = true, Verb = "runas",
Arguments = $"--temperature-helper --pipe={_pipeName} --token={_token} --parent-pid={Environment.ProcessId}",
WindowStyle = ProcessWindowStyle.Hidden
});
_started = true;
return true;
}
catch { return false; }
}
public void Dispose() { }
}