2018-10-09 14:05:38 +02:00
|
|
|
package emlid
|
|
|
|
|
|
|
|
import (
|
2018-10-16 15:23:16 +02:00
|
|
|
"context"
|
2018-10-09 14:05:38 +02:00
|
|
|
"net"
|
|
|
|
"sync"
|
|
|
|
|
2018-10-16 15:23:16 +02:00
|
|
|
"github.com/grandcat/zeroconf"
|
2018-10-09 14:05:38 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
// Service is a ReachRS service discovered via MDNS-SD
|
|
|
|
type Service struct {
|
|
|
|
Name string
|
2018-10-16 15:23:16 +02:00
|
|
|
AddrV4 *net.IP
|
2018-10-09 14:05:38 +02:00
|
|
|
Port int
|
|
|
|
}
|
|
|
|
|
2018-10-16 15:23:16 +02:00
|
|
|
// Discover tries to discover ReachRS services on the local network via mDNS-SD
|
|
|
|
func Discover(ctx context.Context) ([]Service, error) {
|
2018-10-09 14:05:38 +02:00
|
|
|
|
|
|
|
var wg sync.WaitGroup
|
|
|
|
|
|
|
|
wg.Add(1)
|
|
|
|
|
2018-10-16 15:23:16 +02:00
|
|
|
resolver, err := zeroconf.NewResolver(nil)
|
2018-10-09 14:05:38 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
services := make([]Service, 0)
|
2018-10-16 15:23:16 +02:00
|
|
|
entries := make(chan *zeroconf.ServiceEntry)
|
2018-10-09 14:05:38 +02:00
|
|
|
|
|
|
|
go func() {
|
2018-10-16 15:23:16 +02:00
|
|
|
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,
|
2018-10-09 14:05:38 +02:00
|
|
|
}
|
2018-10-16 15:23:16 +02:00
|
|
|
services = append(services, srv)
|
2018-10-09 14:05:38 +02:00
|
|
|
}
|
2018-10-16 15:23:16 +02:00
|
|
|
wg.Done()
|
2018-10-09 14:05:38 +02:00
|
|
|
}()
|
|
|
|
|
2018-10-16 15:23:16 +02:00
|
|
|
if err = resolver.Browse(ctx, "_reach._tcp", ".local", entries); err != nil {
|
2018-10-09 14:05:38 +02:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
wg.Wait()
|
|
|
|
|
|
|
|
return services, nil
|
|
|
|
|
|
|
|
}
|