-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbar.go
305 lines (270 loc) · 5.93 KB
/
bar.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
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package bartend
import (
"container/list"
"fmt"
"log"
"sort"
"strings"
"time"
"github.com/freeconf/yang/fc"
"github.com/freeconf/yang/nodeutil"
"github.com/kidoman/embd"
)
func AvailableLiquids(pumps []*Pump) []string {
liquids := make([]string, len(pumps))
for i, pump := range pumps {
liquids[i] = pump.Liquid
}
sort.Strings(liquids)
return liquids
}
func findStringInSlice(sorted []string, a string) bool {
index := sort.SearchStrings(sorted, a)
if index >= len(sorted) || sorted[index] != a {
return false
}
return true
}
type ByName []*Recipe
func (a ByName) Len() int {
return len(a)
}
func (a ByName) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a ByName) Less(i, j int) bool {
return strings.Compare(a[i].Name, a[j].Name) < 0
}
// Recipes is list of drinks that can be made completely automatically
func Recipes(liquids []string, all []*Recipe) []*Recipe {
available := make([]*Recipe, 0, len(all))
for _, recipe := range all {
var found bool
for _, ingredient := range recipe.Ingredients {
if found = findStringInSlice(liquids, ingredient.Liquid); !found {
break
}
}
if found {
available = append(available, recipe)
}
}
sort.Sort(ByName(available))
return available
}
func DistinctLiquids(recipes []*Recipe) []string {
distinct := make(map[string]struct{}, 10)
for _, recipe := range recipes {
for _, ingredient := range recipe.Ingredients {
distinct[ingredient.Liquid] = struct{}{}
}
}
liquids := make([]string, len(distinct))
var i int
for liquid, _ := range distinct {
liquids[i] = liquid
i++
}
sort.Strings(liquids)
return liquids
}
func FindPumpByLiquid(pumps []*Pump, liquid string) *Pump {
for _, pump := range pumps {
if pump.Liquid == liquid {
return pump
}
}
return nil
}
type Liquid string
type Ingredient struct {
Liquid string
Amount float64
}
func (i *Ingredient) Scale(scale float64) *Ingredient {
copy := *i
copy.Amount = copy.Amount * scale
return ©
}
func (i *Ingredient) Weight() int {
return int(i.Amount * LiquidToGrams)
}
type Recipe struct {
Name string
Description string
MadeCount float64
Ingredients []*Ingredient
}
// Standard volume to weight ratio for distilled water
const LiquidToGrams = 29.57
type Pump struct {
Id int
GpioPin int
Liquid string
TimeToVolumeRatioMs int
}
func (p *Pump) Enable(on bool) error {
var v int
// not sure why, but 1 - off, 0 - on
if on {
v = embd.Low
} else {
v = embd.High
}
pin, err := GetPin(p.GpioPin)
if err != nil {
log.Printf("Err pin %d - %s", p.GpioPin, err)
return err
}
return pin.Write(v)
}
func (p *Pump) calculatePourTime(amount float64) time.Duration {
oneUnit := time.Millisecond * time.Duration(p.TimeToVolumeRatioMs)
return time.Duration(amount * float64(oneUnit))
}
type Bartend struct {
Current *Drink
Pumps []*Pump
Recipes []*Recipe
listeners *list.List
}
func NewBartend() *Bartend {
return &Bartend{
listeners: list.New(),
}
}
var ErrDrinkInProgress = fmt.Errorf("drink in progress. %w", fc.BadRequestError)
type Drink struct {
Name string
Pour []*Step
ticker *time.Ticker
Aborted bool
}
func (d *Drink) Complete() bool {
if d.Aborted {
return true
}
for _, a := range d.Pour {
if !a.Complete {
return false
}
}
return true
}
func (d *Drink) Stop() {
d.ticker.Stop()
d.allPumpsOn(false)
d.Aborted = true
}
func (d *Drink) PercentComplete() int {
n := len(d.Pour)
var pct int
for _, a := range d.Pour {
pct += (a.PercentComplete / n)
}
return pct
}
type Step struct {
pump *Pump
Ingredient *Ingredient
PourTime time.Duration
PercentComplete int
Complete bool
}
func (s *Step) pumpOn(on bool) error {
return s.pump.Enable(on)
}
func (s *Step) calculatePercentageDone(t time.Duration) {
if t > s.PourTime {
s.PercentComplete = 100
} else if t == 0 {
s.PercentComplete = 0
} else {
s.PercentComplete = int(100 * (1 - (float32(s.PourTime-t) / float32(s.PourTime))))
}
}
func (s *Step) update(t time.Duration) error {
s.calculatePercentageDone(t)
complete := t > s.PourTime
if complete != s.Complete {
if err := s.pumpOn(!complete); err != nil {
return err
}
s.Complete = complete
}
return nil
}
func (b *Bartend) OnDrinkUpdate(l DrinkProgressListener) nodeutil.Subscription {
return nodeutil.NewSubscription(b.listeners, b.listeners.PushBack(l))
}
func (b *Bartend) updateJob(job *Drink) {
e := b.listeners.Front()
for e != nil {
e.Value.(DrinkProgressListener)(job)
e = e.Next()
}
}
type DrinkProgressListener func(job *Drink)
func (d *Drink) allPumpsOn(on bool) error {
var err error
for _, step := range d.Pour {
if e := step.pumpOn(on); e != nil {
err = e
}
}
return err
}
func (d *Drink) Start(l DrinkProgressListener) {
timeStep := time.Millisecond * 100
d.ticker = time.NewTicker(timeStep)
var t time.Duration
d.allPumpsOn(true)
defer func() {
// shouldn't be nec. unless error happened
d.allPumpsOn(false)
}()
for {
var incomplete bool
for _, step := range d.Pour {
if err := step.update(t); err != nil {
log.Printf("Cannot update pump : %s", err)
break
}
if !step.Complete {
incomplete = true
}
}
l(d)
if !incomplete {
break
}
if _, more := <-d.ticker.C; !more {
break
}
t += timeStep
}
}
func (b *Bartend) MakeDrink(recipe *Recipe, scale float64) error {
if b.Current != nil && !b.Current.Complete() {
return ErrDrinkInProgress
}
drink := &Drink{Name: recipe.Name}
b.Current = drink
for _, ingredient := range recipe.Ingredients {
scaled := ingredient.Scale(scale)
p := FindPumpByLiquid(b.Pumps, ingredient.Liquid)
if p == nil {
return fmt.Errorf("%s is not available on any pump", ingredient.Liquid)
} else {
drink.Pour = append(drink.Pour, &Step{
Ingredient: scaled,
pump: p,
PourTime: p.calculatePourTime(scaled.Amount),
})
}
}
recipe.MadeCount += scale
go drink.Start(b.updateJob)
// drink responsibly
return nil
}