From a123228e30e15c22fb8a9331e763c28afa4a89c5 Mon Sep 17 00:00:00 2001 From: Greg Date: Fri, 25 Oct 2019 13:29:16 -0400 Subject: [PATCH] Read autoconnect ID out of configuration file, save config file on any change to autoconnect ID. --- main.go | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/main.go b/main.go index 1a05b84..5afc66f 100644 --- a/main.go +++ b/main.go @@ -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)