writer.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package temperature
  2. import (
  3. "fmt"
  4. "strconv"
  5. "time"
  6. influx "github.com/influxdata/influxdb/client/v2"
  7. )
  8. // Writer is used to write out measurements
  9. type Writer interface {
  10. Write(Measurement) error
  11. }
  12. type influxWriter struct {
  13. locations map[int]string
  14. db string
  15. client influx.Client
  16. }
  17. func (i influxWriter) Write(measurement Measurement) error {
  18. bp, err := influx.NewBatchPoints(influx.BatchPointsConfig{
  19. Database: i.db,
  20. Precision: "s",
  21. })
  22. if err != nil {
  23. fmt.Println("Could not log temperature")
  24. fmt.Println(err)
  25. return err
  26. }
  27. var tags = map[string]string{}
  28. if val, ok := i.locations[measurement.ID]; ok {
  29. tags["location"] = val
  30. } else {
  31. tags["location"] = "id:" + strconv.FormatInt(int64(measurement.ID), 10)
  32. }
  33. fields := map[string]interface{}{
  34. "temperature": measurement.Temperature,
  35. "battery_good": measurement.BatteryGood,
  36. }
  37. pt, err := influx.NewPoint("temperature", tags, fields, time.Now())
  38. if err != nil {
  39. fmt.Println("Could not log temperature")
  40. fmt.Println(err)
  41. return err
  42. }
  43. bp.AddPoint(pt)
  44. err = i.client.Write(bp)
  45. if err != nil {
  46. fmt.Println("Could not log temperature")
  47. fmt.Println(err)
  48. return err
  49. }
  50. fmt.Println("Wrote measurement successfully")
  51. return nil
  52. }
  53. // NewInfluxWriter creates an influxdb writer
  54. func NewInfluxWriter(db string, host string, username string, password string, locations map[int]string) (Writer, error) {
  55. client, err := influx.NewHTTPClient(influx.HTTPConfig{
  56. Addr: host,
  57. Username: username,
  58. Password: password,
  59. })
  60. if err != nil {
  61. return nil, err
  62. }
  63. return &influxWriter{db: db, client: client, locations: locations}, nil
  64. }