-
Notifications
You must be signed in to change notification settings - Fork 36
/
atemSocket.ts
182 lines (155 loc) · 5.9 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
import { EventEmitter } from 'events'
import { CommandParser } from './atemCommandParser'
import exitHook = require('exit-hook')
import { VersionCommand, ISerializableCommand, IDeserializedCommand } from '../commands'
import { DEFAULT_PORT } from '../atem'
import { threadedClass, ThreadedClass, ThreadedClassManager } from 'threadedclass'
import { AtemSocketChild } from './atemSocketChild'
export interface AtemSocketOptions {
address: string
port: number
debugBuffers: boolean
disableMultithreaded: boolean
}
export class AtemSocket extends EventEmitter {
private readonly _debugBuffers: boolean
private readonly _disableMultithreaded: boolean
private readonly _commandParser: CommandParser = new CommandParser()
private _nextCommandTrackingId = 0
private _address: string
private _port: number = DEFAULT_PORT
private _socketProcess: ThreadedClass<AtemSocketChild> | undefined
private _exitUnsubscribe?: () => void
public on!: ((event: 'disconnect', listener: () => void) => this) &
((event: 'info', listener: (message: string) => void) => this) &
((event: 'debug', listener: (message: string) => void) => this) &
((event: 'error', listener: (message: string) => void) => this) &
((event: 'commandsReceived', listener: (cmds: IDeserializedCommand[]) => void) => this) &
((event: 'commandsAck', listener: (trackingIds: number[]) => void) => this)
public emit!: ((event: 'disconnect') => boolean) &
((event: 'info', message: string) => boolean) &
((event: 'debug', message: string) => boolean) &
((event: 'error', message: string) => boolean) &
((event: 'commandsReceived', cmds: IDeserializedCommand[]) => boolean) &
((event: 'commandsAck', trackingIds: number[]) => boolean)
constructor (options: AtemSocketOptions) {
super()
this._address = options.address
this._port = options.port
this._debugBuffers = options.debugBuffers
this._disableMultithreaded = options.disableMultithreaded
}
public async connect (address?: string, port?: number): Promise<void> {
if (address) {
this._address = address
}
if (port) {
this._port = port
}
if (!this._socketProcess) {
this._socketProcess = await this._createSocketProcess()
this._exitUnsubscribe = exitHook(() => this.destroy())
} else {
await this._socketProcess.connect(this._address, this._port)
}
}
public async destroy () {
await this.disconnect()
if (this._socketProcess) {
await ThreadedClassManager.destroy(this._socketProcess)
this._socketProcess = undefined
}
if (this._exitUnsubscribe) {
this._exitUnsubscribe()
this._exitUnsubscribe = undefined
}
}
public async disconnect (): Promise<void> {
if (this._socketProcess) {
await this._socketProcess.disconnect()
}
}
get nextCommandTrackingId (): number {
if (this._nextCommandTrackingId >= Number.MAX_SAFE_INTEGER) {
this._nextCommandTrackingId = 0
}
return ++this._nextCommandTrackingId
}
public async sendCommands (commands: Array<{ rawCommand: ISerializableCommand, trackingId: number}>): Promise<void> {
if (this._socketProcess) {
const commands2 = commands.map(cmd => {
if (typeof (cmd.rawCommand as any).serialize !== 'function') {
throw new Error(`Command ${cmd.rawCommand.constructor.name} is not serializable`)
}
const payload = cmd.rawCommand.serialize(this._commandParser.version)
if (this._debugBuffers) this.emit('debug', `PAYLOAD ${cmd.rawCommand.constructor.name} ${payload.toString('hex')}`)
return {
payload: [...payload],
rawName: (cmd.rawCommand.constructor as any).rawName,
trackingId: cmd.trackingId
}
})
await this._socketProcess.sendCommands(commands2)
} else {
throw new Error('Socket process is not open')
}
}
private async _createSocketProcess () {
const socketProcess = await threadedClass<AtemSocketChild, typeof AtemSocketChild>('./atemSocketChild', AtemSocketChild, [
{
address: this._address,
port: this._port,
debugBuffers: this._debugBuffers
},
async () => { this.emit('disconnect') }, // onDisconnect
async (message: string) => { this.emit('info', message) }, // onLog
async (payload: Buffer) => this._parseCommands(Buffer.from(payload)), // onCommandsReceived
async (ids: Array<{ packetId: number, trackingId: number }>) => { this.emit('commandsAck', ids.map(id => id.trackingId)) } // onCommandsAcknowledged
], {
instanceName: 'atem-connection',
freezeLimit: 200,
autoRestart: true,
disableMultithreading: this._disableMultithreaded
})
ThreadedClassManager.onEvent(socketProcess, 'restarted', () => {
this.emit('disconnect')
this.connect().catch(error => {
const errorMsg = `Failed to reconnect after respawning socket process: ${error}`
this.emit('error', errorMsg)
})
})
await socketProcess.connect(this._address, this._port)
return socketProcess
}
private _parseCommands (buffer: Buffer) {
const parsedCommands: IDeserializedCommand[] = []
while (buffer.length > 8) {
const length = buffer.readUInt16BE(0)
const name = buffer.toString('ascii', 4, 8)
if (length < 8) {
// Commands are never less than 8, as that is the header
break
}
const cmdConstructor = this._commandParser.commandFromRawName(name)
if (cmdConstructor && typeof cmdConstructor.deserialize === 'function') {
try {
const cmd: IDeserializedCommand = cmdConstructor.deserialize(buffer.slice(0, length).slice(8), this._commandParser.version)
if (cmdConstructor.name === VersionCommand.name) { // init started
const verCmd = cmd as VersionCommand
this._commandParser.version = verCmd.properties.version
}
parsedCommands.push(cmd)
} catch (e) {
this.emit('error', `Failed to deserialize command: ${cmdConstructor.constructor.name}: ${e}`)
}
} else {
this.emit('debug', `Unknown command ${name} (${length}b)`)
}
// Trim the buffer
buffer = buffer.slice(length)
}
if (parsedCommands.length > 0) {
this.emit('commandsReceived', parsedCommands)
}
}
}