64 lines
1.3 KiB
Go
64 lines
1.3 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"net"
|
|
"time"
|
|
|
|
"github.com/grandcat/zeroconf"
|
|
"golang.org/x/net/context"
|
|
)
|
|
|
|
type Device struct {
|
|
IP net.IP
|
|
Name string
|
|
}
|
|
|
|
func discoverHueBridge() ([]Device, error) {
|
|
// Create a new resolver
|
|
resolver, err := zeroconf.NewResolver(nil)
|
|
if err != nil {
|
|
log.Fatalf("Failed to initialize resolver: %v", err)
|
|
}
|
|
|
|
// Instantiate a new devices slice
|
|
devices := make([]Device, 0)
|
|
|
|
// Set up a context with a timeout
|
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
|
|
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 {
|
|
devices = append(devices, Device{IP: entry.AddrIPv4[0], Name: entry.HostName})
|
|
}
|
|
}()
|
|
|
|
// Wait for the context to expire
|
|
<-ctx.Done()
|
|
fmt.Println("mDNS query finished")
|
|
fmt.Printf("Number of devices found: %d\n", len(devices))
|
|
for _, device := range devices {
|
|
fmt.Printf("Device: %s\n", device.Name)
|
|
fmt.Printf("IP Address: %s\n", device.IP)
|
|
}
|
|
return devices, nil
|
|
}
|
|
|
|
func main() {
|
|
discoverHueBridge()
|
|
}
|