forked from pevecyan/knx-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
discover.go
54 lines (43 loc) · 1.24 KB
/
discover.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Licensed under the MIT license which can be found in the LICENSE file.
package knx
import (
"net"
"time"
"github.com/greenstatic/knx-go/knx/knxnet"
)
// Discover all KNXnet/IP Server
func Discover(multicastDiscoveryAddress string, searchTimeout time.Duration) ([]*knxnet.SearchRes, error) {
return DiscoverOnInterface(nil, multicastDiscoveryAddress, searchTimeout)
}
// DiscoverOnInterface discovers all KNXnet/IP Server on a specific interface. If the
// interface is nil, the system-assigned multicast interface is used.
func DiscoverOnInterface(ifi *net.Interface, multicastDiscoveryAddress string, searchTimeout time.Duration) ([]*knxnet.SearchRes, error) {
socket, err := knxnet.ListenRouterOnInterface(ifi, multicastDiscoveryAddress)
if err != nil {
return nil, err
}
defer socket.Close()
req, err := knxnet.NewSearchReq(socket.Addr())
if err != nil {
return nil, err
}
if err := socket.Send(req); err != nil {
return nil, err
}
results := []*knxnet.SearchRes{}
timeout := time.After(searchTimeout)
loop:
for {
select {
case msg := <-socket.Inbound():
searchRes, ok := msg.(*knxnet.SearchRes)
if !ok {
continue
}
results = append(results, searchRes)
case <-timeout:
break loop
}
}
return results, nil
}