I tried to Access CPU and GPU Temp With Code Below But its not working. Here is Code:
using OpenHardwareMonitor.Hardware;
namespace Monitor
{
class Program
{
// CPU Temp
static float cpuTemp;
// CPU Usage
static float cpuUsage;
// CPU Power Draw (Package)
static float cpuPowerDrawPackage;
// CPU Frequency
static float cpuFrequency;
// GPU Temperature
static float gpuTemp;
// GPU Usage
static float gpuUsage;
// GPU Core Frequency
static float gpuCoreFrequency;
// GPU Memory Frequency
static float gpuMemoryFrequency;
static Computer pc = new Computer()
{
GPUEnabled = true,
CPUEnabled = true,
//RAMEnabled = true,
//MainboardEnabled = true,
//FanControllerEnabled = true,
//HDDEnabled = true,
};
static void ReportSystemInfo()
{
pc.Open();
foreach (var hardware in pc.Hardware)
{
if (hardware.HardwareType == HardwareType.CPU)
{
// only fire the update when found
hardware.Update();
// loop through the data
foreach (var sensor in hardware.Sensors)
if (sensor.SensorType == SensorType.Temperature && sensor.Name.Contains("CPU Package"))
{
// store
cpuTemp = sensor.Value.GetValueOrDefault();
// print to console
System.Diagnostics.Debug.WriteLine("cpuTemp: " + sensor.Value.GetValueOrDefault());
}
else if (sensor.SensorType == SensorType.Load && sensor.Name.Contains("CPU Total"))
{
// store
cpuUsage = sensor.Value.GetValueOrDefault();
// print to console
System.Diagnostics.Debug.WriteLine("cpuUsage: " + sensor.Value.GetValueOrDefault());
}
else if (sensor.SensorType == SensorType.Power && sensor.Name.Contains("CPU Package"))
{
// store
cpuPowerDrawPackage = sensor.Value.GetValueOrDefault();
// print to console
System.Diagnostics.Debug.WriteLine("CPU Power Draw - Package: " + sensor.Value.GetValueOrDefault());
}
else if (sensor.SensorType == SensorType.Clock && sensor.Name.Contains("CPU Core #1"))
{
// store
cpuFrequency = sensor.Value.GetValueOrDefault();
// print to console
System.Diagnostics.Debug.WriteLine("cpuFrequency: " + sensor.Value.GetValueOrDefault());
}
}
// Targets AMD & Nvidia GPUS
if (hardware.HardwareType == HardwareType.GpuAti || hardware.HardwareType == HardwareType.GpuNvidia)
{
// only fire the update when found
hardware.Update();
// loop through the data
foreach (var sensor in hardware.Sensors)
if (sensor.SensorType == SensorType.Temperature && sensor.Name.Contains("GPU Core"))
{
// store
gpuTemp = sensor.Value.GetValueOrDefault();
// print to console
System.Diagnostics.Debug.WriteLine("gpuTemp: " + sensor.Value.GetValueOrDefault());
}
else if (sensor.SensorType == SensorType.Load && sensor.Name.Contains("GPU Core"))
{
// store
gpuUsage = sensor.Value.GetValueOrDefault();
// print to console
System.Diagnostics.Debug.WriteLine("gpuUsage: " + sensor.Value.GetValueOrDefault());
}
else if (sensor.SensorType == SensorType.Clock && sensor.Name.Contains("GPU Core"))
{
// store
gpuCoreFrequency = sensor.Value.GetValueOrDefault();
// print to console
System.Diagnostics.Debug.WriteLine("gpuCoreFrequency: " + sensor.Value.GetValueOrDefault());
}
else if (sensor.SensorType == SensorType.Clock && sensor.Name.Contains("GPU Memory"))
{
// store
gpuMemoryFrequency = sensor.Value.GetValueOrDefault();
// print to console
System.Diagnostics.Debug.WriteLine("gpuMemoryFrequency: " + sensor.Value.GetValueOrDefault());
}
}
// ... you can access any other system information you want here
}
pc.Close();
}
static void Main(string[] args)
{
while (true)
{
ReportSystemInfo();
}
}
}
}
Exception Message :
Unhandled exception. System.MissingMethodException: Method not found:
'System.Threading.Mutex
System.Threading.Mutex.OpenExisting(System.String,
System.Security.AccessControl.MutexRights)'. at
OpenHardwareMonitor.Hardware.Ring0.Open() at
OpenHardwareMonitor.Hardware.Computer.Open() at
Monitor.Program.ReportSystemInfo() in
D:\VisualStudio\Monitor_Test\Monitor_Test\Program.cs:line 37 at
Monitor.Program.Main(String[] args) in
D:\VisualStudio\Monitor_Test\Monitor_Test\Program.cs:line 132
is there any fix for this ???
Related
In my game there is a text that outputs code based on if certain Upgrades are bought I started out coding it like this
if (UpgradeManager.Instance.HasUpgrade("basicFunction") && !UpgradeManager.Instance.HasUpgrade("basicCounter"))
{
codeString = "protected void GainUnits(){ units += " + gains + ";}";
}
else if (UpgradeManager.Instance.HasUpgrade("basicCounter") && UpgradeManager.Instance.HasUpgrade("basicFunction"))
{
codeString = "private timer = 20; private void Update(){ if(timer > 0){GainUnits();}" + "protected void GainUnits(){ units += " + gains + ";}";
}
else if (UpgradeManager.Instance.HasUpgrade("basicCounter") && !UpgradeManager.Instance.HasUpgrade("basicFunction"))
{
codeString = "private timer = 20; private void Update(){ if(timer > 0){GainUnits();}" + "units += " + gains;
}
else
{
codeString = "units += " + gains;
}
as i add more and more upgrades i realize that i have to add more and more rules on top of whats already there creating an exponential amount of work as more is added to the game
So my question is how can i optimize this to lighten the workload?
You can try that approach that can be more maintainable:
// arrange a list of bool predicates and corresponding handlers
var policies = new KeyValuePair<Func<bool>, Action>[]
{
new KeyValuePair<Func<bool>, Action>(
() => {return UpgradeManager.Instance.HasUpgrade("basicFunction") && !UpgradeManager.Instance.HasUpgrade("basicCounter");},
() => {codeString = "protected void GainUnits(){ units += " + gains + ";}";}),
new KeyValuePair<Func<bool>, Action>(
() => {return UpgradeManager.Instance.HasUpgrade("basicCounter") && UpgradeManager.Instance.HasUpgrade("basicFunction");},
() => {codeString = "private timer = 20; private void Update(){ if(timer > 0){GainUnits();}" + "protected void GainUnits(){ units += " + gains + ";}";}),
new KeyValuePair<Func<bool>, Action>(
() => {return UpgradeManager.Instance.HasUpgrade("basicCounter") && !UpgradeManager.Instance.HasUpgrade("basicFunction");},
() => {codeString = "private timer = 20; private void Update(){ if(timer > 0){GainUnits();}" + "units += " + gains;}),
new KeyValuePair<Func<bool>, Action>(
() => {return true;}, // last one should be always true
() => {codeString = "units += " + gains;}),
};
// now let iterate over the policies
foreach(var policy in policies)
{
if (policy.Key()) // evaluate predicates one-by-one
{
policy.Value();
break; // if predicated matched, do the action and break out of the loop
}
}
Depending on the logic necessary, you can employ different containers (that can give you better performance or flexibility, etc.)
else if (UpgradeManager.Instance.HasUpgrade("basicCounter") && !UpgradeManager.Instance.HasUpgrade("basicFunction"))
{
codeString = "private timer = 20; private void Update(){ if(timer > 0){GainUnits();}" + "units += " + gains;
}
Doesn't look like valid code there. I assume you want to increment it directly in the if-block, like this?
"if(timer > 0){ units += " + gains + "; }"
You can start by isolating what part of code that each flag modifies:
basicCounter: adds timer and implements Update() that increments units
basicFunction: encapsulates how units is incremented
With that in mind, it is easier to deconstruct the code:
increasing units:
GainUnits(); // if basicFunction
units += __GAINS__; // if !basicFunction
counter:
private timer = 20;
private void Update() {
if(timer > 0) {
/* use the code from <increasing units> */
}
}
core implementation:
/* use code from <counter> */ // if basicCounter
/* use code from <increasing units> */ // if !basicCounter
And, putting it back together:
string GenerateCode()
{
return string.Join("\n", GetImplementationCode());
}
IEnumerable<string> GetImplementationCode()
{
return UpgradeManager.Instance.HasUpgrade("basicCounter")
? GetCounterCode()
: GetIncreaseUnitsCode();
}
IEnumerable<string> GetCounterCode()
{
yield return "private timer = 20;";
yield return "private void Update() {";
yield return "if(timer > 0) {";
foreach (var loc in GetIncreaseUnitsCode())
{
yield return loc;
}
yield return "}";
yield return "}";
}
IEnumerable<string> GetIncreaseUnitsCode()
{
if (UpgradeManager.Instance.HasUpgrade("basicFunction"))
{
yield return "GainUnits();";
}
else
{
var gains = /* insert logics here */;
yield return $"units += {gains};";
}
}
I've struggled through a uni assignment to create a dice game. I've finished it but of course forgot to add the option to replay the game if necessary and am so lost in code that I don't even know where to being to get the game to play again. I would really appreciate some help to be able to get users to play another game if they want to or escape the console app.
using System;
public class Player {
private int score;
private string name;
private bool isAI = false;
public void reset() {
this.score = 0;
}
public void addScore(int scoreToAdd) {
this.score = this.score + scoreToAdd;
}
public int getScore() {
return this.score;
}
public string getName() {
return this.name;
}
public void setName(string name) {
this.name = name;
}
/// Prompt the player to 'roll the dice'
public void prompt() {
if (isAI) { return; }
Console.WriteLine(getName() + ", please roll the dice (press enter):");
Console.ReadLine();
}
public void promptForName() {
Console.WriteLine("Please enter your name (Enter 'cpu' to play against the computer)");
string name = Console.ReadLine();
setName(name);
// special handling for computer players.
if (name == "cpu") { isAI = true; }
else { isAI = false; }
}
public void printScore() {
Console.WriteLine(name + " score: " + this.score);
}
public int playRound(Random rnd, Die d1, Die d2, Die d3) {
// Prompt the player so the dice don't roll immediately
this.prompt();
// Roll all the dice (pass the same rng for each one)
d1.roll(rnd);
d2.roll(rnd);
d3.roll(rnd);
// Work out which dice is highest, roll the smaller 2 again
if (d1.getValue() > d2.getValue() && d1.getValue() > d3.getValue()) {
d2.roll(rnd);
d3.roll(rnd);
// Work out which is the highest of the two re-rolled, then roll the
// smallest a third time
if (d2.getValue() > d3.getValue()) {
d3.roll(rnd);
}
else {
d2.roll(rnd);
}
}
else if (d2.getValue() > d1.getValue() && d2.getValue() > d3.getValue()) {
d1.roll(rnd);
d3.roll(rnd);
// Work out which is the highest of the two re-rolled, then roll the
// smallest a third time
if (d1.getValue() > d3.getValue()) {
d3.roll(rnd);
}
else {
d1.roll(rnd);
}
}
else {
d1.roll(rnd);
d2.roll(rnd);
// Work out which is the highest of the two re-rolled, then roll the
// smallest a third time
if (d1.getValue() > d2.getValue()) {
d2.roll(rnd);
}
else {
d1.roll(rnd);
}
}
// All dice are rolled, just calculate total
int total = d1.getValue() + d2.getValue() + d3.getValue();
return total;
}
}
public class Die
{
private int value;
public int getValue()
{
return this.value;
}
public void setValue(int value)
{
this.value = value;
}
public void roll(Random rnd)
{
this.value = rnd.Next(1, 7);
}
}
public class Game
{
public static string promptForPlayType()
{
Console.WriteLine("Please enter play type ('match' or 'score')");
string playType = null;
// Make sure the user enters a valid value
while (playType != "match" && playType != "score")
{
playType = Console.ReadLine();
if (playType != "match" && playType != "score")
{
Console.WriteLine("Please enter one of the two options");
}
}
return playType;
}
// Entry point
public static void Main()
{
// Prompt the user for the game play type they'd want (match or score)
string playType = promptForPlayType();
// Create rng, need this because otherwise the seed gets re-initialised to
// the same value each time
Random rnd = new Random();
// Create the players & prompt for their names
Player p1 = new Player();
Player p2 = new Player();
p1.promptForName();
p2.promptForName();
// Create the 3 dice we'll be using
Die d1 = new Die();
Die d2 = new Die();
Die d3 = new Die();
// The big 'game loop' where everything happens
for (int i = 0; i < 5; i = i + 1)
{
// Basically everything happens in these method calls
var p1Result = p1.playRound(rnd, d1, d2, d3);
var p2Result = p2.playRound(rnd, d1, d2, d3);
// Increment score based on result
if (playType == "match")
{
if (p1Result > p2Result)
{
Console.WriteLine(p1.getName() + " won a round");
p1.addScore(1);
}
else if (p2Result > p1Result)
{
Console.WriteLine(p2.getName() + " won a round");
p2.addScore(1);
}
else
{
Console.WriteLine("Game drawn");
}
}
else if (playType == "score")
{
p1.addScore(p1Result);
p2.addScore(p2Result);
}
// Print out running totals
Console.WriteLine("Player scores:");
Console.WriteLine(p1.getName() + ": " + p1.getScore());
Console.WriteLine(p2.getName() + ": " + p2.getScore());
}
Console.WriteLine("\n");
if (p1.getScore() > p2.getScore())
{
Console.WriteLine("Player 1 won");
}
else if (p2.getScore() > p1.getScore())
{
Console.WriteLine("Player 2 won");
}
else
{
Console.WriteLine("The game was a draw");
}
}
}
Enclose it in while loop until users exit from it.
public static void Main()
{
bool flag = true;
while(flag){
//your game here
Console.WriteLine("Play again? ('y' or 'n')");
string playAgain = null;
playAgain = Console.ReadLine();
if(playAgain == "n")
flag = false;
}
}
I have a library that returns CS:GO stats in real-time from the game. I'm making a program that stores the stats and analyse it.
I have this function:
private void UpdateKills(GameState gs)
{
int currentKills = -1;
if (lastKills == -1) // first time getting player info
{
int temp = gs.Player.MatchStats.Kills;
currentKills = temp;
lastKills = temp;
}
else
{
currentKills = gs.Player.MatchStats.Kills;
int dif = currentKills - lastKills;
if (currentKills == 0 && lastKills != 0) // maybe changed server/map/whatever
{
lastKills = -1;
}
else
{
if (dif != 0 && dif > 0) // player killed someone AND it was not teamkill
{
ps.Kills += dif; // add the kills to the main variable
lastKills = currentKills;
dif = 0;
playSimpleSound();
}
}
}
}
This is my function that handles the kills. The most of the time it works very well, but sometimes it just freaks out, and I don't know if the problem is my logic or if it is a library problem.
Note: I'm using this library: github.com/rakijah/CSGSI
My logic is:
Get the player kills
Increment those kills in the PlayerStats object.
Is my code logically correct? Can my code be more "correct"?
I'm still not entirely sure what this function is supposed to be doing, but I simplified it for you:
private void UpdateKills(GameState gs)
{
lastKills = currentKills;
int currentKills = gs.Player.MatchStats.Kills;
int diff = currentKills - lastKills;
if (currentKills == 0 && lastKills != 0) // maybe changed server/map/whatever
{
lastKills = -1;
}
else if (diff > 0) // player killed someone AND it was not teamkill
{
ps.Kills += diff; // add the kills to the main variable
playSimpleSound();
}
}
Well, after some research in finally undertand your problem. You DON'T have to do anything!, the API does all the work for you, watch the next image:
As you can see, the console app shows my steam name, the map and kills. I start with zero kills, then I kill a teammate and after that an enemy. The API created by #rakijah autoupdates those values.
Now the code:
static void Main(string[] args)
{
CsGoIntegration();
}
private static void CsGoIntegration()
{
var gsl = new GameStateListener(3000);
gsl.NewGameState += new NewGameStateHandler(OnNewGameState);
if (!gsl.Start())
{
Environment.Exit(0);
}
System.Console.WriteLine("Listening...");
}
private static void OnNewGameState(GameState gs)
{
System.Console.WriteLine("Map: {0}", gs.Map.Name);
System.Console.WriteLine("Player Name: {0}", gs.Player.Name);
System.Console.WriteLine("Player Kills: {0}", gs.Player.MatchStats.Kills);
}
UPDATE: The OP needs to store the total kills even when the map changes. I experimented with paper and pencil, please try running the program and tell me if it worked or not
private static void Main()
{
CsGoIntegration();
}
private static void CsGoIntegration()
{
var gsl = new GameStateListener(3000);
gsl.NewGameState += OnNewGameState;
if (!gsl.Start())
{
Environment.Exit(0);
}
Console.WriteLine("Listening...");
}
private static void OnNewGameState(GameState gameState)
{
SaveMatchsData(gameState);
}
private static int? _totalKillScore;
private static string _lastMapName;
private static int? _lastKillScore;
private static void SaveMatchsData(GameState gameState)
{
const string undefinedString = "Undefined";
// If the SaveMatchsData is running and the CSGO server is offline
if (gameState.Map.Name == undefinedString && string.IsNullOrEmpty(_lastMapName))
return;
// When the match is not started, the Round is -1
if (gameState.Map.Name != undefinedString && gameState.Map.Round > -1)
{
if (string.IsNullOrEmpty(_lastMapName))
{
UpdateData(gameState, true);
}
else
{
// Same map
if (_lastMapName == gameState.Map.Name)
{
// Check if the Score Changes
if (_lastKillScore == gameState.Player.MatchStats.Kills) return;
UpdateData(gameState);
}
// The Map Changes
else
{
UpdateData(gameState, true);
}
}
}
}
private static void UpdateData(GameState gameState, bool updateMap = false)
{
if (updateMap)
_lastMapName = gameState.Map.Name;
_lastKillScore = gameState.Player.MatchStats.Kills;
_totalKillScore += gameState.Player.MatchStats.Kills;
}
Cheers.
I have a thread that is supposed to run continuously in my program and parse incoming serial data from a collection of sensors.
//initialized as a global variable
System.Threading.Thread processThread = new System.Threading.Thread(ProcessSerialData);
//this gets called when you press the start button
processThread.Start();
private void ProcessSerialData()
{
while (true)
{
//do a whole bunch of parsing stuff
}
int howDidYouGetHere = 0;
}
How is it possible that my program is reaching the "int howDidYouGetHere = 0" line??
Full code can be found here:
/// <summary>
/// ProcessSerialData thread will be used to continue testing the connection to the controller,
/// process messages in the incoming message queue (actually a linked list),
/// and sends new messages for updated data.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ProcessSerialData()
{
while (true)
{
UpdateAhTextbox(test.ampHoursOut.ToString());
if (!relayBoard.OpenConn())
{
MessageBox.Show("Connection to controller has been lost.");
testInterrupted = "Lost connection. Time = " + test.duration;
UpdateStatusText(false);
ShutErDown();
}
/////////////////////////////////////////////////////
if (incomingData.Count > 0)
{
string dataLine = "";
try
{
dataLine = incomingData.First();
UpdateParsedDataTextbox(dataLine + "\r\n");
}
catch (System.InvalidOperationException emai)
{
break; //data hasn't come in yet, it will by the time this runs next.
}
incomingData.RemoveFirst();
if (dataLine.Contains("GET")) // some sensor values (analog/temp/digital) has come in
{
if (dataLine.Contains("GETANALOG")) // an analog value has come in
{
int index = dataLine.IndexOf("CH");
int pin = (int)Char.GetNumericValue(dataLine[index + 2]);
double value = 0;
int dataLineLength = dataLine.Length;
if (dataLineLength > 13) // value is appended to end of line
{
try
{
value = Convert.ToDouble(dataLine.Substring(13));
}
catch // can't convert to double
{
int index2 = dataLine.IndexOf("CH", 3);
if (index2 != -1) // there happen to be two sets of commands stuck together into one
{
string secondHalf = dataLine.Substring(index2);
incomingData.AddFirst(secondHalf);
}
}
}
else // value is on the next line
{
try
{
value = Convert.ToDouble(incomingData.First());
incomingData.RemoveFirst();
}
catch // can't convert to double
{
MessageBox.Show("Error occured: " + dataLine);
}
}
switch (pin)
{
case 1:
ReadVoltage(value);
break;
case 2:
ReadAmperage(value);
break;
}
}
else if (dataLine.Contains("GETTEMP")) // received reply with temperature data
{
int index = dataLine.IndexOf("CH");
int pin = (int)Char.GetNumericValue(dataLine[index + 2]); // using index of CH, retrieve which pin this message is coming from
double value = 0;
int dataLineLength = dataLine.Length;
if (dataLineLength > 11) // value is appended to end of line
{
try
{
value = Convert.ToDouble(dataLine.Substring(11));
}
catch // can't convert to double
{
int index2 = dataLine.IndexOf("CH", 3);
if (index2 != -1) // there happen to be two sets of commands stuck together into one
{
string secondHalf = dataLine.Substring(index2);
incomingData.AddFirst(secondHalf);
}
}
}
else // value is on the next line
{
value = Convert.ToDouble(incomingData.First());
incomingData.RemoveFirst();
}
ReadTemperature(pin, value);
}
else // must be CH3.GET
{
int index = dataLine.IndexOf("CH");
int pin = (int)Char.GetNumericValue(dataLine[index + 2]); // using index of CH, retrieve which pin this message is coming from
if (pin == 3) // only care if it's pin 3 (BMS), otherwise it's a mistake
{
double value = 0;
int dataLineLength = dataLine.Length;
if (dataLineLength > 7) // value is appended to end of line
{
try
{
value = Convert.ToDouble(dataLine.Substring(7));
}
catch // can't convert to double
{
int index2 = dataLine.IndexOf("CH", 3);
if (index2 != -1) // there happen to be two sets of commands stuck together into one
{
string secondHalf = dataLine.Substring(index2);
incomingData.AddFirst(secondHalf);
}
}
}
else // value is on the next line
{
value = Convert.ToDouble(incomingData.First());
incomingData.RemoveFirst();
}
ReadBMS(value);
}
}
}
else if (dataLine.Contains("REL")) // received reply about relay turning on or off.
{
if (dataLine.Contains("RELS")) // all relays turning on/off
{
if (dataLine.Contains("ON"))
{
for (int pin = 1; pin <= 4; pin++)
{
test.contactors[pin] = true;
}
}
else // "OFF"
{
for (int pin = 1; pin <= 4; pin++)
{
test.contactors[pin] = false;
}
}
}
else // single relay is turning on/off
{
int index = dataLine.IndexOf("REL");
int pin = (int)Char.GetNumericValue(dataLine[index + 3]);
if (dataLine.Contains("ON"))
{
test.contactors[pin] = true;
}
else if (dataLine.Contains("OFF"))
{
test.contactors[pin] = false;
}
else if (dataLine.Contains("GET"))
{
if (Convert.ToInt32(incomingData.First()) == 1)
test.contactors[pin] = true;
else
test.contactors[pin] = false;
incomingData.RemoveFirst();
}
}
}
}
/////////////////////////////////////////////////////
// we only want more data if we're done processing the current data, otherwise we're stuck with too much and processing is heavily delayed.
if (isTestRunning && incomingData.Count < 3)
{
//read & output v, a, bms state
sendToController("CH1.GETANALOG"); // get voltage
sendToController("CH2.GETANALOG"); // get amperage
sendToController("CH3.GET"); // get BMS state
//read & output temperature
sendToController("CH4.GETTEMP"); // get temperature
sendToController("CH5.GETTEMP");
string lines = "Ah Out: " + test.ampHoursOut + ", Voltage: " + test.voltage +
", Amperage: " + test.amperage + ", Cell Temperature: " + test.tempBattery +
", Load Temperature: " + test.tempLoad;
WriteToLog(lines);
}
}
int howDidYouGetHere = 0;
}
The break (ignoring those inside the nested switch) breaks out of the while loop.
Perhaps you have tried to update your UI using UpdateParsedDataTextbox This will cause InvalidOperationException(then breaks the while loop) because you tries to access the UI control from thread that doesn't own the control.
This is the code:
public float? cpuView(bool pause , CpuTemperature cpuTemp , Form1 f1 , List<string> myData , float? myCpuTemp , Button b1, decimal numeric)
{
try
{
if (pause == true)
{
}
else
{
Trace.WriteLine("");
foreach (var hardwareItem in myComputer.Hardware)
{
if (hardwareItem.HardwareType == HardwareType.CPU)
{
hardwareItem.Update();
foreach (IHardware subHardware in hardwareItem.SubHardware)
subHardware.Update();
foreach (var sensor in hardwareItem.Sensors)
{
cpuTemp.SetValue("sensor", sensor.Value.ToString());
if (sensor.SensorType == SensorType.Fan)
{
MessageBox.Show("test");
sensor.Hardware.Update();
cpuTemp.GetValue("sensor", sensor.Value.ToString());
if (!f1.IsDisposed)//f1.IsHandleCreated && !f1.IsDisposed)
{
Thread.Sleep(1000);
f1.Invoke(new Action(() => myData.Add("Cpu Temeprature --- " + sensor.Value.ToString())));
}
myCpuTemp = sensor.Value;
//if (sensor.Value > 60)
//{
CpulabelTemp = sensor.Value;
cpuSensorValues.Add(sensor.Value);
if (cpuSensorValues.Count == 300 && sensor.Value >= (float)numeric)
{
float a = ComputeStats(cpuSensorValues).Item1;
float b = ComputeStats(cpuSensorValues).Item2;
float c = ComputeStats(cpuSensorValues).Item3;
Logger.Write("********************************");
Logger.Write("CPU Minimum Temperature Is ===> " + a);
Logger.Write("CPU Maximum Temperature Is ===> " + b);
Logger.Write("CPU Average Temperature Is ===> " + c);
Logger.Write("********************************" + Environment.NewLine);
cpuSensorValues = new List<float?>();
}
b1.Enabled = true;
//}
break;
}
}
}
}
}
}
catch(Exception err)
{
Logger.Write("There was an exception: " + err.ToString());
}
return myCpuTemp;
}
In this line:
if (sensor.SensorType == SensorType.Fan)
Instead Fan it was Temperature.
When it was Temperature it was working no problems.
But once i changed it to Fan to get the CPU/GPU Fan speed it dosen't get in it's jumping over this IF and keep on.
It's never get to the MessageBox.Show line.
What could be the problem ? Tried to google but nothing so far.
Your problem is the conditional
if (hardwareItem.HardwareType == HardwareType.CPU)
The fans are not on the CPU. You need to use the appropriate HardwareType that the fans show up on, probably HardwareType.Mainboard.