huego/huego.go

99 lines
2.2 KiB
Go
Raw Normal View History

2024-07-17 04:10:05 +00:00
package main
import (
"bytes"
2024-07-17 04:10:05 +00:00
"fmt"
"io"
2024-07-17 04:10:05 +00:00
"log"
2024-07-17 05:37:56 +00:00
"net"
"net/http"
2024-07-17 04:10:05 +00:00
"time"
"github.com/grandcat/zeroconf"
"golang.org/x/net/context"
)
type Bridge struct {
2024-07-17 05:37:56 +00:00
IP net.IP
Name string
}
2024-07-17 04:10:05 +00:00
type RegisteredApplication struct {
bridge Bridge
applicationName string
deviceName string
token string
}
func discoverHueBridge() ([]Bridge, error) {
2024-07-17 04:10:05 +00:00
// Create a new resolver
resolver, err := zeroconf.NewResolver(nil)
if err != nil {
log.Fatalf("Failed to initialize resolver: %v", err)
}
// Instantiate a new bridges slice
bridges := make([]Bridge, 0)
2024-07-17 05:37:56 +00:00
2024-07-17 04:10:05 +00:00
// Set up a context with a timeout
2024-07-17 05:37:56 +00:00
ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
2024-07-17 04:10:05 +00:00
defer cancel()
// Channel to recive the results
entries := make(chan *zeroconf.ServiceEntry)
// Start the lookup for the Hue Bridge
go func() {
err = resolver.Browse(ctx, "_hue._tcp", "local.", entries)
if err != nil {
log.Fatalf("Failed to browse for Hue Bridge: %v", err)
}
}()
// Process the results
go func() {
for entry := range entries {
bridges = append(bridges, Bridge{IP: entry.AddrIPv4[0], Name: entry.HostName})
2024-07-17 04:10:05 +00:00
}
}()
// Wait for the context to expire
<-ctx.Done()
fmt.Println("mDNS query finished")
fmt.Printf("Number of devices found: %d\n", len(bridges))
for _, device := range bridges {
2024-07-17 05:37:56 +00:00
fmt.Printf("Device: %s\n", device.Name)
fmt.Printf("IP Address: %s\n", device.IP)
}
return bridges, nil
}
func registerApplication(bridge Bridge) RegisteredApplication {
var applicationName string
var deviceName 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)
}
defer resp.Body.Close()
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)
return registeredApplication
2024-07-17 05:37:56 +00:00
}
func main() {
2024-07-17 04:10:05 +00:00
}