added more registration and wait on user to press button

This commit is contained in:
christian 2024-07-17 21:28:23 +02:00
parent 8d63a2415c
commit ae11219aaf

View File

@ -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)
}