Skip to content

Commit

Permalink
Add temperature unit conversion for GPU temperature display
Browse files Browse the repository at this point in the history
  • Loading branch information
shm11C3 committed Jan 6, 2025
1 parent 945edc6 commit 5a26ed2
Show file tree
Hide file tree
Showing 6 changed files with 129 additions and 15 deletions.
31 changes: 29 additions & 2 deletions src-tauri/src/commands/hardware.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
use crate::commands::config;
use crate::enums;
use crate::enums::error::BackendError;
use crate::services::directx_gpu_service;
use crate::services::nvidia_gpu_service;
use crate::services::system_info_service;
use crate::services::wmi_service;
use crate::structs::hardware::NetworkInfo;
use crate::structs::hardware::{GraphicInfo, MemoryInfo, StorageInfo};
use crate::utils;
use crate::{log_error, log_internal};
use serde::{Deserialize, Serialize, Serializer};
use specta::Type;
Expand Down Expand Up @@ -233,9 +236,33 @@ pub async fn get_gpu_usage() -> Result<i32, String> {
///
#[command]
#[specta::specta]
pub async fn get_gpu_temperature() -> Result<Vec<nvidia_gpu_service::NameValue>, String> {
pub async fn get_gpu_temperature(
state: tauri::State<'_, config::AppState>,
) -> Result<Vec<nvidia_gpu_service::NameValue>, String> {
let temperature_unit = {
let config = state.settings.lock().unwrap();
config.temperature_unit.clone()
};

match nvidia_gpu_service::get_nvidia_gpu_temperature().await {
Ok(temps) => Ok(temps),
Ok(temps) => {
let temps = temps
.iter()
.map(|temp| {
let value = utils::formatter::format_temperature(
enums::config::TemperatureUnit::Celsius,
temperature_unit.clone(),
temp.value,
);

nvidia_gpu_service::NameValue {
name: temp.name.clone(),
value,
}
})
.collect();
Ok(temps)
}
Err(e) => Err(format!("Failed to get GPU temperature: {:?}", e)),
}
}
Expand Down
8 changes: 4 additions & 4 deletions src-tauri/src/services/nvidia_gpu_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,8 @@ pub async fn get_nvidia_gpu_usage() -> Result<f32, nvapi::Status> {
#[derive(Debug, Clone, serde::Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct NameValue {
name: String,
value: f64, // 摂氏温度
pub name: String,
pub value: i32, // 摂氏温度
}

///
Expand Down Expand Up @@ -114,7 +114,7 @@ pub async fn get_nvidia_gpu_temperature() -> Result<Vec<NameValue>, nvapi::Statu

temperatures.push(NameValue {
name: gpu.full_name().unwrap_or("Unknown".to_string()),
value: thermal_settings[0].current_temperature.0 as f64, // thermal_settings の0番目の温度を f64 に変換
value: thermal_settings[0].current_temperature.0,
});
}

Expand Down Expand Up @@ -167,7 +167,7 @@ pub async fn get_nvidia_gpu_cooler_stat() -> Result<Vec<NameValue>, nvapi::Statu

cooler_infos.push(NameValue {
name: gpu.full_name().unwrap_or("Unknown".to_string()),
value: cooler_settings[0].current_level.0 as f64,
value: cooler_settings[0].current_level.0 as i32,
});
}

Expand Down
56 changes: 56 additions & 0 deletions src-tauri/src/tests/utils/formatter.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#[cfg(test)]
mod tests {
use crate::enums;
use crate::utils::formatter::*;
use nvapi::Kibibytes;

Expand Down Expand Up @@ -85,4 +86,59 @@ mod tests {
};
assert_eq!(kibibytes.to_string(), "2.00 GB");
}

#[test]
fn test_celsius_to_fahrenheit() {
let value = 100; // 100°C
let result = format_temperature(
enums::config::TemperatureUnit::Celsius,
enums::config::TemperatureUnit::Fahrenheit,
value,
);
assert_eq!(result, 212); // 100°C = 212°F
}

#[test]
fn test_fahrenheit_to_celsius() {
let value = 212; // 212°F
let result = format_temperature(
enums::config::TemperatureUnit::Fahrenheit,
enums::config::TemperatureUnit::Celsius,
value,
);
assert_eq!(result, 100); // 212°F = 100°C
}

#[test]
fn test_celsius_to_fahrenheit_negative() {
let value = -40; // -40°C
let result = format_temperature(
enums::config::TemperatureUnit::Celsius,
enums::config::TemperatureUnit::Fahrenheit,
value,
);
assert_eq!(result, -40); // -40°C = -40°F (特殊なケース)
}

#[test]
fn test_fahrenheit_to_celsius_negative() {
let value = -40; // -40°F
let result = format_temperature(
enums::config::TemperatureUnit::Fahrenheit,
enums::config::TemperatureUnit::Celsius,
value,
);
assert_eq!(result, -40); // -40°F = -40°C (特殊なケース)
}

