json_get.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package main
  2. import (
  3. "encoding/json"
  4. "flag"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "strings"
  9. "time"
  10. temperature "git.snppla.net/snppla/log_temperature"
  11. )
  12. var host *string
  13. var db *string
  14. var username *string
  15. var password *string
  16. var dbHost *string
  17. var location *string
  18. var seconds *int
  19. type jsonPacket struct {
  20. Temperature_C float64
  21. Temperature_F float64
  22. }
  23. func checkTemperature(writer temperature.Writer) {
  24. resp, err := http.Get(*host)
  25. if err != nil {
  26. fmt.Println(err.Error())
  27. return
  28. }
  29. defer resp.Body.Close()
  30. contents, err := ioutil.ReadAll(resp.Body)
  31. if err != nil {
  32. fmt.Println(err.Error())
  33. return
  34. }
  35. buffer := []byte(contents)
  36. if json.Valid(buffer) {
  37. var jsonPacket jsonPacket
  38. err := json.Unmarshal(buffer, &jsonPacket)
  39. if err != nil {
  40. fmt.Println(err.Error())
  41. return
  42. }
  43. if strings.Contains(strings.ToLower(string(contents)), "_f") {
  44. jsonPacket.Temperature_C = (jsonPacket.Temperature_F - 32) * 5 / 9
  45. }
  46. fmt.Printf("Celcius: %f. Fahrenheit: %f \n", jsonPacket.Temperature_C, jsonPacket.Temperature_F)
  47. measurement := temperature.Measurement{Temperature: jsonPacket.Temperature_C, BatteryState: temperature.BATT_NOT_AVAILABLE, ID: 0}
  48. err = writer.Write(measurement)
  49. if err != nil {
  50. fmt.Println(err.Error())
  51. return
  52. }
  53. }
  54. }
  55. func main() {
  56. host = flag.String("host", "http://localhost:80", "Http address (http://localhost:80)")
  57. db = flag.String("db", "temperature", "Influxdb database")
  58. username = flag.String("user", "", "Username")
  59. password = flag.String("password", "", "Password")
  60. dbHost = flag.String("dbHost", "http://localhost:8086", "Host to connect to")
  61. location = flag.String("location", "unknown", "Location of the device")
  62. seconds = flag.Int("delay", 1, "Number of seconds to delay between pollings")
  63. flag.Parse()
  64. locations := map[int]string{0: *location}
  65. writer, err := temperature.NewInfluxWriter(*db, *dbHost, *username, *password, locations)
  66. if err != nil {
  67. fmt.Println(err.Error())
  68. return
  69. }
  70. for {
  71. checkTemperature(writer)
  72. time.Sleep(time.Duration(*seconds) * time.Second)
  73. }
  74. }