Skip to content

Commit

Permalink
リファクタ
Browse files Browse the repository at this point in the history
  • Loading branch information
shm11C3 committed Nov 5, 2024
1 parent c8066ae commit 560d0fc
Show file tree
Hide file tree
Showing 4 changed files with 131 additions and 184 deletions.
6 changes: 3 additions & 3 deletions src-tauri/src/commands/hardware.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ 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::GraphicInfo;
use crate::structs::hardware::{GraphicInfo, MemoryInfo};
use crate::{log_debug, log_error, log_info, log_internal, log_warn};
use serde::{Serialize, Serializer};
use std::collections::HashMap;
Expand Down Expand Up @@ -124,7 +124,7 @@ pub fn get_cpu_usage(state: tauri::State<'_, AppState>) -> i32 {
#[serde(rename_all = "camelCase")]
pub struct SysInfo {
pub cpu: Option<system_info_service::CpuInfo>,
pub memory: Option<system_info_service::MemoryInfo>,
pub memory: Option<MemoryInfo>,
pub gpus: Option<Vec<GraphicInfo>>,
}

Expand All @@ -136,7 +136,7 @@ pub async fn get_hardware_info(
state: tauri::State<'_, AppState>,
) -> Result<SysInfo, String> {
let cpu_result = system_info_service::get_cpu_info(state.system.lock().unwrap());
let memory_result = system_info_service::get_memory_info();
let memory_result = wmi_service::get_memory_info();
let nvidia_gpus_result = nvidia_gpu_service::get_nvidia_gpu_info().await;
let amd_gpus_result = directx_gpu_service::get_amd_gpu_info().await;

Expand Down
183 changes: 2 additions & 181 deletions src-tauri/src/services/system_info_service.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
use crate::utils::{self, formatter};
use crate::{log_debug, log_error, log_info, log_internal};
use crate::utils;

use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::sync::mpsc::{channel, Receiver, Sender};
use serde::Serialize;
use std::sync::MutexGuard;
use std::thread;
use sysinfo::System;
use wmi::{COMLibrary, WMIConnection};

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
Expand Down Expand Up @@ -42,177 +37,3 @@ pub fn get_cpu_info(system: MutexGuard<'_, System>) -> Result<CpuInfo, String> {

Ok(cpu_info)
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MemoryInfo {
size: String,
clock: u64,
clock_unit: String,
memory_count: usize,
total_slots: usize,
memory_type: String,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
struct Win32PhysicalMemory {
capacity: u64,
speed: u32,
memory_type: Option<u16>,
smbios_memory_type: Option<u16>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
struct Win32PhysicalMemoryArray {
memory_devices: Option<u32>,
}

///
/// ## メモリ情報を取得
///
pub fn get_memory_info() -> Result<MemoryInfo, String> {
let physical_memory: Vec<Win32PhysicalMemory> = get_memory_info_in_thread(
"SELECT Capacity, Speed, MemoryType, SMBIOSMemoryType FROM Win32_PhysicalMemory"
.to_string(),
)?;

let physical_memory_array: Vec<Win32PhysicalMemoryArray> = get_memory_info_in_thread(
"SELECT MemoryDevices FROM Win32_PhysicalMemoryArray".to_string(),
)?;

log_info!(
&format!("mem info: {:?}", physical_memory),
"get_memory_info",
None::<&str>
);

let memory_info = MemoryInfo {
size: formatter::format_size(physical_memory.iter().map(|mem| mem.capacity).sum(), 1),
clock: physical_memory[0].speed as u64,
clock_unit: "MHz".to_string(),
memory_count: physical_memory.len(),
total_slots: physical_memory_array[0].memory_devices.unwrap_or(0) as usize,
memory_type: get_memory_type_with_fallback(
physical_memory[0].memory_type,
physical_memory[0].smbios_memory_type,
),
};

Ok(memory_info)
}

///
/// ## MemoryTypeの値に対応するメモリの種類を文字列で返す
///
/// - [TODO] DDR5に対応する
///
fn get_memory_type_description(memory_type: Option<u16>) -> String {
log_info!(
&format!("mem type: {:?}", memory_type),
"get_memory_type_description",
None::<&str>
);

match memory_type {
Some(0) => "Unknown or Unsupported".to_string(),
Some(1) => "Other".to_string(),
Some(2) => "DRAM".to_string(),
Some(3) => "Synchronous DRAM".to_string(),
Some(4) => "Cache DRAM".to_string(),
Some(5) => "EDO".to_string(),
Some(6) => "EDRAM".to_string(),
Some(7) => "VRAM".to_string(),
Some(8) => "SRAM".to_string(),
Some(9) => "RAM".to_string(),
Some(10) => "ROM".to_string(),
Some(11) => "Flash".to_string(),
Some(12) => "EEPROM".to_string(),
Some(13) => "FEPROM".to_string(),
Some(14) => "EPROM".to_string(),
Some(15) => "CDRAM".to_string(),
Some(16) => "3DRAM".to_string(),
Some(17) => "SDRAM".to_string(),
Some(18) => "SGRAM".to_string(),
Some(19) => "RDRAM".to_string(),
Some(20) => "DDR".to_string(),
Some(21) => "DDR2".to_string(),
Some(22) => "DDR2 FB-DIMM".to_string(),
Some(24) => "DDR3".to_string(),
Some(25) => "FBD2".to_string(),
Some(26) => "DDR4".to_string(),
Some(mt) => format!("Other or Unknown Memory Type ({})", mt),
None => "Unknown".to_string(),
}
}

///
/// ## MemoryType もしくは SMBIOSMemoryType からメモリの種類を取得
///
fn get_memory_type_with_fallback(
memory_type: Option<u16>,
smbios_memory_type: Option<u16>,
) -> String {
match memory_type {
Some(0) => match smbios_memory_type {
Some(20) => "DDR".to_string(),
Some(21) => "DDR2".to_string(),
Some(24) => "DDR3".to_string(),
Some(26) => "DDR4".to_string(),
Some(34) => "DDR5".to_string(),
Some(mt) => format!("Other SMBIOS Memory Type ({})", mt),
None => "Unknown".to_string(),
},
Some(mt) => get_memory_type_description(Some(mt)),
None => "Unknown".to_string(),
}
}

///
/// ## メモリ情報を別スレッドで取得する(WMIを使用)
///
fn get_memory_info_in_thread<T>(query: String) -> Result<Vec<T>, String>
where
T: DeserializeOwned + std::fmt::Debug + Send + 'static,
{
let (tx, rx): (
Sender<Result<Vec<T>, String>>,
Receiver<Result<Vec<T>, String>>,
) = channel();

// 別スレッドを起動してWMIクエリを実行
thread::spawn(move || {
let result = (|| {
let com_con = COMLibrary::new()
.map_err(|e| format!("Failed to initialize COM Library: {:?}", e))?;
let wmi_con = WMIConnection::new(com_con)
.map_err(|e| format!("Failed to create WMI connection: {:?}", e))?;

// WMIクエリを実行してメモリ情報を取得
let results: Vec<T> = wmi_con
.raw_query(query.clone())
.map_err(|e| format!("Failed to execute query: {:?}", e))?;

log_info!(
&format!("mem info: {:?}", results),
"get_memory_info_in_thread",
Some(&format!("query: {}", query))
);

Ok(results)
})();

// メインスレッドに結果を送信
if let Err(err) = tx.send(result) {
log_error!(
"Failed to send data from thread",
"get_wmi_data_in_thread",
Some(err.to_string())
);
}
});

// メインスレッドで結果を受信
rx.recv().map_err(|_| "Failed to receive data from thread".to_string())?
}
115 changes: 115 additions & 0 deletions src-tauri/src/services/wmi_service.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use crate::structs::hardware::MemoryInfo;
use crate::utils::formatter;
use crate::{log_debug, log_error, log_info, log_internal};

use regex::Regex;
Expand All @@ -8,6 +10,55 @@ use std::sync::mpsc::{channel, Receiver, Sender};
use std::thread;
use wmi::{COMLibrary, WMIConnection};

#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
struct Win32PhysicalMemory {
capacity: u64,
speed: u32,
memory_type: Option<u16>,
smbios_memory_type: Option<u16>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
struct Win32PhysicalMemoryArray {
memory_devices: Option<u32>,
}

///
/// ## メモリ情報を取得
///
pub fn get_memory_info() -> Result<MemoryInfo, String> {
let physical_memory: Vec<Win32PhysicalMemory> = wmi_query_in_thread(
"SELECT Capacity, Speed, MemoryType, SMBIOSMemoryType FROM Win32_PhysicalMemory"
.to_string(),
)?;

let physical_memory_array: Vec<Win32PhysicalMemoryArray> = wmi_query_in_thread(
"SELECT MemoryDevices FROM Win32_PhysicalMemoryArray".to_string(),
)?;

log_info!(
&format!("mem info: {:?}", physical_memory),
"get_memory_info",
None::<&str>
);

let memory_info = MemoryInfo {
size: formatter::format_size(physical_memory.iter().map(|mem| mem.capacity).sum(), 1),
clock: physical_memory[0].speed as u64,
clock_unit: "MHz".to_string(),
memory_count: physical_memory.len(),
total_slots: physical_memory_array[0].memory_devices.unwrap_or(0) as usize,
memory_type: get_memory_type_with_fallback(
physical_memory[0].memory_type,
physical_memory[0].smbios_memory_type,
),
};

Ok(memory_info)
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
struct GpuEngineLoadInfo {
Expand Down Expand Up @@ -100,3 +151,67 @@ where
rx.recv()
.map_err(|_| "Failed to receive data from thread".to_string())?
}

///
/// ## MemoryTypeの値に対応するメモリの種類を文字列で返す
///
fn get_memory_type_description(memory_type: Option<u16>) -> String {
log_info!(
&format!("mem type: {:?}", memory_type),
"get_memory_type_description",
None::<&str>
);

match memory_type {
Some(0) => "Unknown or Unsupported".to_string(),
Some(1) => "Other".to_string(),
Some(2) => "DRAM".to_string(),
Some(3) => "Synchronous DRAM".to_string(),
Some(4) => "Cache DRAM".to_string(),
Some(5) => "EDO".to_string(),
Some(6) => "EDRAM".to_string(),
Some(7) => "VRAM".to_string(),
Some(8) => "SRAM".to_string(),
Some(9) => "RAM".to_string(),
Some(10) => "ROM".to_string(),
Some(11) => "Flash".to_string(),
Some(12) => "EEPROM".to_string(),
Some(13) => "FEPROM".to_string(),
Some(14) => "EPROM".to_string(),
Some(15) => "CDRAM".to_string(),
Some(16) => "3DRAM".to_string(),
Some(17) => "SDRAM".to_string(),
Some(18) => "SGRAM".to_string(),
Some(19) => "RDRAM".to_string(),
Some(20) => "DDR".to_string(),
Some(21) => "DDR2".to_string(),
Some(22) => "DDR2 FB-DIMM".to_string(),
Some(24) => "DDR3".to_string(),
Some(25) => "FBD2".to_string(),
Some(26) => "DDR4".to_string(),
Some(mt) => format!("Other or Unknown Memory Type ({})", mt),
None => "Unknown".to_string(),
}
}

///
/// ## MemoryType もしくは SMBIOSMemoryType からメモリの種類を取得
///
fn get_memory_type_with_fallback(
memory_type: Option<u16>,
smbios_memory_type: Option<u16>,
) -> String {
match memory_type {
Some(0) => match smbios_memory_type {
Some(20) => "DDR".to_string(),
Some(21) => "DDR2".to_string(),
Some(24) => "DDR3".to_string(),
Some(26) => "DDR4".to_string(),
Some(34) => "DDR5".to_string(),
Some(mt) => format!("Other SMBIOS Memory Type ({})", mt),
None => "Unknown".to_string(),
},
Some(mt) => get_memory_type_description(Some(mt)),
None => "Unknown".to_string(),
}
}
11 changes: 11 additions & 0 deletions src-tauri/src/structs/hardware.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
use serde::Serialize;

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MemoryInfo {
pub size: String,
pub clock: u64,
pub clock_unit: String,
pub memory_count: usize,
pub total_slots: usize,
pub memory_type: String,
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GraphicInfo {
Expand Down

0 comments on commit 560d0fc

Please sign in to comment.