Add parser
This commit is contained in:
parent
6418618c5d
commit
945c185426
|
@ -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
|
||||
}
|
|
@ -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()
|
||||
}
|
||||
})
|
||||
}
|
Loading…
Reference in New Issue