83 lines
1.8 KiB
Go
83 lines
1.8 KiB
Go
// Package datapoint implements measurement and datapoint
|
|
// for database gateways.
|
|
package datapoint
|
|
|
|
import (
|
|
"encoding/json"
|
|
"time"
|
|
)
|
|
|
|
type Topic struct {
|
|
Subject string
|
|
Content string
|
|
}
|
|
|
|
// DataPointInfo provides an interface for accessing
|
|
// all fields of a DataPoint.
|
|
type DataPointInfo interface {
|
|
MeasurementName() string
|
|
Tags() []Topic
|
|
PayloadAsAny() map[string]any
|
|
Timestamp() time.Time
|
|
}
|
|
|
|
// A Measurement represents a type of measurement such as
|
|
// temperature, humidity, ...
|
|
type Measurement[T any] struct {
|
|
name string
|
|
}
|
|
|
|
// A DataPoint represents values associated with a measurement, along with tags,
|
|
// values, and a timestamp. It contains a pointer to its parent Measurement
|
|
type DataPoint[T any] struct {
|
|
measurement *Measurement[T]
|
|
tags []Topic
|
|
values T
|
|
timestamp time.Time
|
|
}
|
|
|
|
func CreateMeasurement[T any](name string) Measurement[T] {
|
|
return Measurement[T]{
|
|
name: name,
|
|
}
|
|
}
|
|
|
|
// CreateDataPoint forces the creation of DataPoint with the type according
|
|
// to the generic.
|
|
func (m *Measurement[T]) CreateDataPoint(tags []Topic, values T, timestamp time.Time) DataPoint[T] {
|
|
return DataPoint[T]{
|
|
measurement: m,
|
|
tags: tags,
|
|
values: values,
|
|
timestamp: timestamp,
|
|
}
|
|
}
|
|
|
|
func (dp *DataPoint[T]) MeasurementName() string {
|
|
return dp.measurement.name
|
|
}
|
|
|
|
func (dp *DataPoint[T]) Tags() []Topic {
|
|
return dp.tags
|
|
}
|
|
|
|
func (dp *DataPoint[T]) GetValues() T {
|
|
return dp.values
|
|
}
|
|
|
|
// PayloadAsAny returns the DataPoint value with type any.
|
|
// (useful for adding the DataPoint for batching)
|
|
func (dp *DataPoint[T]) PayloadAsAny() map[string]any {
|
|
b, err := json.Marshal(dp.values)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
var res map[string]any
|
|
_ = json.Unmarshal(b, &res)
|
|
return res
|
|
}
|
|
|
|
func (dp *DataPoint[T]) Timestamp() time.Time {
|
|
return dp.timestamp
|
|
}
|