mirror of
https://github.com/mainflux/mainflux.git
synced 2025-05-06 19:29:15 +08:00
76 lines
1.7 KiB
Go
76 lines
1.7 KiB
Go
![]() |
package influxdb
|
||
|
|
||
|
import (
|
||
|
"strconv"
|
||
|
"time"
|
||
|
|
||
|
"github.com/mainflux/mainflux/writers"
|
||
|
|
||
|
influxdata "github.com/influxdata/influxdb/client/v2"
|
||
|
"github.com/mainflux/mainflux"
|
||
|
)
|
||
|
|
||
|
var _ writers.MessageRepository = (*influxRepo)(nil)
|
||
|
|
||
|
type influxRepo struct {
|
||
|
database string
|
||
|
pointName string
|
||
|
client influxdata.Client
|
||
|
}
|
||
|
|
||
|
type fields map[string]interface{}
|
||
|
type tags map[string]string
|
||
|
|
||
|
// New returns new InfluxDB writer.
|
||
|
func New(client influxdata.Client, database, pointName string) (writers.MessageRepository, error) {
|
||
|
return &influxRepo{database, pointName, client}, nil
|
||
|
}
|
||
|
|
||
|
func (repo *influxRepo) Save(msg mainflux.Message) error {
|
||
|
bp, err := influxdata.NewBatchPoints(influxdata.BatchPointsConfig{
|
||
|
Database: repo.database,
|
||
|
})
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
tags, fields := repo.tagsOf(&msg), repo.fieldsOf(&msg)
|
||
|
pt, err := influxdata.NewPoint(repo.pointName, tags, fields, time.Now())
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
bp.AddPoint(pt)
|
||
|
if err := repo.client.Write(bp); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func (repo *influxRepo) tagsOf(msg *mainflux.Message) tags {
|
||
|
time := strconv.FormatFloat(msg.Time, 'f', -1, 64)
|
||
|
update := strconv.FormatFloat(msg.UpdateTime, 'f', -1, 64)
|
||
|
channel := strconv.FormatUint(msg.Channel, 10)
|
||
|
publisher := strconv.FormatUint(msg.Publisher, 10)
|
||
|
return tags{
|
||
|
"Channel": channel,
|
||
|
"Publisher": publisher,
|
||
|
"Protocol": msg.Protocol,
|
||
|
"Name": msg.Name,
|
||
|
"Unit": msg.Unit,
|
||
|
"Link": msg.Link,
|
||
|
"Time": time,
|
||
|
"UpdateTime": update,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (repo *influxRepo) fieldsOf(msg *mainflux.Message) fields {
|
||
|
return fields{
|
||
|
"Value": msg.Value,
|
||
|
"ValueSum": msg.ValueSum,
|
||
|
"BoolValue": msg.BoolValue,
|
||
|
"StringValue": msg.StringValue,
|
||
|
"DataValue": msg.DataValue,
|
||
|
}
|
||
|
}
|