-
Notifications
You must be signed in to change notification settings - Fork 36
/
atemSocketChild.ts
369 lines (315 loc) · 11.4 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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
import { createSocket, Socket, RemoteInfo } from 'dgram'
import * as Util from './atemUtil'
import * as NanoTimer from 'nanotimer'
const IN_FLIGHT_TIMEOUT = 60 // ms
const CONNECTION_TIMEOUT = 5000 // ms
const CONNECTION_RETRY_INTERVAL = 1000 // ms
const MAX_PACKET_RETRIES = 10
const MAX_PACKET_ID = 1 << 15 // Atem expects 15 not 16 bits before wrapping
const MAX_PACKET_PER_ACK = 16
export enum ConnectionState {
Closed = 0x00,
SynSent = 0x01,
Established = 0x02
}
export enum PacketFlag {
AckRequest = 0x01,
NewSessionId = 0x02,
IsRetransmit = 0x04,
RetransmitRequest = 0x08,
AckReply = 0x10
}
interface InFlightPacket {
readonly packetId: number
readonly trackingId: number
readonly payload: Buffer
lastSent: number
resent: number
}
export class AtemSocketChild {
private readonly _debugBuffers: boolean
private _connectionState = ConnectionState.Closed
private _reconnectTimer: NodeJS.Timer | undefined
private _retransmitTimer: NodeJS.Timer | undefined
private _nextSendPacketId = 1
private _sessionId = 0
private _address: string
private _port: number
private _socket: Socket
private _lastReceivedAt: number = Date.now()
private _lastReceivedPacketId = 0
private _inFlight: InFlightPacket[] = []
private readonly _ackTimer = new NanoTimer()
private _ackTimerRunning = false
private _receivedWithoutAck = 0
private readonly onDisconnect: () => Promise<void>
private readonly onLog: (message: string) => Promise<void>
private readonly onCommandsReceived: (payload: Buffer, packetId: number) => Promise<void>
private readonly onCommandsAcknowledged: (ids: Array<{ packetId: number; trackingId: number }>) => Promise<void>
constructor(
options: { address: string; port: number; debugBuffers: boolean },
onDisconnect: () => Promise<void>,
onLog: (message: string) => Promise<void>,
onCommandReceived: (payload: Buffer, packetId: number) => Promise<void>,
onCommandAcknowledged: (ids: Array<{ packetId: number; trackingId: number }>) => Promise<void>
) {
this._debugBuffers = options.debugBuffers
this._address = options.address
this._port = options.port
this.onDisconnect = onDisconnect
this.onLog = onLog
this.onCommandsReceived = onCommandReceived
this.onCommandsAcknowledged = onCommandAcknowledged
this._socket = this._createSocket()
}
private startTimers(): void {
if (!this._reconnectTimer) {
this._reconnectTimer = setInterval(async () => {
if (this._lastReceivedAt + CONNECTION_TIMEOUT > Date.now()) {
// We heard from the atem recently
return
}
try {
await this.restartConnection()
} catch (e) {
this.log(`Reconnect failed: ${e}`)
}
}, CONNECTION_RETRY_INTERVAL)
}
// Check for retransmits every 10 milliseconds
if (!this._retransmitTimer) {
this._retransmitTimer = setInterval(() => this._checkForRetransmit(), 10)
}
}
public connect(address: string, port: number): Promise<void> {
this.startTimers()
this._address = address
this._port = port
return this.restartConnection()
}
public disconnect(): Promise<void> {
// Stop timers, as they just cause pointless work now.
if (this._retransmitTimer) {
clearInterval(this._retransmitTimer)
this._retransmitTimer = undefined
}
if (this._reconnectTimer) {
clearInterval(this._reconnectTimer)
this._reconnectTimer = undefined
}
return new Promise(resolve => {
try {
this._socket.close(() => resolve())
} catch (e) {
resolve()
}
}).then(() => {
this._connectionState = ConnectionState.Closed
this._createSocket()
return this.onDisconnect()
})
}
private async restartConnection(): Promise<void> {
// This includes a 'disconnect'
if (this._connectionState === ConnectionState.Established) {
this._connectionState = ConnectionState.Closed
this._createSocket()
await this.onDisconnect()
}
// Reset connection
this._nextSendPacketId = 1
this._sessionId = 0
this._inFlight = []
this.log('reconnect')
// Try doing reconnect
this._sendPacket(Util.COMMAND_CONNECT_HELLO)
this._connectionState = ConnectionState.SynSent
}
private log(message: string): void {
// tslint:disable-next-line: no-floating-promises
this.onLog(message)
}
public sendCommands(commands: Array<{ payload: number[]; rawName: string; trackingId: number }>): void {
commands.forEach(cmd => {
this.sendCommand(cmd.payload, cmd.rawName, cmd.trackingId)
})
}
private sendCommand(payload: number[], rawName: string, trackingId: number): void {
const packetId = this._nextSendPacketId++
if (this._nextSendPacketId >= MAX_PACKET_ID) this._nextSendPacketId = 0
const opcode = PacketFlag.AckRequest << 11
const buffer = Buffer.alloc(20 + payload.length, 0)
buffer.writeUInt16BE(opcode | (payload.length + 20), 0) // Opcode & Length
buffer.writeUInt16BE(this._sessionId, 2)
buffer.writeUInt16BE(packetId, 10)
// Command
buffer.writeUInt16BE(payload.length + 8, 12)
buffer.write(rawName, 16, 4)
// Body
Buffer.from(payload).copy(buffer, 20)
this._sendPacket(buffer)
this._inFlight.push({
packetId,
trackingId,
lastSent: Date.now(),
payload: buffer,
resent: 0
})
}
private _createSocket(): Socket {
this._socket = createSocket('udp4')
this._socket.bind()
this._socket.on('message', (packet, rinfo) => this._receivePacket(packet, rinfo))
this._socket.on('error', async err => {
this.log(`Connection error: ${err}`)
if (this._connectionState === ConnectionState.Established) {
// If connection is open, then restart. Otherwise the reconnectTimer will handle it
await this.restartConnection()
}
})
return this._socket
}
private _isPacketCoveredByAck(ackId: number, packetId: number): boolean {
const tolerance = MAX_PACKET_ID / 2
const pktIsShortlyBefore = packetId < ackId && packetId + tolerance > ackId
const pktIsShortlyAfter = packetId > ackId && packetId < ackId + tolerance
const pktIsBeforeWrap = packetId > ackId + tolerance
return packetId === ackId || ((pktIsShortlyBefore || pktIsBeforeWrap) && !pktIsShortlyAfter)
}
private async _receivePacket(packet: Buffer, rinfo: RemoteInfo): Promise<void> {
if (this._debugBuffers) this.log(`RECV ${packet.toString('hex')}`)
this._lastReceivedAt = Date.now()
const length = packet.readUInt16BE(0) & 0x07ff
if (length !== rinfo.size) return
const flags = packet.readUInt8(0) >> 3
this._sessionId = packet.readUInt16BE(2)
const remotePacketId = packet.readUInt16BE(10)
// Send hello answer packet when receive connect flags
if (flags & PacketFlag.NewSessionId) {
this._connectionState = ConnectionState.Established
this._lastReceivedPacketId = remotePacketId
this._sendAck(remotePacketId)
return
}
const ps: Array<Promise<void>> = []
if (this._connectionState === ConnectionState.Established) {
// Device asked for retransmit
if (flags & PacketFlag.RetransmitRequest) {
const fromPacketId = packet.readUInt16BE(6)
this.log(`Retransmit request: ${fromPacketId}`)
ps.push(this._retransmitFrom(fromPacketId))
}
// Got a packet that needs an ack
if (flags & PacketFlag.AckRequest) {
// Check if it next in the sequence
if (remotePacketId === (this._lastReceivedPacketId + 1) % MAX_PACKET_ID) {
this._lastReceivedPacketId = remotePacketId
this._sendOrQueueAck()
// It might have commands
if (length > 12) {
ps.push(this.onCommandsReceived(packet.slice(12), remotePacketId))
}
} else if (this._isPacketCoveredByAck(this._lastReceivedPacketId, remotePacketId)) {
// We got a retransmit of something we have already acked, so reack it
this._sendOrQueueAck()
}
}
// Device ack'ed our packet
if (flags & PacketFlag.AckReply) {
const ackPacketId = packet.readUInt16BE(4)
const ackedCommands: Array<{ packetId: number; trackingId: number }> = []
this._inFlight = this._inFlight.filter(pkt => {
if (this._isPacketCoveredByAck(ackPacketId, pkt.packetId)) {
ackedCommands.push({
packetId: pkt.packetId,
trackingId: pkt.trackingId
})
return false
} else {
// Not acked yet
return true
}
})
ps.push(this.onCommandsAcknowledged(ackedCommands))
// this.log(`${Date.now()} Got ack ${ackPacketId} Remaining=${this._inFlight.length}`)
}
}
await Promise.all(ps)
}
private _sendPacket(packet: Buffer): void {
if (this._debugBuffers) this.log(`SEND ${packet.toString('hex')}`)
this._socket.send(packet, 0, packet.length, this._port, this._address)
}
private _sendOrQueueAck(): void {
this._receivedWithoutAck++
if (this._receivedWithoutAck >= MAX_PACKET_PER_ACK) {
this._receivedWithoutAck = 0
this._ackTimerRunning = false
this._ackTimer.clearTimeout()
this._sendAck(this._lastReceivedPacketId)
} else if (!this._ackTimerRunning) {
this._ackTimerRunning = true
// timeout for 5 ms (syntax for nanotimer says m)
this._ackTimer.setTimeout(
() => {
this._receivedWithoutAck = 0
this._ackTimerRunning = false
this._sendAck(this._lastReceivedPacketId)
},
[],
'5m'
)
}
}
private _sendAck(packetId: number): void {
const opcode = PacketFlag.AckReply << 11
const length = 12
const buffer = Buffer.alloc(length, 0)
buffer.writeUInt16BE(opcode | length, 0)
buffer.writeUInt16BE(this._sessionId, 2)
buffer.writeUInt16BE(packetId, 4)
this._sendPacket(buffer)
}
private async _retransmitFrom(fromId: number): Promise<void> {
// this.log(`Resending from ${fromId} to ${this._inFlight.length > 0 ? this._inFlight[this._inFlight.length - 1].packetId : '-'}`)
// The atem will ask for MAX_PACKET_ID to be retransmitted when it really wants 0
fromId = fromId % MAX_PACKET_ID
const fromIndex = this._inFlight.findIndex(pkt => pkt.packetId === fromId)
if (fromIndex === -1) {
// fromId is not inflight, so we cannot resend. only fix is to abort
this.log(`Unable to resend: ${fromId}`)
await this.restartConnection()
} else {
this.log(`Resending from ${fromId} to ${this._inFlight[this._inFlight.length - 1].packetId}`)
// Resend from the requested
for (let i = fromIndex; i < this._inFlight.length; i++) {
const sentPacket = this._inFlight[i]
if (sentPacket.packetId === fromId || !this._isPacketCoveredByAck(fromId, sentPacket.packetId)) {
sentPacket.lastSent = Date.now()
sentPacket.resent++
// this.log(`${Date.now()} Resending ${sentPacket.packetId} Last=${this._nextSendPacketId - 1}`)
this._sendPacket(sentPacket.payload)
}
}
}
}
private _checkForRetransmit(): Promise<void> {
for (const sentPacket of this._inFlight) {
if (sentPacket.lastSent + IN_FLIGHT_TIMEOUT < Date.now()) {
if (
sentPacket.resent <= MAX_PACKET_RETRIES &&
this._isPacketCoveredByAck(this._nextSendPacketId, sentPacket.packetId)
) {
this.log(`Retransmit from timeout: ${sentPacket.packetId}`)
// Retransmit the packet and anything after it
return this._retransmitFrom(sentPacket.packetId)
} else {
// A command has timed out, so we need to reset to avoid getting stuck
this.log(`Packet timed out: ${sentPacket.packetId}`)
return this.restartConnection()
}
}
}
return Promise.resolve()
}
}