diff --git a/parse.go b/parse.go new file mode 100644 index 0000000..c1a38a7 --- /dev/null +++ b/parse.go @@ -0,0 +1,31 @@ +package main + +import ( + "fmt" + "regexp" + "strconv" + "strings" +) + +var reg = regexp.MustCompile("t=\\d+") + +func ParseTemp() { + +} + +func parse(w1Out string) float64 { + t := reg.FindString(w1Out) + if t == "" { + return 0 + } + + temp := strings.TrimLeft(t, "t=") + + f, err := strconv.ParseFloat(temp, 64) + if err != nil { + fmt.Printf("error parsing temperature %s: %s\n", temp, err) + return 0 + } + + return f / 1000 +} diff --git a/parse_test.go b/parse_test.go new file mode 100644 index 0000000..c293da6 --- /dev/null +++ b/parse_test.go @@ -0,0 +1,24 @@ +package main + +import "testing" + +func TestParse(t *testing.T) { + t.Run("should find temperature", func(t *testing.T) { + const out = `5b 01 4b 46 7f ff 0c 10 07 : crc=07 YES +5b 01 4b 46 7f ff 0c 10 07 t=21687` + temp := parse(out) + if temp != 21.687 { + t.Errorf("temp is not 21.687, is %f", temp) + t.Fail() + } + }) + t.Run("should not find temperature", func(t *testing.T) { + const out = `5b 01 4b 46 7f ff 0c 10 07 : crc=07 YES +5b 01 4b 46 7f ff 0c 10 07` + temp := parse(out) + if temp != 0 { + t.Errorf("temp is not 0, is %f", temp) + t.Fail() + } + }) +}