Files
up_go/api/HandleTemperature.go
T
2026-03-19 14:07:10 +07:00

108 lines
2.8 KiB
Go
Raw 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"
"io/ioutil"
"net/http"
"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 := ioutil.ReadFile(tempPath)
if err != nil {
continue
}
// Читаем тип зоны, если доступен
typePath := fmt.Sprintf("/sys/class/thermal/thermal_zone%d/type", i)
typeData, _ := ioutil.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
// Проверяем, является ли зона CPU/SOC
isCPU := strings.Contains(strings.ToLower(zoneType), "cpu") ||
strings.Contains(strings.ToLower(zoneType), "soc")
temperature = temp
success = true
if isCPU {
break // предпочитаем CPU
}
// иначе продолжаем искать CPU
}
// Если thermal не дал результата, пробуем hwmon 0–3
for i := 0; i < 4 && !success; i++ {
tempPath := fmt.Sprintf("/sys/class/hwmon/hwmon%d/temp1_input", i)
data, err := ioutil.ReadFile(tempPath)
if err != nil {
continue
}
// Читаем имя сенсора
namePath := fmt.Sprintf("/sys/class/hwmon/hwmon%d/name", i)
nameData, _ := ioutil.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
}
}
// Финальный fallback – просто temp1_input для первых 4 hwmon
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 := ioutil.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
}
}
// Формируем JSON-ответ
response := map[string]interface{}{
"success": success,
"temperature": temperature,
"unit": "Celsius",
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}