package writer import ( "fmt" "time" "git.snppla.net/snppla/log-temperature/parser" influx "github.com/influxdata/influxdb/client/v2" ) // Writer is used to write out measurements type Writer interface { Write(parser.Measurement) error } type influxWriter struct { locations map[int]string db string client influx.Client } func (i influxWriter) Write(measurement parser.Measurement) error { bp, err := influx.NewBatchPoints(influx.BatchPointsConfig{ Database: i.db, Precision: "s", }) if err != nil { fmt.Println("Could not log temperature") fmt.Println(err) return err } var tags = map[string]string{} if val, ok := i.locations[measurement.ID]; ok { tags["location"] = val } else { tags["location"] = "id:" + string(measurement.ID) } fields := map[string]interface{}{ "temperature": measurement.Temperature, } pt, err := influx.NewPoint("temperature", tags, fields, time.Now()) if err != nil { fmt.Println("Could not log temperature") fmt.Println(err) return err } bp.AddPoint(pt) err = i.client.Write(bp) if err != nil { fmt.Println("Could not log temperature") fmt.Println(err) return err } return nil } // NewInfluxWriter creates an influxdb writer func NewInfluxWriter(db string, host string, username string, password string, locations map[int]string) (Writer, error) { client, err := influx.NewHTTPClient(influx.HTTPConfig{ Addr: host, Username: username, Password: password, }) if err != nil { return nil, err } return &influxWriter{db: db, client: client, locations: locations}, nil }