Read autoconnect ID out of configuration file, save config file

on any change to autoconnect ID.
This commit is contained in:
Greg 2019-10-25 13:29:16 -04:00
parent 45863ab212
commit a123228e30
1 changed files with 20 additions and 9 deletions

29
main.go
View File

@ -25,12 +25,14 @@ import (
)
type conf struct {
Autoconnect string
}
var Config conf
var conffile string
func main() {
conffile := path.Join(confDir, "config.yml")
conffile = path.Join(confDir, "config.yml")
if _, err := os.Stat(conffile); os.IsNotExist(err) {
fd, err := os.Create(conffile)
if err != nil {
@ -50,6 +52,14 @@ func main() {
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 {
flags := x[0]
if flags&0x80 != 0 { // uint16 format
@ -84,9 +94,6 @@ func eventloop() {
periphs := make([]ble.Peripheral, 0)
btns := make([]*widget.Button, 0)
var autoconnectID string // should load from config file
//autoconnectID = "93D3A64F-1664-497D-8B01-77951DB8E0F3"
var page, offpage, scanpage, connpage, hrpage func()
f := &layout.Flex{Axis: layout.Vertical}
@ -166,10 +173,10 @@ func eventloop() {
page = offpage
} else {
if autoconnectID != "" {
b.Connect(ble.Peripheral{Identifier: autoconnectID})
if Config.Autoconnect != "" && b.Connect(ble.Peripheral{Identifier: Config.Autoconnect}) {
page = connpage
} else {
periphs = periphs[:0]
page = scanpage
b.Scan()
}
@ -178,20 +185,24 @@ func eventloop() {
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 == autoconnectID {
b.Connect(e.Peripheral)
if e.Peripheral.Identifier == Config.Autoconnect && b.Connect(e.Peripheral) {
page = connpage
}
case ble.ConnectEvent:
fmt.Printf("Connect event\n")
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"
autoconnectID = ""
periphs = periphs[:0]
page = scanpage
Config.Autoconnect = ""
saveConfig()
b.Scan()
case ble.DiscoverServiceEvent:
fmt.Printf("DiscoverService %s\n", e.Gatt.UUID)