#[test]
fn test_no_conversion() {
let value = 25; // 25°C
let result = format_temperature(
enums::config::TemperatureUnit::Celsius,
enums::config::TemperatureUnit::Celsius,
value,
);
assert_eq!(result, 25); // 単位が同じ場合、変換しない
}
}
19 changes: 19 additions & 0 deletions src-tauri/src/utils/formatter.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::enums;
use nvapi::Kibibytes;
use rust_decimal::prelude::{FromPrimitive, ToPrimitive};
use rust_decimal::Decimal;
Expand Down Expand Up @@ -157,3 +158,21 @@ pub fn format_vendor_name(vendor_id: &str) -> String {
_ => vendor_id.to_string(),
}
}

pub fn format_temperature(
current_unit: enums::config::TemperatureUnit,
unit: enums::config::TemperatureUnit,
value: i32,
) -> i32 {
match (current_unit, unit) {
(
enums::config::TemperatureUnit::Celsius,
enums::config::TemperatureUnit::Fahrenheit,
) => (value * 9 / 5) + 32,
(
enums::config::TemperatureUnit::Fahrenheit,
enums::config::TemperatureUnit::Celsius,
) => (value - 32) * 5 / 9,
_ => value,
}
}
25 changes: 17 additions & 8 deletions src/components/charts/DoughnutChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { type ChartConfig, ChartContainer } from "@/components/ui/chart";
import { Skeleton } from "@/components/ui/skeleton";
import { minOpacity } from "@/consts";
import type { HardwareDataType } from "@/types/hardwareDataType";
import type { Settings } from "@/types/settingsType";
import { Lightning, Speedometer, Thermometer } from "@phosphor-icons/react";
import type { JSX } from "react";
import { useTranslation } from "react-i18next";
Expand All @@ -14,6 +15,16 @@ import {
RadialBarChart,
} from "recharts";

const dataType2Units = (dataType: HardwareDataType, settings: Settings) => {
const units = {
usage: "%",
temp: settings.temperatureUnit === "C" ? "°C" : "°F",
clock: "MHz",
} as const;

return units[dataType];
};

export const DoughnutChart = ({
chartValue,
dataType,
Expand Down Expand Up @@ -52,12 +63,6 @@ export const DoughnutChart = ({
clock: <Speedometer className="mr-1" size={12} weight="duotone" />,
};

const dataTypeUnits: Record<HardwareDataType, string> = {
usage: "%",
temp: "°C",
clock: "MHz",
};

return (
<ChartContainer
config={chartConfig}
Expand All @@ -67,7 +72,11 @@ export const DoughnutChart = ({
<RadialBarChart
data={chartData}
startAngle={0}
endAngle={chartValue * 3.6}
endAngle={
dataType === "temp" && settings.temperatureUnit === "F"
? ((chartValue - 32) / 1.8) * 3.6 // 華氏から摂氏に換算し、100を最大値としてスケール
: chartValue * 3.6
}
innerRadius={50}
outerRadius={70}
>
Expand Down Expand Up @@ -102,7 +111,7 @@ export const DoughnutChart = ({
dominantBaseline="middle"
className="fill-foreground text-2xl font-bold"
>
{`${chartValue}${dataTypeUnits[dataType]}`}
{`${chartValue}${dataType2Units(dataType, settings)}`}
</text>
{/* ラベルとアイコンの表示 */}
<foreignObject
Expand Down
5 changes: 4 additions & 1 deletion src/template/Settings.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { gpuTempAtom } from "@/atom/chart";
import { useSettingsAtom } from "@/atom/useSettingsAtom";
import { PreviewChart } from "@/components/charts/Preview";
import { BackgroundImageList } from "@/components/forms/SelectBackgroundImage/SelectBackgroundImage";
Expand All @@ -21,6 +22,7 @@ import {
} from "@/types/hardwareDataType";
import type { Settings as SettingTypes } from "@/types/settingsType";
import { DotOutline } from "@phosphor-icons/react";
import { useAtom, useSetAtom } from "jotai";

Check failure on line 25 in src/template/Settings.tsx

View workflow job for this annotation

GitHub Actions / test-tauri (windows-latest)

'useAtom' is declared but its value is never read.
import { useTranslation } from "react-i18next";

const SettingGraphType = () => {
Expand Down Expand Up @@ -290,12 +292,13 @@ const SettingColorReset = () => {
const SettingTemperatureUnit = () => {
const { settings, updateSettingAtom } = useSettingsAtom();
const { t } = useTranslation();
const setData = useSetAtom(gpuTempAtom);

const changeTemperatureUnit = async (
value: SettingTypes["temperatureUnit"],
) => {
console.log(value);
await updateSettingAtom("temperatureUnit", value);
setData([]);
};

return (
Expand Down

0 comments on commit 5a26ed2

Please sign in to comment.