api/app/stats.go

91 lines
1.7 KiB
Go

package app
import (
"reflect"
"time"
"git.fuyu.moe/5GPowerQuality/api/app/internal/model"
"git.ultraware.nl/NiseVoid/qb"
"git.ultraware.nl/NiseVoid/qb/qc"
"git.ultraware.nl/NiseVoid/qb/qf"
)
// Count returns the number of measurements
func Count() int {
m := model.Measurement()
q := m.Select(qf.CountAll())
var count *int
err := db.QueryRow(q).Scan(&count)
if err != nil {
panic(err)
}
if count == nil {
return 0
}
return *count
}
// Attribute represents a single attribute
type Attribute struct {
Name string
Index int
}
// GetAttributes returns a list of all known attributes
func GetAttributes() (list []Attribute) {
m := model.Measurement()
r := reflect.TypeOf(m).Elem()
for i := 0; i < r.NumField(); i++ {
f := r.Field(i)
if f.Name[len(f.Name)-1] == '1' {
list = append(list, Attribute{f.Name[:len(f.Name)-1], i})
}
}
return
}
// GetAttribute returns the specified attribute for all phases since the specified date
func GetAttribute(index int, date time.Time) (data []Phases) {
m := model.Measurement()
r := reflect.ValueOf(m).Elem()
f1, f2, f3 :=
r.Field(index).Interface().(*qb.TableField),
r.Field(index+1).Interface().(*qb.TableField),
r.Field(index+2).Interface().(*qb.TableField)
q := m.Select(m.Time, f1, f2, f3).
OrderBy(qb.Desc(m.Time)).
Where(qc.Gte(m.Time, date))
rows, err := db.Query(q)
if err != nil {
panic(err)
}
for rows.Next() {
var phases Phases
err := rows.Scan(&phases.Time, &phases.P1, &phases.P2, &phases.P3)
if err != nil {
panic(err)
}
data = append(data, phases)
}
return
}
// Phases contains data for all phases
type Phases struct {
Time time.Time `json:"time"`
P1 float64 `json:"phase_1"`
P2 float64 `json:"phase_2"`
P3 float64 `json:"phase_3"`
}