Files
up_go/api/HandleTemperature.go
wt 7f0e5b7b10
Build / Build (push) Successful in 10s
up some deprecated fixes
2026-03-19 14:54:33 +07:00

100 lines
2.3 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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)
}