forked from woodnathan/broadlink
-
Notifications
You must be signed in to change notification settings - Fork 0
/
manager.go
100 lines (82 loc) · 1.78 KB
/
manager.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package broadlink
import (
"errors"
"log"
"net"
"time"
)
const DISCOVERY_PORT = 80
type Manager struct {
conn *net.UDPConn
laddr *net.UDPAddr
devices []Device
}
func NewManager() (*Manager, error) {
udpconn, err := net.ListenUDP("udp", nil)
if err != nil {
return nil, err
}
laddr := GetLocalAddr()
return &Manager{
conn: udpconn,
laddr: laddr,
}, nil
}
func (m *Manager) Discover(timeout time.Duration) (devices []Device, err error) {
devices = make([]Device, 0)
mcaddr := &net.UDPAddr{
IP: net.IPv4bcast,
Port: DISCOVERY_PORT,
}
// broadcast
dp := NewDiscoveryPacket(time.Now(), m.laddr)
dps, err := dp.Bytes()
if err != nil {
return devices, err
}
m.conn.WriteTo(dps, mcaddr)
//read
m.conn.SetReadDeadline(time.Now().Add(timeout))
resp := make([]byte, 1024)
for {
size, raddr, err := m.conn.ReadFromUDP(resp)
if err != nil {
return devices, err
}
// if err, ok := err.(net.Error); ok && err.Timeout() {
// return
// }
if size == 0 {
err = errors.New("Unable to read discovery response")
return devices, err
}
dr := NewDiscoveryResponse(resp)
bd, err := newBaseDevice(raddr, dr.MAC)
if err != nil {
return devices, err
}
dev := bd.newDevice(dr.DeviceType)
m.devices = append(m.devices, dev)
break // Use channels to push out new devices
}
return m.devices, nil
}
func GetLocalAddr() *net.UDPAddr {
udpcon, err := net.DialUDP("udp",
nil,
&net.UDPAddr{
IP: net.ParseIP("8.8.8.8"),
Port: 53,
},
)
if err != nil {
log.Fatalf("Failed to obtain local address: %s\n", err)
}
defer udpcon.Close()
laddr := udpcon.LocalAddr()
ludpaddr, err := net.ResolveUDPAddr(laddr.Network(), laddr.String())
if err != nil {
log.Fatalf("Failed to resolve local UDP address: %s\n", err)
}
return ludpaddr
}