From e77f611d8117de28ea1c61bc2978d6bc5f58644a Mon Sep 17 00:00:00 2001 From: lulzette Date: Thu, 1 Jun 2023 15:53:53 +0300 Subject: [PATCH] Init --- .gitignore | 2 ++ go.mod | 3 ++ lin_temp_mon.go | 79 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 84 insertions(+) create mode 100644 .gitignore create mode 100644 go.mod create mode 100644 lin_temp_mon.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7e3f571 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.idea/ +lin_temp_mon.csv \ No newline at end of file diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..b4ee49f --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module temp_monitor + +go 1.20 diff --git a/lin_temp_mon.go b/lin_temp_mon.go new file mode 100644 index 0000000..31505fd --- /dev/null +++ b/lin_temp_mon.go @@ -0,0 +1,79 @@ +package main + +import ( + "encoding/csv" + "fmt" + "log" + "os" + "runtime" + "strconv" + "strings" + "time" +) + +func readTemp() string { + temperatureFilePath := "/sys/class/hwmon/hwmon6/temp1_input" + f, err := os.ReadFile(temperatureFilePath) + + if err != nil { + log.Fatal(err) + } + //defer f.Close() + tempFloat, err := strconv.ParseFloat(strings.Fields(string(f))[0], 32) + if err != nil { + log.Fatal(err) + } + + tempFloat = tempFloat / 1000 + + return string(fmt.Sprintf("%f", tempFloat)) +} + +func writeCsv(temp string, load string) { + // Input: temp, load + // Result: write data to CSV file + t := time.Now() + timestamp := t.Unix() + targetFile := "lin_temp_mon.csv" + fmt.Println(temp, load, timestamp) + + targetArr := []string{strconv.FormatInt(timestamp, 10), load, temp} + + f, err := os.OpenFile(targetFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) + if err != nil { + log.Fatal("Error: ", err) + return + } + w := csv.NewWriter(f) + err = w.Write(targetArr) + if err != nil { + log.Fatal("Error: ", err) + return + } + w.Flush() + f.Close() +} + +func getPerCPU() string { + loadavgFile := "/proc/loadavg" + nproc := float64(runtime.NumCPU()) + + loadAvgRaw, err := os.ReadFile(loadavgFile) + + if err != nil { + log.Fatal(err) + } + //defer loadAvgRaw.Close() + + loadAvgCur, err := strconv.ParseFloat(strings.Fields(string(loadAvgRaw))[0], 32) + + loadPerCpu := loadAvgCur / nproc + + return string(fmt.Sprintf("%f", loadPerCpu)) + +} + +func main() { + // Timestamp, LA, Temp + writeCsv(readTemp(), getPerCPU()) +}