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

71 lines
1.0 KiB
Go

package emlid
import (
"net"
"sync"
"time"
"github.com/oleksandr/bonjour"
)
// 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(timeout time.Duration) ([]Service, error) {
var wg sync.WaitGroup
wg.Add(1)
resolver, err := bonjour.NewResolver(nil)
if err != nil {
return nil, err
}
services := make([]Service, 0)
entries := make(chan *bonjour.ServiceEntry)
timer := time.NewTimer(timeout)
defer timer.Stop()
stop := func() {
resolver.Exit <- true
wg.Done()
}
go func() {
for {
select {
case e, ok := <-entries:
if !ok {
stop()
return
}
services = append(services, Service{
Name: e.Instance,
AddrV4: e.AddrIPv4,
Port: e.Port,
})
case <-timer.C:
stop()
return
}
}
}()
if err = resolver.Browse("_reach._tcp", ".local", entries); err != nil {
return nil, err
}
wg.Wait()
return services, nil
}