-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.js
2342 lines (2052 loc) · 111 KB
/
main.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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
*
* iobroker x-touch Adapter
*
* Copyright (c) 2020-2024, Bannsaenger <[email protected]>
*
* MIT License
*
*/
/*
* ToDo:
* - when maxBanks or maxChannels changes, delete when createBank is set
* - resend data on group membership change
*/
// The adapter-core module gives you access to the core ioBroker functions
// you need to create an adapter
const utils = require('@iobroker/adapter-core');
// Load your modules here, e.g.:
const fs = require('fs');
const udp = require('dgram');
// eslint-disable-next-line no-unused-vars
const { debug } = require('console');
const POLL_REC = 'F0002032585400F7';
const POLL_REPLY = 'F00000661400F7';
//const HOST_CON_QUERY = 'F000006658013031353634303730344539F7';
const HOST_CON_QUERY = 'F000006658013031353634303732393345F7';
const HOST_CON_REPLY = 'F0000066580230313536343037353D1852F7';
class XTouch extends utils.Adapter {
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
constructor(options) {
super({
...options,
name: 'x-touch',
});
this.on('ready', this.onReady.bind(this));
this.on('stateChange', this.onStateChange.bind(this));
// this.on('objectChange', this.onObjectChange.bind(this));
this.on('message', this.onMessage.bind(this));
this.on('unload', this.onUnload.bind(this));
// read Objects template for object generation
this.objectsTemplate = JSON.parse(fs.readFileSync(__dirname + '/lib/objects_templates.json', 'utf8'));
// Midi mapping
this.midi2Objects = JSON.parse(fs.readFileSync(__dirname + '/lib/midi_mapping.json', 'utf8'));
this.objects2Midi = {};
// and layout
this.consoleLayout = JSON.parse(fs.readFileSync(__dirname + '/lib/console_layout.json', 'utf8'));
// mapping of the encoder modes to LED values
this.encoderMapping = JSON.parse(fs.readFileSync(__dirname + '/lib/encoder_mapping.json', 'utf8'));
// mapping of the characters in timecode display to 7-segment
// coding is in Siekoo-Alphabet (https://fakoo.de/siekoo.html)
// not as described in Logic Control Manual
this.characterMapping = JSON.parse(fs.readFileSync(__dirname + '/lib/character_mapping.json', 'utf8'));
// devices object, key is ip address. Values are connection and memberOfGroup
this.devices = [];
this.nextDevice = 0; // next device index for db creation
this.deviceGroups = [];
this.timers = {}; // a place to store timers
this.timers.encoderWheels = {}; // e.g. encoder wheel reset timers by device group
this.timers.sendDelay = undefined; // put the timer based on the configured sendDelay here
// Send buffer (Array of sendData objects)
// sendData = {
// data: {buffer | array of buffers}
// address : {string} // ipAddress
// port: {string | number} // port to send back (normally 10111)
// }
this.sendBuffer = [];
this.sendActive = false; // true if data sending is ongoing right now
// creating a udp server
this.server = udp.createSocket('udp4');
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
const self = this;
try {
// Initialize your adapter here
// Reset the connection indicator during startup
self.setState('info.connection', false, true);
// emits when any error occurs
self.server.on('error', self.onServerError.bind(self));
// emits when socket is ready and listening for datagram msgs
self.server.on('listening', self.onServerListening.bind(self));
// emits after the socket is closed using socket.close();
self.server.on('close', self.onServerClose.bind(self));
// emits on new datagram msg
self.server.on('message', self.onServerMessage.bind(self));
// The adapters config (in the instance object everything under the attribute 'native' is accessible via
// this.config:
/*
* create a vice versa mapping in object2Midi
*/
for (const mapping of Object.keys(self.midi2Objects)) {
self.objects2Midi[self.midi2Objects[mapping]] = mapping;
}
/*
* For every state in the system there has to be also an object of type state
*/
for (const element of self.objectsTemplate.common) {
await self.setObjectNotExistsAsync(element._id, element);
}
/*
* create the database
*/
await self.createDatabaseAsync();
// Read all devices in the db
let tempObj;
let actDeviceNum = '-1';
const result_state = await self.getStatesOfAsync('devices');
for (const element of result_state) {
const splitStringArr = element._id.split('.');
if (splitStringArr[3] !== actDeviceNum) {
// next device detected
actDeviceNum = splitStringArr[3];
tempObj = await self.getStateAsync('devices.' + actDeviceNum + '.ipAddress');
// @ts-ignore
const actIpAddress = (tempObj && tempObj.val) ? tempObj.val.toString() : '';
tempObj = await self.getStateAsync('devices.' + actDeviceNum + '.port');
// @ts-ignore
const actPort = (tempObj && tempObj.val) ? tempObj.val.toString() : '';
tempObj = await self.getStateAsync('devices.' + actDeviceNum + '.memberOfGroup');
// @ts-ignore
const actMemberOfGroup = (tempObj && tempObj.val) ? tempObj.val : 0;
tempObj = await self.getStateAsync('devices.' + actDeviceNum + '.serialNumber');
// @ts-ignore
const actSerialNumber = (tempObj && tempObj.val) ? tempObj.val.toString() : '';
tempObj = await self.getStateAsync('devices.' + actDeviceNum + '.activeBank');
// @ts-ignore
const actActiveBank = (tempObj && tempObj.val) ? tempObj.val : 0;
tempObj = await self.getStateAsync('devices.' + actDeviceNum + '.activeBaseChannel');
// @ts-ignore
const actActiveBaseChannel = (tempObj && tempObj.val) ? tempObj.val : 0;
self.devices[actIpAddress] = {
'index' : actDeviceNum,
'connection' : false, // connection must be false on system start
'ipAddress' : actIpAddress,
'port' : actPort,
'memberOfGroup' : actMemberOfGroup,
'serialNumber' : actSerialNumber,
'activeBank' : actActiveBank,
'activeBaseChannel' : actActiveBaseChannel
};
self.log.debug('X-Touch got device with ip address ' + self.devices[actIpAddress].ipAddress + ' from the db');
}
}
self.nextDevice = Number(actDeviceNum) + 1;
self.log.info('X-Touch got ' + Object.keys(self.devices).length + ' devices from the db. Next free device number: "' + self.nextDevice + '"');
// read all states from the device groups to memory
const device_states = await self.getStatesOfAsync('deviceGroups');
for (const device_state of device_states) {
self.deviceGroups[device_state._id] = device_state;
tempObj = await self.getStateAsync(device_state._id);
// @ts-ignore
self.deviceGroups[device_state._id].val = (tempObj && tempObj.val !== undefined) ? tempObj.val : '';
self.deviceGroups[device_state._id].helperBool = false; // used for e.g. autoToggle
self.deviceGroups[device_state._id].helperNum = -1; // used for e.g. display of encoders
}
self.log.info('X-Touch got ' + Object.keys(self.deviceGroups).length + ' states from the db');
// In order to get state updates, you need to subscribe to them. The following line adds a subscription for our variable we have created above.
// Or, if you really must, you can also watch all states. Don't do this if you don't need to. Otherwise this will cause a lot of unnecessary load on the system:
self.subscribeStates('*');
// try to open open configured server port
self.log.info('Bind UDP socket to: "' + self.config.bind + ':' + self.config.port + '"');
self.server.bind(self.config.port, self.config.bind);
// Set the connection indicator after startup
// self.setState('info.connection', true, true);
// set by onServerListening
// create a timer to reset the encoder state for each device group
for (let index = 0; index < self.config.deviceGroups; index++) {
self.timers.encoderWheels[index] = setTimeout(self.onEncoderWheelTimeoutExceeded.bind(self, index.toString()), 1000);
}
// last action is to create the timer for the sendDelay and unref it immediately
self.timers.sendDelay = setTimeout(self.deviceSendNext.bind(self, undefined, 'timer'), self.config.sendDelay || 1);
//self.timers.sendDelay.unref();
} catch (err) {
self.errorHandler(err, 'onReady');
}
}
/**
* Is called to set the connection state in db and log
* @param {string} deviceAddress
* @param {number} port
* @param {boolean} status
*/
async setConnection(deviceAddress, port, status) {
const self = this;
try {
if (status) {
/*
create new device if this is the first polling since start of adapter
*/
if (!(deviceAddress in self.devices)) {
self.devices[deviceAddress] = {
'activeBank': 0,
'activeBaseChannel': 1,
'connection': true,
'ipAddress': deviceAddress,
'port': port,
'memberOfGroup': 0,
'serialNumber': '',
'index': self.nextDevice,
};
let prefix = 'devices.' + self.nextDevice.toString();
self.setObjectNotExists(prefix, self.objectsTemplate.device);
prefix += '.';
self.nextDevice++;
for (const element of self.objectsTemplate.devices) {
await self.setObjectNotExistsAsync(prefix + element._id, element);
}
self.log.info('X-Touch device with IP <' + deviceAddress + '> created. Is now online.');
await self.setStateAsync(prefix + 'ipAddress', deviceAddress, true);
await self.setStateAsync(prefix + 'port', port, true);
await self.setStateAsync(prefix + 'memberOfGroup', 0, true);
await self.setStateAsync(prefix + 'connection', true, true);
self.deviceUpdateDevice(deviceAddress);
if (self.devices[deviceAddress].timerDeviceInactivityTimeout) {
self.devices[deviceAddress].timerDeviceInactivityTimeout.refresh();
} else {
self.devices[deviceAddress].timerDeviceInactivityTimeout = setTimeout(this.onDeviceInactivityTimeoutExceeded.bind(this, deviceAddress), this.config.deviceInactivityTimeout);
}
} else { // object in db must exist. Only set state if connection changed to true
if (!self.devices[deviceAddress].connection) {
self.devices[deviceAddress].connection = true;
self.devices[deviceAddress].port = port;
self.log.info('X-Touch device with IP <' + deviceAddress + '> is now online.');
await self.setStateAsync('devices.' + self.devices[deviceAddress].index + '.connection', true, true);
await self.setStateAsync('devices.' + self.devices[deviceAddress].index + '.port', port, true); // port can have changed
self.deviceUpdateDevice(deviceAddress);
}
if (self.devices[deviceAddress].timerDeviceInactivityTimeout) {
self.devices[deviceAddress].timerDeviceInactivityTimeout.refresh();
} else {
self.devices[deviceAddress].timerDeviceInactivityTimeout = setTimeout(this.onDeviceInactivityTimeoutExceeded.bind(this, deviceAddress), this.config.deviceInactivityTimeout);
}
}
} else {
self.devices[deviceAddress].connection = false;
self.log.info('X-Touch device with IP <' + deviceAddress + '> now offline.');
await self.setStateAsync('devices.' + self.devices[deviceAddress].index + '.connection', false, true);
if (self.devices[deviceAddress].timerDeviceInactivityTimeout) {
clearTimeout(self.devices[deviceAddress].timerDeviceInactivityTimeout);
self.devices[deviceAddress].timerDeviceInactivityTimeout = undefined;
}
}
} catch (err) {
self.errorHandler(err, 'setConnection');
}
}
// Methods related to Server events
/**
* Is called if a server error occurs
* @param {any} error
*/
onServerError(error) {
this.log.error('Server got Error: <' + error + '> closing server.');
// Reset the connection indicator
this.setState('info.connection', false, true);
this.server.close();
}
/**
* Is called when the server is ready to process traffic
*/
onServerListening() {
const addr = this.server.address();
this.log.info('X-Touch server ready on <' + addr.address + '> port <' + addr.port + '> proto <' + addr.family + '>');
// Set the connection indicator after server goes for listening
this.setState('info.connection', true, true);
}
/**
* Is called when the server is closed via server.close
*/
onServerClose() {
this.log.info('X-Touch server is closed');
}
/**
* Is called when the activity timer of a device expires
* @param {string} deviceAddress
*/
onDeviceInactivityTimeoutExceeded(deviceAddress) {
this.log.debug('X-Touch device "' + deviceAddress + '" reached inactivity timeout');
this.setConnection(deviceAddress, 0, false);
}
/**
* Is called when the encoder wheel values must be resetted to false
* @param {string} deviceGroup
*/
onEncoderWheelTimeoutExceeded(deviceGroup) {
this.log.debug(`X-Touch encoder wheel from device group ${deviceGroup}" reached inactivity timeout`);
this.setState(`deviceGroups.${deviceGroup}.transport.encoder.cw`, false, true); // reset the
this.setState(`deviceGroups.${deviceGroup}.transport.encoder.ccw`, false, true); // state values
}
/**
* Is called on new datagram msg from server
* @param {Buffer} msg the message content received by the server socket
* @param {Object} info the info for e.g. address of sending host
*/
async onServerMessage(msg, info) {
const self = this;
try {
const msg_hex = msg.toString('hex').toUpperCase();
const memberOfGroup = self.devices[info.address] ? self.devices[info.address].memberOfGroup : '0';
let midiMsg;
let stepsTaken;
let direction;
// If a polling is received then answer the polling to hold the device online
if (msg_hex === POLL_REC){
self.log.silly(`X-Touch received Polling from device ${info.address}, give an reply "${self.logHexData(POLL_REPLY)}"`);
self.setConnection(info.address, info.port, true);
self.deviceSendData(self.fromHexString(POLL_REPLY), info.address, info.port);
} else if (msg_hex === HOST_CON_QUERY){
self.log.silly('X-Touch received Host Connection Query, give no reply, probably "' + self.logHexData(HOST_CON_REPLY) + '" in the future');
} else { // other than polling and connection setup
self.log.debug('-> ' + msg.length + ' bytes from ' + info.address + ':' + info.port + ': <' + self.logHexData(msg_hex) + '> org: <' + msg.toString() + '>');
midiMsg = self.parseMidiData(msg);
let baseId;
const actPressed = midiMsg.value === '127' ? true : false;
switch (midiMsg.msgType) {
case 'NoteOff': // No NoteOff events for now, description wrong. Only NoteOn with dynamic 0
break;
case 'NoteOn': // NoteOn
baseId = self.midi2Objects[midiMsg.note] ? self.namespace + '.deviceGroups.' + memberOfGroup + '.' + self.midi2Objects[midiMsg.note] : '';
if (Number(midiMsg.note) >= 104 && Number(midiMsg.note) <= 112) { // Fader touched, Fader 1 - 8 + Master
await self.handleFader(baseId , undefined, actPressed ? 'touched' : 'released', info.address);
} else if (Number(midiMsg.note) >= 46 && Number(midiMsg.note) <= 49) { // fader or channel switch
if (actPressed) { // only on butten press, omit release
let action = '';
switch (Number(midiMsg.note)) {
case 46: // fader bank down
action = 'bankDown';
break;
case 47: // fader bank up
action = 'bankUp';
break;
case 48: // channel bank up
action = 'channelDown';
break;
case 49: // channel bank down
action = 'channelUp';
break;
}
await self.deviceSwitchChannels(action, info.address);
}
}
else {
await self.handleButton(baseId, undefined, actPressed ? 'pressed' : 'released', info.address);
}
break;
case 'Pitchbend': // Pitchbend (Fader value)
baseId = self.namespace + '.deviceGroups.' + memberOfGroup;
if (Number(midiMsg.channel) > 7) { // Master Fader
baseId += '.masterFader';
} else {
baseId += '.banks.0.channels.' + (Number(midiMsg.channel) + 1) + '.fader';
}
await self.handleFader(baseId, midiMsg.value, 'fader', info.address);
break;
case 'ControlChange': // Encoders do that
baseId = self.namespace + '.deviceGroups.' + memberOfGroup;
if ((Number(midiMsg.controller) >= 16) &&
(Number(midiMsg.controller) <= 23)){ // Channel encoder
baseId += '.banks.0.channels.' + (Number(midiMsg.controller) - 15) + '.encoder';
} else {
baseId += '.transport.encoder';
}
//self.log.info(`midi message controller ${midiMsg.controller} value ${midiMsg.value}`);
stepsTaken = 1;
direction = 'cw';
if (midiMsg.value < 65) {
stepsTaken = midiMsg.value;
} else {
stepsTaken = midiMsg.value - 64;
direction = 'ccw';
}
await self.handleEncoder(baseId, stepsTaken, direction, info.address);
break;
}
}
} catch (err) {
self.errorHandler(err, 'onServerMessage');
}
}
/********************************************************************************
* handler functions to handle the values coming from the database or the device
********************************************************************************
* only the fader is not allowed to be transmitted to the sending device
* primary behaviour is correction of values and the processing of the
* autofunction process
********************************************************************************/
/**
* handle the button events and call the sendback if someting is changed
* @param {string} buttonId full button id via onStateChange
* @param {any | null | undefined} value
* @param {string} event pressed, released, fader or value (value = when called via onStateChange)
* @param {string} deviceAddress only chen called via onServerMessage
*/
async handleButton(buttonId, value = undefined, event = 'value', deviceAddress = '') {
const self = this;
try {
let baseId;
let stateName = ''; // the name of the particular state when called via onStateChange
const buttonArr = buttonId.split('.');
let activeBank = 0;
let activeBaseChannel = 1;
let actStatus;
let isDirty = false; // if true the button states has changed and must be sent
if (buttonId === '') {
self.log.debug('X-Touch button not supported');
return;
}
if (event === 'value') { // when called via onStateChange there is the full button id, cut the last part for baseId
baseId = buttonId.substr(0, buttonId.lastIndexOf('.'));
stateName = buttonId.substr(buttonId.lastIndexOf('.') + 1);
if (stateName === '') {
self.log.error('handleButton called with value and only baseId');
return; // if no value part provided throw an error
}
switch (stateName) {
case 'autoToggle':
// ToDo: check values and write back
self.deviceGroups[baseId + '.autoToggle'].val = value; // only update the internal db
return;
case 'syncGlobal':
self.deviceGroups[baseId + '.syncGlobal'].val = Boolean(value); // only update the internal db
return;
case 'flashing':
if (self.deviceGroups[baseId + '.flashing'].val != Boolean(value)) { // if changed send
self.deviceGroups[baseId + '.flashing'].val = Boolean(value);
isDirty = true;
}
break;
case 'pressed':
event = value ? 'pressed' : 'released'; // if button press is simulated via state db
break;
default:
if (self.deviceGroups[baseId + '.status'].val != Boolean(value)) { // if changed send
self.deviceGroups[baseId + '.status'].val = Boolean(value);
isDirty = true;
}
}
} else { // when called by midiMsg determine the real channel
if ((deviceAddress !== '') && self.devices[deviceAddress]) {
activeBank = self.devices[deviceAddress].activeBank;
activeBaseChannel = self.devices[deviceAddress].activeBaseChannel;
}
if (buttonArr[4] === 'banks') { // replace bank and baseChannel on channel buttons
buttonArr[5] = activeBank.toString();
buttonArr[7] = (Number(buttonArr[7]) + activeBaseChannel - 1).toString();
}
baseId = buttonArr.join('.');
}
const buttonName = buttonArr.length > 8 ? buttonArr[8] : '';
const actPressed = event === 'pressed' ? true : false;
if (buttonName === 'encoder') { // encoder is only pressed event
await self.setStateAsync(baseId + '.pressed', actPressed, true);
} else {
actStatus = self.deviceGroups[baseId + '.status'].val;
let setValue = actStatus;
if (event === 'value') {
setValue = Boolean(value);
isDirty = true;
} else { // handle the button auto mode
if (self.deviceGroups[baseId + '.pressed'].val !== actPressed) { // if status changed
self.deviceGroups[baseId + '.pressed'].val = actPressed;
await self.setStateAsync(baseId + '.pressed', actPressed, true);
switch (self.deviceGroups[baseId + '.autoToggle'].val) {
case 0: // no auto function
break;
case 1: // tip
setValue = actPressed ? true : false;
break;
case 2: // on press
if (actPressed) setValue = actStatus ? false : true;
break;
case 3: // on release
if (!actPressed) setValue = actStatus ? false : true;
break;
case 4: // on press / release
if (actPressed && !actStatus) {
setValue = true;
self.deviceGroups[baseId + '.autoToggle'].helperBool = true;
}
if (!actPressed && actStatus) {
if (self.deviceGroups[baseId + '.autoToggle'].helperBool) {
self.deviceGroups[baseId + '.autoToggle'].helperBool = false;
} else {
setValue = false;
}
}
break;
}
}
if (self.deviceGroups[baseId + '.status'].val !== setValue){ // if status changed
self.deviceGroups[baseId + '.status'].val = setValue;
await self.setStateAsync(baseId + '.status', setValue, true);
isDirty = true;
}
}
if (isDirty) {
self.sendButton(baseId);
}
}
} catch (err) {
self.errorHandler(err, 'handleButton');
}
}
/**
* handle the fader events and call the sendback if someting is changed
* @param {string} faderId full fader id via onStateChange
* @param {any | null | undefined} value
* @param {string} event pressed, released or value (value = when called via onStateChange)
* @param {string} deviceAddress only chen called via onServerMessage
*/
async handleFader(faderId, value = undefined, event = 'value', deviceAddress = '') {
const self = this;
try {
let baseId;
let stateName = ''; // the name of the particular state when called via onStateChange
const faderArr = faderId.split('.');
let activeBank = 0;
let activeBaseChannel = 1;
let isDirty = false; // if true the fader states has changed and must be sent
let locObj = self.calculateFaderValue(value, 'midiValue');
if (faderId === '') {
self.log.debug('X-Touch fader not supported');
return;
}
if (event === 'value') { // if called via onStateChange there is the full fader id, cut the last part for baseId
baseId = faderId.substr(0, faderId.lastIndexOf('.'));
stateName = faderId.substr(faderId.lastIndexOf('.') + 1);
switch (stateName) {
case 'syncGlobal':
self.deviceGroups[baseId + '.syncGlobal'].val = Boolean(value); // only update the internal db
return;
case 'touched':
self.deviceGroups[baseId + '.touched'].val = Boolean(value); // only update the internal db
return;
case 'value':
locObj = self.calculateFaderValue(value, 'linValue');
if (self.deviceGroups[baseId + '.value'].val != locObj.linValue) {
self.deviceGroups[baseId + '.value'].val = locObj.linValue;
self.deviceGroups[baseId + '.value_db'].val = locObj.logValue;
isDirty = true;
}
await self.setStateAsync(baseId + '.value', Number(locObj.linValue), true); // maybe correct the format
await self.setStateAsync(baseId + '.value_db', Number(locObj.logValue), true); // update log value too
break;
case 'value_db':
locObj = self.calculateFaderValue(value, 'logValue');
if (self.deviceGroups[baseId + '.value_db'].val != locObj.logValue) {
self.deviceGroups[baseId + '.value_db'].val = locObj.logValue;
self.deviceGroups[baseId + '.value'].val = locObj.linValue;
isDirty = true;
}
await self.setStateAsync(baseId + '.value_db', Number(locObj.logValue), true); // maybe correct the format
await self.setStateAsync(baseId + '.value', Number(locObj.linValue), true); // update lin value too
break;
default:
self.log.warn('X-Touch unknown fader value: "' + faderId + '"');
return;
}
} else { // if called by midiMsg determine the real channel
if ((deviceAddress !== '') && self.devices[deviceAddress]) {
activeBank = self.devices[deviceAddress].activeBank;
activeBaseChannel = self.devices[deviceAddress].activeBaseChannel;
}
if (faderArr[4] === 'banks') { // replace bank and baseChannel
faderArr[5] = activeBank.toString();
faderArr[7] = (Number(faderArr[7]) + activeBaseChannel - 1).toString();
}
baseId = faderArr.join('.');
if (event === 'touched') {
if (!self.deviceGroups[baseId + '.touched'].val) { // if status changed
self.deviceGroups[baseId + '.touched'].val = true;
await self.setStateAsync(baseId + '.touched', true, true);
}
} else if (event === 'released') {
if (self.deviceGroups[baseId + '.touched'].val) { // if status changed
self.deviceGroups[baseId + '.touched'].val = false;
await self.setStateAsync(baseId + '.touched', false, true);
}
} else if (event === 'fader') {
if (self.deviceGroups[baseId + '.value'].val != locObj.linValue) {
self.deviceGroups[baseId + '.value'].val = locObj.linValue;
await self.setStateAsync(baseId + '.value', Number(locObj.linValue), true);
isDirty = true;
}
if (self.deviceGroups[baseId + '.value_db'].val != locObj.logValue) {
self.deviceGroups[baseId + '.value_db'].val = locObj.logValue;
await self.setStateAsync(baseId + '.value_db', Number(locObj.logValue), true);
isDirty = true;
}
} else {
self.log.error('X-Touch handleFader received unknown event: "' + event + '"');
}
}
if (isDirty) {
self.sendFader(baseId, deviceAddress, true);
}
} catch (err) {
self.errorHandler(err, 'handleFader');
}
}
/**
* handle the display status and call the send back if someting is changed
* @param {string} displayId only when called via onStateChange
* @param {any | null | undefined} value
*/
async handleDisplay(displayId, value = undefined) {
const self = this;
try {
const displayArr = displayId.split('.');
const stateName = displayArr.length > 9 ? displayArr[9] : '';
const baseId = displayId.substr(0, displayId.lastIndexOf('.'));
if (value === undefined) return; // nothing to do
if (stateName === '') return; // if only base id there is nothing to handle. only called via onStateChange. Sending is done via sendDisplay
let color = Number(self.deviceGroups[baseId + '.color'].val);
let inverted = self.deviceGroups[baseId + '.inverted'].val;
let line1 = self.deviceGroups[baseId + '.line1'].val || '';
let line1_ct = self.deviceGroups[baseId + '.line1_ct'].val;
let line2 = self.deviceGroups[baseId + '.line2'].val || '';
let line2_ct = self.deviceGroups[baseId + '.line2_ct'].val;
switch (stateName) { // correction of malformed values
case 'color':
color = Number(value);
if (color < 0 || color > 7) {
color = 0;
await self.setStateAsync(baseId + '.color', color, true);
}
self.deviceGroups[baseId + '.color'].val = color.toString();
break;
case 'inverted':
inverted = Boolean(value);
self.deviceGroups[baseId + '.inverted'].val = inverted;
break;
case 'line1':
line1 = value.toString();
if (!self.isASCII(line1)) {
line1 = '';
await self.setStateAsync(baseId + '.line1', line1, true);
}
if (line1.length > 7) {
line1 = line1.substr(0,7);
await self.setStateAsync(baseId + '.line1', line1, true);
}
self.deviceGroups[baseId + '.line1'].val = line1;
break;
case 'line1_ct':
line1_ct = Boolean(value);
self.deviceGroups[baseId + '.line1_ct'].val = line1_ct;
break;
case 'line2':
line2 = value.toString();
if (!self.isASCII(line2)) {
line2 = '';
await self.setStateAsync(baseId + '.line2', line2, true);
}
if (line1.length > 7) {
line1 = line1.substr(0,7);
await self.setStateAsync(baseId + '.line1', line1, true);
}
self.deviceGroups[baseId + '.line2'].val = line2;
break;
case 'line2_ct':
line2_ct = Boolean(value);
self.deviceGroups[baseId + '.line2_ct'].val = line2_ct;
break;
}
self.sendDisplay(baseId);
// ToDo: handle syncGlobal
} catch (err) {
self.errorHandler(err, 'handleDisplay');
}
}
/**
* handle the encoder status and call the send back if someting is changed
* @param {string} encoderId only when called via onStateChange
* @param {any | null | undefined} value
* @param {string} event pressed, released or value (value = when called via onStateChange)
* @param {string} deviceAddress only chen called via onServerMessage
*/
async handleEncoder(encoderId, value = undefined, event = 'value', deviceAddress = '') {
const self = this;
try {
let baseId;
let stateName = ''; // the name of the particular state when called via onStateChange
const encoderArr = encoderId.split('.');
let activeBank = 0;
let activeBaseChannel = 1;
const deviceGroup = encoderArr[3];
let actVal;
let isDirty = false; // if true the encoder states has changed and must be sent
if (encoderId === '') {
self.log.debug('X-Touch encoder not supported');
return;
}
if (event === 'value') { // when called via onStateChange there is the full encoder id, cut the last part for baseId
baseId = encoderId.substr(0, encoderId.lastIndexOf('.'));
stateName = encoderId.substr(encoderId.lastIndexOf('.') + 1);
if (stateName === '') {
self.log.error('handleEncoder called with value and only baseId');
return; // if no value part provided throw an error
}
switch (stateName) {
case 'cw': // if wheel movement is simulated via database
case 'ccw': // only on encoder wheel possible
self.timers.devicegroup[deviceGroup].refresh(); // restart/refresh the timer
return;
case 'enabled':
if (self.deviceGroups[baseId + '.enabled'].val != Boolean(value)) { // if changed send
self.deviceGroups[baseId + '.enabled'].val = Boolean(value);
isDirty = true;
}
break;
case 'mode':
if ((value < 0) || (value > 3) || !Number.isInteger(value)) value = 0; // correct ?
if (self.deviceGroups[baseId + '.mode'].val != value) { // if changed send
self.deviceGroups[baseId + '.mode'].val = value;
isDirty = true;
}
break;
case 'pressed': // reset if sent via database
self.setState(baseId + '.pressed', false, true);
return;
case 'stepsPerTick': // check and correct
actVal = value;
if (value < 0) actVal = 0;
if (value > 1000) actVal = 1000;
if (!Number.isInteger(value)) actVal = parseInt(value, 10);
if (value != actVal) { // value corrected ?
await self.setStateAsync(baseId + '.stepsPerTick', Number(actVal), true);
}
if (self.deviceGroups[baseId + '.stepsPerTick'].val != actVal) {
self.deviceGroups[baseId + '.stepsPerTick'].val = actVal;
self.log.info(`handleEncoder changed the stepsPerTick to "${actVal}"`);
}
return;
case 'value':
if (value < 0) value = 0;
if (value > 1000) value = 1000;
if (!Number.isInteger(value)) value = parseInt(value, 10);
if (self.deviceGroups[baseId + '.value'].val != value) {
self.deviceGroups[baseId + '.value'].val = value;
await self.setStateAsync(baseId + '.value', Number(value), true);
}
break;
}
} else { // when called by midiMsg determine the real channel
if ((deviceAddress !== '') && self.devices[deviceAddress]) {
activeBank = self.devices[deviceAddress].activeBank;
activeBaseChannel = self.devices[deviceAddress].activeBaseChannel;
}
if (encoderArr[4] === 'banks') { // replace bank and baseChannel on channel encoders
encoderArr[5] = activeBank.toString();
encoderArr[7] = (Number(encoderArr[7]) + activeBaseChannel - 1).toString();
}
baseId = encoderArr.join('.');
}
if (encoderArr[5] === 'encoder') { // only on encoder wheel
switch (event) {
case 'cw':
await self.setStateAsync(baseId + '.cw', true, true);
self.timers.encoderWheels[deviceGroup].refresh(); // restart/refresh the timer
return; // nothing more to do
case 'ccw':
await self.setStateAsync(baseId + '.ccw', true, true);
self.timers.encoderWheels[deviceGroup].refresh(); // restart/refresh the timer
return; // nothing more to do
default:
self.log.error(`handleEncoder called with unknown event ${event} on encoder wheel`);
}
}
if ((self.deviceGroups[baseId + '.enabled'].val !== true) && !isDirty) return; // no farther processing if encoder disabled, only to send the status disabled on value "enabled" changed
actVal = self.deviceGroups[baseId + '.value'].val;
if (self.deviceGroups[baseId + '.value'].helperNum == -1) { // first call
self.deviceGroups[baseId + '.value'].helperNum = self.calculateEncoderValue(actVal);
}
switch (event) {
case 'cw': // rotate to increment value
actVal += (self.deviceGroups[baseId + '.stepsPerTick'].val * value); // value contains the steps taken
if (actVal > 1000) actVal = 1000;
break;
case 'ccw': // rotate to decrement value
actVal -= (self.deviceGroups[baseId + '.stepsPerTick'].val * value);
if (actVal < 0) actVal = 0;
break;
}
self.deviceGroups[baseId + '.value'].val = actVal;
await self.setStateAsync(baseId + '.value', actVal, true);
if (self.deviceGroups[baseId + '.value'].helperNum != this.calculateEncoderValue(actVal)) {
self.deviceGroups[baseId + '.value'].helperNum = this.calculateEncoderValue(actVal);
// if display value changed send
isDirty = true;
}
let logStr = `handleEncoder event: ${event} new value ${actVal} `;
if (isDirty) {
logStr += `going to send ${self.deviceGroups[baseId + '.value'].helperNum}`;
self.sendEncoder(baseId);
}
self.log.debug(logStr);
// ToDo: handle syncGlobal
} catch (err) {
self.errorHandler(err, 'handleEncoder');
}
}
/**
* handle the timecode display character status and call the send back if someting is changed
* @param {string} charId only when called via onStateChange
* @param {any | null | undefined} value
*/
async handleDisplayChar(charId, value = undefined) {
const self = this;
try {
const characterArr = charId.split('.');
const stateName = characterArr.length > 6 ? characterArr[6] : '';
const baseId = charId.substr(0, charId.lastIndexOf('.'));
if (value === undefined) return; // nothing to do
if (stateName === '') return; // if only base id there is nothing to handle. only called via onStateChange. Sending is done via sendDisplayChar
let char = self.deviceGroups[baseId + '.char'].val || '';
let dot = self.deviceGroups[baseId + '.dot'].val || false;
let enabled = self.deviceGroups[baseId + '.enabled'].val || false;
let extended = self.deviceGroups[baseId + '.extended'].val;
let mode = self.deviceGroups[baseId + '.mode'].val;
switch (stateName) { // correction of malformed values
case 'char':
char = value.toString();
if (!self.isASCII(char)) {
char = '';
await self.setStateAsync(baseId + '.char', char, true);
}
if (char.length > 1) {
char = char.substr(0,1);
await self.setStateAsync(baseId + '.char', char, true);
}
self.deviceGroups[baseId + '.char'].val = char;
break;
case 'dot':
dot = Boolean(value);
self.deviceGroups[baseId + '.dot'].val = dot;
break;
case 'enabled':
enabled = Boolean(value);
self.deviceGroups[baseId + '.enabled'].val = enabled;
break;
case 'extended':
extended = Number(value);
if (extended < 0 || extended > 127) {
extended = 0;
await self.setStateAsync(baseId + '.extended', extended, true);
}
self.deviceGroups[baseId + '.extended'].val = extended.toString();
break;
case 'mode':
mode = Number(value);
if ((mode < 0) || (mode > 1) || !Number.isInteger(mode)) {
mode = 0;
await self.setStateAsync(baseId + '.mode', mode, true);
}
self.deviceGroups[baseId + '.mode'].val = mode.toString();
break;
}
self.sendDisplayChar(baseId);
// ToDo: handle syncGlobal
} catch (err) {
self.errorHandler(err, 'handleDisplayChar');
}
}