Fix Reach services discovery

- Use github.com/grandcat/zeroconf lib instead of github.com/oleksandr/bonjour
This commit is contained in:
2018-10-16 15:23:16 +02:00
parent 9bd20331ef
commit 187d53fd29
5 changed files with 77 additions and 42 deletions

View File

@ -1,65 +1,52 @@
package emlid
import (
"context"
"net"
"sync"
"time"
"github.com/oleksandr/bonjour"
"github.com/grandcat/zeroconf"
)
// Service is a ReachRS service discovered via MDNS-SD
type Service struct {
Name string
AddrV4 net.IP
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) {
// 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 := bonjour.NewResolver(nil)
resolver, err := zeroconf.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()
}
entries := make(chan *zeroconf.ServiceEntry)
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
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("_reach._tcp", ".local", entries); err != nil {
if err = resolver.Browse(ctx, "_reach._tcp", ".local", entries); err != nil {
return nil, err
}

View File

@ -1,6 +1,7 @@
package emlid
import (
"context"
"testing"
"time"
)
@ -11,7 +12,10 @@ func TestDiscovery(t *testing.T) {
t.Skip("To run this test, use: go test -discovery-integration")
}
services, err := Discover(3 * time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
services, err := Discover(ctx)
if err != nil {
t.Fatal(err)
}