-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
59 lines (52 loc) · 1.16 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package main
import (
"flag"
"fmt"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
var (
devicesDirFlag = flag.String("devices-dir", "/sys/bus/w1/devices", "devices directory")
)
func main() {
flag.Parse()
deviceID, err := findDeviceID(*devicesDirFlag)
if err != nil {
log.Fatalf("unable to find device id: %v", err)
}
for {
temperature, err := deviceTemperature(*devicesDirFlag, deviceID)
if err != nil {
log.Fatalf("unable to get device temperature: %v", err)
}
fmt.Println("Temperature:", temperature)
time.Sleep(time.Second * 5)
}
}
func findDeviceID(devicesDir string) (string, error) {
fis, err := os.ReadDir(devicesDir)
if err != nil {
return "", err
}
for _, fi := range fis {
if strings.Contains(fi.Name(), "-") {
return fi.Name(), nil
}
}
return "", fmt.Errorf("no device id found in %q", devicesDir)
}
func deviceTemperature(devicesDir, deviceID string) (float32, error) {
temp, err := os.ReadFile(filepath.Join(devicesDir, deviceID, "temperature"))
if err != nil {
return 0, err
}
t, err := strconv.Atoi(strings.TrimSpace(string(temp)))
if err != nil {
return 0, err
}
return float32(t) / 1000, nil
}