-
Notifications
You must be signed in to change notification settings - Fork 3
/
translater.go
83 lines (66 loc) · 1.92 KB
/
translater.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package openminder
import (
"fmt"
)
var translatableFields = []string{
"irrig_ph",
"irrig_ec",
"runoff_ph",
"runoff_ec",
"irrig_volume",
"runoff_volume",
"moisture",
}
// ErrNotTranslatable is returned by the Translater when a field is not translatable
var ErrNotTranslatable = fmt.Errorf("non-translatable field")
// DefaultDBPath is the default path to the database
var DefaultDBPath = "minder.db"
// NewTranslater returns a new translater object
func NewTranslater() (*Translater, error) {
db, err := NewBoltedJSON(DefaultDBPath, "minder")
return &Translater{db}, err
}
// Translater is an object that translates readings
type Translater struct {
jdb *BoltedJSON
}
type calibration struct {
Scale float64 `json:"scale"`
Offset float64 `json:"offset"`
}
func (c calibration) Transform(v float64) float64 {
return (v * c.Scale) + c.Offset
}
func (c calibration) TransformPercent(v float64) float64 {
return ((v - c.Offset) / c.Scale) * 100
}
// SetCalibration sets the calibration for the given field
func (tr *Translater) SetCalibration(field string, scale, offset float64) error {
var translatable bool
for _, f := range translatableFields {
if f == field {
translatable = true
}
}
if !translatable {
return ErrNotTranslatable
}
return tr.jdb.Set(field, calibration{scale, offset})
}
// getCalibration gets the calibration for the given field
func (tr *Translater) getCalibration(field string) (calibration, error) {
calib := calibration{}
err := tr.jdb.Get(field, &calib)
return calib, err
}
// Translate will convert the given value as per the calibrations stored for the given field
func (tr *Translater) Translate(field string, value float64) (float64, error) {
c, err := tr.getCalibration(field)
if err != nil {
return value, fmt.Errorf("can't find calibration constant for %s", field)
}
if field == "moisture" {
return c.TransformPercent(value), nil
}
return c.Transform(float64(value)), nil
}