This repository has been archived on 2024-08-02. You can view files and clone it, but cannot push or open issues or pull requests.
orion/emlid/discovery.go

58 lines
942 B
Go

package emlid
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
}