github.com/simpleiot/simpleiot@v0.18.3/data/point_averager.go (about)

     1  package data
     2  
     3  import (
     4  	"time"
     5  )
     6  
     7  // PointAverager accumulates points, and averages them. The average can
     8  // be reset.
     9  type PointAverager struct {
    10  	total     float64
    11  	count     int
    12  	min       float64
    13  	max       float64
    14  	pointType string
    15  	pointTime time.Time
    16  }
    17  
    18  // NewPointAverager initializes and returns an averager
    19  func NewPointAverager(pointType string) *PointAverager {
    20  	return &PointAverager{
    21  		pointType: pointType,
    22  	}
    23  }
    24  
    25  // AddPoint takes a point, and adds it to the total
    26  func (pa *PointAverager) AddPoint(s Point) {
    27  	// avg point timestamp is set to last point time
    28  	if s.Time.After(pa.pointTime) {
    29  		pa.pointTime = s.Time
    30  	}
    31  
    32  	// update statistical values.
    33  	pa.total += s.Value
    34  	pa.count++
    35  }
    36  
    37  // ResetAverage sets the accumulated total to zero
    38  func (pa *PointAverager) ResetAverage() {
    39  	pa.total = 0
    40  	pa.count = 0
    41  	pa.min = 0
    42  	pa.max = 0
    43  }
    44  
    45  // GetAverage returns the average of the accumulated points
    46  func (pa *PointAverager) GetAverage() Point {
    47  	var value float64
    48  	if pa.count == 0 {
    49  		value = 0
    50  	} else {
    51  		value = pa.total / float64(pa.count)
    52  	}
    53  
    54  	return Point{
    55  		Type:  pa.pointType,
    56  		Time:  pa.pointTime,
    57  		Value: value,
    58  	}
    59  }