1 Commits
Author SHA1 Message Date
gmp 1813e1bd25 add README.md 2019-12-04 17:26:45 -05:00
21 changed files with 344 additions and 1016 deletions
+1 -4
View File
@@ -1,5 +1,2 @@
hrm/hrm
hrm
*.apk
.DS_Store
*.idsig
-21
View File
@@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2019 Gregory Pomerantz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+4 -14
View File
@@ -2,16 +2,11 @@
An example heart rate monitor app for Android and MacOS using [git.wow.st/gmp/ble](https://git.wow.st/gmp/ble) and [Gio](https://gioui.org).
The MacOS implementation uses a Core Bluetooth binding created by
[NSWrap](https://git.wow.st/gmp/nswrap). On Android, Martijn van Welie's
[Blessed](https://github.com/weliem/blessed-android) library is used to
simplify access to the Bluetooth Low-Energy hardware.
## MacOS:
```
git clone https://git.wow.st/gmp/hrm
cd hrm/hrm
go get git.wow.st/gmp/hrm
cd ~/go/src/git.wow.st/gmp/hrm
go build
./hrm
```
@@ -22,13 +17,8 @@ The `gogio` command from `gioui.org/cmd/gogio` must be installed to build
an Android APK.
```
git clone https://git.wow.st/gmp/hrm
cd hrm/hrm
go get git.wow.st/gmp/hrm
cd ~/go/src/git.wow.st/gmp/hrm
gogio -target android .
adb install -r hrm.apk
```
The compiled Java code for the Android implementation is pre-packaged in
jar files. If you want to, you can re-compile these dependencies by running
`go generate` from the `depjars` directory. You will need to have `gradle`,
an Android SDK, and who knows what else installed on your machine.
-3
View File
@@ -1,3 +0,0 @@
//go:generate go generate git.wow.st/gmp/ble/depjars
package main
@@ -1,3 +0,0 @@
Simple bluetooth low-energy heart rate monitor with a stopwatch function to
time your workouts. Automatically connects to your last-used peripheral or you
can scan for nearby bluetooth devices.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

@@ -1 +0,0 @@
Simple bluetooth low-energy heart rate monitor
+9
View File
@@ -0,0 +1,9 @@
module git.wow.st/gmp/hrm
go 1.13
require (
gioui.org v0.0.0-20191126175243-2ca2e5462f16
git.wow.st/gmp/ble v0.0.0-20191204222510-e7f82ac9e7f9
gopkg.in/yaml.v2 v2.2.7
)
+34
View File
@@ -0,0 +1,34 @@
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
gioui.org v0.0.0-20191126175243-2ca2e5462f16 h1:p31rtmKm51xpj2QtqGNlljAyHEP1oStU8MDRl2Dv7Gs=
gioui.org v0.0.0-20191126175243-2ca2e5462f16/go.mod h1:KqFFi2Dq5gYA3FJ0sDOt8OBXoMsuxMtE8v2f0JExXAY=
git.wow.st/gmp/ble v0.0.0-20191127164604-2af636b9461a h1:Nr6kwAliHs2EsGv4Q1EgQACfbb/hVnTYq0CkWfqIj+g=
git.wow.st/gmp/ble v0.0.0-20191127164604-2af636b9461a/go.mod h1:Fh9BYe6AckJS7dzv2LFPr/wSYVMROUwmtc01VyQmuZo=
git.wow.st/gmp/ble v0.0.0-20191204222510-e7f82ac9e7f9 h1:IfBmZRWVb0CfjjiSDStqblKMGSwCkGVewkpOuzl+lGY=
git.wow.st/gmp/ble v0.0.0-20191204222510-e7f82ac9e7f9/go.mod h1:Fh9BYe6AckJS7dzv2LFPr/wSYVMROUwmtc01VyQmuZo=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20191002040644-a1355ae1e2c3 h1:n9HxLrNxWWtEb1cA950nuEEj3QnKbtsCJ6KjcgisNUs=
golang.org/x/exp v0.0.0-20191002040644-a1355ae1e2c3/go.mod h1:NOZ3BPKG0ec/BKJQgnvsSFpcKLM5xXVWnvZS97DWHgE=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b h1:+qEpEAPhDZ1o0x3tHzZTQDArnOixOzGD9HUJfcg0mb4=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o=
golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a h1:aYOabOQFp6Vj6W1F80affTUvO9UxmJRx8K0gsfABByQ=
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/tools v0.0.0-20190927191325-030b2cf1153e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.7 h1:VUgggvou5XRW9mHwD/yXxIYSMtY0zoKQf/v226p2nyo=
gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

-19
View File
@@ -1,19 +0,0 @@
module st.wow.git/gmp/hrm/hrm
go 1.24.0
require (
gioui.org v0.10.2
git.wow.st/gmp/ble v0.0.0-20260822003457-e53c7be9766b
gopkg.in/yaml.v2 v2.3.0
)
require (
gioui.org/shader v1.0.9 // indirect
github.com/go-text/typesetting v0.3.4 // indirect
golang.org/x/exp/shiny v0.0.0-20250408133849-7e4ce0ab07d0 // indirect
golang.org/x/image v0.26.0 // indirect
golang.org/x/net v0.48.0 // indirect
golang.org/x/sys v0.39.0 // indirect
golang.org/x/text v0.32.0 // indirect
)
-52
View File
@@ -1,52 +0,0 @@
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
eliasnaur.com/font v0.0.0-20230308162249-dd43949cb42d h1:ARo7NCVvN2NdhLlJE9xAbKweuI9L6UgfTbYb0YwPacY=
eliasnaur.com/font v0.0.0-20230308162249-dd43949cb42d/go.mod h1:OYVuxibdk9OSLX8vAqydtRPP87PyTFcT9uH3MlEGBQA=
gioui.org v0.0.0-20200829162755-829ee4559c5a/go.mod h1:Y+uS7hHMvku1Q+ooaoq6fYD5B2LGoT8JtFgvmYmRzTw=
gioui.org v0.10.2 h1:bZU5CORROwc51sNha0zYdE2qWVaDncOp5EjV5nrZQZ8=
gioui.org v0.10.2/go.mod h1:iKILKNq6+LHMWhP/HjGDW/wDidUzRnb7B6c7ZD9y1Mg=
gioui.org/cpu v0.0.0-20210808092351-bfe733dd3334/go.mod h1:A8M0Cn5o+vY5LTMlnRoK3O5kG+rH0kWfJjeKd9QpBmQ=
gioui.org/shader v1.0.9 h1:XxnqIfmClWpN49kizxH2W0JcCFrrEP4q3jZmNYaltbs=
gioui.org/shader v1.0.9/go.mod h1:mWdiME581d/kV7/iEhLmUgUK5iZ09XR5XpduXzbePVM=
git.wow.st/gmp/ble v0.0.0-20260822003457-e53c7be9766b h1:AUvcBwxTD+OlayRckL57H1GTtY0/qOiGJEUlkAFS9z8=
git.wow.st/gmp/ble v0.0.0-20260822003457-e53c7be9766b/go.mod h1:NrH2R84qUcPGoI9MmPGB1GFIbQxCWEw4WpVnDEn/WUc=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
github.com/go-text/typesetting v0.3.4 h1:YYurUOtEb9kGSOz4uE3k4OpBGsp1dDL8+fjCeaFamAU=
github.com/go-text/typesetting v0.3.4/go.mod h1:4qZCQphq4KSgGTAeI0uMEkVbROgfah8BuyF5LRYr7XY=
github.com/go-text/typesetting-utils v0.0.0-20260223113751-2d88ac90dae3 h1:drBZzMgdYPbmyXqOto4YhhJGrFIQCX94FpR4MzTCsos=
github.com/go-text/typesetting-utils v0.0.0-20260223113751-2d88ac90dae3/go.mod h1:3/62I4La/HBRX9TcTpBj4eipLiwzf+vhI+7whTc9V7o=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20191002040644-a1355ae1e2c3/go.mod h1:NOZ3BPKG0ec/BKJQgnvsSFpcKLM5xXVWnvZS97DWHgE=
golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0 h1:R84qjqJb5nVJMxqWYb3np9L5ZsaDtB+a39EqjV0JSUM=
golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0/go.mod h1:S9Xr4PYopiDyqSyp5NjCrhFrqg6A5zA2E/iPHPhqnS8=
golang.org/x/exp/shiny v0.0.0-20250408133849-7e4ce0ab07d0 h1:tMSqXTK+AQdW3LpCbfatHSRPHeW6+2WuxaVQuHftn80=
golang.org/x/exp/shiny v0.0.0-20250408133849-7e4ce0ab07d0/go.mod h1:ygj7T6vSGhhm/9yTpOQQNvuAUFziTH7RUiH74EoE2C8=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.0.0-20200618115811-c13761719519/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.26.0 h1:4XjIFEZWQmCZi6Wv8BoxsDhRU3RVnLX04dToTDAEPlY=
golang.org/x/image v0.26.0/go.mod h1:lcxbMFAovzpnJxzXS3nyL83K27tmqtKzIJpctK8YO5c=
golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o=
golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200124204421-9fbb57f87de9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
golang.org/x/tools v0.0.0-20190927191325-030b2cf1153e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
-610
View File
@@ -1,610 +0,0 @@
package main
import (
"encoding/binary"
"fmt"
"image"
"image/color"
"log"
"os"
"path"
"runtime"
"sync"
"time"
"git.wow.st/gmp/ble"
"gopkg.in/yaml.v2"
"gioui.org/app"
"gioui.org/f32"
"gioui.org/layout"
"gioui.org/op"
"gioui.org/op/clip"
"gioui.org/op/paint"
"gioui.org/text"
"gioui.org/unit"
"gioui.org/widget"
"gioui.org/widget/material"
"gioui.org/font/gofont"
)
type (
D = layout.Dimensions
C = layout.Context
)
type conf struct {
Autoconnect string
}
var Config conf
var conffile string
var (
// bleMu guards bleView, scanPending and the UI state read by the
// frame handler and written by the Bluetooth event goroutine.
bleMu sync.Mutex
bleView uintptr
scanPending bool
rendered bool
stopwatchRunning bool // live stopwatch on screen; needs continuous redraw
)
func main() {
conffile = path.Join(getConfDir(), "config.yml")
if _, err := os.Stat(conffile); os.IsNotExist(err) {
fd, err := os.Create(conffile)
if err != nil {
log.Fatal("Cannot create configuration file: ", err)
}
fd.Close()
}
confbytes, err := os.ReadFile(conffile)
if err != nil {
log.Fatal("Cannot read configuration file: ", err)
}
if err = yaml.UnmarshalStrict(confbytes, &Config); err != nil {
log.Fatal("Cannot parse configuration file: ", err)
}
go eventloop()
app.Main()
}
func saveConfig() {
confbytes, err := yaml.Marshal(&Config)
if err != nil {
log.Fatal("Cannot encode configuration: ", err)
}
err = os.WriteFile(conffile, confbytes, 0700)
}
func hrDecode(x []byte) int {
if len(x) < 4 {
return 0
}
flags := x[0]
if flags&0x80 != 0 { // uint16 format
return int(binary.BigEndian.Uint16(x[1:3]))
} else {
return int(x[1])
}
}
type Stopwatch struct {
lasttime time.Time
elapsed time.Time
running bool
startstopBtn *widget.Clickable
resetBtn *widget.Clickable
h, m, s int
}
// circleClip returns a clip operation for a circle of the given radius
// centered at center, approximated by four cubic Bézier curves.
//
// clip.Path.Cube takes control points relative to the current pen
// position. Starting at the right point and going clockwise, the
// control points for the first segment are (0,k), (k-r, r) and the end
// point is (-r, r); the other three segments follow by symmetry. The
// second control point of each segment sits k before the end point
// along the tangent, i.e. at (k-r) — not (k) — from the start along
// the tangential axis. With (k) the shape bulges out past the circle
// near the diagonal corners.
func circleClip(ops *op.Ops, center f32.Point, radius float32) clip.Op {
p := &clip.Path{}
p.Begin(ops)
k := radius * 0.5522847498
p.MoveTo(center.Add(f32.Point{X: radius}))
p.Cube(f32.Point{Y: k}, f32.Point{X: k - radius, Y: radius}, f32.Point{X: -radius, Y: radius})
p.Cube(f32.Point{X: -k}, f32.Point{X: -radius, Y: k - radius}, f32.Point{X: -radius, Y: -radius})
p.Cube(f32.Point{Y: -k}, f32.Point{X: radius - k, Y: -radius}, f32.Point{X: radius, Y: -radius})
p.Cube(f32.Point{X: k}, f32.Point{X: radius, Y: radius - k}, f32.Point{X: radius, Y: radius})
p.Close()
return clip.Outline{Path: p.End()}.Op()
}
func NewStopwatch() Stopwatch {
return Stopwatch{
startstopBtn: &widget.Clickable{},
resetBtn: &widget.Clickable{},
}
}
func eventloop() {
w := new(app.Window)
w.Option(
app.Size(unit.Dp(350), unit.Dp(600)),
app.Title("HRM"),
)
th := material.NewTheme()
th.Face = gofont.Collection()[0].Font.Typeface
th.TextSize = unit.Sp(fontSize)
var ops op.Ops
sysinset := &layout.Inset{}
resetSysinset := func(x app.Insets) {
sysinset.Top = x.Top
sysinset.Bottom = x.Bottom
sysinset.Left = x.Left
sysinset.Right = x.Right
}
margin := layout.UniformInset(unit.Dp(10))
b := ble.NewBLE()
// requestScan defers a scan to the worker goroutine, which checks the
// runtime permission (JNI on a dedicated attached thread) and starts
// the scan. Callers must hold bleMu.
requestScan := func() {
scanPending = true
}
state := "starting"
var hr int
var periph ble.Peripheral
var wide bool
periphs := make([]ble.Peripheral, 0)
btns := make([]*widget.Clickable, 0)
backBtn := &widget.Clickable{}
var page, offpage, scanpage, connpage, hrpage func(gtx C) D
f := &layout.Flex{Axis: layout.Vertical}
offpage = func(gtx C) D {
return f.Layout(gtx,
layout.Rigid(func(gtx C) D {
return material.Body1(th, "Heart Rate Monitor").Layout(gtx)
}),
layout.Rigid(func(gtx C) D {
return material.Body1(th, "Bluetooth is Powered Off").Layout(gtx)
}),
)
}
appname := func(gtx C) D {
return layout.Center.Layout(gtx, func(gtx C) D {
return material.Body1(th, "Heart Rate Monitor").Layout(gtx)
})
}
appstate := func(gtx C) D {
return layout.Center.Layout(gtx, func(gtx C) D {
return material.Body1(th, state).Layout(gtx)
})
}
periphname := func(gtx C) D {
return layout.Center.Layout(gtx, func(gtx C) D {
return material.Body1(th, periph.Name).Layout(gtx)
})
}
leftbar := func(gtx C) D {
f := &layout.Flex{Axis: layout.Vertical}
return f.Layout(gtx,
layout.Rigid(appname),
layout.Rigid(func(gtx C) D {
return material.Body1(th, "").Layout(gtx)
}),
layout.Rigid(appstate),
)
}
scanlist := func(gtx C) D {
lst := &layout.List{Axis: layout.Vertical}
return lst.Layout(gtx, len(periphs), func(gtx C, i int) D {
gtx.Constraints.Min.X = gtx.Constraints.Max.X
// Clicked must be called before Layout: in Gio v0.10 the
// Clickable consumes its click events during Layout, and a
// later Clicked call would never see them.
clicked := btns[i].Clicked(gtx)
ret := layout.UniformInset(unit.Dp(2)).Layout(gtx, func(gtx C) D {
return material.Button(th, btns[i], periphs[i].Name).Layout(gtx)
})
if clicked {
b.StopScan()
periph = periphs[i]
b.Connect(periph)
state = "connecting"
page = connpage
w.Invalidate()
}
return ret
})
}
scanpage = func(gtx C) D {
if wide {
f2 := &layout.Flex{Axis: layout.Horizontal}
return f2.Layout(gtx,
layout.Rigid(leftbar),
layout.Flexed(1, scanlist),
)
} else {
return f.Layout(gtx,
layout.Rigid(appname),
layout.Rigid(appstate),
layout.Rigid(scanlist),
)
}
}
connpage = func(gtx C) D {
return f.Layout(gtx,
layout.Rigid(appname),
layout.Rigid(appstate),
layout.Rigid(periphname),
layout.Rigid(func(gtx C) D {
clicked := backBtn.Clicked(gtx)
ret := material.Button(th, backBtn, "Cancel").Layout(gtx)
if clicked {
ble.CancelConnection(periph)
periphs = periphs[:0]
Config.Autoconnect = ""
saveConfig()
requestScan()
state = "scanning"
page = scanpage
w.Invalidate()
}
return ret
}),
)
}
hrcircle := func(gtx C) (int, D) {
var w, h1 float32
ret := layout.Center.Layout(gtx, func(gtx C) D {
blue := color.NRGBA{0x3f, 0x51, 0xb5, 255}
white := color.NRGBA{255, 255, 255, 255}
w, h1 = float32(gtx.Constraints.Max.X), float32(gtx.Constraints.Max.Y)
if w < h1 {
h1 = w
}
s2 := h1 * 0.9
p2a := f32.Point{(h1 - s2) / 2, (h1 - s2) / 2}
center := f32.Point{X: h1 / 2, Y: h1 / 2}
paint.FillShape(gtx.Ops, blue, circleClip(gtx.Ops, center, h1/2))
paint.FillShape(gtx.Ops, white, circleClip(gtx.Ops, center, h1*0.9/2))
op.Affine(f32.NewAffine2D(1, 0, p2a.X, 0, 1, p2a.Y)).Add(gtx.Ops)
gtx.Constraints.Max.X = int(s2)
gtx.Constraints.Max.Y = int(s2)
gtx.Constraints.Min.X = int(s2)
gtx.Constraints.Min.Y = int(s2)
l := material.H1(th, fmt.Sprintf("%d", hr))
l.Alignment = text.Middle
layout.Center.Layout(gtx, func(gtx C) D {
return l.Layout(gtx)
})
var ret D
ret.Size = image.Point{int(h1), int(h1)}
return ret
})
return int(h1), ret
}
sw := NewStopwatch()
stopwatch := func(gtx C) D {
// The live stopwatch needs continuous redraws; tell the worker.
stopwatchRunning = sw.running
startstoptxt := "start"
if sw.running {
sw.elapsed = sw.elapsed.Add(time.Since(sw.lasttime))
startstoptxt = "stop"
}
sw.lasttime = time.Now()
f := layout.Flex{Axis: layout.Vertical}
return f.Layout(gtx,
layout.Rigid(func(gtx C) D {
return layout.Center.Layout(gtx, func(gtx C) D {
gtx.Constraints.Max.X = 1e6
return material.H4(th, sw.elapsed.Format("15:04:05.00")).Layout(gtx)
})
}),
layout.Rigid(func(gtx C) D {
f2 := layout.Flex{Axis: layout.Horizontal}
gtx.Constraints.Min.Y = 100
startstopClicked := sw.startstopBtn.Clicked(gtx)
resetClicked := sw.resetBtn.Clicked(gtx)
ret := f2.Layout(gtx,
layout.Flexed(0.5, func(gtx C) D {
return layout.UniformInset(unit.Dp(2)).Layout(gtx, func(gtx C) D {
return material.Button(th, sw.startstopBtn, startstoptxt).Layout(gtx)
})
}),
layout.Flexed(0.5, func(gtx C) D {
return layout.UniformInset(unit.Dp(2)).Layout(gtx, func(gtx C) D {
return material.Button(th, sw.resetBtn, "reset").Layout(gtx)
})
}),
)
if startstopClicked {
if sw.running {
sw.running = false
} else {
sw.running = true
}
w.Invalidate()
}
if resetClicked {
sw.elapsed = time.Time{}
sw.running = false
w.Invalidate()
}
return ret
}),
)
}
swidth := new(int)
hrpage = func(gtx C) D {
backBtnClicked := backBtn.Clicked(gtx)
var ret, ret2 D
stopbtn := func(gtx C) D {
gtx.Constraints.Min.Y = 100
return layout.UniformInset(unit.Dp(2)).Layout(gtx, func(gtx C) D {
return material.Button(th, backBtn, "Disconnect").Layout(gtx)
})
}
if wide {
f2 := &layout.Flex{Axis: layout.Horizontal}
ret = f2.Layout(gtx,
layout.Flexed(0.4, func(gtx C) D {
f3 := &layout.Flex{Axis: layout.Vertical}
c1 := layout.Rigid(func(gtx C) D {
ret2 = appname(gtx)
*swidth = ret2.Size.X
return ret2
})
c2 := layout.Rigid(func(gtx C) D {
ret2 = periphname(gtx)
s2 := ret2.Size.X
if s2 > *swidth {
*swidth = s2
}
return ret2
})
var c3 layout.FlexChild
if gtx.Constraints.Max.X > 370 {
c3 = layout.Rigid(stopwatch)
} else {
c3 = layout.Rigid(func(gtx C) D {
return D{}
})
}
c4 := layout.Rigid(stopbtn)
return f3.Layout(gtx,
c1,
layout.Rigid(appstate),
c2,
layout.Flexed(1.0, func(gtx C) D {
return material.Body1(th, "").Layout(gtx)
}),
c3,
c4,
)
}),
layout.Flexed(0.6, func(gtx C) D {
_, ret := hrcircle(gtx)
return ret
}),
)
} else { // !wide
c1 := layout.Rigid(func(gtx C) D {
return layout.Center.Layout(gtx, func(gtx C) D {
gtx.Constraints.Min.X = *swidth
gtx.Constraints.Max.X = *swidth
return stopwatch(gtx)
})
})
//swheight := gtx.Dimensions.Size.Y
c2 := layout.Rigid(func(gtx C) D {
return layout.Center.Layout(gtx, func(gtx C) D {
gtx.Constraints.Min.X = *swidth
gtx.Constraints.Max.X = *swidth
return stopbtn(gtx)
})
})
if gtx.Constraints.Max.Y < 775 {
//gtx.Constraints.Max.Y += swheight
ret = f.Layout(gtx,
layout.Rigid(appname),
layout.Rigid(appstate),
layout.Rigid(periphname),
layout.Flexed(1.0, func(gtx C) D {
*swidth, ret2 = hrcircle(gtx)
return ret2
}),
c2,
)
} else {
ret = f.Layout(gtx,
layout.Rigid(appname),
layout.Rigid(appstate),
layout.Rigid(periphname),
layout.Flexed(1.0, func(gtx C) D {
*swidth, ret2 = hrcircle(gtx)
return ret2
}),
c1,
c2,
)
}
}
if backBtnClicked {
ble.Disconnect(periph)
periphs = periphs[:0]
Config.Autoconnect = ""
saveConfig()
requestScan()
state = "scanning"
page = scanpage
w.Invalidate()
}
return ret
}
page = offpage
// Worker: start any scan that was deferred waiting for the runtime
// permission grant, and drive the live stopwatch animation.
//
// There is no fixed redraw rate: everything else is event-driven
// (Bluetooth events and clicks call w.Invalidate). The permission
// check is a binder call, so it is only made while a scan is
// actually pending, and at most a few times per second.
//
// This goroutine is pinned to its OS thread and attached to the JVM
// exactly once for the life of the app (see jvmReady): repeated
// attach/detach of a Go thread eventually stack-overflows the
// Java side. Running b.Scan from the same thread also keeps ble's
// runInJVM from attaching/detaching on its own.
go func() {
runtime.LockOSThread()
t := time.NewTicker(time.Second / 30)
tick := 0
for range t.C {
tick++
if !jvmReady() {
// JVM not up yet; retry next tick.
continue
}
bleMu.Lock()
if scanPending && rendered && tick%10 == 0 && scanPermGranted(bleView) {
scanPending = false
b.Scan()
}
// Redraw at 30 FPS until the first frame has actually been
// produced: invalidations before the surface is ready are lost,
// and nothing else may arrive if no Bluetooth events flow.
invalidate := stopwatchRunning || !rendered
bleMu.Unlock()
if invalidate {
w.Invalidate()
}
}
}()
// Handle Bluetooth events off the render loop and mark the window
// dirty so a new frame is produced. Gio requires the window's event
// loop and Frame calls to happen in a single goroutine, so state
// shared with the frame handler is guarded by bleMu.
go func() {
for e := range b.Events() {
log.Print("<-b.Events")
bleMu.Lock()
switch e := e.(type) {
case ble.UpdateStateEvent:
fmt.Printf("UpdateState: %s\n", e.State)
state = e.State
if state != "powered on" {
periphs = periphs[:0]
page = offpage
} else {
if Config.Autoconnect != "" && b.Connect(ble.Peripheral{Identifier: Config.Autoconnect}) {
state = "connecting"
page = connpage
} else {
periphs = periphs[:0]
state = "scanning"
page = scanpage
requestScan()
}
}
case ble.DiscoverPeripheralEvent:
fmt.Printf("found %s (%s)\n", e.Peripheral.Name, e.Peripheral.Identifier)
periphs = append(periphs, e.Peripheral)
btns = append(btns, &widget.Clickable{})
if e.Peripheral.Identifier == Config.Autoconnect && b.Connect(e.Peripheral) {
state = "connecting"
page = connpage
}
case ble.ConnectEvent:
fmt.Printf("Connect event\n")
b.StopScan()
state = "connected"
periph = e.Peripheral
Config.Autoconnect = periph.Identifier
saveConfig()
e.Peripheral.DiscoverServices()
page = hrpage
case ble.ConnectTimeoutEvent:
fmt.Printf("Connect timeout\n")
state = "timeout"
periphs = periphs[:0]
page = scanpage
Config.Autoconnect = ""
saveConfig()
requestScan()
case ble.DiscoverServiceEvent:
fmt.Printf("DiscoverService %s\n", e.Gatt.UUID)
//if e.Gatt.UUID == "180D" {
if e.Gatt.IsHRM() {
fmt.Printf("Found HRM Service\n")
e.Peripheral.DiscoverCharacteristics(e.Service)
}
case ble.DiscoverCharacteristicEvent:
fmt.Printf("DiscoverCharacteristic %s\n", e.Gatt.UUID)
//if e.Gatt.UUID == "2A37" {
if e.Gatt.IsHRV() {
fmt.Printf("Found heart rate value\n")
e.Peripheral.SetNotifyValue(e.Characteristic)
}
case ble.UpdateValueEvent:
hr = hrDecode(e.Data)
}
bleMu.Unlock()
w.Invalidate() // refresh on any Bluetooth event
}
}()
// The render loop. Gio requires Event and Frame to be driven from
// one goroutine.
for {
switch e := w.Event().(type) {
case app.DestroyEvent:
os.Exit(0)
case app.FrameEvent:
bleMu.Lock()
rendered = true
stopwatchRunning = false // set by the stopwatch layout if drawn
gtx := app.NewContext(&ops, e)
if e.Size.X > e.Size.Y {
wide = true
} else {
wide = false
}
resetSysinset(e.Insets)
sysinset.Layout(gtx, func(gtx C) D {
return margin.Layout(gtx, page)
})
bleMu.Unlock()
e.Frame(gtx.Ops)
default:
handleEvent(e, b, w)
}
}
}
-41
View File
@@ -1,41 +0,0 @@
package main
import (
"log"
"gioui.org/app"
"gioui.org/io/event"
"git.wow.st/gmp/ble"
)
var confDir string
var fontSize float32 = 24
func getConfDir() string {
if confDir == "" {
var err error
confDir, err = app.DataDir()
if err != nil {
log.Fatal("Cannot get configuration directory")
}
}
return confDir
}
func handleEvent(e event.Event, b *ble.BLE, w *app.Window) {
switch e := e.(type) {
case app.AndroidViewEvent:
b.Enable(e.View)
bleMu.Lock()
bleView = e.View
bleMu.Unlock()
// The runtime permission is requested by BlessedConnect.onAttach;
// the worker goroutine starts the pending scan once the grant is
// observed. Invalidate for the first frame: nothing else redraws
// until a Bluetooth or input event arrives.
if e.Valid() {
w.Invalidate()
}
}
}
-15
View File
@@ -1,15 +0,0 @@
//go:build !android
package main
import (
"gioui.org/io/event"
"git.wow.st/gmp/ble"
)
func handleEvent(e event.Event, b *ble.BLE, w *app.Window) {
}
// Non-Android platforms have no runtime BLE permission gate.
func jvmReady() bool { return true }
func scanPermGranted(view uintptr) bool { return true }
-123
View File
@@ -1,123 +0,0 @@
//go:build android
package main
/*
#include <jni.h>
#include <android/log.h>
// JNIEnv/JavaVM accessors (the JNI macros are not visible to cgo).
static jint hrm_getenv(JavaVM *vm, JNIEnv **env) {
return (*vm)->GetEnv(vm, (void **)env, JNI_VERSION_1_6);
}
static jint hrm_attach(JavaVM *vm, JNIEnv **env) {
return (*vm)->AttachCurrentThread(vm, (void **)env, 0);
}
static jobject hrm_context(JNIEnv *env, jobject view) {
jclass cls = (*env)->GetObjectClass(env, view);
jmethodID m = (*env)->GetMethodID(env, cls, "getContext", "()Landroid/content/Context;");
return (*env)->CallObjectMethod(env, view, m);
}
static int hrm_sdk(JNIEnv *env) {
jclass b = (*env)->FindClass(env, "android/os/Build$VERSION");
jfieldID f = (*env)->GetStaticFieldID(env, b, "SDK_INT", "I");
return (*env)->GetStaticIntField(env, b, f);
}
// Returns 1 if the given permission is granted to ctx, 0 otherwise.
// checkSelfPermission requires API 23; on older devices permissions were
// granted at install time, so report granted.
static int hrm_perm_granted(JNIEnv *env, jobject ctx, const char *perm) {
jclass cls = (*env)->GetObjectClass(env, ctx);
jmethodID m = (*env)->GetMethodID(env, cls, "checkSelfPermission", "(Ljava/lang/String;)I");
if (m == 0) {
(*env)->ExceptionClear(env);
return 1;
}
jstring s = (*env)->NewStringUTF(env, perm);
int r = (*env)->CallIntMethod(env, ctx, m, s);
(*env)->DeleteLocalRef(env, s);
if ((*env)->ExceptionOccurred(env)) {
(*env)->ExceptionClear(env);
return 0;
}
return r == 0;
}
// Returns 1 if the permission required to scan is currently granted.
// The request itself is made by BlessedConnect.onAttach (see the ble
// package); this only observes the result.
static int hrm_scan_perm_granted(JNIEnv *env, jobject view) {
jobject ctx = hrm_context(env, view);
if (ctx == 0) {
return 0;
}
int sdk = hrm_sdk(env);
const char *perm;
if (sdk >= 31) {
perm = "android.permission.BLUETOOTH_SCAN";
} else {
perm = "android.permission.ACCESS_FINE_LOCATION";
}
int r = hrm_perm_granted(env, ctx, perm);
(*env)->DeleteLocalRef(env, ctx);
return r;
}
*/
import "C"
import (
"unsafe"
"gioui.org/app"
)
// workerEnv is the JNIEnv of the pinned worker OS thread. It is written
// exactly once (on that thread) and read only there.
var workerEnv *C.JNIEnv
// jvmReady attaches the current OS thread to the JVM, once, and reports
// whether a JNIEnv is available.
//
// The worker must call this from a pinned goroutine (runtime.LockOSThread)
// and must NEVER detach: ART allocates the Java-side stack at first attach
// based on the thread's stack pointer at that moment. Repeatedly
// attaching/detaching a Go OS thread (whose stack is managed by the Go
// runtime) eventually leaves the Java stack exhausted and the next JNI
// call dies with "No pending exception expected:
// java.lang.StackOverflowError".
//
// As a side effect, calling ble.BLE methods from this same thread makes
// ble's own runInJVM skip its attach/detach (GetEnv already succeeds).
func jvmReady() bool {
if workerEnv != nil {
return true
}
if app.JavaVM() == 0 {
return false
}
vm := (*C.JavaVM)(unsafe.Pointer(app.JavaVM()))
var env *C.JNIEnv
if C.hrm_getenv(vm, &env) == 0 {
// Already attached (e.g. this is the UI thread).
workerEnv = env
return true
}
if C.hrm_attach(vm, &env) != 0 {
return false
}
workerEnv = env
return true
}
// scanPermGranted reports whether the runtime permission needed for
// Bluetooth scanning is currently granted. Call from the worker.
func scanPermGranted(view uintptr) bool {
if view == 0 || !jvmReady() {
return false
}
return C.hrm_scan_perm_granted(workerEnv, C.jobject(view)) == 1
}
+275
View File
@@ -0,0 +1,275 @@
package main
import (
"encoding/binary"
"fmt"
"io/ioutil"
"log"
"os"
"path"
"git.wow.st/gmp/ble"
"gopkg.in/yaml.v2"
"gioui.org/app"
"gioui.org/io/system"
"gioui.org/layout"
"gioui.org/text"
"gioui.org/unit"
"gioui.org/widget"
"gioui.org/widget/material"
"gioui.org/font/gofont"
)
type conf struct {
Autoconnect string
}
var Config conf
var conffile string
func main() {
conffile = path.Join(getConfDir(), "config.yml")
if _, err := os.Stat(conffile); os.IsNotExist(err) {
fd, err := os.Create(conffile)
if err != nil {
log.Fatal("Cannot create configuration file: ", err)
}
fd.Close()
}
confbytes, err := ioutil.ReadFile(conffile)
if err != nil {
log.Fatal("Cannot read configuration file: ", err)
}
if err = yaml.UnmarshalStrict(confbytes, &Config); err != nil {
log.Fatal("Cannot parse configuration file: ", err)
}
go eventloop()
app.Main()
}
func saveConfig() {
confbytes, err := yaml.Marshal(&Config)
if err != nil {
log.Fatal("Cannot encode configuration: ", err)
}
err = ioutil.WriteFile(conffile, confbytes, 0700)
}
func hrDecode(x []byte) int {
if len(x) < 4 {
return 0
}
flags := x[0]
if flags&0x80 != 0 { // uint16 format
return int(binary.BigEndian.Uint16(x[1:3]))
} else {
return int(x[1])
}
}
func eventloop() {
w := app.NewWindow(
app.Size(unit.Dp(400), unit.Dp(400)),
app.Title("HRM"),
)
gofont.Register()
th := material.NewTheme()
th.TextSize = unit.Sp(fontSize)
gtx := &layout.Context{Queue: w.Queue()}
sysinset := &layout.Inset{}
resetSysinset := func(x system.Insets) {
sysinset.Top = x.Top
sysinset.Bottom = x.Bottom
sysinset.Left = x.Left
sysinset.Right = x.Right
}
margin := layout.UniformInset(unit.Dp(10))
b := ble.NewBLE()
b.Enable(w)
state := "starting"
var hr int
var periph ble.Peripheral
periphs := make([]ble.Peripheral, 0)
btns := make([]*widget.Button, 0)
backBtn := &widget.Button{}
var page, offpage, scanpage, connpage, hrpage func()
f := &layout.Flex{Axis: layout.Vertical}
offpage = func() {
c1 := f.Rigid(gtx, func() {
th.Body1("Heart Rate Monitor").Layout(gtx)
})
c2 := f.Rigid(gtx, func() {
th.Body1("Bluetooth is Powered Off").Layout(gtx)
})
f.Layout(gtx, c1, c2)
}
scanpage = func() {
c1 := f.Rigid(gtx, func() {
th.Body1("Heart Rate Monitor").Layout(gtx)
})
c2 := f.Rigid(gtx, func() {
th.Body1(state).Layout(gtx)
})
c3 := f.Rigid(gtx, func() {
lst := &layout.List{Axis: layout.Vertical}
lst.Layout(gtx, len(periphs), func(i int) {
gtx.Constraints.Width.Min = gtx.Constraints.Width.Max
layout.UniformInset(unit.Dp(2)).Layout(gtx, func() {
th.Button(periphs[i].Name).Layout(gtx, btns[i])
})
if btns[i].Clicked(gtx) {
b.StopScan()
periph = periphs[i]
b.Connect(periph)
state = "connecting"
page = connpage
w.Invalidate()
}
})
})
f.Layout(gtx, c1, c2, c3)
}
connpage = func() {
c1 := f.Rigid(gtx, func() {
th.Body1("Heart Rate Monitor").Layout(gtx)
})
c2 := f.Rigid(gtx, func() {
th.Body1("Connecting").Layout(gtx)
})
c3 := f.Rigid(gtx, func() {
th.Body1(periph.Name).Layout(gtx)
})
c4 := f.Rigid(gtx, func() {
th.Button("Cancel").Layout(gtx, backBtn)
if backBtn.Clicked(gtx) {
ble.CancelConnection(periph)
periphs = periphs[:0]
Config.Autoconnect = ""
saveConfig()
b.Scan()
state = "scanning"
page = scanpage
}
})
f.Layout(gtx, c1, c2, c3, c4)
}
hrpage = func() {
c1 := f.Rigid(gtx, func() {
th.Body1("Heart Rate Monitor").Layout(gtx)
})
c2 := f.Rigid(gtx, func() {
th.Body1(periph.Name).Layout(gtx)
})
c3 := f.Rigid(gtx, func() {
l := th.H1(fmt.Sprintf("%d", hr))
l.Alignment = text.Middle
l.Layout(gtx)
})
c4 := f.Rigid(gtx, func() {
th.Button("Stop").Layout(gtx, backBtn)
if backBtn.Clicked(gtx) {
ble.Disconnect(periph)
periphs = periphs[:0]
Config.Autoconnect = ""
saveConfig()
b.Scan()
state = "scanning"
page = scanpage
}
})
f.Layout(gtx, c1, c2, c3, c4)
}
page = offpage
for {
select {
case e := <-b.Events():
switch e := e.(type) {
case ble.UpdateStateEvent:
fmt.Printf("UpdateState: %s\n", e.State)
state = e.State
if state != "powered on" {
periphs = periphs[:0]
page = offpage
} else {
if Config.Autoconnect != "" && b.Connect(ble.Peripheral{Identifier: Config.Autoconnect}) {
state = "connecting"
page = connpage
} else {
periphs = periphs[:0]
state = "scanning"
page = scanpage
b.Scan()
}
}
case ble.DiscoverPeripheralEvent:
fmt.Printf("found %s (%s)\n", e.Peripheral.Name, e.Peripheral.Identifier)
periphs = append(periphs, e.Peripheral)
btns = append(btns, &widget.Button{})
if e.Peripheral.Identifier == Config.Autoconnect && b.Connect(e.Peripheral) {
state = "connecting"
page = connpage
}
case ble.ConnectEvent:
fmt.Printf("Connect event\n")
b.StopScan()
state = "connected"
periph = e.Peripheral
Config.Autoconnect = periph.Identifier
saveConfig()
e.Peripheral.DiscoverServices()
page = hrpage
case ble.ConnectTimeoutEvent:
fmt.Printf("Connect timeout\n")
state = "timeout"
periphs = periphs[:0]
page = scanpage
Config.Autoconnect = ""
saveConfig()
b.Scan()
case ble.DiscoverServiceEvent:
fmt.Printf("DiscoverService %s\n", e.Gatt.UUID)
//if e.Gatt.UUID == "180D" {
if e.Gatt.IsHRM() {
fmt.Printf("Found HRM Service\n")
e.Peripheral.DiscoverCharacteristics(e.Service)
}
case ble.DiscoverCharacteristicEvent:
fmt.Printf("DiscoverCharacteristic %s\n", e.Gatt.UUID)
//if e.Gatt.UUID == "2A37" {
if e.Gatt.IsHRV() {
fmt.Printf("Found heart rate value\n")
e.Peripheral.SetNotifyValue(e.Characteristic)
}
case ble.UpdateValueEvent:
hr = hrDecode(e.Data)
}
w.Invalidate() // refresh on any Bluetooth event
case e := <-w.Events():
switch e := e.(type) {
case system.DestroyEvent:
return
case system.FrameEvent:
gtx.Reset(e.Config, e.Size)
resetSysinset(e.Insets)
sysinset.Layout(gtx, func() {
margin.Layout(gtx, page)
})
e.Frame(gtx.Ops)
}
}
}
}
+21
View File
@@ -0,0 +1,21 @@
package main
import (
"log"
"gioui.org/app"
)
var confDir string
var fontSize float32 = 24
func getConfDir() string {
if confDir == "" {
var err error
confDir,err = app.DataDir()
if err != nil {
log.Fatal("Cannot get configuration directory")
}
}
return confDir
}
View File
-110
View File
@@ -1,110 +0,0 @@
#!/usr/bin/env bash
# Build (and optionally install) the HRM Android APK.
#
# Usage:
# ./scripts/build.sh [phone|emu] # build + install (default: phone)
# ./scripts/build.sh phone --no-install # build only
#
# Output: hrm/hrm.apk
#
# Prereqs on this workstation (the script checks each and explains what is
# missing):
# - JDK (java on PATH)
# - Go + gogio v0.10.0 (~/go/bin)
# - Android SDK at ~/android-sdk (platform-tools, build-tools 35.0.0,
# NDK for gogio)
# - debug keystore at ~/.android/debug.keystore
# apktool is not a prerequisite: if it is missing, the script downloads
# v3.0.3 to the stable location ~/android-sdk/tools/apktool.jar.
#
# Why the apktool detour: gogio's manifest permissions come from a hardcoded
# table and only declare the pre-Android-12 BLUETOOTH/BLUETOOTH_ADMIN
# permissions. With targetSdk 31+ those are no-ops and BLE needs the
# runtime permissions BLUETOOTH_SCAN and BLUETOOTH_CONNECT declared in the
# manifest. So we decode the gogio APK, inject the two permissions into
# AndroidManifest.xml, rebuild, and re-sign with the debug key. (The
# runtime request and scan gating are implemented in Go: see
# hrm/perm_android.go.)
set -euo pipefail
REPO=$(cd "$(dirname "$0")/.." && pwd)
export ANDROID_HOME=${ANDROID_HOME:-$HOME/android-sdk}
export PATH=$PATH:$ANDROID_HOME/platform-tools:$ANDROID_HOME/build-tools/35.0.0:$HOME/go/bin
MODE=${1:-phone}
INSTALL=1
[ "${2:-}" = "--no-install" ] && INSTALL=0
case "$MODE" in
phone) ARCH="arm64,arm";;
emu) ARCH="amd64";;
*) echo "usage: $0 [phone|emu] [--no-install]" >&2; exit 1;;
esac
die() { echo "ERROR: $*" >&2; exit 1; }
command -v java >/dev/null 2>&1 || die "java not found"
command -v gogio >/dev/null 2>&1 || die "gogio not found (need v0.10.0 in ~/go/bin)"
command -v apksigner >/dev/null 2>&1 || die "apksigner not found (need $ANDROID_HOME/build-tools/35.0.0)"
command -v adb >/dev/null 2>&1 || die "adb not found (need $ANDROID_HOME/platform-tools)"
[ -f "$HOME/.android/debug.keystore" ] || die "debug keystore missing: $HOME/.android/debug.keystore"
# apktool: auto-download to a stable location if missing.
APKTOOL="$ANDROID_HOME/tools/apktool.jar"
if [ ! -f "$APKTOOL" ]; then
echo "=== apktool missing; downloading v3.0.3 to $APKTOOL ==="
mkdir -p "$ANDROID_HOME/tools"
curl -fsSL -o "$APKTOOL" \
https://github.com/iBotPeaches/Apktool/releases/download/v3.0.3/apktool_3.0.3.jar \
|| die "apktool download failed"
fi
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
echo "=== gogio (Go -> APK) ==="
# targetSdk 34: targeting 35 makes Android 15 force edge-to-edge, which the
# app does not handle.
(cd "$REPO/hrm" && gogio -target android -targetsdk 34 -arch "$ARCH" -o "$WORK/hrm-raw.apk" .)
[ -f "$WORK/hrm-raw.apk" ] || die "gogio did not produce an APK"
echo "=== apktool decode + inject BLE permissions ==="
# gogio's manifest permissions come from a hardcoded table and only declare
# the pre-Android-12 permissions; the runtime permission logic itself lives
# in the Go code (hrm/perm_android.go).
java -jar "$APKTOOL" d "$WORK/hrm-raw.apk" -o "$WORK/decoded" -f >/dev/null
python3 - "$WORK/decoded/AndroidManifest.xml" << 'PYEOF'
import sys, pathlib
p = pathlib.Path(sys.argv[1])
t = p.read_text()
perms = [
'<uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation"/>',
'<uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>',
]
for perm in perms:
if perm not in t:
t = t.replace(" <application", " " + perm + "\n <application", 1)
if perm not in t:
sys.exit("ERROR: failed to inject " + perm)
p.write_text(t)
print("manifest: BLUETOOTH_SCAN + BLUETOOTH_CONNECT present")
PYEOF
echo "=== apktool rebuild ==="
java -jar "$APKTOOL" b "$WORK/decoded" -o "$WORK/hrm-unsigned.apk" >/dev/null
echo "=== sign ==="
apksigner sign \
--ks "$HOME/.android/debug.keystore" --ks-pass pass:android \
--key-pass pass:android --ks-key-alias androiddebugkey \
--out "$REPO/hrm/hrm.apk" "$WORK/hrm-unsigned.apk"
# ADB_SERIAL selects the device when several are attached (adb devices).
ADB="adb${ADB_SERIAL:+ -s $ADB_SERIAL}"
if [ "$INSTALL" = "1" ]; then
echo "=== install ==="
$ADB get-state >/dev/null 2>&1 || die "no adb device (start the emulator or plug in a phone; set ADB_SERIAL if several are attached)"
$ADB install -r "$REPO/hrm/hrm.apk"
fi
echo "=== DONE: $REPO/hrm/hrm.apk ==="