feat: initial commit
This commit is contained in:
56
reach/discovery/discovery.go
Normal file
56
reach/discovery/discovery.go
Normal file
@ -0,0 +1,56 @@
|
||||
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
|
||||
|
||||
}
|
53
reach/discovery/discovery_test.go
Normal file
53
reach/discovery/discovery_test.go
Normal file
@ -0,0 +1,53 @@
|
||||
package discovery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"regexp"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"forge.cadoles.com/cadoles/go-emlid/reach"
|
||||
)
|
||||
|
||||
func TestDiscovery(t *testing.T) {
|
||||
reach.AssertIntegrationTests(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
services, err := Discover(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if g, e := len(services), 1; g < e {
|
||||
t.Fatalf("len(services): got '%d', expected > %d", g, e)
|
||||
}
|
||||
|
||||
t.Logf("Found %d services", len(services))
|
||||
|
||||
patterns := []string{"reach", "Reach", "^RS.*"}
|
||||
|
||||
for i, s := range services {
|
||||
t.Logf("Service #%d: %s - %s:%d", i, s.Name, s.AddrV4.String(), s.Port)
|
||||
|
||||
matched := false
|
||||
|
||||
for _, p := range patterns {
|
||||
re, err := regexp.Compile(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if re.Match([]byte(s.Name)) {
|
||||
matched = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !matched {
|
||||
t.Errorf("services[%d].Name ('%s') to match on of '%v'", i, s.Name, patterns)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
Reference in New Issue
Block a user