json.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package temperature
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "strings"
  8. )
  9. // JSONParser reads the json output
  10. type jsonParser struct {
  11. scanner *bufio.Scanner
  12. }
  13. // NewJSONParser returns a parser for reading json temperature strings
  14. func NewJSONParser(reader *bufio.Reader) Parser {
  15. return &jsonParser{scanner: bufio.NewScanner(reader)}
  16. }
  17. // {"time" : "2018-04-13 23:04:50", "model" : "Acurite 606TX Sensor", "id" : -5, "battery" : "OK", "temperature_C" : 21.800}
  18. type jsonPacket struct {
  19. Time string
  20. Model string
  21. ID int
  22. Battery string
  23. Temperature_C float64
  24. }
  25. // Measure returns the temperature. Null if it can't
  26. func (jp jsonParser) Measure() (*Measurement, error) {
  27. if !jp.scanner.Scan() {
  28. return nil, errors.New("EOF")
  29. }
  30. if err := jp.scanner.Err(); err != nil {
  31. return nil, err
  32. }
  33. text := jp.scanner.Text()
  34. firstIndex := strings.Index(text, "{")
  35. if firstIndex != -1 {
  36. text = text[firstIndex:]
  37. }
  38. buffer := []byte(text)
  39. if json.Valid(buffer) {
  40. var jsonPacket jsonPacket
  41. err := json.Unmarshal(buffer, &jsonPacket)
  42. if err != nil {
  43. fmt.Println(err.Error())
  44. return nil, err
  45. }
  46. if len(jsonPacket.Model) > 0 {
  47. batteryState := BATT_BAD
  48. if strings.Compare(jsonPacket.Battery, "OK") == 0 {
  49. batteryState = BATT_GOOD
  50. }
  51. fmt.Printf("Model: %s, ID:%d, Temperature:%f, Battery good: %t\n", jsonPacket.Model, jsonPacket.ID, jsonPacket.Temperature_C, batteryState)
  52. return &Measurement{ID: jsonPacket.ID, Temperature: jsonPacket.Temperature_C, BatteryState: batteryState}, nil
  53. }
  54. }
  55. return nil, nil
  56. }