-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwaterer.go
More file actions
134 lines (114 loc) · 2.46 KB
/
waterer.go
File metadata and controls
134 lines (114 loc) · 2.46 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package main
import (
"machine"
"time"
ui "github.com/itohio/tinygui"
"tinygo.org/x/drivers"
)
type Waterer struct {
ui.WidgetBase
cfg *Config
active bool
index byte
adc machine.ADC
pump machine.Pin
lastVal float32
setHighTh bool
}
func NewWaterer(n byte, adc machine.Pin, pump machine.Pin, cfg *Config) *Waterer {
ret := &Waterer{
WidgetBase: ui.NewWidgetBase(uint16(WIDTH), 8),
cfg: cfg,
active: false,
index: n,
adc: machine.ADC{Pin: adc},
pump: pump,
}
pump.Configure(machine.PinConfig{Mode: machine.PinOutput})
ret.adc.Configure(machine.ADCConfig{})
return ret
}
func (w *Waterer) run() {
ticker := time.NewTicker(time.Millisecond * 100)
for range ticker.C {
w.read()
if !w.active {
continue
}
if !w.cfg.IsOn(w.index) {
continue
}
// Don't pump at night!
if !day {
w.pump.Low()
continue
}
//
th := w.cfg.High(w.index)
if w.pump.Get() {
th = w.cfg.Low(w.index)
}
w.pump.Set(w.lastVal > th && day)
}
}
func (w *Waterer) read() {
time.Sleep(time.Microsecond)
val := float32(w.adc.Get()) / 65535.0
w.lastVal = (w.lastVal*9 + val) / 10
}
func (w *Waterer) Draw(ctx ui.Context) {
x, y := ctx.DisplayPos()
w.display(ctx.D(), x, y)
}
func (w *Waterer) SetSelected(s bool) {
if s {
w.setHighTh = false
}
w.WidgetBase.SetSelected(s)
}
func (w *Waterer) display(d drivers.Displayer, x, y int16) {
y += 4
ui.VLine(d, x, y+1, HEIGHT-2, white)
ui.VLine(d, x+WIDTH-1, y+1, HEIGHT-2, white)
if w.Selected() {
ui.VLine(d, x+1, y, HEIGHT, white)
ui.VLine(d, x+WIDTH-2, y, HEIGHT, white)
}
th := int16(w.cfg.Low(w.index) * float32(WIDTH))
if w.Selected() && !w.setHighTh {
ui.VLine(d, x+th, y, HEIGHT, white)
} else {
ui.VLine(d, x+th, y+4, 2, white)
}
th = int16(w.cfg.High(w.index) * float32(WIDTH))
if w.Selected() && w.setHighTh {
ui.VLine(d, x+th, y, HEIGHT, white)
} else {
ui.VLine(d, x+th, y+2, 2, white)
}
val := w.lastVal
ui.HLine(d, x, y+4, int16(val*float32(WIDTH)), white)
}
func (w *Waterer) Interact(cmd ui.UserCommand) bool {
switch cmd {
case ui.NEXT:
if w.setHighTh {
w.cfg.HighThreshold[w.index] += 0.01
} else {
w.cfg.LowThreshold[w.index] += 0.01
}
case ui.PREV:
if w.setHighTh {
w.cfg.HighThreshold[w.index] -= 0.01
} else {
w.cfg.LowThreshold[w.index] -= 0.01
}
case ui.ENTER:
if w.setHighTh {
w.SetSelected(false)
return true
}
w.setHighTh = true
}
return w.WidgetBase.Interact(cmd)
}