From ae11219aafd66144ae269687f6fb9233022aa097 Mon Sep 17 00:00:00 2001 From: christian Date: Wed, 17 Jul 2024 21:28:23 +0200 Subject: [PATCH] added more registration and wait on user to press button --- huego.go | 37 +++++++++++++++++++++++++++++++++---- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/huego.go b/huego.go index de92ba4..80a29db 100644 --- a/huego.go +++ b/huego.go @@ -1,12 +1,15 @@ package main import ( + "bufio" "bytes" "fmt" "io" "log" "net" "net/http" + "os" + "strings" "time" "github.com/grandcat/zeroconf" @@ -75,24 +78,50 @@ func registerApplication(bridge Bridge) RegisteredApplication { fmt.Scan(&applicationName) fmt.Printf("Enter name of your device: ") fmt.Scan(&deviceName) - resp, err := http.Post("http://"+bridge.IP.String()+"/api", "application/json", bytes.NewBuffer([]byte(`{"devicetype:`+applicationName+` #`+deviceName+`"}`))) + resp, err := http.Post( + "http://"+bridge.IP.String()+"/api", + "application/json", + bytes.NewBuffer([]byte(`{"devicetype":"`+applicationName+`#`+deviceName+`"}`))) if err != nil { log.Fatal(err) } - defer resp.Body.Close() body, err := io.ReadAll(resp.Body) + defer resp.Body.Close() if err != nil { log.Fatal(err) } + // if body has link button not pressed, tell user to press it then send the request again to register the application + if strings.Contains(string(body), "link button not pressed") { + fmt.Println("Link button not pressed. Press link button on bridge and press anter to continue.") + bufio.NewReader(os.Stdin).ReadBytes('\n') + resp.Body.Close() + http.Post( + "http://"+bridge.IP.String()+"/api", + "application/json", + bytes.NewBuffer([]byte(`{"devicetype":"`+applicationName+`#`+deviceName+`"}`))) + body, err = io.ReadAll(resp.Body) + if err != nil { + log.Fatal(err) + } + } registeredApplication := RegisteredApplication{ bridge: bridge, applicationName: applicationName, deviceName: deviceName, token: string(body)} - fmt.Println(registeredApplication) + resp.Body.Close() return registeredApplication } func main() { - + bridges, err := discoverHueBridge() + if err != nil { + log.Fatal(err) + } + registeredApplications := make([]RegisteredApplication, 0) + for _, bridge := range bridges { + newApplication := registerApplication(bridge) + registeredApplications = append(registeredApplications, newApplication) + } + fmt.Println(registeredApplications) }