From fe6e3d231b98a117da4f467b59ddc2e30effeb71 Mon Sep 17 00:00:00 2001 From: christian Date: Fri, 19 Jul 2024 20:07:07 +0200 Subject: [PATCH] authing the app works now, but the string needs to be trimmed --- huego.go | 64 +++++++++++++++++++++++++++++++++++++------------------- 1 file changed, 43 insertions(+), 21 deletions(-) diff --git a/huego.go b/huego.go index 80a29db..42f7116 100644 --- a/huego.go +++ b/huego.go @@ -3,6 +3,7 @@ package main import ( "bufio" "bytes" + "encoding/json" "fmt" "io" "log" @@ -74,42 +75,63 @@ func discoverHueBridge() ([]Bridge, error) { func registerApplication(bridge Bridge) RegisteredApplication { var applicationName string var deviceName string + var token string + fmt.Printf("Enter name of your application: ") 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+`"}`))) - if err != nil { - log.Fatal(err) - } - 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( + + for { + resp, err := 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) } + + body, err := io.ReadAll(resp.Body) + resp.Body.Close() + if err != nil { + log.Fatal(err) + } + + type Success struct { + Username string `json:"username"` + } + + if !strings.Contains(string(body), "link button not pressed") { + // Define a struct matching the expected JSON response structure + type SuccessResponse struct { + Success struct { + Username string `json:"username"` + } `json:"success"` + } + + // Unmarshal the response body into the struct + var successResponse []SuccessResponse + if err := json.Unmarshal(body, &successResponse); err != nil { + log.Fatalf("Error parsing response: %v", err) + } + + // Assign the username to the token + if len(successResponse) > 0 { + token = successResponse[0].Success.Username + } + break + } + + fmt.Println("Link button not pressed. Press link button on bridge and press Enter to continue.") + bufio.NewReader(os.Stdin).ReadBytes('\n') } + registeredApplication := RegisteredApplication{ bridge: bridge, applicationName: applicationName, deviceName: deviceName, - token: string(body)} - resp.Body.Close() + token: token, + } return registeredApplication }