api/app/stats.go

125 lines
2.3 KiB
Go
Raw Normal View History

2018-05-14 14:19:29 +02:00
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
}
2018-05-28 14:17:59 +02:00
// Attribute represents a single attribute
type Attribute struct {
Name string
Index int
}
// GetAttributes returns a list of all known attributes
func GetAttributes() (list []Attribute) {
2018-05-14 14:19:29 +02:00
m := model.Measurement()
2018-05-28 14:17:59 +02:00
r := reflect.TypeOf(m).Elem()
2018-05-14 14:19:29 +02:00
2018-05-28 14:17:59 +02:00
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})
}
2018-05-14 14:19:29 +02:00
}
2018-05-28 14:17:59 +02:00
return
}
2018-06-08 13:06:20 +02:00
// Meter represents a single meter
type Meter struct {
ID int `json:"id"`
Name string `json:"name"`
FortopUID string `json:"fortop_uid"`
}
// GetMeters returns a list of all known meters
func GetMeters() (list []Meter) {
me := model.Meter()
q := me.Select(me.ID, me.Name, me.FortopUID)
rows, err := db.Query(q)
if err != nil {
panic(err)
}
for rows.Next() {
var meter Meter
err = rows.Scan(&meter.ID, &meter.Name, &meter.FortopUID)
if err != nil {
panic(err)
}
list = append(list, meter)
}
return
}
2018-05-28 14:17:59 +02:00
// GetAttribute returns the specified attribute for all phases since the specified date
2018-06-08 13:06:20 +02:00
func GetAttribute(index, meter int, date time.Time) (data []Phases) {
2018-05-28 14:17:59 +02:00
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)
2018-05-14 14:19:29 +02:00
q := m.Select(m.Time, f1, f2, f3).
OrderBy(qb.Desc(m.Time)).
2018-06-08 13:06:20 +02:00
Where(
qc.Gte(m.Time, date),
qc.Eq(m.MeterID, meter),
)
2018-05-14 14:19:29 +02:00
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"`
}