2024-01-20 18:35:50 +02:00
|
|
|
package hardware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2024-01-22 00:28:07 +02:00
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
2024-01-20 18:35:50 +02:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"gorm.io/gorm"
|
|
|
|
)
|
|
|
|
|
|
|
|
type HardDrive struct {
|
|
|
|
ID uint `gorm:"primarykey"`
|
|
|
|
CreatedAt time.Time
|
|
|
|
UpdatedAt time.Time
|
|
|
|
DeletedAt gorm.DeletedAt `gorm:"index"`
|
|
|
|
Name string
|
|
|
|
Transport string
|
|
|
|
Size string
|
|
|
|
Model string
|
|
|
|
Serial string
|
|
|
|
Type string
|
2024-01-22 00:28:07 +02:00
|
|
|
HWID string
|
2024-01-20 18:35:50 +02:00
|
|
|
Temperatures []HardDriveTemperature `gorm:"foreignKey:HardDriveID"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type HardDriveTemperature struct {
|
|
|
|
gorm.Model
|
|
|
|
HardDriveID uint
|
|
|
|
TimeStamp time.Time
|
|
|
|
Temperature int
|
|
|
|
}
|
|
|
|
|
|
|
|
// A snapshot in time of the current state of the harddrives
|
|
|
|
type HardwareSnapshot struct {
|
|
|
|
TimeStamp time.Time
|
|
|
|
HDD []*HardDrive
|
|
|
|
}
|
|
|
|
|
|
|
|
type Snapshots struct {
|
|
|
|
List []*HardwareSnapshot
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *HardDrive) GetTemperature() int {
|
2024-01-22 00:28:07 +02:00
|
|
|
// Try HDD/SSD path
|
|
|
|
temp, found := h.getTemperatureFromPath("/sys/block/" + h.Name + "/device/hwmon/")
|
|
|
|
if found {
|
|
|
|
return temp
|
|
|
|
}
|
|
|
|
|
|
|
|
// Try NVMe path
|
|
|
|
temp, found = h.getTemperatureFromPath("/sys/block/" + h.Name + "/device/")
|
|
|
|
if found {
|
|
|
|
return temp
|
2024-01-20 18:35:50 +02:00
|
|
|
}
|
|
|
|
|
2024-01-22 00:28:07 +02:00
|
|
|
fmt.Printf("[🛑] Failed to get temperature for %s\n", h.Name)
|
|
|
|
return -1
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *HardDrive) getTemperatureFromPath(basePath string) (int, bool) {
|
|
|
|
hwmonDirs, err := os.ReadDir(basePath)
|
2024-01-20 18:35:50 +02:00
|
|
|
if err != nil {
|
2024-01-22 00:28:07 +02:00
|
|
|
return 0, false
|
2024-01-20 18:35:50 +02:00
|
|
|
}
|
|
|
|
|
2024-01-22 00:28:07 +02:00
|
|
|
for _, dir := range hwmonDirs {
|
|
|
|
if strings.HasPrefix(dir.Name(), "hwmon") {
|
|
|
|
tempPath := filepath.Join(basePath, dir.Name(), "temp1_input")
|
|
|
|
if _, err := os.Stat(tempPath); err == nil {
|
|
|
|
tempBytes, err := os.ReadFile(tempPath)
|
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
tempStr := strings.TrimSpace(string(tempBytes))
|
|
|
|
temperature, err := strconv.Atoi(tempStr)
|
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Convert millidegree Celsius to degree Celsius
|
|
|
|
return temperature / 1000, true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-01-20 18:35:50 +02:00
|
|
|
|
2024-01-22 00:28:07 +02:00
|
|
|
return 0, false
|
2024-01-20 18:35:50 +02:00
|
|
|
}
|