-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVortexPort.js
941 lines (868 loc) · 32.8 KB
/
VortexPort.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
import Notification from './Notification.js';
export default class VortexPort {
// Constants
EDITOR_VERB_HELLO = 'a';
EDITOR_VERB_READY = 'b';
EDITOR_VERB_PULL_MODES = 'c';
EDITOR_VERB_PULL_MODES_DONE = 'd';
EDITOR_VERB_PULL_MODES_ACK = 'e';
EDITOR_VERB_PUSH_MODES = 'f';
EDITOR_VERB_PUSH_MODES_ACK = 'g';
EDITOR_VERB_DEMO_MODE = 'h';
EDITOR_VERB_DEMO_MODE_ACK = 'i';
EDITOR_VERB_CLEAR_DEMO = 'j';
EDITOR_VERB_CLEAR_DEMO_ACK = 'k';
EDITOR_VERB_GOODBYE = 'l';
EDITOR_VERB_TRANSMIT_VL = 'm';
EDITOR_VERB_TRANSMIT_VL_ACK = 'n';
EDITOR_VERB_LISTEN_VL = 'o';
EDITOR_VERB_LISTEN_VL_ACK = 'p';
EDITOR_VERB_PULL_CHROMA_HDR = 'q';
EDITOR_VERB_PULL_CHROMA_HDR_ACK = 'r';
EDITOR_VERB_PUSH_CHROMA_HDR = 's';
EDITOR_VERB_PUSH_CHROMA_HDR_ACK = 't';
EDITOR_VERB_PULL_CHROMA_MODE = 'u';
EDITOR_VERB_PULL_CHROMA_MODE_ACK = 'v';
EDITOR_VERB_PUSH_CHROMA_MODE = 'w';
EDITOR_VERB_PUSH_CHROMA_MODE_ACK = 'x';
EDITOR_VERB_PULL_SINGLE_MODE = 'y';
EDITOR_VERB_PULL_SINGLE_MODE_ACK = 'z';
EDITOR_VERB_PUSH_SINGLE_MODE = 'A';
EDITOR_VERB_PUSH_SINGLE_MODE_ACK = 'B';
EDITOR_VERB_PULL_EACH_MODE = 'C';
EDITOR_VERB_PULL_EACH_MODE_ACK = 'D';
EDITOR_VERB_PULL_EACH_MODE_DONE = 'E';
EDITOR_VERB_PUSH_EACH_MODE = 'F';
EDITOR_VERB_PUSH_EACH_MODE_ACK = 'G';
EDITOR_VERB_PUSH_EACH_MODE_DONE = 'H';
EDITOR_VERB_FLASH_FIRMWARE = "I";
EDITOR_VERB_FLASH_FIRMWARE_ACK = "J";
EDITOR_VERB_FLASH_FIRMWARE_DONE = "K";
accumulatedData = ""; // A buffer to store partial lines.
reader = null;
isTransmitting = null; // Flag to track if a transmission is active
sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
constructor() {
this.cancelListeningForGreeting = false;
this.debugSending = false;
this.resetState();
}
cancelListening() {
console.log("Cancel listening");
this.cancelListeningForGreeting = true;
if (this.reader) {
this.reader.cancel().catch(err => {
console.warn('Error canceling reader:', err);
});
}
}
resetState() {
if (this.reader) {
try {
this.reader.releaseLock();
} catch (error) {
console.warn('Error releasing reader in resetState:', error);
} finally {
this.reader = null;
}
}
this.portActive = false;
this.name = '';
this.version = 0;
this.buildDate = '';
this.isTransmitting = null; // Reset the transmission state on reset
this.hasUPDI = false;
if (this.serialPort) {
this.serialPort.close();
this.serialPort = null;
}
// Further state reset logic if necessary
}
isActive = () => {
return this.portActive;
}
async requestDevice(callback) {
this.deviceCallback = callback;
try {
if (!this.serialPort) {
this.serialPort = await navigator.serial.requestPort();
if (!this.serialPort) {
throw new Error('Failed to open serial port');
}
await this.serialPort.open({ baudRate: 115200 });
// is this necessary...? I don't remember why it's here
await this.serialPort.setSignals({ dataTerminalReady: true });
if (this.deviceCallback && typeof this.deviceCallback === 'function') {
this.deviceCallback('waiting');
}
}
await this.beginConnection();
} catch (error) {
console.error('Error:', error);
}
}
async beginConnection(){
if (!this.serialPort) {
return;
}
console.log("Beginning connection...");
this.portActive = false;
this.listenForGreeting();
}
async writeData(data) {
if (!this.serialPort || !this.serialPort.writable) {
console.error('Port is not writable.');
return;
}
const writer = this.serialPort.writable.getWriter();
const encoded = new TextEncoder().encode(data);
try {
await writer.write(encoded);
} catch (error) {
console.error('Error writing data:', error);
} finally {
writer.releaseLock();
}
}
// helper for 1.3.0 compatibility version check
isVersionGreaterOrEqual(currentVersion, targetVersion = '1.3.0') {
const currentParts = currentVersion.split('.').map(Number);
const targetParts = targetVersion.split('.').map(Number);
for (let i = 0; i < targetParts.length; i++) {
if (currentParts[i] > targetParts[i]) return true;
if (currentParts[i] < targetParts[i]) return false;
}
return true;
}
listenForGreeting = async () => {
let tries = 0;
while (!this.portActive && !this.cancelListeningForGreeting && tries++ < 30) {
if (this.serialPort) {
try {
console.log("Listening for greeting...");
// Read data from the serial port
const response = await this.readData(true);
if (!response) {
console.log("Error: Connection broken");
// broken connection
await this.sleep(500);
continue;
}
console.log("Matching: [" + response + "]...");
let responseRegex = /== Vortex Engine v(\d+\.\d+.\d+) '([\w\s]+)' \(built (.*)\) ==/;
let match = response.match(responseRegex);
if (!match) {
// TODO: removeme later! backwards compatibility for old connection string
responseRegex = /== Vortex Engine v(\d+\.\d+) '([\w\s]+)' \( built (.*)\) ==/;
match = response.match(responseRegex);
}
if (match) {
this.version = match[1]; // Capturing the version number
this.name = match[2]; // Capturing the name
this.buildDate = match[3]; // Capturing the build date
console.log('Successfully Received greeting from Vortex Device');
console.log('Device Type:', this.name);
console.log('Version:', this.version);
console.log('Date:', this.buildDate);
// old logic: sending updi in the name
// new logic: a command to check if updi is available
//// check if this is UPDI supported chromadeck
//const regex = /\bUPDI\b/;
//if (regex.test(this.name)) {
// // Replace 'UPDI' with an empty string and trim any remaining spaces
// this.name = this.name.replace(regex, '').replace(/\s+/g, ' ').trim();
// // note that we have updi support for this chromadeck
// this.hasUPDI = true;
//}
// 1.3.0 compatibility layer
this.useNewPushPull = this.isVersionGreaterOrEqual(this.version, '1.3.0');
//if (this.useNewPushPull) {
// console.log('Detected 1.3.0+');
//}
this.portActive = true;
this.serialPort.addEventListener("disconnect", (event) => {
this.disconnect();
});
if (this.deviceCallback && typeof this.deviceCallback === 'function') {
this.deviceCallback('connect');
}
}
} catch (err) {
if (this.cancelListeningForGreeting) {
this.cancelListeningForGreeting = false;
console.error('Cancelling...');
} else {
console.error('Error reading data:', err);
}
}
}
await new Promise(resolve => setTimeout(resolve, 300));
}
if (tries >= 30) {
throw new Error('Failed to listen for greeting, tried 30 times');
}
this.cancelListeningForGreeting = false;
}
async restartConnecton() {
await this.beginConnection();
}
async disconnect() {
if (this.reader) {
await this.reader.cancel();
}
this.resetState();
if (this.deviceCallback && typeof this.deviceCallback === 'function') {
this.deviceCallback('disconnect');
}
}
startReading() {
// todo: implement async read waiting for quit that can be canceled
}
cancelReading() {
// todo: implement async read cancel
}
async readData(fullResponse) {
if (!this.serialPort || !this.serialPort.readable) {
return null;
}
if (this.accumulatedData.length > 0) {
// check the buffer first...
// Return any single byte
const singleByte = this.accumulatedData[0];
this.accumulatedData = this.accumulatedData.substring(1);
return singleByte;
}
if (this.reader) {
try {
this.reader.releaseLock();
} catch (error) {
console.warn('Failed to release reader lock:', error);
}
}
this.reader = this.serialPort.readable.getReader();
try {
while (true) {
const { value, done } = await this.reader.read();
if (done) {
// Ensure the reader is not released multiple times
if (this.reader) {
this.reader.releaseLock();
this.reader = null;
}
break;
}
const text = new TextDecoder().decode(value);
this.accumulatedData += text;
if (fullResponse) {
const responseRegex = /==.*==/;
const match = this.accumulatedData.match(responseRegex);
if (match) {
const result = this.accumulatedData;
this.accumulatedData = '';
return result;
}
// If it starts with '=' or '==', look for the end delimiter '=='
//if (this.accumulatedData.startsWith('=') || this.accumulatedData.startsWith('==')) {
// const endIndex = this.accumulatedData.indexOf('==', 2); // Search for '==' after the first one.
// if (endIndex >= 0) {
// const fullMessage = this.accumulatedData.substring(0, endIndex + 2).trim();
// this.accumulatedData = this.accumulatedData.substring(endIndex + 2); // Trim accumulatedData
// return fullMessage; // Return the full message
// }
} else {
// Return any single byte
const singleByte = this.accumulatedData[0];
this.accumulatedData = this.accumulatedData.substring(1);
return singleByte;
}
}
} catch (error) {
console.error('Error reading data:', error);
return null;
} finally {
if (this.reader) {
try {
this.reader.releaseLock(); // Ensure release of reader in the finally block
} catch (error) {
console.warn('Failed to release reader lock in finally:', error);
}
this.reader = null;
}
}
}
constructCustomBufferRaw(vortexLib, rawDataArray, size) {
// Create the custom array with size and rawData
const sizeArray = new Uint32Array([size]); // No byte swapping
// Combine sizeArray and rawDataArray into a single array
const combinedArray = new Uint8Array(sizeArray.length * 4 + rawDataArray.length);
combinedArray.set(new Uint8Array(sizeArray.buffer), 0); // Copy sizeArray bytes
combinedArray.set(rawDataArray, sizeArray.length * 4); // Copy rawDataArray bytes
return combinedArray;
}
constructCustomBuffer(vortexLib, curMode) {
let data = vortexLib.getRawDataArray(curMode);
//console.log("Raw data: " + JSON.stringify(data));
return this.constructCustomBufferRaw(vortexLib, data, curMode.rawSize());
}
async transmitVL(vortexLib, vortex) {
if (!this.isActive()) {
throw new Error('Port not active');
}
if (this.isTransmitting) {
throw new Error('Already transmitting:' + this.isTransmitting);
}
if (!vortex.engine().modes().curMode()) {
throw new Error('No current mode');
}
//console.log("transmitVL Start");
this.isTransmitting = 'transmitVL'; // Set the transmitting flag
try {
// Unserialize the stream of data
const curMode = new vortexLib.ByteStream();
if (!vortex.getCurMode(curMode)) {
throw new Error('Failed to get cur mode');
}
await this.cancelReading();
await this.sendCommand(this.EDITOR_VERB_TRANSMIT_VL);
await this.expectData(this.EDITOR_VERB_TRANSMIT_VL_ACK);
} catch (error) {
console.error('Error during transmitVL:', error);
} finally {
this.startReading();
this.isTransmitting = null; // Reset the transmitting flag
//console.log("transmitVL End");
}
}
async demoColor(vortexLib, vortex, color) {
if (!this.isActive()) {
throw new Error('Port not active');
}
if (this.isTransmitting) {
throw new Error('Already transmitting:' + this.isTransmitting);
}
//console.log("demoColor Start");
this.isTransmitting = 'demoColor'; // Set the transmitting flag
try {
// Unserialize the stream of data
const curMode = new vortexLib.ByteStream();
let args = new vortexLib.PatternArgs();
args.addArgs(1);
let set = new vortexLib.Colorset();
set.addColor(color);
let patID = vortexLib.intToPatternID(0);
let mode = new vortexLib.createMode(vortex, patID, args, set);
mode.init();
mode.saveToBuffer(curMode, vortex.engine().leds().ledCount());
await this.cancelReading();
await this.sendCommand(this.EDITOR_VERB_DEMO_MODE);
await this.expectData(this.EDITOR_VERB_READY);
await this.sendRaw(this.constructCustomBuffer(vortexLib, curMode));
await this.expectData(this.EDITOR_VERB_DEMO_MODE_ACK);
} catch (error) {
console.error('Error during demoColor:', error);
} finally {
this.startReading();
this.isTransmitting = null; // Reset the transmitting flag
//console.log("demoColor End");
}
}
async demoCurMode(vortexLib, vortex) {
if (!this.isActive()) {
throw new Error('Port not active');
}
if (this.isTransmitting) {
throw new Error('Already transmitting:' + this.isTransmitting);
}
if (!vortex.engine().modes().curMode()) {
throw new Error('No current mode');
}
//console.log("demoCurMode Start");
this.isTransmitting = 'demoCurMode'; // Set the transmitting flag
try {
// Unserialize the stream of data
const curMode = new vortexLib.ByteStream();
if (!vortex.getCurMode(curMode)) {
throw new Error('Failed to get cur mode');
}
await this.cancelReading();
await this.sendCommand(this.EDITOR_VERB_DEMO_MODE);
await this.expectData(this.EDITOR_VERB_READY);
await this.sendRaw(this.constructCustomBuffer(vortexLib, curMode));
await this.expectData(this.EDITOR_VERB_DEMO_MODE_ACK);
} catch (error) {
console.error('Error during demoCurMode:', error);
} finally {
this.startReading();
this.isTransmitting = null; // Reset the transmitting flag
//console.log("demoCurMode End");
}
}
async pushEachToDevice(vortexLib, vortex) {
if (!this.isActive()) {
throw new Error('Port not active');
}
if (this.isTransmitting) {
throw new Error('Already transmitting:' + this.isTransmitting);
}
//console.log("pushEachToDevice Start");
this.isTransmitting = 'pushEachToDevice'; // Set the transmitting flag
try {
// Unserialize the stream of data
const modes = new vortexLib.ByteStream();
if (!vortex.getModes(modes)) {
throw new Error('Failed to get cur mode');
}
await this.cancelReading();
await this.sendCommand(this.EDITOR_VERB_PUSH_EACH_MODE);
await this.expectData(this.EDITOR_VERB_PUSH_EACH_MODE_ACK);
const numModes = vortex.numModes();
const numModesBuf = new vortexLib.ByteStream();
numModesBuf.serialize8(numModes);
await this.sendRaw(this.constructCustomBuffer(vortexLib, numModesBuf));
await this.expectData(this.EDITOR_VERB_PUSH_EACH_MODE_ACK);
vortex.setCurMode(0, false);
for (let i = 0; i < numModes; ++i) {
const modeBuf = new vortexLib.ByteStream();
vortex.getCurMode(modeBuf);
await this.sendRaw(this.constructCustomBuffer(vortexLib, modeBuf));
await this.expectData(this.EDITOR_VERB_PUSH_EACH_MODE_ACK);
vortex.nextMode(false);
}
// these aren't really working... oh well it works good without them
//await this.sendCommand(this.EDITOR_VERB_PUSH_EACH_MODE_DONE);
//await this.expectData(this.EDITOR_VERB_PUSH_EACH_MODE_DONE);
} catch (error) {
console.error('Error during pushToDevice:', error);
} finally {
this.startReading();
this.isTransmitting = null; // Reset the transmitting flag
//console.log("pushEachToDevice End");
}
}
async pushToDevice(vortexLib, vortex) {
if (!this.isActive()) {
throw new Error('Port not active');
}
if (this.isTransmitting) {
throw new Error('Already transmitting:' + this.isTransmitting);
}
// 1.3.0+ use new push pull logic
if (this.useNewPushPull) {
return await this.pushEachToDevice(vortexLib, vortex);
}
//console.log("pushToDevice Start");
this.isTransmitting = 'pushToDevice'; // Set the transmitting flag
try {
// Unserialize the stream of data
const modes = new vortexLib.ByteStream();
if (!vortex.getModes(modes)) {
throw new Error('Failed to get cur mode');
}
await this.cancelReading();
await this.sendCommand(this.EDITOR_VERB_PUSH_MODES);
await this.expectData(this.EDITOR_VERB_READY);
await this.sendRaw(this.constructCustomBuffer(vortexLib, modes));
await this.expectData(this.EDITOR_VERB_PUSH_MODES_ACK);
} catch (error) {
console.error('Error during pushToDevice:', error);
} finally {
this.startReading();
this.isTransmitting = null; // Reset the transmitting flag
//console.log("pushToDevice End");
}
}
async pullEachFromDevice(vortexLib, vortex) {
if (!this.isActive()) {
throw new Error('Port not active');
}
if (this.isTransmitting) {
throw new Error('Already transmitting:' + this.isTransmitting);
}
//console.log("pullEachFromDevice Start");
this.isTransmitting = 'pullEachFromDevice'; // Set the transmitting flag
try {
// Unserialize the stream of data
await this.cancelReading();
await this.sendCommand(this.EDITOR_VERB_PULL_EACH_MODE);
const numModesBuf = await this.readByteStream(vortexLib);
let numModesStream = new vortexLib.ByteStream();
vortexLib.createByteStreamFromRawData(numModesBuf, numModesStream);
// this is quite dumb, idk I guess header is 12 bytes so 13th byte is the one data byte
let numModes = numModesBuf['12'];
await this.sendCommand(this.EDITOR_VERB_PULL_EACH_MODE_ACK);
vortex.clearModes();
for (let i = 0; i < numModes; ++i) {
const modeBuf = await this.readByteStream(vortexLib);
// Call the Wasm function
let modeStream = new vortexLib.ByteStream();
vortexLib.createByteStreamFromRawData(modeBuf, modeStream);
vortex.addNewMode(modeStream, true);
await this.sendCommand(this.EDITOR_VERB_PULL_EACH_MODE_ACK);
}
await this.expectData(this.EDITOR_VERB_PULL_EACH_MODE_DONE);
} catch (error) {
console.error('Error during pullFromDevice:', error);
} finally {
this.startReading();
this.isTransmitting = null; // Reset the transmitting flag
//console.log("pullEachFromDevice End");
}
}
async pullFromDevice(vortexLib, vortex) {
if (!this.isActive()) {
throw new Error('Port not active');
}
if (this.isTransmitting) {
throw new Error('Already transmitting:' + this.isTransmitting);
}
// 1.3.0+ use new push pull logic
if (this.useNewPushPull) {
return await this.pullEachFromDevice(vortexLib, vortex);
}
//console.log("pullFromDevice Start");
this.isTransmitting = 'pullFromDevice'; // Set the transmitting flag
try {
// Unserialize the stream of data
await this.cancelReading();
await this.sendCommand(this.EDITOR_VERB_PULL_MODES);
const modes = await this.readByteStream(vortexLib);
// Call the Wasm function
let modesStream = new vortexLib.ByteStream();
vortexLib.createByteStreamFromRawData(modes, modesStream);
vortex.matchLedCount(modesStream, false);
vortex.setModes(modesStream, true);
await this.sendCommand(this.EDITOR_VERB_PULL_MODES_DONE);
await this.expectData(this.EDITOR_VERB_PULL_MODES_ACK);
} catch (error) {
console.error('Error during pullFromDevice:', error);
} finally {
this.startReading();
this.isTransmitting = null; // Reset the transmitting flag
//console.log("pullFromDevice End");
}
}
// Function to connect the Duo via Chromalink
async connectChromalink(vortexLib) {
if (!this.isActive()) {
throw new Error('Port not active');
}
if (this.isTransmitting) {
throw new Error('Already transmitting:' + this.isTransmitting);
}
let duoHeader = {};
//console.log("connectChromaLink Start");
this.isTransmitting = 'connectChromalink'; // Reset the transmitting flag
try {
await this.cancelReading();
// Start the connection process
await this.sendCommand(this.EDITOR_VERB_PULL_CHROMA_HDR);
const header = await this.readByteStream(vortexLib);
// Call the Wasm function
let headerStream = new vortexLib.ByteStream();
vortexLib.createByteStreamFromRawData(header, headerStream);
if (!headerStream.checkCRC() || headerStream.size() < 5) {
throw new Error('Bad CRC or size: ' + headerStream.size());
}
// process header
const headerData = vortexLib.getDataArray(headerStream);
duoHeader.vMajor = headerData[0];
duoHeader.vMinor = headerData[1];
duoHeader.vBuild = 0;
duoHeader.flags = headerData[2];
duoHeader.brightness = headerData[3];
duoHeader.numModes = headerData[4];
if (headerStream.size() > 5) {
duoHeader.vBuild = headerData[5];
}
// construct a full version string
duoHeader.version = duoHeader.vMajor + '.' + duoHeader.vMinor + '.' + duoHeader.vBuild;
duoHeader.rawData = headerData;
console.log('Successfully Chromalinked Duo');
console.log('Version:', duoHeader.version);
console.log('Flags:', duoHeader.flags);
console.log('Brightness:', duoHeader.brightness);
console.log('Mode Count:', duoHeader.numModes);
} catch (error) {
console.error('Error connecting to Duo via Chromalink:', error);
} finally {
this.startReading();
this.isTransmitting = null; // Reset the transmitting flag
//console.log("connectChromaLink End");
}
return duoHeader;
}
async writeDuoHeader(vortexLib, vortex, duoHeader) {
if (!this.isActive()) {
throw new Error('Port not active');
}
if (this.isTransmitting) {
throw new Error('Already transmitting:' + this.isTransmitting);
}
//console.log("connectChromaLink Start");
this.isTransmitting = 'writeDuoHeader'; // Reset the transmitting flag
try {
await this.cancelReading();
// Start the connection process
await this.sendCommand(this.EDITOR_VERB_PUSH_CHROMA_HDR);
await this.expectData(this.EDITOR_VERB_READY);
// build the header
const headerData = [
duoHeader.vMajor,
duoHeader.vMinor,
duoHeader.flags,
duoHeader.brightness,
duoHeader.numModes,
];
let headerStream = new vortexLib.ByteStream();
vortexLib.createByteStreamFromData(headerData, headerStream);
await this.sendRaw(this.constructCustomBuffer(vortexLib, headerStream));
await this.expectData(this.EDITOR_VERB_PUSH_CHROMA_HDR_ACK);
//console.log("DuoHeader: " + JSON.stringify(duoHeader));
//console.log("Header: " + JSON.stringify(headerData));
} catch (error) {
console.error('Error connecting to Duo via Chromalink:', error);
} finally {
this.startReading();
this.isTransmitting = null; // Reset the transmitting flag
//console.log("connectChromaLink End");
}
}
// Function to pull all modes from the Duo via Chromalink
async pullDuoModes(vortexLib, vortex, numModes) {
if (!this.isActive()) {
throw new Error('Port not active');
}
if (this.isTransmitting) {
throw new Error('Already transmitting:' + this.isTransmitting);
}
vortex.clearModes();
//console.log("pullDuoModes Start");
this.isTransmitting = 'pullDuoModes'; // Set the transmitting flag
try {
await this.cancelReading();
for (let i = 0; i < numModes; ++i) {
// Send command to pull modes from the Duo
await this.sendCommand(this.EDITOR_VERB_PULL_CHROMA_MODE);
await this.expectData(this.EDITOR_VERB_READY); // Wait for ACK
const sizeBuffer = new Uint8Array([i]);
await this.sendRaw(sizeBuffer);
const mode = await this.readByteStream(vortexLib);
// Call the Wasm function
let modeStream = new vortexLib.ByteStream();
vortexLib.createByteStreamFromRawData(mode, modeStream);
if (!modeStream.checkCRC() || !modeStream.size()) {
throw new Error(`Bad CRC or size for mode ${i}`);
}
// need to use addNewModeRaw here because the duo mode buffers
// are not the full 'mode save' buffer with the header that would
// be needed for addNewMode(), this will just 'unserialize' the mode
// then add it without using the mode.loadFromBuffer() function
if (!vortex.addNewModeRaw(modeStream, false)) { // Add each mode
throw new Error(`Failed to add mode ${i}`);
}
// seems to be an issue where it gets stuck on mode 3 (the first flash mode),
// something to do with the underlying updi connection getting hung up and idk
// why but the sleep fixes it lol
await this.sleep(10);
}
} catch (error) {
console.error('Error pulling modes from Duo via Chromalink:', error);
} finally {
this.startReading();
this.isTransmitting = null; // Reset the transmitting flag
//console.log("pullDuoModes End");
}
return true;
}
// Function to push all modes to the Duo via Chromalink
async pushDuoModes(vortexLib, vortex) {
if (!this.isActive()) {
throw new Error('Port not active');
}
if (this.isTransmitting) {
throw new Error('Already transmitting:' + this.isTransmitting);
}
//console.log("pushDuoModes Start");
this.isTransmitting = 'pushDuoModes'; // Set the transmitting flag
try {
vortex.setCurMode(0, false);
// TODO: detect total modes?
for (let i = 0; i < vortex.numModes(); ++i) {
// Send the push command
await this.sendCommand(this.EDITOR_VERB_PUSH_CHROMA_MODE);
await this.expectData(this.EDITOR_VERB_READY); // Wait for ACK
const sizeBuffer = new Uint8Array([i]);
await this.sendRaw(sizeBuffer);
await this.expectData(this.EDITOR_VERB_READY); // Wait for ACK
const modeBuf = new vortexLib.ByteStream();
vortex.getCurModeRaw(modeBuf);
await this.sendRaw(this.constructCustomBuffer(vortexLib, modeBuf));
await this.expectData(this.EDITOR_VERB_PUSH_CHROMA_MODE_ACK);
vortex.nextMode(false);
}
} catch (error) {
console.error('Error pushing modes to Duo via Chromalink:', error);
} finally {
this.startReading();
this.isTransmitting = null; // Reset the transmitting flag
//console.log("pushDuoModes End");
}
}
// Function to flash firmware to the Duo via Chromalink
// Method for flashing firmware
async flashFirmware(vortexLib, firmwareData, progressCallback) {
try {
if (!this.isActive()) {
throw new Error('Port not active');
}
// Step 1: Check firmware size
const firmwareSize = firmwareData.length;
if (firmwareSize <= 0) {
throw new Error('Invalid firmware file.');
}
// Step 2: Send Flash Firmware command, wait for ACK
await this.sendCommand(this.EDITOR_VERB_FLASH_FIRMWARE);
await this.expectData(this.EDITOR_VERB_READY);
// Step 3: Send firmware size, wait for ACK
const sizeBuffer = new Uint32Array([firmwareSize]);
await this.sendRaw(new Uint8Array(sizeBuffer.buffer));
await this.expectData(this.EDITOR_VERB_READY);
// Step 4: Send firmware data in chunks
const chunkSize = 128; // Firmware chunk size
let offset = 0;
let chunk = 0;
const totalChunks = Math.ceil(firmwareSize / chunkSize);
while (offset < firmwareSize) {
const bytesToSend = Math.min(chunkSize, firmwareSize - offset);
const chunkData = firmwareData.slice(offset, offset + bytesToSend);
const chunkStream = new vortexLib.ByteStream();
vortexLib.createByteStreamFromData(chunkData, chunkStream);
// Send the current chunk, wait for ACK
await this.sendRaw(this.constructCustomBuffer(vortexLib, chunkStream));
await this.expectData(this.EDITOR_VERB_FLASH_FIRMWARE_ACK); // Wait for ACK
offset += bytesToSend;
chunk++;
if (progressCallback && typeof progressCallback === 'function') {
progressCallback(chunk, totalChunks);
}
}
} catch (error) {
console.log("Firmware flash failed: " + error);
Notification.failure('Firmware flash failed: ' + error.message);
}
}
async readFromSerialPort() {
if (!this.serialPort || !this.serialPort.readable) {
throw new Error('Serial port is not readable');
}
if (this.reader) {
this.reader.releaseLock();
}
this.reader = this.serialPort.readable.getReader();
let result = null;
try {
result = await this.reader.read();
//console.log("RECEIVED BYTE:" + JSON.stringify(result));
} catch (error) {
// do nothing?
console.log("Failed to read: " + error);
}
this.reader.releaseLock();
this.reader = null;
return result;
}
async readByteStream(vortexLib) {
if (!this.isActive()) {
throw new Error('Port not active');
}
try {
// Function to append new data to existing data
const appendData = (existing, newData) => {
const combined = new Uint8Array(existing.length + newData.length);
combined.set(existing);
combined.set(newData, existing.length);
return combined;
};
// Read the initial 4 bytes for size
let sizeData = new Uint8Array(0);
while (sizeData.length < 4) {
const data = await this.readFromSerialPort();
sizeData = appendData(sizeData, data.value);
}
// Interpret the first 4 bytes as size
const size = new DataView(sizeData.buffer).getUint32(0, true);
// Read the remaining data
let accumulatedData = sizeData.slice(4);
while (accumulatedData.length < size) {
const data = await this.readFromSerialPort();
accumulatedData = appendData(accumulatedData, data.value);
}
// Validate the size of the accumulated data
if (accumulatedData.length === size) {
//console.log("RECEIVED BUFFER (size: " + size + "):" + JSON.stringify(accumulatedData));
return new Uint8Array(accumulatedData);
} else {
console.error("Data size mismatch.");
return null;
}
} catch (error) {
console.error('Error reading modes:', error);
return null;
}
}
// wait for a specific response
async expectData(expectedResponse, timeoutMs = 10000) {
//console.log("EXPECTING:" + expectedResponse);
const startTime = Date.now();
while (Date.now() - startTime < timeoutMs) {
const response = await this.readData();
if (response === expectedResponse) {
//console.log('RECEIVED GOOD:', response, ' (expected: ', expectedResponse, ')');
return; // Expected response received
}
if (!response) {
//console.log('RECEIVED NOTHING (expected: ', expectedResponse, ')');
return;
}
//console.log('RECEIVED BAD:', response, ' (expected: ', expectedResponse, ')');
return;
//throw new Error('BAD: Expected response not received');
}
//console.log('RECEIVE TIMEOUT (expected: ', expectedResponse, ')');
throw new Error('Timeout: Expected response not received');
}
// finish up and close
async closePort() {
if (this.serialPort) {
await this.serialPort.close();
this.serialPort = null;
console.log('Port closed.');
}
}
// send raw data to the device
async sendRaw(data) {
if (!this.serialPort || !this.serialPort.writable) {
console.error('Port is not writable.');
return;
}
const writer = this.serialPort.writable.getWriter();
try {
//console.log("SENDING RAW: " + JSON.stringify(data));
await writer.write(data);
} catch (error) {
console.error('Error writing data:', error);
} finally {
writer.releaseLock();
}
}
// send a command to the device
async sendCommand(verb) {
if (!this.isActive()) {
console.error('Port not active or another transmission is ongoing. Cannot send command.');
return;
}
//console.log("SENDING: " + verb);
const encodedVerb = new TextEncoder().encode(verb); // Ensure encoding for consistent communication
await this.sendRaw(encodedVerb);
}
}