package temperature import ( "bufio" "encoding/json" "errors" "fmt" "strings" ) // JSONParser reads the json output type jsonParser struct { scanner *bufio.Scanner } // NewJSONParser returns a parser for reading json temperature strings func NewJSONParser(reader *bufio.Reader) Parser { return &jsonParser{scanner: bufio.NewScanner(reader)} } // {"time" : "2018-04-13 23:04:50", "model" : "Acurite 606TX Sensor", "id" : -5, "battery" : "OK", "temperature_C" : 21.800} type jsonPacket struct { Time string Model string ID int Battery string Temperature_C float64 } // Measure returns the temperature. Null if it can't func (jp jsonParser) Measure() (*Measurement, error) { if !jp.scanner.Scan() { return nil, errors.New("EOF") } if err := jp.scanner.Err(); err != nil { return nil, err } text := jp.scanner.Text() firstIndex := strings.Index(text, "{") if firstIndex != -1 { text = text[firstIndex:] } buffer := []byte(text) if json.Valid(buffer) { var jsonPacket jsonPacket err := json.Unmarshal(buffer, &jsonPacket) if err != nil { fmt.Println(err.Error()) return nil, err } if len(jsonPacket.Model) > 0 { batteryState := BATT_BAD if strings.Compare(jsonPacket.Battery, "OK") == 0 { batteryState = BATT_GOOD } fmt.Printf("Model: %s, ID:%d, Temperature:%f, Battery good: %t\n", jsonPacket.Model, jsonPacket.ID, jsonPacket.Temperature_C, batteryState) return &Measurement{ID: jsonPacket.ID, Temperature: jsonPacket.Temperature_C, BatteryState: batteryState}, nil } } return nil, nil }