writer.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package temperature
  2. import (
  3. "fmt"
  4. "strconv"
  5. "time"
  6. influx "github.com/influxdata/influxdb1-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. var batteryState int
  34. batteryState = int(measurement.BatteryState)
  35. fields := map[string]interface{}{
  36. "temperature": measurement.Temperature,
  37. "battery_good": batteryState,
  38. }
  39. pt, err := influx.NewPoint("temperature", tags, fields, time.Now())
  40. if err != nil {
  41. fmt.Println("Could not log temperature")
  42. return err
  43. }
  44. bp.AddPoint(pt)
  45. err = i.client.Write(bp)
  46. if err != nil {
  47. fmt.Println("Could not log temperature")
  48. fmt.Println(err)
  49. return err
  50. }
  51. fmt.Println("Wrote measurement successfully")
  52. return nil
  53. }
  54. // NewInfluxWriter creates an influxdb writer
  55. func NewInfluxWriter(db string, host string, username string, password string, locations map[int]string) (Writer, error) {
  56. client, err := influx.NewHTTPClient(influx.HTTPConfig{
  57. Addr: host,
  58. Username: username,
  59. Password: password,
  60. })
  61. if err != nil {
  62. return nil, err
  63. }
  64. return &influxWriter{db: db, client: client, locations: locations}, nil
  65. }