writer.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. }
  36. pt, err := influx.NewPoint("temperature", tags, fields, time.Now())
  37. if err != nil {
  38. fmt.Println("Could not log temperature")
  39. fmt.Println(err)
  40. return err
  41. }
  42. bp.AddPoint(pt)
  43. err = i.client.Write(bp)
  44. if err != nil {
  45. fmt.Println("Could not log temperature")
  46. fmt.Println(err)
  47. return err
  48. }
  49. fmt.Println("Wrote measurement successfully")
  50. return nil
  51. }
  52. // NewInfluxWriter creates an influxdb writer
  53. func NewInfluxWriter(db string, host string, username string, password string, locations map[int]string) (Writer, error) {
  54. client, err := influx.NewHTTPClient(influx.HTTPConfig{
  55. Addr: host,
  56. Username: username,
  57. Password: password,
  58. })
  59. if err != nil {
  60. return nil, err
  61. }
  62. return &influxWriter{db: db, client: client, locations: locations}, nil
  63. }