100 lines
2.3 KiB
Go
100 lines
2.3 KiB
Go
package api
|
||
|
||
import (
|
||
"encoding/json"
|
||
"fmt"
|
||
"net/http"
|
||
"os"
|
||
"strings"
|
||
)
|
||
|
||
func HandleTemperature(w http.ResponseWriter, r *http.Request) {
|
||
temperature := 0.0
|
||
success := false
|
||
|
||
// Thermal zones 0–3
|
||
for i := 0; i < 4 && !success; i++ {
|
||
tempPath := fmt.Sprintf("/sys/class/thermal/thermal_zone%d/temp", i)
|
||
data, err := os.ReadFile(tempPath)
|
||
if err != nil {
|
||
continue
|
||
}
|
||
typePath := fmt.Sprintf("/sys/class/thermal/thermal_zone%d/type", i)
|
||
typeData, _ := os.ReadFile(typePath)
|
||
zoneType := strings.TrimSpace(string(typeData))
|
||
|
||
var tempRaw int
|
||
if _, err := fmt.Sscanf(string(data), "%d", &tempRaw); err != nil {
|
||
continue
|
||
}
|
||
temp := float64(tempRaw) / 1000.0
|
||
|
||
isCPU := strings.Contains(strings.ToLower(zoneType), "cpu") ||
|
||
strings.Contains(strings.ToLower(zoneType), "soc")
|
||
|
||
temperature = temp
|
||
success = true
|
||
if isCPU {
|
||
break
|
||
}
|
||
}
|
||
|
||
for i := 0; i < 4 && !success; i++ {
|
||
tempPath := fmt.Sprintf("/sys/class/hwmon/hwmon%d/temp1_input", i)
|
||
data, err := os.ReadFile(tempPath)
|
||
if err != nil {
|
||
continue
|
||
}
|
||
namePath := fmt.Sprintf("/sys/class/hwmon/hwmon%d/name", i)
|
||
nameData, _ := os.ReadFile(namePath)
|
||
sensorName := strings.TrimSpace(string(nameData))
|
||
|
||
var tempRaw int
|
||
if _, err := fmt.Sscanf(string(data), "%d", &tempRaw); err != nil {
|
||
continue
|
||
}
|
||
temp := float64(tempRaw) / 1000.0
|
||
|
||
isCPU := strings.Contains(strings.ToLower(sensorName), "cpu") ||
|
||
strings.Contains(strings.ToLower(sensorName), "sunxi") ||
|
||
strings.Contains(strings.ToLower(sensorName), "acpitz")
|
||
|
||
temperature = temp
|
||
success = true
|
||
if isCPU {
|
||
break
|
||
}
|
||
}
|
||
|
||
if !success {
|
||
fallbackPaths := []string{
|
||
"/sys/class/hwmon/hwmon0/temp1_input",
|
||
"/sys/class/hwmon/hwmon1/temp1_input",
|
||
"/sys/class/hwmon/hwmon2/temp1_input",
|
||
"/sys/class/hwmon/hwmon3/temp1_input",
|
||
}
|
||
for _, path := range fallbackPaths {
|
||
data, err := os.ReadFile(path)
|
||
if err != nil {
|
||
continue
|
||
}
|
||
var tempRaw int
|
||
if _, err := fmt.Sscanf(string(data), "%d", &tempRaw); err != nil {
|
||
continue
|
||
}
|
||
temperature = float64(tempRaw) / 1000.0
|
||
success = true
|
||
break
|
||
}
|
||
}
|
||
|
||
response := map[string]interface{}{
|
||
"success": success,
|
||
"temperature": temperature,
|
||
"unit": "Celsius",
|
||
}
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
json.NewEncoder(w).Encode(response)
|
||
}
|