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 package main
import ( import (
"bufio"
"bytes" "bytes"
"fmt" "fmt"
"io" "io"
"log" "log"
"net" "net"
"net/http" "net/http"
"os"
"strings"
"time" "time"
"github.com/grandcat/zeroconf" "github.com/grandcat/zeroconf"
@ -75,24 +78,50 @@ func registerApplication(bridge Bridge) RegisteredApplication {
fmt.Scan(&applicationName) fmt.Scan(&applicationName)
fmt.Printf("Enter name of your device: ") fmt.Printf("Enter name of your device: ")
fmt.Scan(&deviceName) 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 { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil { if err != nil {
log.Fatal(err) 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{ registeredApplication := RegisteredApplication{
bridge: bridge, bridge: bridge,
applicationName: applicationName, applicationName: applicationName,
deviceName: deviceName, deviceName: deviceName,
token: string(body)} token: string(body)}
fmt.Println(registeredApplication) resp.Body.Close()
return registeredApplication return registeredApplication
} }
func main() { 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)
} }