-
Notifications
You must be signed in to change notification settings - Fork 11
/
ds18b20.go
53 lines (41 loc) · 1.04 KB
/
ds18b20.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
// Copyright 2016 yryz Author. All Rights Reserved.
package ds18b20
import (
"errors"
"io/ioutil"
"strconv"
"strings"
)
var ErrReadSensor = errors.New("failed to read sensor temperature")
// Sensors get all connected sensor IDs as array
func Sensors() ([]string, error) {
data, err := ioutil.ReadFile("/sys/bus/w1/devices/w1_bus_master1/w1_master_slaves")
if err != nil {
return nil, err
}
sensors := strings.Split(string(data), "\n")
if len(sensors) > 0 {
sensors = sensors[:len(sensors)-1]
}
return sensors, nil
}
// Temperature get the temperature of a given sensor
func Temperature(sensor string) (float64, error) {
data, err := ioutil.ReadFile("/sys/bus/w1/devices/" + sensor + "/w1_slave")
if err != nil {
return 0.0, ErrReadSensor
}
raw := string(data)
if !strings.Contains(raw, " YES") {
return 0.0, ErrReadSensor
}
i := strings.LastIndex(raw, "t=")
if i == -1 {
return 0.0, ErrReadSensor
}
c, err := strconv.ParseFloat(raw[i+2:len(raw)-1], 64)
if err != nil {
return 0.0, ErrReadSensor
}
return c / 1000.0, nil
}