Add parser

This commit is contained in:
kolaente 2021-10-02 13:30:37 +02:00
parent 6418618c5d
commit 945c185426
Signed by: konrad
GPG Key ID: F40E70337AB24C9B
2 changed files with 55 additions and 0 deletions

31
parse.go Normal file
View File

@ -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
}

24
parse_test.go Normal file
View File

@ -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()
}
})
}