package app import ( "fmt" "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 } type Source string func (s *Source) Scan(v interface{}) error { i, ok := v.(int64) if !ok { return fmt.Errorf(`Unsupported scan, storing driver.Value type %T into type %T`, v, s) } *s = Source([]string{``, `Fortop`, `Envitron`}[i]) return nil } // Meter represents a single meter type Meter struct { ID int `json:"id"` Name string `json:"name"` Source Source `json:"source"` } // GetMeters returns a list of all known meters func GetMeters() (list []Meter) { me := model.Meter() q := me.Select(me.ID, me.Name, me.Source) rows, err := db.Query(q) if err != nil { panic(err) } for rows.Next() { var meter Meter err = rows.Scan(&meter.ID, &meter.Name, &meter.Source) if err != nil { panic(err) } list = append(list, meter) } return } // GetAttribute returns the specified attribute for all phases since the specified date func GetAttribute(index, meter 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), qc.Eq(m.MeterID, meter), ) 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"` }