-
Notifications
You must be signed in to change notification settings - Fork 36
/
atemSocket.ts
239 lines (203 loc) · 7.24 KB
/
atemSocket.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
import { createSocket, Socket } from 'dgram'
import { EventEmitter } from 'events'
import { Util } from './atemUtil'
import { CommandParser } from './atemCommandParser'
import { ConnectionState, PacketFlag } from '../enums'
import AbstractCommand from '../commands/AbstractCommand'
export class AtemSocket extends EventEmitter {
private _connectionState = ConnectionState.Closed
private _debug = false
private _reconnectTimer: NodeJS.Timer | undefined
private _retransmitTimer: NodeJS.Timer | undefined
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 = 200
private _maxRetries = 5
private _lastReceivedAt: number = Date.now()
private _inFlight: Array<{packetId: number, lastSent: number, packet: Buffer, resent: number}> = []
private _commandParser: CommandParser = new CommandParser()
constructor (options: { address?: string, port?: number, debug?: boolean, log?: (args1: any, args2?: any, args3?: any) => void }) {
super()
this._address = options.address || this._address
this._port = options.port || this._port
this._debug = options.debug || false
this.log = options.log || this.log
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('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)
}
if (!this._retransmitTimer) {
this._retransmitTimer = setInterval(() => this._checkForRetransmit(), 50)
}
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(() => {
clearInterval(this._retransmitTimer as NodeJS.Timer)
clearInterval(this._reconnectTimer as NodeJS.Timer)
this._retransmitTimer = undefined
this._reconnectTimer = undefined
this._connectionState = ConnectionState.Closed
this._createSocket()
this.emit('disconnect')
resolve()
})
} else {
resolve()
}
})
}
public log (..._args: any[]): void {
// Will be re-assigned by the top-level ATEM class.
}
get nextPacketId (): number {
return this._localPacketId
}
public _sendCommand (command: AbstractCommand) {
if (typeof command.serialize !== 'function') {
return
}
const payload = command.serialize()
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, 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))
this._socket.on('close', () => this.emit('disconnect'))
}
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 && length > 12) {
this._parseCommand(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
}
// Send ack packet (called by answer packet in Skaarhoj)
if (flags & PacketFlag.AckRequest && this._connectionState === ConnectionState.Established) {
this._sendAck(remotePacketId)
this.emit('ping')
}
// Device ack'ed our command
if (flags & PacketFlag.AckReply && this._connectionState === ConnectionState.Established) {
const ackPacketId = packet[4] << 8 | packet[5]
for (const i in this._inFlight) {
if (ackPacketId >= this._inFlight[i].packetId) {
this.emit('commandAcknowleged', this._inFlight[i].packetId)
delete this._inFlight[i]
}
}
}
}
private _parseCommand (buffer: Buffer, packetId?: number) {
const length = buffer.readUInt16BE(0)
const name = buffer.toString('ascii', 4, 8)
if (name === 'InCm') {
this.emit('connect')
}
// this.log('COMMAND', `${name}(${length})`, buffer.slice(0, length))
const cmd = this._commandParser.commandFromRawName(name)
if (cmd && typeof cmd.deserialize === 'function') {
try {
cmd.deserialize(buffer.slice(0, length).slice(8))
cmd.packetId = packetId || -1
this.emit('receivedStateChange', cmd)
} catch (e) {
this.emit('error', e)
}
}
if (buffer.length > length) {
this._parseCommand(buffer.slice(length), packetId)
}
}
private _sendPacket (packet: Buffer) {
if (this._debug) this.log('SEND ', packet)
this._socket.send(packet, 0, packet.length, this._port, this._address)
}
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 () {
for (const sentPacket of this._inFlight) {
if (sentPacket && sentPacket.lastSent + this._inFlightTimeout < Date.now()) {
if (sentPacket.resent <= this._maxRetries) {
sentPacket.lastSent = Date.now()
sentPacket.resent++
this.log('RESEND: ', sentPacket)
this._sendPacket(sentPacket.packet)
} else {
this._inFlight.splice(this._inFlight.indexOf(sentPacket), 1)
this.log('TIMED OUT: ', sentPacket.packet)
// @todo: we should probably break up the connection here.
}
}
}
}
}