初始化提交
This commit is contained in:
66
mengyamonitor-backend/utils.go
Normal file
66
mengyamonitor-backend/utils.go
Normal file
@@ -0,0 +1,66 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"math"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// round 将浮点数四舍五入到指定小数位
|
||||
func round(v float64, places int) float64 {
|
||||
factor := math.Pow(10, float64(places))
|
||||
return math.Round(v*factor) / factor
|
||||
}
|
||||
|
||||
// readFirstLine 读取文件的第一行
|
||||
func readFirstLine(path string) string {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
defer f.Close()
|
||||
scanner := bufio.NewScanner(f)
|
||||
if scanner.Scan() {
|
||||
return scanner.Text()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// firstMatchInFile 在文件中查找第一个匹配指定前缀的行,并返回冒号后的内容
|
||||
func firstMatchInFile(path, prefix string) string {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
defer f.Close()
|
||||
scanner := bufio.NewScanner(f)
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
if strings.HasPrefix(strings.TrimSpace(line), prefix) {
|
||||
parts := strings.SplitN(line, ":", 2)
|
||||
if len(parts) == 2 {
|
||||
return strings.TrimSpace(parts[1])
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// readTempFromFile 从文件读取温度值
|
||||
func readTempFromFile(path string) float64 {
|
||||
content := readFirstLine(path)
|
||||
if content == "" {
|
||||
return 0
|
||||
}
|
||||
val, err := strconv.ParseFloat(strings.TrimSpace(content), 64)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
// 温度通常以毫度为单位
|
||||
if val > 1000 {
|
||||
return round(val/1000, 1)
|
||||
}
|
||||
return round(val, 1)
|
||||
}
|
||||
Reference in New Issue
Block a user