-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
370 lines (322 loc) · 9.55 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
// Control module for Neutrik NA2-IO-DPRO
// Andrew Broughton <[email protected]>
// October 2024 Version 1.0.0 (for Companion v3)
const { InstanceBase, InstanceStatus, Regex, runEntrypoint, combineRgb, TCPHelper } = require('@companion-module/base')
const paramFuncs = require('./paramFuncs')
const actionFuncs = require('./actions.js')
const varFuncs = require('./variables.js')
const upgrades = require('./upgrades')
const RCP_PORT = 49280
const MSG_DELAY = 5
const METER_REFRESH = 10000
const KA_INTERVAL = 10000
// Instance Setup
class Neutrik_DPRO extends InstanceBase {
constructor(internal) {
super(internal)
}
// Startup
async init(cfg) {
this.updateStatus(InstanceStatus.Connecting, 'Starting')
global.config = cfg
global.rcpCommands = []
this.colorCommands = [] // Commands which have a color field
this.rcpPresets = []
this.dataStore = {} // status, Address (using ":"), X, Y, Val
this.cmdQueue = [] // prefix, Address (using ":"), X, Y, Val
this.queueTimer
this.kaTimer = {}
this.variables = []
this.newConsole()
}
// Change in Configuration
async configUpdated(cfg) {
config = cfg
if (config.model) {
this.newConsole()
}
}
// Module deletion
async destroy() {
clearTimeout(this.queueTimer)
clearInterval(this.kaTimer)
this.socket?.destroy()
this.log('debug', `[${new Date().toJSON()}] destroyed ${this.id}`)
}
// Web UI config fields
getConfigFields() {
let config = [
{
type: 'dropdown',
id: 'model',
label: 'Device Type',
width: 12,
default: 'NA2-IO-DPRO',
choices: [{ id: 'NA2-IO-DPRO', label: 'NA2-IO-DPRO' }],
isVisible: () => false,
},
{
type: 'bonjour-device',
id: 'bonjour_host',
label: 'Bonjour Address of Device',
width: 6,
default: '',
regex: Regex.HOSTNAME,
},
{
type: 'textinput',
id: 'host',
label: 'IP Address of Device',
width: 6,
default: '192.168.0.128',
regex: Regex.IP,
isVisible: (options) => !options.bonjour_host,
},
{
type: 'static-text',
label: '',
width: 6,
isVisible: (options) => !!options.bonjour_host,
},
]
return config
}
// Whenever the console type changes, update the info
newConsole() {
this.log('info', `Device selected: ${config.model}`)
rcpCommands = paramFuncs.getParams(this, config)
actionFuncs.updateActions(this) // Re-do the actions once the console is chosen
varFuncs.initVars(this)
this.createPresets()
config.host = config.bonjour_host?.split(':')[0] || config.host
this.initTCP()
}
// Initialize TCP
initTCP() {
let receiveBuffer = ''
let receivedLines = []
let receivedCmds = []
let foundCmd = {}
this.socket?.destroy()
delete this.socket
if (config.host) {
this.socket = new TCPHelper(config.host, RCP_PORT)
this.socket.on('status_change', (status, message) => {
this.updateStatus(status, message)
})
this.socket.on('error', (err) => {
this.log('error', `Network error: ${err.message}`)
this.updateStatus(InstanceStatus.ConnectionFailure)
})
this.socket.on('connect', () => {
this.log('info', `Connected!`)
this.updateStatus(InstanceStatus.Ok)
clearInterval(this.kaTimer)
varFuncs.getVars(this)
this.queueTimer = {}
this.processCmdQueue()
this.subscribeActions()
this.subscribeFeedbacks()
this.sendCmd(`scpmode keepalive ${KA_INTERVAL * 2}`) // Tell device to close connection after 2 * KA interval without RXing any messages
this.kaTimer = setInterval(() => this.sendCmd('devstatus runmode'), KA_INTERVAL) // Send message on KA interval to ensure connection isn't closed
})
this.socket.on('data', (chunk) => {
receiveBuffer += chunk
receivedLines = receiveBuffer.split('\x0A') // Split by line break
if (receivedLines.length == 0) {
return // No messages
}
if (receiveBuffer.endsWith('\x0A')) {
receiveBuffer = receivedLines[receivedLines.length - 1] // Broken line, leave it for next time...
receivedLines.splice(receivedLines.length - 1) // Remove it.
} else {
receiveBuffer = ''
}
for (let line of receivedLines) {
if (line.length == 0) {
continue
}
this.log('debug', `[${new Date().toJSON()}] Received: '${line}'`)
receivedCmds = paramFuncs.parseData(line) // Break out the parameters
for (let i = 0; i < receivedCmds.length; i++) {
let curCmd = JSON.parse(JSON.stringify(receivedCmds[i])) // deep clone
foundCmd = paramFuncs.findRcpCmd(curCmd.Address, curCmd.Action) // Find which command
switch (curCmd.Action) {
case 'set':
case 'get':
if (foundCmd != undefined) {
if (!(curCmd.Status == 'OK' && curCmd.Action == 'set')) {
this.addToDataStore(curCmd)
}
if (this.isRecordingActions) {
this.addToActionRecording({ rcpCmd: foundCmd, options: curCmd })
}
}
}
varFuncs.setVar(this, curCmd)
this.processCmdQueue(curCmd)
}
}
})
}
}
// New Command (Action or Feedback) to Add
addToCmdQueue(cmd) {
clearTimeout(this.queueTimer)
let cmdToAdd = JSON.parse(JSON.stringify(cmd)) // Deep Clone
let rcpCmd = paramFuncs.findRcpCmd(cmdToAdd.Address)
let i = this.cmdQueue.findIndex(
(c) =>
c.prefix == cmdToAdd.prefix &&
c.Address == cmdToAdd.Address &&
((c.X == cmdToAdd.X && c.Y == cmdToAdd.Y) || (rcpCmd.Action == 'mtrinfo' && c.Y == cmdToAdd.Y)),
)
if (i > -1) {
this.cmdQueue[i] = cmdToAdd // Replace queued message with new one
} else {
this.cmdQueue.push(cmdToAdd)
}
if (this.queueTimer) {
this.queueTimer = setTimeout(() => {
this.processCmdQueue()
}, MSG_DELAY)
}
}
// When a message comes in from the console, match it up and delete it, and send the next message
processCmdQueue(cmd) {
clearTimeout(this.queueTimer)
if (this.cmdQueue == undefined || this.cmdQueue.length == 0) return
if (cmd != undefined) {
let i = this.cmdQueue.findIndex(
(c) => c.prefix == 'get' && c.Address == cmd.Address && c.X == cmd.X && c.Y == cmd.Y,
)
if (i > -1) {
this.cmdQueue.splice(i, 1) // Got value from matching request so remove it!
}
}
if (this.cmdQueue.length > 0) {
// Messages still to send?
let nextCmd = this.cmdQueue[0] // Oldest
if (nextCmd.prefix == 'set') {
let nextCmdVal = paramFuncs.parseVal(this, nextCmd)
if (nextCmdVal == undefined) {
this.cmdQueue.shift()
this.cmdQueue.push(nextCmd)
this.queueTimer = setTimeout(() => {
this.processCmdQueue()
}, MSG_DELAY)
return
}
nextCmd.Val = nextCmdVal
}
let msg = paramFuncs.fmtCmd(nextCmd)
if (this.sendCmd(msg)) {
if (nextCmd.prefix == 'set') {
this.addToDataStore(nextCmd) // Update to latest value
}
}
this.cmdQueue.shift() // Get rid of message, whether sent or not
this.queueTimer = setTimeout(() => {
this.processCmdQueue()
}, MSG_DELAY)
}
}
// Create the preset definitions
createPresets() {
this.rcpPresets = []
this.setPresetDefinitions(this.rcpPresets)
}
// Track whether actions are being recorded
handleStartStopRecordActions(isRecording) {
this.isRecordingActions = isRecording
}
// Add a command to the Action Recorder
async addToActionRecording(c) {
let aId = c.rcpCmd.Address.replace(/:/g, '_')
let cX = parseInt(c.options.X) + 1
let cY = parseInt(c.options.Y) + 1
let cV
switch (c.rcpCmd.Type) {
case 'integer':
case 'binary':
cV = c.options.Val == -32768 ? '-Inf' : c.options.Val / c.rcpCmd.Scale
break
case 'freq':
cV = c.options.Val / c.rcpCmd.Scale
break
case 'bool':
cV = 'Toggle'
break
case 'string':
cV = c.options.Val
break
}
this.recordAction(
{
actionId: aId,
options: { X: cX, Y: cY, Val: cV },
},
`${aId} ${cX} ${cY}`, // uniqueId to stop duplicates
)
}
sendCmd(c) {
if (c !== undefined) {
c = c.trim()
this.log(
'debug',
`[${new Date().toJSON()}] Sending : '${c}' to ${this.getVariableValue('modelName')} @ ${config.host}`,
)
if (this.socket !== undefined && this.socket.isConnected) {
this.socket.send(`${c}\n`) // send the message to the device
return true
}
this.log('info', 'Socket not connected :(')
}
return false
}
// Poll the console for it's status to update buttons via feedback
pollConsole() {
//varFuncs.getVars(this)
this.dataStore = {}
this.subscribeActions()
this.checkFeedbacks()
}
// Add a value to the dataStore
addToDataStore(cmd) {
const dsAddr = cmd.Address
const dsX = cmd.X == undefined ? 0 : parseInt(cmd.X)
const dsY = cmd.Y == undefined ? 0 : parseInt(cmd.Y)
if (this.dataStore[dsAddr] == undefined) {
this.dataStore[dsAddr] = {}
}
if (this.dataStore[dsAddr][dsX] == undefined) {
this.dataStore[dsAddr][dsX] = {}
}
if (this.dataStore[dsAddr][dsX][dsY] != cmd.Val) {
this.dataStore[dsAddr][dsX][dsY] = cmd.Val
this.checkFeedbacks(dsAddr.replace(/:/g, '_')) // Make sure variables are updated
}
}
// Get a value from the dataStore. If the value doesn't exist, send a request to get it.
getFromDataStore(cmd) {
let data = undefined
if (cmd == undefined) return data
if (cmd.Address !== undefined) {
if (
this.dataStore[cmd.Address] !== undefined &&
this.dataStore[cmd.Address][cmd.X] !== undefined &&
this.dataStore[cmd.Address][cmd.X][cmd.Y] !== undefined
) {
data = this.dataStore[cmd.Address][cmd.X][cmd.Y]
return data
}
let rcpCmd = paramFuncs.findRcpCmd(cmd.Address)
if (rcpCmd !== undefined && rcpCmd.RW.includes('r')) {
cmd.prefix = 'get'
this.addToCmdQueue(cmd)
}
}
return data
}
}
runEntrypoint(Neutrik_DPRO, upgrades)