Repository navigation
Expand file tree
/
Copy pathfocusrite-client.js
More file actions
698 lines (596 loc) · 18.9 KB
/
Copy pathfocusrite-client.js
File metadata and controls
698 lines (596 loc) · 18.9 KB
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
/**
* Focusrite Control Server TCP Client
*
* @author Linus Wileryd
* @repository https://github.com/lnswlrd/companion-module-focusrite-clarett
*
* Protocol: XML messages with "Length=XXXXXX " prefix (6-digit uppercase hex)
* Port: 49152 (localhost)
*
* ============================================
* PROTOCOL REVERSE ENGINEERING SOURCES
* ============================================
*
* This implementation is based on protocol analysis from:
*
* 1. Focusrite Midi Control by Radu Varga
* https://github.com/raduvarga/Focusrite-Midi-Control
* - TCP message format: "Length=%06X <xml>" (prefix, not suffix)
* - client-key attribute requirement for client-details
* - Keep-alive mechanism (3 second interval)
* - Device subscription and approval flow
*
* 2. Focusrite Control API by Mathieu2301
* https://github.com/Mathieu2301/Focusrite-Control-API
* - XML <set devid="X"><item id="Y" value="Z"/></set> command structure
* - Device discovery via <device-arrival> messages
*
* 3. Original protocol discovery via packet capture
* of communication between Focusrite Control app
* and FocusriteControlServer daemon.
*
* The FocusriteControlServer is installed as part of Focusrite Control
* software and runs as a system daemon on macOS (launchd) and Windows.
* ============================================
*/
import { EventEmitter } from 'events'
import net from 'net'
import { parseStringPromise } from 'xml2js'
export class FocusriteClient extends EventEmitter {
constructor(options = {}) {
super()
this.host = options.host || '127.0.0.1'
this.port = options.port || 49152
this.clientId = options.clientId || this.generateClientId()
this.clientName = options.clientName || 'Companion'
this.socket = null
this.connected = false
this.approved = false
this.buffer = ''
this.devices = new Map()
this.deviceState = new Map()
this.keepAliveInterval = null
this.reconnectTimeout = null
// Source name map (source ID -> name like "Analogue 1", "Playback 1")
this.sourceNames = new Map()
}
generateClientId() {
// Generate UUID-like client ID
const hex = () => Math.floor(Math.random() * 16).toString(16)
const section = (len) => Array(len).fill(0).map(hex).join('')
return `${section(8)}-${section(4)}-${section(4)}-${section(4)}-${section(12)}`
}
connect() {
return new Promise((resolve, reject) => {
if (this.socket) {
this.socket.destroy()
}
this.socket = new net.Socket()
this.socket.setEncoding('utf8')
this.socket.on('connect', () => {
this.connected = true
this.emit('connected')
this.sendClientDetails()
this.startKeepAlive()
resolve()
})
this.socket.on('data', (data) => {
this.handleData(data)
})
this.socket.on('close', () => {
this.connected = false
this.approved = false
this.stopKeepAlive()
this.emit('disconnected')
this.scheduleReconnect()
})
this.socket.on('error', (err) => {
this.emit('error', err)
if (!this.connected) {
reject(err)
}
})
this.socket.connect(this.port, this.host)
})
}
disconnect() {
this.stopKeepAlive()
if (this.reconnectTimeout) {
clearTimeout(this.reconnectTimeout)
this.reconnectTimeout = null
}
if (this.socket) {
this.socket.destroy()
this.socket = null
}
this.connected = false
this.approved = false
}
scheduleReconnect() {
if (this.reconnectTimeout) return
this.reconnectTimeout = setTimeout(() => {
this.reconnectTimeout = null
this.connect().catch(() => {})
}, 5000)
}
startKeepAlive() {
this.stopKeepAlive()
this.keepAliveInterval = setInterval(() => {
this.sendKeepAlive()
}, 3000)
}
stopKeepAlive() {
if (this.keepAliveInterval) {
clearInterval(this.keepAliveInterval)
this.keepAliveInterval = null
}
}
/**
* Send XML message with length PREFIX
* Format: Length=XXXXXX <xml> (uppercase hex, space before xml)
*/
send(xml) {
if (!this.socket || !this.connected) {
return false
}
const message = `Length=${xml.length.toString(16).toUpperCase().padStart(6, '0')} ${xml}`
this.socket.write(message)
return true
}
sendClientDetails() {
const xml = `<client-details hostname="${this.clientName}" client-key="${this.clientId}"/>`
this.send(xml)
}
sendKeepAlive() {
this.send('<keep-alive/>')
}
/**
* Subscribe to a device
*/
subscribeDevice(deviceId) {
const xml = `<device-subscribe devid="${deviceId}"/>`
this.send(xml)
}
/**
* Set a control value
*/
setValue(deviceId, itemId, value) {
const xml = `<set devid="${deviceId}"><item id="${itemId}" value="${value}"/></set>`
this.send(xml)
this.emit('debug', `SET: device=${deviceId} item=${itemId} value=${value}`)
}
/**
* Handle incoming data from server
* Format: Length=XXXXXX <xml> (Length PREFIX, not suffix)
*/
handleData(data) {
this.buffer += data
// Parse messages: Length=XXXXXX <xml>
while (true) {
// Look for Length= prefix
const lengthMatch = this.buffer.match(/^Length=([0-9A-Fa-f]{6}) /)
if (!lengthMatch) break
const msgLength = parseInt(lengthMatch[1], 16)
const headerLength = lengthMatch[0].length // "Length=XXXXXX "
// Check if we have the full message
if (this.buffer.length < headerLength + msgLength) break
// Extract XML
const xml = this.buffer.substring(headerLength, headerLength + msgLength)
this.buffer = this.buffer.substring(headerLength + msgLength)
// Parse message
this.parseMessage(xml)
}
}
async parseMessage(xml) {
try {
// Handle server announcement
if (xml.startsWith('<server-announcement')) {
this.emit('debug', 'Received server announcement')
return
}
// Handle device arrival
if (xml.includes('<device-arrival>') || xml.includes('<device ')) {
await this.parseDeviceArrival(xml)
return
}
// Handle device removal
if (xml.includes('<device-removal')) {
const match = xml.match(/id="([^"]+)"/)
if (match) {
const deviceId = match[1]
this.devices.delete(deviceId)
this.emit('device-removed', deviceId)
}
return
}
// Handle approval
if (xml.includes('<approval')) {
this.approved = true
this.emit('approved')
return
}
// Handle value updates
if (xml.includes('<set ') || xml.includes('<item ')) {
await this.parseValueUpdate(xml)
return
}
this.emit('debug', `Unknown message: ${xml.substring(0, 100)}...`)
} catch (err) {
this.emit('error', err)
}
}
async parseDeviceArrival(xml) {
try {
const result = await parseStringPromise(xml, { explicitArray: false })
// Find device element
let device = result.device || result['device-arrival']?.device
if (!device) return
// Handle array of devices
if (!Array.isArray(device)) {
device = [device]
}
for (const dev of device) {
const deviceId = dev.$.id
const deviceInfo = {
id: deviceId,
name: dev.$.name || 'Unknown',
model: dev.$.model || '',
serial: dev.$.serial || '',
items: new Map(),
hardwareInputs: [],
mixes: [],
outputs: [],
inputSourceControls: [],
monitoring: {},
}
// Parse all items recursively
this.parseItems(dev, deviceInfo.items, '')
// Parse hardware inputs (analogue) with Air and Mode controls
this.parseHardwareInputs(xml, deviceInfo)
// Build source name map
this.parseSourceNames(xml)
// Parse mixer inputs source controls
this.parseInputSourceControls(xml, deviceInfo)
// Parse outputs
this.parseOutputs(xml, deviceInfo)
// Parse monitoring controls (dim, mute, gain on Out 1-2)
this.parseMonitoring(xml, deviceInfo)
// Parse mixes
this.parseMixes(xml, deviceInfo)
this.devices.set(deviceId, deviceInfo)
this.emit('device-arrived', deviceInfo)
this.emit(
'debug',
`Device arrived: ${deviceInfo.name} (${deviceId}) - ${deviceInfo.hardwareInputs.length} inputs, ${deviceInfo.mixes.length} mixes, ${deviceInfo.outputs.length} outputs`,
)
// Auto-subscribe to device
this.subscribeDevice(deviceId)
}
} catch (err) {
this.emit('error', err)
}
}
/**
* Parse hardware inputs (analogue) with Air, Mode, Phantom, Pad, HPF, Phase controls
*/
parseHardwareInputs(xml, deviceInfo) {
const analogueRegex = /<analogue([^>]*)>([\s\S]*?)<\/analogue>/g
let match
while ((match = analogueRegex.exec(xml)) !== null) {
const attrs = match[1]
const content = match[2]
const idMatch = attrs.match(/id="(\d+)"/)
const nameMatch = attrs.match(/name="([^"]*)"/)
if (!idMatch || !nameMatch) continue
const name = nameMatch[1]
if (!name || name.trim() === '') continue
if (name.includes('-') || name.includes('Monitor')) continue
const input = { id: idMatch[1], name: name }
// Air control
const airMatch = content.match(/<air[^>]+id="(\d+)"/)
if (airMatch) input.air = airMatch[1]
// Mode control with valid enum values
const modeMatch = content.match(/<mode[^>]+id="(\d+)"[^>]*>([\s\S]*?)<\/mode>/)
if (modeMatch) {
input.mode = modeMatch[1]
const modeContent = modeMatch[2]
const enumValues = []
const enumRegex = /<enum[^>]+value="([^"]+)"/g
let enumMatch
while ((enumMatch = enumRegex.exec(modeContent)) !== null) {
enumValues.push(enumMatch[1])
}
input.modeValues = enumValues
}
// Phantom power (48V)
const phantomMatch = content.match(/<phantom[^>]+id="(\d+)"/)
if (phantomMatch) input.phantom = phantomMatch[1]
// Pad (-10dB)
const padMatch = content.match(/<pad[^>]+id="(\d+)"/)
if (padMatch) input.pad = padMatch[1]
// High pass filter
const hpfMatch = content.match(/<highpass[^>]+id="(\d+)"/) || content.match(/<hpf[^>]+id="(\d+)"/)
if (hpfMatch) input.hpf = hpfMatch[1]
// Phase invert / polarity
const phaseMatch = content.match(/<polarity[^>]+id="(\d+)"/) || content.match(/<phase[^>]+id="(\d+)"/)
if (phaseMatch) input.phase = phaseMatch[1]
// Gain control
const gainMatch = content.match(/<gain[^>]+id="(\d+)"/)
if (gainMatch) input.gain = gainMatch[1]
// Stereo link
const stereoMatch = content.match(/<stereolink[^>]+id="(\d+)"/) || content.match(/<stereo[^>]+id="(\d+)"/)
if (stereoMatch) input.stereo = stereoMatch[1]
deviceInfo.hardwareInputs.push(input)
}
}
/**
* Build source name map from all source types
*/
parseSourceNames(xml) {
this.sourceNames = new Map()
const extractSources = (tagName) => {
const regex = new RegExp(`<${tagName}([^>]*)>`, 'g')
let match
while ((match = regex.exec(xml)) !== null) {
const attrs = match[1]
const idMatch = attrs.match(/id="(\d+)"/)
const nameMatch = attrs.match(/name="([^"]*)"/)
if (idMatch && nameMatch && nameMatch[1].trim() !== '') {
this.sourceNames.set(idMatch[1], nameMatch[1])
}
}
}
extractSources('analogue')
extractSources('playback')
extractSources('spdif')
extractSources('adat')
extractSources('loopback')
}
/**
* Parse mixer input source controls
*/
parseInputSourceControls(xml, deviceInfo) {
const inputsMatch = xml.match(/<inputs>([\s\S]*?)<\/inputs>/)
if (!inputsMatch) return
const inputsContent = inputsMatch[1]
const inputBlockRegex = /<input>([\s\S]*?)<\/input>/g
let blockMatch
while ((blockMatch = inputBlockRegex.exec(inputsContent)) !== null) {
const inputContent = blockMatch[1]
const sourceMatch = inputContent.match(/<source([^>]*)\/?>|<source([^>]*)>/)
if (sourceMatch) {
const attrs = sourceMatch[1] || sourceMatch[2]
const idMatch = attrs.match(/id="(\d+)"/)
const valueMatch = attrs.match(/value="(\d+)"/)
if (idMatch) {
deviceInfo.inputSourceControls.push({
id: idMatch[1],
value: valueMatch ? valueMatch[1] : null,
})
}
}
}
}
/**
* Parse outputs with volume/mute controls (scoped to <outputs> section).
* Handles analogue, S/PDIF, ADAT, loopback and any other output types.
* Detects stereo pairs via stereo-name attribute; routes right-channel
* controls to the left channel's IDs (server only responds to left channel).
*/
parseOutputs(xml, deviceInfo) {
const outSectionMatch = xml.match(/<outputs[^>]*>([\s\S]*?)<\/outputs>/)
if (!outSectionMatch) {
this.emit('debug', 'parseOutputs: no <outputs> section found')
return
}
const outXml = outSectionMatch[1]
const outputElementRegex = /<([\w-]+)([^>]*)>([\s\S]*?)<\/\1>/g
let match
let index = 0
let lastStereoPairMute = null
let lastStereoPairVolume = null
while ((match = outputElementRegex.exec(outXml)) !== null) {
const attrs = match[2]
const content = match[3]
const nameMatch = attrs.match(/name="([^"]*)"/)
if (!nameMatch) continue
const name = nameMatch[1]
if (!name || name.trim() === '') continue
const output = { id: String(index), name: name }
index++
// Mark monitor outputs (stereo pair controlled via hardware-controls mute)
if (attrs.match(/monitor="true"/)) output.monitor = true
// Store stereo pair name and detect right channel (stereo-name="" = right/secondary)
const stereoNameMatch = attrs.match(/stereo-name="([^"]*)"/)
const isRightChannel = stereoNameMatch && stereoNameMatch[1] === ''
if (stereoNameMatch && stereoNameMatch[1]) output.stereoName = stereoNameMatch[1]
const gainMatch = content.match(/<gain[^>]+id="(\d+)"/)
if (gainMatch) output.volume = gainMatch[1]
const muteMatch = content.match(/<mute[^>]+id="(\d+)"/)
if (muteMatch) output.mute = muteMatch[1]
// Route right channel to left channel's controls (server ignores right channel)
if (isRightChannel) {
if (lastStereoPairMute) output.mute = lastStereoPairMute
if (lastStereoPairVolume) output.volume = lastStereoPairVolume
} else {
lastStereoPairMute = output.mute || null
lastStereoPairVolume = output.volume || null
}
if (output.volume || output.mute) deviceInfo.outputs.push(output)
}
}
/**
* Parse monitoring section (dim/mute/gain on monitor outputs, i.e. Out 1-2)
*/
parseMonitoring(xml, deviceInfo) {
const monSection = xml.match(/<monitoring>([\s\S]*?)<\/monitoring>/)
if (!monSection) return
const hwControls = monSection[1].match(/<hardware-controls[^>]*exclusive[^>]*>([\s\S]*?)<\/hardware-controls>/)
if (!hwControls) return
const content = hwControls[1]
const gainMatch = content.match(/<gain[^>]+id="(\d+)"/)
if (gainMatch) deviceInfo.monitoring.gain = gainMatch[1]
const dimMatch = content.match(/<dim[^>]+id="(\d+)"/)
if (dimMatch) deviceInfo.monitoring.dim = dimMatch[1]
const muteMatch = content.match(/<mute[^>]+id="(\d+)"/)
if (muteMatch) deviceInfo.monitoring.mute = muteMatch[1]
}
/**
* Parse mixes with inputs (gain, pan, mute, solo)
*/
parseMixes(xml, deviceInfo) {
const mixRegex = /<mix[^>]+id="(\d+)"[^>]*name="([^"]*)"[^>]*>([\s\S]*?)<\/mix>/g
let mixMatch
while ((mixMatch = mixRegex.exec(xml)) !== null) {
const mixName = mixMatch[2]
if (!mixName || mixName.trim() === '') continue
const mix = {
id: mixMatch[1],
name: mixName,
inputs: [],
}
const inputRegex = /<input>([\s\S]*?)<\/input>/g
let inputMatch
const mixContent = mixMatch[3]
while ((inputMatch = inputRegex.exec(mixContent)) !== null) {
const inputContent = inputMatch[1]
const gainMatch = inputContent.match(/<gain[^>]+id="(\d+)"/)
const panMatch = inputContent.match(/<pan[^>]+id="(\d+)"/)
const muteMatch = inputContent.match(/<mute[^>]+id="(\d+)"/)
const soloMatch = inputContent.match(/<solo[^>]+id="(\d+)"/)
if (gainMatch) {
mix.inputs.push({
gain: gainMatch[1],
pan: panMatch ? panMatch[1] : null,
mute: muteMatch ? muteMatch[1] : null,
solo: soloMatch ? soloMatch[1] : null,
})
}
}
const meterMatch = mixContent.match(/<meter[^>]+id="(\d+)"/)
if (meterMatch) mix.meter = meterMatch[1]
deviceInfo.mixes.push(mix)
}
}
parseItems(element, itemsMap, prefix) {
if (!element) return
// Check for item elements
if (element.item) {
const items = Array.isArray(element.item) ? element.item : [element.item]
for (const item of items) {
if (item.$ && item.$.id) {
const itemId = item.$.id
const path = prefix ? `${prefix}` : itemId
itemsMap.set(itemId, {
id: itemId,
path: path,
value: item.$.value,
name: item.$.name || itemId,
type: item.$.type || 'unknown',
min: item.$.min,
max: item.$.max,
})
}
}
}
// Also capture named control elements that have id (e.g. <air id="X" value="Y"/>, <mute id="X"/>, <dim id="X"/>)
for (const key of Object.keys(element)) {
if (key === '$' || key === 'item') continue
const children = Array.isArray(element[key]) ? element[key] : [element[key]]
for (const child of children) {
if (child && typeof child === 'object' && child.$ && child.$.id !== undefined) {
const itemId = child.$.id
if (!itemsMap.has(itemId)) {
const childPath = prefix ? `${prefix}/${key}` : key
itemsMap.set(itemId, {
id: itemId,
path: childPath,
value: child.$.value,
name: child.$.name || key,
type: child.$.type || key,
min: child.$.min,
max: child.$.max,
})
}
}
}
}
// Recurse into child elements
for (const key of Object.keys(element)) {
if (key !== '$' && key !== 'item' && typeof element[key] === 'object') {
const childPrefix = prefix ? `${prefix}/${key}` : key
this.parseItems(element[key], itemsMap, childPrefix)
}
}
}
async parseValueUpdate(xml) {
try {
const result = await parseStringPromise(xml, { explicitArray: false })
let setElement = result.set
if (!setElement) return
const deviceId = setElement.$.devid
// Parse items
let items = setElement.item
if (!items) return
if (!Array.isArray(items)) items = [items]
for (const item of items) {
const itemId = item.$.id
const value = item.$.value
// Update local state (add item if not yet known)
const device = this.devices.get(deviceId)
if (device) {
if (device.items.has(itemId)) {
device.items.get(itemId).value = value
} else {
device.items.set(itemId, { id: itemId, value, name: itemId, type: 'unknown' })
}
}
this.emit('value-changed', { deviceId, itemId, value })
}
} catch (err) {
this.emit('error', err)
}
}
/**
* Get all devices
*/
getDevices() {
return Array.from(this.devices.values())
}
/**
* Get device by ID
*/
getDevice(deviceId) {
return this.devices.get(deviceId)
}
/**
* Get item value
*/
getItemValue(deviceId, itemId) {
const device = this.devices.get(deviceId)
if (!device) return undefined
const item = device.items.get(itemId)
return item ? item.value : undefined
}
/**
* Get source name by ID
*/
getSourceName(sourceId) {
return this.sourceNames.get(sourceId)
}
/**
* Get short label from source name
*/
getShortSourceLabel(sourceName) {
if (!sourceName) return null
return sourceName
.replace('Analogue ', 'An')
.replace('Playback ', 'Pb')
.replace('S/PDIF ', 'SP')
.replace('SPDIF ', 'SP')
.replace('ADAT ', 'AD')
.replace('Loopback ', 'Lb')
.replace(' ', '')
}
}
export default FocusriteClient