-
Notifications
You must be signed in to change notification settings - Fork 1
/
receiver.go
199 lines (166 loc) · 5.6 KB
/
receiver.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
package sacn
import (
"errors"
"fmt"
"golang.org/x/net/ipv4"
"log"
"net"
"time"
"github.com/libp2p/go-reuseport"
"gitlab.com/patopest/go-sacn/packet"
)
// PacketCallbackFunc is the function type to be used with [Receiver.RegisterPacketCallback].
// The arguments are the latest received [packet.SACNPacket] on any universe and the source IP that sent the packet as a string.
type PacketCallbackFunc func(p packet.SACNPacket, source string)
// TerminationCallbackFunc is the function type to be used with [Receiver.RegisterTerminationCallback].
// The universe argument is the universe number which entered Network Data Loss conditions.
type TerminationCallbackFunc func(universe uint16)
// A sACN Receiver. Use [NewReceiver] to create a receiver.
type Receiver struct {
conn *ipv4.PacketConn
itf *net.Interface
stop chan bool
lastPackets map[uint16]networkPacket
streamTerminated map[uint16]bool
packetCallbacks map[packet.SACNPacketType]PacketCallbackFunc
terminationCallback TerminationCallbackFunc
}
type networkPacket struct {
ts time.Time
packet packet.SACNPacket
// source net.UDPAddr
}
// NewReceiver creates a new receiver bound to the provided interface
func NewReceiver(itf *net.Interface) *Receiver {
r := &Receiver{}
addr := fmt.Sprintf(":%d", SACN_PORT)
listener, err := reuseport.ListenPacket("udp4", addr)
if err != nil {
log.Panicln(err)
}
udpConn := listener.(*net.UDPConn)
r.conn = ipv4.NewPacketConn(udpConn)
r.itf = itf
r.lastPackets = make(map[uint16]networkPacket)
r.streamTerminated = make(map[uint16]bool)
r.packetCallbacks = make(map[packet.SACNPacketType]PacketCallbackFunc)
return r
}
// Starts the receiver
func (r *Receiver) Start() {
r.stop = make(chan bool)
go r.recvLoop()
}
// Stops the receiver
func (r *Receiver) Stop() {
close(r.stop)
}
// JoinUniverse starts listening for packets sent on the provided universe.
// Universe number shall be in the range 1 to 63999.
// Joins the multicast group associated with the universe number.
func (r *Receiver) JoinUniverse(universe uint16) error {
if universe == 0 || (universe > 64000 && universe != DISCOVERY_UNIVERSE) { // Section 9.1.1 of ANSI E1.31—2018
return errors.New(fmt.Sprintf("Invalid universe number: %d\n", universe))
}
err := r.conn.JoinGroup(r.itf, universeToAddress(universe))
if err != nil {
return errors.New(fmt.Sprintf("Could not join multicast group for universe %v: %v", universe, err))
}
return nil
}
// Stops listening for packets sent on a universe.
// Leaves the multicast groups associated with the universe number.
func (r *Receiver) LeaveUniverse(universe uint16) error {
err := r.conn.LeaveGroup(r.itf, universeToAddress(universe))
if err != nil {
return errors.New(fmt.Sprintf("Could not leave multicast group for universe %v: %v", universe, err))
}
return nil
}
// RegisterPacketCallback registers a callback of type PacketCallbackFunc.
// The callback will be triggered on reception of a new packet of type [packet.SACNPacketType] on any universe
func (r *Receiver) RegisterPacketCallback(packetType packet.SACNPacketType, callback PacketCallbackFunc) {
r.packetCallbacks[packetType] = callback
}
// RegisterTerminationCallback registers a callback for when a universe enters Network Data Loss conditions as defined in section 6.7.1 of ANSI E1.31—2018.
//
// Network Data Loss conditions:
// - Did not receive data for [NETWORK_DATA_LOSS_TIMEOUT].
// - Data packet contained the StreamTerminated bit in the [packet.DataPacket] Options field.
func (r *Receiver) RegisterTerminationCallback(callback TerminationCallbackFunc) {
r.terminationCallback = callback
}
func (r *Receiver) recvLoop() {
defer r.conn.Close()
for {
select {
case <-r.stop:
return
default:
buf := make([]byte, 1144) // 1144 is max packet size (full DiscoveryPacket)
err := r.conn.SetDeadline(time.Now().Add(time.Millisecond * NETWORK_DATA_LOSS_TIMEOUT))
if err != nil {
log.Panic(fmt.Sprintf("Could not set deadline on socket: %v", err))
}
n, _, addr, _ := r.conn.ReadFrom(buf)
if addr == nil { // timeout
r.checkTimeouts()
continue
}
source := addr.(*net.UDPAddr)
// fmt.Printf("Received %d bytes from %s\n", n, source.String())
var p packet.SACNPacket
p, err = packet.Unmarshal(buf[:n])
if err != nil {
continue
}
r.handlePacket(p, source.IP.String())
}
}
}
func (r *Receiver) handlePacket(p packet.SACNPacket, source string) {
r.checkTimeouts()
packetType := p.GetType()
switch packetType {
case packet.PacketTypeData:
d, _ := p.(*packet.DataPacket)
r.storeLastPacket(d.Universe, d)
if d.IsStreamTerminated() { // Bit 6: Stream Terminated
r.terminateUniverse(d.Universe)
return
}
if d.SyncAddress > 0 {
_, ok := r.streamTerminated[d.SyncAddress]
if !ok { // only join sync universe if not already
r.JoinUniverse(d.SyncAddress)
}
}
case packet.PacketTypeSync:
s, _ := p.(*packet.SyncPacket)
r.storeLastPacket(s.SyncAddress, s)
}
callback := r.packetCallbacks[packetType]
if callback != nil {
go callback(p, source)
}
}
func (r *Receiver) storeLastPacket(universe uint16, p packet.SACNPacket) {
r.lastPackets[universe] = networkPacket{
ts: time.Now(),
packet: p,
}
r.streamTerminated[universe] = false
}
func (r *Receiver) checkTimeouts() {
for universe, last := range r.lastPackets {
if time.Since(last.ts) > time.Millisecond*NETWORK_DATA_LOSS_TIMEOUT {
r.terminateUniverse(universe)
}
}
}
func (r *Receiver) terminateUniverse(universe uint16) {
if r.terminationCallback != nil && !r.streamTerminated[universe] {
go r.terminationCallback(universe)
r.streamTerminated[universe] = true
}
}