-
Notifications
You must be signed in to change notification settings - Fork 2
/
gatewaylistener.go
90 lines (76 loc) · 1.84 KB
/
gatewaylistener.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
package aqara
import (
"errors"
"fmt"
"log"
"net"
)
// GatewayListener provide a way to listen to a list of gateways
type GatewayListener struct {
Gateways []*Gateway
}
// NewGatewayListener create a GatewayListener instance
func NewGatewayListener(gateways []*Gateway) GatewayListener {
return GatewayListener{
Gateways: gateways,
}
}
func (g *GatewayListener) validateGatewaySameIface() error {
if len(g.Gateways) == 0 {
return errors.New("no gateway configured for GatewayListener")
}
expected := g.Gateways[0].Iface
for _, item := range g.Gateways {
if item.Iface != expected {
return fmt.Errorf("configured gateways have different interface. use several GatewayListener to listen.\nexpected %v, found %v", expected, item.Iface)
}
}
return nil
}
// Listen start listening for traffic from the gateways
func (g *GatewayListener) Listen(c chan ListenResponse) error {
if err := g.validateGatewaySameIface(); err != nil {
return err
}
iface, err := net.InterfaceByName(g.Gateways[0].Iface)
if err != nil {
return err
}
con, err := net.ListenMulticastUDP("udp4", iface, &net.UDPAddr{
IP: net.IPv4(224, 0, 0, 50),
Port: 9898,
})
if err != nil {
return err
}
defer con.Close()
buffer := make([]byte, 1024)
for {
size, addr, err := con.ReadFromUDP(buffer)
if err != nil {
return err
}
gateway := g.getGatewayFromAddr(addr)
if gateway == nil {
log.Printf("message from unknown gateway %v", addr)
continue
}
message, err := parseBuffer(buffer[:size], gateway)
if err != nil {
log.Printf("error parsing message %v", err)
continue
}
c <- ListenResponse{
Message: *message,
Gateway: gateway,
}
}
}
func (g *GatewayListener) getGatewayFromAddr(addr *net.UDPAddr) *Gateway {
for _, gateway := range g.Gateways {
if gateway.IP.Equal(addr.IP) {
return gateway
}
}
return nil
}