-
Notifications
You must be signed in to change notification settings - Fork 36
/
atemSocketChild.ts
249 lines (220 loc) · 8.16 KB
/
atemSocketChild.ts
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
import { createSocket, Socket } from 'dgram'
import { EventEmitter } from 'events'
import { format } from 'util'
import { Util } from './atemUtil'
import { ConnectionState, IPCMessageType, PacketFlag } from '../enums'
import * as NanoTimer from 'nanotimer'
export class AtemSocketChild extends EventEmitter {
private _connectionState = ConnectionState.Closed
private _debug = false
private _reconnectTimer: NodeJS.Timer | undefined
private _retransmitTimer = new NanoTimer()
private _localPacketId = 1
private _maxPacketID = (1 << 15) - 1 // Atem expects 15 not 16 bits before wrapping
private _sessionId: number
private _address: string
private _port: number = 9910
private _socket: Socket
private _reconnectInterval = 5000
private _inFlightTimeout = 30
private _maxRetries = 5
private _lastReceivedAt: number = Date.now()
private _lastReceivedPacketId = 0
private _inFlight: Array<{packetId: number, trackingId: number, lastSent: number, packet: Buffer, resent: number}> = []
private _ackTimer = new NanoTimer()
private _hasTimeout = false
private _receivedWithoutAck = 0
private _lastAcked = 0
constructor (options: { address?: string, port?: number } = {}) {
super()
this._address = options.address || this._address
this._port = options.port || this._port
this._createSocket()
}
public connect (address?: string, port?: number) {
if (!this._reconnectTimer) {
this._reconnectTimer = setInterval(() => {
if (this._lastReceivedAt + this._reconnectInterval > Date.now()) return
if (this._connectionState === ConnectionState.Established) {
this._connectionState = ConnectionState.Closed
this.emit(IPCMessageType.Disconnect, null, null)
}
this._localPacketId = 1
this._sessionId = 0
this.log('reconnect')
if (this._address && this._port) {
this._sendPacket(Util.COMMAND_CONNECT_HELLO)
this._connectionState = ConnectionState.SynSent
}
}, this._reconnectInterval)
}
this._retransmitTimer.setInterval(() => this._checkForRetransmit(), [], '10ms')
if (address) {
this._address = address
}
if (port) {
this._port = port
}
this._sendPacket(Util.COMMAND_CONNECT_HELLO)
this._connectionState = ConnectionState.SynSent
}
public disconnect () {
return new Promise((resolve) => {
if (this._connectionState === ConnectionState.Established) {
this._socket.close(() => {
this._retransmitTimer.clearInterval()
clearInterval(this._reconnectTimer as NodeJS.Timer)
this._reconnectTimer = undefined
this._connectionState = ConnectionState.Closed
this._createSocket()
this.emit(IPCMessageType.Disconnect)
resolve()
})
} else {
resolve()
}
})
}
public log (...args: any[]): void {
const payload = format.apply(format, args)
this.emit(IPCMessageType.Log, payload)
}
get nextPacketId (): number {
return this._localPacketId
}
public _sendCommand (serializedCommand: Buffer, trackingId: number) {
const payload = serializedCommand
if (this._debug) this.log('PAYLOAD', payload)
const buffer = new Buffer(16 + payload.length)
buffer.fill(0)
buffer[0] = (16 + payload.length) / 256 | 0x08
buffer[1] = (16 + payload.length) % 256
buffer[2] = this._sessionId >> 8
buffer[3] = this._sessionId & 0xff
buffer[10] = this._localPacketId / 256
buffer[11] = this._localPacketId % 256
buffer[12] = (4 + payload.length) / 256
buffer[13] = (4 + payload.length) % 256
payload.copy(buffer, 16)
this._sendPacket(buffer)
this._inFlight.push({
packetId: this._localPacketId,
trackingId,
lastSent: Date.now(),
packet: buffer,
resent: 0 })
this._localPacketId++
if (this._maxPacketID < this._localPacketId) this._localPacketId = 0
}
private _createSocket () {
this._socket = createSocket('udp4')
this._socket.bind(1024 + Math.floor(Math.random() * 64511))
this._socket.on('message', (packet, rinfo) => this._receivePacket(packet, rinfo))
}
private _receivePacket (packet: Buffer, rinfo: any) {
if (this._debug) this.log('RECV ', packet)
this._lastReceivedAt = Date.now()
const length = ((packet[0] & 0x07) << 8) | packet[1]
if (length !== rinfo.size) return
const flags = packet[0] >> 3
// this._sessionId = [packet[2], packet[3]]
this._sessionId = packet[2] << 8 | packet[3]
const remotePacketId = packet[10] << 8 | packet[11]
// Send hello answer packet when receive connect flags
if (flags & PacketFlag.Connect && !(flags & PacketFlag.Repeat)) {
this._sendPacket(Util.COMMAND_CONNECT_HELLO_ANSWER)
}
// Parse commands, Emit 'stateChanged' event after parse
if (flags & PacketFlag.AckRequest) {
if (this._connectionState === ConnectionState.Established) {
if (remotePacketId === (this._lastReceivedPacketId + 1) % this._maxPacketID) {
this._attemptAck(remotePacketId)
this._lastReceivedPacketId = remotePacketId
} else {
return
}
}
if (length > 12) {
this.emit(IPCMessageType.InboundCommand, packet.slice(12), remotePacketId)
}
}
// Send ping packet, Emit 'connect' event after receive all stats
if (flags & PacketFlag.AckRequest && length === 12 && this._connectionState === ConnectionState.SynSent) {
this._connectionState = ConnectionState.Established
this._sendAck(remotePacketId)
this._lastReceivedPacketId = remotePacketId
}
// Device ack'ed our command
if (flags & PacketFlag.AckReply && this._connectionState === ConnectionState.Established) {
const ackPacketId = packet[4] << 8 | packet[5]
this._lastAcked = ackPacketId
for (const i in this._inFlight) {
if (ackPacketId >= this._inFlight[i].packetId || this._localPacketId < this._inFlight[i].packetId) {
this.emit(IPCMessageType.CommandAcknowledged, this._inFlight[i].packetId, this._inFlight[i].trackingId)
this._inFlight.splice(Number(i), 1)
}
}
}
}
private _sendPacket (packet: Buffer) {
if (this._debug) this.log('SEND ', packet)
this._socket.send(packet, 0, packet.length, this._port, this._address)
}
private _attemptAck (packetId: number) {
this._lastReceivedPacketId = packetId
this._receivedWithoutAck++
if (this._receivedWithoutAck === 16) {
this._receivedWithoutAck = 0
this._hasTimeout = false
this._ackTimer.clearTimeout()
this._sendAck(this._lastReceivedPacketId)
} else if (!this._hasTimeout) {
this._hasTimeout = true
this._ackTimer.setTimeout(() => {
this._receivedWithoutAck = 0
this._hasTimeout = false
this._sendAck(this._lastReceivedPacketId)
}, [], '5ms')
}
}
private _sendAck (packetId: number) {
const buffer = new Buffer(12)
buffer.fill(0)
buffer[0] = 0x80
buffer[1] = 0x0C
buffer[2] = this._sessionId >> 8
buffer[3] = this._sessionId & 0xFF
buffer[4] = packetId >> 8
buffer[5] = packetId & 0xFF
buffer[9] = 0x41
this._sendPacket(buffer)
}
private _checkForRetransmit () {
let retransmitFromPacketId: number | undefined
for (const sentPacket of this._inFlight) {
if (sentPacket.packetId <= this._lastAcked || sentPacket.packetId > this._localPacketId) {
this.emit(IPCMessageType.CommandAcknowledged, sentPacket.packetId, sentPacket.trackingId)
this._inFlight.splice(this._inFlight.indexOf(sentPacket), 1)
continue
}
if (retransmitFromPacketId && sentPacket.packetId > retransmitFromPacketId) {
sentPacket.lastSent = Date.now()
sentPacket.resent++
this._sendPacket(sentPacket.packet)
} else if (sentPacket && sentPacket.lastSent + this._inFlightTimeout < Date.now()) {
if (sentPacket.resent <= this._maxRetries && sentPacket.packetId < this.nextPacketId) {
sentPacket.lastSent = Date.now()
sentPacket.resent++
this.log('RESEND: ', sentPacket)
this._sendPacket(sentPacket.packet)
retransmitFromPacketId = sentPacket.packetId
} else {
this.emit(IPCMessageType.CommandTimeout, sentPacket.packetId, sentPacket.trackingId)
this._inFlight.splice(this._inFlight.indexOf(sentPacket), 1)
this.log('TIMED OUT: ', sentPacket.packet)
// @todo: we should probably break up the connection here.
}
}
}
}
}