Skip to content

Commit

Permalink
Adjustable timeout in speaker discovery
Browse files Browse the repository at this point in the history
  • Loading branch information
hilli committed Feb 25, 2024
1 parent 3fd0296 commit 88b4848
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
6 changes: 4 additions & 2 deletions cmd/kefw2/cmd/config_speaker.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ func init() {
speakerCmd.AddCommand(speakerSetDefaultCmd)
speakerCmd.AddCommand(speakerDiscoverCmd)
speakerDiscoverCmd.PersistentFlags().BoolP("save", "", false, "Save the discovered speakers to config file")
speakerDiscoverCmd.PersistentFlags().IntP("timeout", "t", 1, "Set the timeout for speaker discovery (seconds)")
}

var speakerDiscoverCmd = &cobra.Command{
Expand All @@ -33,14 +34,15 @@ var speakerDiscoverCmd = &cobra.Command{
Long: `Discover speakers with mDNS`,
Run: func(cmd *cobra.Command, args []string) {
save, _ := cmd.Flags().GetBool("save")
timeout, _ := cmd.Flags().GetInt("timeout")

newSpeakers, err := kefw2.DiscoverSpeakers()
newSpeakers, err := kefw2.DiscoverSpeakers(timeout)
if err != nil {
fmt.Println(err)
return
}
if len(newSpeakers) == 0 {
fmt.Println("No speakers found")
fmt.Println("No new speakers found")
return
}
for _, speaker := range newSpeakers {
Expand Down
21 changes: 16 additions & 5 deletions kefw2/discover.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ import (
"github.com/brutella/dnssd"
)

func DiscoverSpeakers() ([]KEFSpeaker, error) {
func DiscoverSpeakers(timeout int) ([]KEFSpeaker, error) {
discoveredSpeakers := []KEFSpeaker{}
ips, err := discoverIPs()
ips, err := discoverIPs(timeout)
if err != nil {
return discoveredSpeakers, err
}
Expand All @@ -20,13 +20,24 @@ func DiscoverSpeakers() ([]KEFSpeaker, error) {
}
discoveredSpeakers = append(discoveredSpeakers, speaker)
}

// Service Discovery may have the same speakers multiple times. Lets filter it down to single instance
found := map[string]KEFSpeaker{}
for _, s := range discoveredSpeakers {
found[s.IPAddress] = s
}
discoveredSpeakers = []KEFSpeaker{}
for _, s := range found {
discoveredSpeakers = append(discoveredSpeakers, s)
}

return discoveredSpeakers, nil
}

func discoverIPs() ([]string, error) {
func discoverIPs(timeout int) ([]string, error) {
ips := []string{}
waitForDiscoveryTimeout := 1 * time.Second
discoveryTimeout := 1 * time.Second
waitForDiscoveryTimeout := time.Duration(timeout) * time.Second
discoveryTimeout := time.Duration(timeout) * time.Second
ctx, cancel := context.WithTimeout(
context.Background(),
time.Duration(discoveryTimeout))
Expand Down

0 comments on commit 88b4848

Please sign in to comment.