go-emlid/reach/discovery/discovery.go

57 lines
945 B
Go
Raw Normal View History

2024-07-30 14:28:39 +02:00
package discovery
import (
"context"
"net"
"sync"
"github.com/grandcat/zeroconf"
)
// Service is a ReachRS service discovered via MDNS-SD
type Service struct {
Name string
AddrV4 *net.IP
Port int
}
// Discover tries to discover ReachRS services on the local network via mDNS-SD
func Discover(ctx context.Context) ([]Service, error) {
var wg sync.WaitGroup
wg.Add(1)
resolver, err := zeroconf.NewResolver()
if err != nil {
return nil, err
}
services := make([]Service, 0)
entries := make(chan *zeroconf.ServiceEntry)
go func() {
for e := range entries {
var addr *net.IP
if len(e.AddrIPv4) > 0 {
addr = &e.AddrIPv4[0]
}
srv := Service{
Name: e.Instance,
AddrV4: addr,
Port: e.Port,
}
services = append(services, srv)
}
wg.Done()
}()
if err = resolver.Browse(ctx, "_reach._tcp", ".local", entries); err != nil {
return nil, err
}
wg.Wait()
return services, nil
}