-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
721 lines (643 loc) · 19.5 KB
/
index.js
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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
import got from 'got';
import { CookieJar } from 'tough-cookie'
import { InstanceBase, Regex, combineRgb, runEntrypoint } from '@companion-module/base'
import UpgradeScripts from './upgrades.js'
class AjaKumoInstance extends InstanceBase {
watchForNewEvents() {
if (this.connectionId === null) {
return // Do not attempt to connect to a disabled connection
}
const request_con_id = this.connectionId
const url = `http://${this.config.ip}/config?action=wait_for_config_events&configid=0&connectionid=${this.connectionId}`
got.get(url, {cookieJar: this.cookieJar, timeout: { request: 10000 }}).then(response => {
if (this.connectionId === null) return // do not return an error here, since the kumo keeps old connections open for a second
else if (request_con_id !== this.connectionId) return // this request came from an old connection
let parsedResponse = JSON.parse(response.body.toString())
if (Array.isArray(parsedResponse)) {
parsedResponse.forEach((x) => {
if(x.param_id) {
let dest_update = x.param_id.match(/eParamID_XPT_Destination([0-9]{1,2})_Status/)
if (dest_update !== null) {
this.setSrcToDest(dest_update[1], x.int_value)
}
}
})
}
this.watchForNewEvents()
})
.catch(e => {
if (e.code === "ETIMEDOUT") {
this.log('error', 'Lost connection for 10000ms, attempting to reconnect')
} else {
this.log('error', `Error with new event: ${e.message}, will attempt to reconnect...`)
}
// Attempt to reconnect since things could now be out of sync with the device
this.disconnect(true)
})
}
async configUpdated(config) {
if(this.config.ip === config.ip &&
this.config.src_count === config.src_count &&
this.config.dest_count === config.dest_count &&
this.config.password === config.password) return // Nothing updated
this.disconnect()
this.config = config
this.connect()
}
async init(config) {
this.config = config
this.RECONNECT_TIME = 5 // Attempt a reconnect every 5 seconds
this.CONNWAIT = 10 // Time to wait between each status connection (if 64x64, there will be 64*3 + 64*2 http conns made on enable)
this.SALVO_COUNT = 8 // Number of salvos; currently, every Kumo model has 8 salvos
this.names = {
dest_name: {},
src_name: {},
salvo: {},
}
this.cookieJar = new CookieJar() // CookieJar for storing auth cookies
this.actions()
this.initFeedbacks()
this.initPresets()
this.connect()
}
getNameList(type = 'dest') {
let list = []
let count = this.config[`${type}_count`]
let nameType = `${type}_name`
for (let i = 1; i <= count; ++i) {
let name
name = i in this.names[nameType] ? `${i}: ${this.names[nameType][i].join(' ')}` : i
list.push({
id: i,
label: name
})
}
return list
}
getSalvoList() {
let list = []
for (let i = 1; i <= this.SALVO_COUNT; ++i) {
list.push({
id: i,
label: i in this.names.salvo ? `${i}: ${this.names.salvo[i]}` : i
})
}
return list
}
disconnect(reconnect = false) {
this.updateStatus('disconnected')
this.connectionId = null
this.cookieJar.removeAllCookies()
if (this.reconnectTimeout) {
clearTimeout(this.reconnectTimeout)
}
if (reconnect) {
this.reconnectTimeout = setTimeout(this.connect.bind(this), this.RECONNECT_TIME * 1000)
}
}
setSrcToDest(dest, src) {
if (dest in this.srcToDestMap && this.srcToDestMap[dest] === src) return // #nothingchanged
this.srcToDestMap[dest] = src
this.setDynamicVariable(`dest_${dest}`, src)
this.checkFeedbacks('source_match')
this.checkFeedbacks('destination_match')
}
setDynamicVariable(name, value) {
const variable = {};
variable[name] = value
this.setVariableValues(variable)
}
device_reset() {
this.connectionId = null
this.reconnectTimeout = null
this.srcToDestMap = {}
this.selectedDestination = null
this.selectedSource = null
this.variables = [
{ variableId: 'destination', name: 'Current pre-selected destination' },
{ variableId: 'source', name: 'Current pre-selected source' }
]
}
async connect() {
this.device_reset()
if(!this.config.ip) return
this.updateStatus('connecting')
const ip = this.config.ip
const url = `http://${ip}/config?action=connect&configid=0`
const password = this.config.password
if (password) {
this.log('debug', 'Attempting to get auth cookies')
const authResponse = await got
.post(`http://${ip}/authenticator/login`, {
form: {
password_provided: password,
},
timeout: {
request: 3000
},
cookieJar: this.cookieJar,
})
.json()
.catch((e) => {
if (e.code === "ETIMEDOUT") {
this.log('error', `Could not reach AJA KUMO at ${ip}`)
} else {
this.log('error', `Unknown error during authentication: ${e.toString()}`)
}
this.disconnect(true)
this.updateStatus('connection_failure')
})
// Don't continue if original auth request fails, gets retried in the .catch
if (!authResponse) return
if (authResponse.login != 'success') {
this.log('error', 'Authentication failed')
this.log('debug', 'Authentication response: ' + authResponse.login)
this.disconnect() // Don't retry until password has been updated
this.updateStatus('connection_failure', 'Wrong password')
return
}
}
const parsedResponse = await got.get(url, {
timeout: {
request: 3000
},
cookieJar: this.cookieJar
})
.json()
.catch(e => {
if(ip !== this.config.ip) return
this.disconnect(true)
this.updateStatus('connection_failure')
switch (e.code){
case 'ETIMEDOUT':
this.log('error', `Could not reach AJA KUMO at ${ip}`)
break
case 'ERR_NON_2XX_3XX_RESPONSE':
this.log('error', 'Missing password')
this.updateStatus('connection_failure', 'Missing password')
// Disable reconnecting until password has been added
clearTimeout(this.reconnectTimeout)
break
default:
this.log('error', `Unknown error during connecting: ${e.toString()}`)
}
})
if(!parsedResponse || ip !== this.config.ip) return
this.connectionId = parsedResponse.connectionid
this.updateStatus('ok', 'Loading status...')
// It could several seconds to get the initial status due to the many status requests we must make
// So, we're going to get everything setup, then show the variables so the user doesn't have to wait
// And then the vars will be populated as they come in
let currentStatus = this.getCurrentStatus()
this.initVariables()
return Promise.all(currentStatus)
.then(() => {
this.updateStatus('ok')
this.log('info', `Connected to device, connection ID ${this.connectionId}`)
this.actions()
this.initFeedbacks()
this.initPresets()
this.watchForNewEvents()
this.setLabelComboVariables('dest')
this.setLabelComboVariables('src')
}).catch(x => {
if (this.connectionId === parsedResponse.connectionid) {
// If connection is disabled before all promises, we don't want to try reconnecting
this.disconnect(true)
}
})
}
createVariable(name, label) {
this.variables.push({
variableId: name,
name: label
})
}
getCurrentStatus() {
let statusPromises = []
let destsrc = ['dest', 'src']
destsrc.forEach(x => {
let title = x === 'dest' ? 'Destination' : 'Source'
for (let i = 1; i <= this.config[`${x}_count`]; ++i) {
if (x === 'dest') {
this.createVariable(`dest_${i}`, `Destination ${i} source`)
statusPromises.push(this.getParam('dest', { num: i }, statusPromises.length * this.CONNWAIT))
}
this.createVariable(`${x}_name_${i}_line1`, `${title} ${i} name, line 1`)
this.createVariable(`${x}_name_${i}_line2`, `${title} ${i} name, line 2`)
this.createVariable(`${x}_${i}_label_combo`, `${title} ${i} full label`)
statusPromises.push(this.getParam(`${x}_name`, { num: i, line: 1 }, statusPromises.length * this.CONNWAIT))
statusPromises.push(this.getParam(`${x}_name`, { num: i, line: 2 }, statusPromises.length * this.CONNWAIT))
}
})
for (let i = 1; i <= this.SALVO_COUNT; ++i) {
this.createVariable(`salvo_name_${i}`, `Salvo ${i} name`)
statusPromises.push(this.getParam('salvo', { num: i }, statusPromises.length * this.CONNWAIT))
}
return statusPromises
}
getParam(param, options, timewait) {
const connectionId = this.connectionId
let url
if (param === 'dest') {
url = this.buildParamIdUrl(`eParamID_XPT_Destination${options.num}_Status`)
} else if (param === 'dest_name') {
url = this.buildParamIdUrl(`eParamID_XPT_Destination${options.num}_Line_${options.line}`)
} else if (param === 'src_name') {
url = this.buildParamIdUrl(`eParamID_XPT_Source${options.num}_Line_${options.line}`)
} else if (param === 'salvo') {
url = this.buildParamIdUrl(`eParamID_Salvo${options.num}`)
}
return new Promise((resolve, reject) => {
setTimeout(() => {
if (connectionId !== this.connectionId) {
return reject('Connection aborted.')
}
got.get(url, {cookieJar: this.cookieJar}).then((response) => {
// Make sure we're consistent before updating anything, these should be aborted, but could not be...
if (connectionId !== this.connectionId) reject()
let parsedResponse = JSON.parse(response.body.toString())
if (param === 'dest') {
this.setSrcToDest(options.num, parsedResponse.value)
} else if (param === 'dest_name' || param === 'src_name') {
this.setSrcDestName(param, options, parsedResponse.value)
} else if (param === 'salvo' && parsedResponse.value && parsedResponse.value.name) {
this.setSalvoName(options.num, parsedResponse.value.name)
}
resolve()
}).catch(x => {
reject(x.message)
})
}, timewait)
})
}
setSalvoName(num, name) {
this.names['salvo'][num] = name
this.setDynamicVariable(`salvo_name_${num}`, name)
}
buildParamIdUrl(param) {
return `http://${this.config.ip}/config?action=get&configid=0¶mid=${param}`
}
// Create a combination string containing number and name lines, separated by newlines
setLabelComboVariables(type) {
const combo_variables = {}
for (let i = 1; i <= this.config[`${type}_count`]; i++) {
if ( i in this.names[`${type}_name`] ) {
let variable_name = `${type}_${i}_label_combo`
let label_text = `${i}\n` + this.names[`${type}_name`][i].join('\n')
combo_variables[variable_name] = label_text
}
}
this.setVariableValues(combo_variables)
}
setSrcDestName(param, options, value) {
let line = parseInt(options.line) - 1
if (!(options.num in this.names[param])) {
this.names[param][options.num] = []
}
this.names[param][options.num][line] = value
this.setDynamicVariable(`${param}_${options.num}_line${options.line}`, value)
}
// Return config fields for web config
getConfigFields() {
return [
{
type: 'textinput',
id: 'ip',
label: 'IP Address',
tooltip: 'Set the IP address of the KUMO router',
regex: Regex.IP,
width: 12,
},
{
type: 'textinput',
id: 'password',
label: 'Password',
tooltip: 'Password if authentication is enabled, leave blank if not',
width: 12,
},
{
type: 'textinput',
label: 'Source Count',
id: 'src_count',
default: 16,
tooltip: 'Number of inputs/sources the router has.',
regex: Regex.NUMBER,
},
{
type: 'textinput',
label: 'Destination Count',
id: 'dest_count',
default: 4,
tooltip: 'Number of outputs/destinations the router has.',
regex: Regex.NUMBER,
}
]
}
// When module gets deleted
async destroy() {
this.disconnect()
this.updateStatus('disconnected')
}
actions(system) {
const actions = {
route: {
name: 'Route a source (input) to a destination (output)',
description: 'For explicitly routing a source to a destination. Used to perform a route in a single button press.',
options: [
{
type: 'dropdown',
label: 'destination',
id: 'destination',
default: '1',
useVariables: true,
allowCustom: true,
choices: this.getNameList('dest')
},
{
type: 'dropdown',
label: 'source',
id: 'source',
default: '1',
useVariables: true,
allowCustom: true,
choices: this.getNameList('src')
},
],
callback: async (event) => {
const dest = await this.parseVariablesInString(event.options.destination);
const src = await this.parseVariablesInString(event.options.source);
this.actionCall(`eParamID_XPT_Destination${dest}_Status`, src)
this.checkFeedbacks('source_match')
}
},
destination: {
name: 'Pre-select a destination',
description: 'Sets a draft destination and Companion remembers it. Then next, use "Send source" action and this destination will be used.',
options: [
{
type: 'dropdown',
label: 'Destination',
id: 'destination',
default: '1',
choices: this.getNameList('dest')
}
],
callback: (event) => {
this.selectedDestination = event.options.destination
this.setVariableValues({ destination: event.options.destination })
this.checkFeedbacks('active_destination', 'source_match')
},
},
source: {
name: 'Send source to the pre-selected destination',
description: 'Sends a route command with the Source being the one chosen here, and the Destination being the one pre-selected with the action "Pre-select".',
options: [
{
type: 'dropdown',
label: 'source number',
id: 'source',
default: 1,
choices: this.getNameList('src')
}
],
callback: async (event) => {
const destination = this.getVariableValue('destination');
this.selectedSource = event.options.source
this.setVariableValues({ source: event.options.source })
if (destination) {
this.actionCall(`eParamID_XPT_Destination${destination}_Status`, event.options.source)
}
this.checkFeedbacks('active_source', 'source_match')
}
},
salvo: {
name: 'Take (apply) a salvo',
options: [
{
type: 'dropdown',
label: 'salvo',
id: 'salvo',
default: '1',
choices: this.getSalvoList()
},
],
callback: (event) => {
this.actionCall('eParamID_TakeSalvo', event.options.salvo)
this.checkFeedbacks('source_match')
}
},
swap_sources: {
name: 'Swap sources',
description: 'Swap the sources of two specified destinations',
options: [
{
type: 'dropdown',
label: 'destination A',
id: 'dest_A',
default: '1',
choices: this.getNameList()
},
{
type: 'dropdown',
label: 'destination B',
id: 'dest_B',
default: '2',
choices: this.getNameList()
},
],
callback: (event) => {
let source_of_dest_A = this.srcToDestMap[event.options.dest_A]
let source_of_dest_B = this.srcToDestMap[event.options.dest_B]
this.actionCall(`eParamID_XPT_Destination${event.options.dest_A}_Status`, source_of_dest_B)
this.actionCall(`eParamID_XPT_Destination${event.options.dest_B}_Status`, source_of_dest_A)
this.checkFeedbacks('active_destination', 'source_match')
}
},
}
this.setActionDefinitions(actions)
}
actionCall(id, val, action = 'set') {
const url = `http://${this.config.ip}/config?action=${action}&configid=0¶mid=${id}&value=${val}`
got.get(url, {cookieJar: this.cookieJar}).then(response => {
if (this.connectionId === null) reject()
})
.catch(e => {
this.log('error', `Failed to send command to device: ${e}`)
})
}
initVariables() {
this.setVariableDefinitions(this.variables)
this.setVariableValues({
destination: 'Not yet selected',
source: 'Not yet selected'
})
}
initFeedbacks() {
const feedbacks = {
active_destination: {
type: 'boolean',
name: 'Selection of a destination button',
description: 'When a destination button is selected in Companion.',
defaultStyle: {
color: combineRgb(255, 255, 255),
bgcolor: combineRgb(255, 0, 0)
},
options: [{
type: 'dropdown',
label: 'Destination',
id: 'destination',
default: 1,
choices: this.getNameList('dest'),
}],
callback: (feedback) => {
return this.selectedDestination == feedback.options.destination
}
},
active_source: {
type: 'boolean',
name: 'Selection of a source button',
description: 'When a source button is selected in Companion.',
defaultStyle: {
color: combineRgb(255, 255, 255),
bgcolor: combineRgb(255, 0, 0)
},
options: [{
type: 'dropdown',
label: 'Source',
id: 'source',
default: 1,
choices: this.getNameList('src'),
}],
callback: (feedback) => {
return this.selectedSource == feedback.options.source
}
},
source_match: {
type: 'boolean',
name: 'Source matches the pre-selected destination',
description: 'When this source is routed to the pre-selected destination remembered by Companion.',
defaultStyle: {
color: combineRgb(255, 255, 255),
bgcolor: combineRgb(255, 0, 0)
},
options: [
{
type: 'dropdown',
label: 'Source',
id: 'source',
default: 1,
choices: this.getNameList('src')
},
],
callback: (feedback) => {
return this.selectedDestination in this.srcToDestMap && feedback.options.source == this.srcToDestMap[this.selectedDestination]
}
},
destination_match: {
type: 'boolean',
name: 'Specific source is routed to a specific destination',
description: 'When routing on this device changes to a specific source and destination.',
defaultStyle: {
color: combineRgb(255, 255, 255),
bgcolor: combineRgb(255, 0, 0)
},
options: [
{
type: 'dropdown',
label: 'Destination',
id: 'dest',
default: 1,
choices: this.getNameList()
},
{
type: 'dropdown',
label: 'Source',
id: 'src',
default: 1,
choices: this.getNameList('src')
}
],
callback: (feedback) => {
return feedback.options.dest in this.srcToDestMap
&& this.srcToDestMap[feedback.options.dest] == feedback.options.src
}
},
}
this.setFeedbackDefinitions(feedbacks)
}
initPresets() {
const presets = []
// Preset for 'Source buttons' and 'Destination buttons'
function make_src_dest_button_preset(type, n) {
let type_name
let actions = []
let feedbacks = []
if ( type == 'dest' ) {
type_name = 'Destination'
actions = [
{ actionId: 'destination', options: { destination: n } },
]
feedbacks = [
{
feedbackId: 'active_destination',
options: {
destination: n,
},
style: {
color: combineRgb(255, 255, 255),
bgcolor: combineRgb(255, 0, 0)
}
}
]
}
else {
type_name = 'Source'
actions = [
{ actionId: 'source', options: { source: n } },
]
feedbacks = [
{
feedbackId: 'source_match',
options: {
source: n,
},
style: {
color: combineRgb(255, 255, 255),
bgcolor: combineRgb(255, 0, 0)
}
}
]
}
return {
category: `${type_name} buttons`,
name: `${type_name} ${n}`,
type: 'button',
style: {
text: `$(kumo:${type}_${n}_label_combo)`,
size: '18',
color: combineRgb(255, 255, 255),
bgcolor: combineRgb(0, 0, 0),
show_topbar: false,
},
steps: [
{
down: actions,
up: []
}
],
feedbacks: feedbacks,
}
}
// Create for each src & dest in the matrix
let destsrc = [ 'dest', 'src' ]
destsrc.forEach(type => {
for (let i = 1; i <= this.config[`${type}_count`]; ++i) {
presets.push( make_src_dest_button_preset( type, i ) )
}
})
// Apply presets
this.setPresetDefinitions(presets)
}
}
runEntrypoint(AjaKumoInstance, UpgradeScripts)