-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
483 lines (399 loc) · 14 KB
/
main.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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
package main
import (
"fmt"
"image/color"
"log"
bt "pedal/internal/bluetoothctl"
"pedal/internal/fit"
"time"
gui "github.com/gen2brain/raylib-go/raygui"
rl "github.com/gen2brain/raylib-go/raylib"
)
type AppState struct {
DataSet fit.DataSet
Screen ApplicationScreen
WorkoutElapsedTime uint32
CurrentInterval fit.Interval
CurrentIntervalNumber int
NextIntervalStartsAt int
BluetoothCtl bt.BluetoothControl
}
const (
windowHeight = 450
windowWidth = 800
fontSize = 30
defaultBtnSize float32 = 30
canvasMaxPowerDisplay int32 = 600
// Colors
// Fonts
)
var (
needlePosX float64 = 0
needlePosPercent float64 = 0
needleIncrementX float64 = 0
backBtnClicked bool = false
scanBtnClicked bool = false
devicesBtnClicked bool = false
endWorkoutClicked bool = false
startWorkoutClicked bool = false
scannedDevices []bt.BluetoothDevice = []bt.BluetoothDevice{}
selectedDeviceIdx int32 = int32(0)
listViewBounds rl.Rectangle
currentHeartRate uint8
currentPower uint8
currentCadence uint8
ticker *time.Ticker
stopTicker chan struct{}
workoutInProgress bool = false
)
type ApplicationScreen int
const (
TitleScreen ApplicationScreen = iota
WorkoutScreen
SettingsScreen
DevicesScreen
WorkoutCompletedScreen
)
func initApp() (state AppState) {
state.Screen = TitleScreen
state.WorkoutElapsedTime = 0
state.CurrentIntervalNumber = 0
state.NextIntervalStartsAt = 0
state.BluetoothCtl = bt.Init()
return state
}
func main() {
appState := initApp()
rl.InitWindow(windowWidth, windowHeight, "Pedal")
defer rl.CloseWindow()
rl.SetTargetFPS(60)
rl.SetWindowPosition(
(rl.GetMonitorWidth(0) - (windowWidth / 2)),
(rl.GetMonitorHeight(0) / 2) - (windowHeight / 2))
for !rl.WindowShouldClose() {
appState.update()
rl.BeginDrawing()
rl.ClearBackground(rl.RayWhite)
appState.draw()
rl.EndDrawing()
}
}
func (state *AppState) update() {
//================ Title screen =================
if (state.Screen == TitleScreen) {
droppedFile := make([]string, 0)
if (rl.IsFileDropped()) {
droppedFile = rl.LoadDroppedFiles()
if (len(droppedFile) > 0) {
state.DataSet = fit.ParseWorkoutFile(droppedFile[0])
rl.UnloadDroppedFiles()
state.Screen = WorkoutScreen
}
}
return
}
//================ Workout screen =================
if state.Screen == WorkoutScreen {
if startWorkoutClicked && !workoutInProgress {
workoutInProgress = true
ticker = time.NewTicker(1 * time.Second)
stopTicker = make(chan struct{})
go func() {
for {
select {
// TODO: on each tick read
// timestamp; power;hr;cadence
// and write to DB (could use a queue probably)
// TODO later: Also display hr and power and cadence on canvas
case <-ticker.C:
state.WorkoutElapsedTime += 1
state.moveNeedleBasedOnElapsedTime()
state.setIntervalBasedOnElapsedTime()
case <-stopTicker:
workoutInProgress = false
ticker.Stop()
return
}
}
}()
}
if endWorkoutClicked && workoutInProgress {
close(stopTicker)
}
/*if rl.IsKeyDown(rl.KeyRight) && state.WorkoutElapsedTime < uint32(state.DataSet.TotalDurationSeconds) {
state.WorkoutElapsedTime += 1
state.moveNeedleBasedOnElapsedTime()
state.setIntervalBasedOnElapsedTime()
return
}*/
if devicesBtnClicked {
state.Screen = DevicesScreen
return
}
return
}
//================= Devices screen =================
if state.Screen == DevicesScreen {
if (backBtnClicked) {
state.Screen = WorkoutScreen
return;
}
// Scan devices btn click ---------------------------
if scanBtnClicked {
scannedDevices = []bt.BluetoothDevice{}
ch := make(chan bt.BluetoothDevice)
go state.BluetoothCtl.Scan(ch, []string{})
go func() {
for {
bltDevice, ok := <-ch
if !ok {
break
}
if len(scannedDevices) == 0 {
scannedDevices = append(scannedDevices, bltDevice)
} else {
exists := false
for _, device := range scannedDevices {
if device.Address == bltDevice.Address {
exists = true
break;
}
}
if !exists {
scannedDevices = append(scannedDevices, bltDevice)
}
}
}
}()
}
// Connect to device click ------------------------
mousePos := rl.GetMousePosition()
if rl.CheckCollisionPointRec(mousePos, listViewBounds) {
if rl.IsMouseButtonPressed(rl.MouseLeftButton) {
if len(scannedDevices) == 0 {
return
}
if len(scannedDevices) < int(selectedDeviceIdx) {
log.Printf("how did i get here. Selected index: %d", selectedDeviceIdx)
return;
}
selectedDevice := scannedDevices[selectedDeviceIdx]
if selectedDevice.Type == bt.HeartRateMonitor && !state.BluetoothCtl.HrMonitorConnected {
hrMonitorCh := make(chan uint8)
go state.BluetoothCtl.ConnectToHrMonitor(selectedDevice.Address, hrMonitorCh)
go func() {
for {
hrValue, ok := <-hrMonitorCh
if !ok {
break
}
log.Printf("HR: %d", hrValue)
currentHeartRate = hrValue
}
}()
}
if selectedDevice.Type == bt.SmartTrainer && !state.BluetoothCtl.SmartTrainerConnected {
//TODO: listen smart trainer power and cadence
log.Println("Connecting to smart trainer")
powerChannel := make(chan uint8)
go state.BluetoothCtl.ConnectToSmartTrainer(selectedDevice.Address, powerChannel)
}
}
}
}
}
func (state *AppState) draw() {
if state.Screen == TitleScreen {
rl.DrawText("Drop a .FIT workout file here!",
190, 200, 20,
rl.LightGray)
return
}
if state.Screen == WorkoutScreen {
if len(state.DataSet.Intervals) > 0 {
// Settings button
gui.Button(rl.Rectangle{
X: float32(rl.GetScreenWidth()) - (10 + defaultBtnSize),
Y: 10,
Width: defaultBtnSize,
Height: defaultBtnSize,
}, gui.IconText(gui.ICON_GEAR_BIG, ""))
// Devices button
devicesBtnClicked = gui.Button(rl.Rectangle{
X: float32(rl.GetScreenWidth()) - (50 + defaultBtnSize),
Y: 10,
Width: defaultBtnSize,
Height: defaultBtnSize,
}, gui.IconText(gui.ICON_TOOLS, ""))
endWorkoutClicked = gui.Button(rl.Rectangle{
X: float32(rl.GetScreenWidth()) - 195,
Y: 10,
Width: 100,
Height: defaultBtnSize,
}, "End workout")
startWorkoutClicked = gui.Button(rl.Rectangle{
X: float32(rl.GetScreenWidth()) - 310,
Y: 10,
Width: 100,
Height: defaultBtnSize,
}, "Start workout")
rl.DrawText(
fmt.Sprintf("Target power: %d - %d", state.CurrentInterval.TargetLow,
state.CurrentInterval.TargetHigh),
10, 10, 20,
rl.Black)
rl.DrawText(
fmt.Sprintf("Interval: %d", state.CurrentInterval.DurationSeconds),
10, 30, 20,
rl.Black)
rl.DrawText(
fmt.Sprintf("Elapsed time: %d", state.WorkoutElapsedTime),
10, 50, 20,
rl.Black)
rl.DrawText(
fmt.Sprintf("Current HR: %d", currentHeartRate),
10, 70, 20,
rl.Black)
state.drawWorkoutGraph()
} else {
log.Print("Could not read any data from fit file")
state.Screen = TitleScreen
}
}
if (state.Screen == DevicesScreen) {
backBtnClicked = gui.Button(rl.Rectangle{
X: 10,
Y: 10,
Width: defaultBtnSize,
Height: defaultBtnSize,
}, gui.IconText(gui.ICON_ARROW_LEFT, ""))
scanBtnClicked = gui.Button(rl.Rectangle{
X: 50,
Y: 10,
Width: 100,
Height: defaultBtnSize,
}, "Scan devices")
listViewBounds = rl.Rectangle{
X: (float32(rl.GetScreenWidth()) / 2) - 200,
Y: 10,
Height: float32(rl.GetScreenHeight()) - 20,
Width: 400,
}
selectedDeviceIdx = gui.ListViewEx(
listViewBounds,
bt.ListToString(&scannedDevices),
nil,
nil,
selectedDeviceIdx)
}
}
// NOTE: maybe shoud use DrawingTexture
// to group the whole thing
func (state *AppState) drawWorkoutGraph() {
rl.DrawText(fmt.Sprint(state.DataSet.TotalDurationSeconds),
190, 200, 20,
rl.Green)
// canvas is always 50% of the screen height
canvasHeight := float32(rl.GetScreenHeight()) * float32(0.5)
canvas := renderCanvas(state.DataSet, canvasHeight)
// makes sure that on window resize
// the needle is in the correct poisition
// Assumes that canvas width is same as window width
needlePosX = (float64(needlePosPercent) * float64(canvas.Width)) / 100
// Draw the Needle
startPos := rl.Vector2{
X: float32(needlePosX),
Y: canvas.Y,
}
endPos := rl.Vector2{
X: float32(needlePosX),
Y: canvas.Y + canvas.Height,
}
rl.DrawLineV(startPos, endPos, rl.Red)
}
func renderCanvas(data fit.DataSet, height float32) rl.Rectangle {
canvasX, canvasY := 0, float32(rl.GetScreenHeight()) - height
canvas := rl.Rectangle{
X: float32(canvasX),
Y: canvasY,
Height: height,
Width: float32(rl.GetScreenWidth()),
}
// draw canvas element (the parent element)
rl.DrawRectangleRec(canvas, rl.Black)
// calculate 1sec and 1w pixels
timeGap := float64(canvas.Width) / float64(data.TotalDurationSeconds)
powerGap := float64(canvas.Height) / float64(canvasMaxPowerDisplay)
needleIncrementX = timeGap
blockX := 0.0
for _, b := range data.Intervals {
blockHighEndHeight := float64(b.TargetHigh) * powerGap
blockLowEndHeight := float64(b.TargetLow) * powerGap
blockWidth := float64(b.DurationSeconds) * timeGap
// blocks are dependent of the canvas position
// if canvas heigh and location is changed
// block will move with it
// or at least should
block := rl.Rectangle{
X: float32(blockX),
Y: canvas.Y + canvas.Height - float32(blockHighEndHeight),
Height: float32(blockHighEndHeight),
Width: float32(blockWidth),
}
rl.DrawRectangleRec(block, color.RGBA{38, 210, 66, 255})
lowEndBlock := rl.Rectangle{
X: float32(blockX),
Y: canvas.Y + canvas.Height - float32(blockLowEndHeight),
Height: float32(blockLowEndHeight),
Width: float32(blockWidth),
}
rl.DrawRectangleRec(lowEndBlock, color.RGBA{30, 167, 53, 255})
blockX = blockX + blockWidth
}
// Draw canvas power guide lines
rl.DrawText("600",
canvas.ToInt32().X,
canvas.ToInt32().Y,
18,
rl.White)
rl.DrawText("300",
canvas.ToInt32().X,
canvas.ToInt32().Y + (canvas.ToInt32().Height / 2),
18,
rl.White)
rl.DrawLine(
0,
canvas.ToInt32().Y + (canvas.ToInt32().Height / 2),
canvas.ToInt32().Width,
canvas.ToInt32().Y + (canvas.ToInt32().Height / 2),
rl.White)
return canvas
}
func (state *AppState) moveNeedleBasedOnElapsedTime() {
needlePosX = float64(state.WorkoutElapsedTime) * needleIncrementX
needlePosPercent = (needlePosX * 100) / float64(rl.GetScreenWidth())
}
func (state *AppState) setIntervalBasedOnElapsedTime() {
if (len(state.DataSet.Intervals) == 0) {
return
}
// fix: do not index into array every time
// save the block into some sort of an application state
state.CurrentInterval = state.DataSet.Intervals[state.CurrentIntervalNumber]
if (state.CurrentIntervalNumber == 0) {
state.NextIntervalStartsAt = int(state.CurrentInterval.DurationSeconds)
}
if (state.WorkoutElapsedTime >= uint32(state.NextIntervalStartsAt)) {
state.CurrentIntervalNumber += 1
// TODO: send some sort of a signal
// save the workout
// change the screen
// show the completed workout
if (state.CurrentIntervalNumber == len(state.DataSet.Intervals)) {
fmt.Println("workout ENDED")
return;
}
nextInterval := state.DataSet.Intervals[state.CurrentIntervalNumber]
state.NextIntervalStartsAt = int(state.WorkoutElapsedTime) + int(nextInterval.DurationSeconds)
}
}