-
Notifications
You must be signed in to change notification settings - Fork 1
/
ifc2.js
1370 lines (1152 loc) · 48.1 KB
/
ifc2.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
/*
ifc2: A Node JS module providing a client the Infinite Flight Connect version 2 API.
Version: 1.0.22
Author: @likeablegeek (https://likeablegeek.com/)
Distributed by: FlightSim Ninja (http://flightim.ninja)
Copyright 2022.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/** ***
* Import required modules
*/
const dgram = require('dgram'); // For listening for UDP broadcasts
const net = require('net'); // For establishing socket connections
const events = require('events'); // For emitting events back to calling scripts
/** **
* Define IFC2 object
*/
const IFC2 = {
/** ***
* Module name
*/
name: 'IFC2', // Module name
/** ***
* Constants for referencing error levels in logging
*/
INFO: 3,
WARN: 2,
ERROR: 1,
MANDATORY: 0,
/** ***
* Constants for sending the correct flag for get/set calls in v2 API
*/
GETCMD: 0,
SETCMD: 1,
RUNCMD: -1,
LE: true,
/** ***
* Constant for the manifest command
*/
MANIFESTCMD: -1,
/** ***
* Constants for IF Connect v2 data types
*/
BOOLEAN: 0,
INTEGER: 1,
FLOAT: 2,
DOUBLE: 3,
STRING: 4,
LONG: 5,
/** ***
* Object to hold connection data, manifest data, socket objects and more
*/
infiniteFlight: {
// Infinite Flight connection data
broadcastPort: 15000, // Port to listen for broadcast from Infinite Flight
serverPort: 10112, // Port for socket connection to Infinite Flight
serverAddress: '127.0.0.1', // Default is localhost just as a placeholder
clientSocket: new net.Socket(), // Socket for regular one-off commands
manifestSocket: new net.Socket(), // Socket for fetching the manifest
pollSocket: new net.Socket(), // Socket for the regular polling loop
manifestTimeout: 1000, // How long to wait for the manifest before giving up
manifestData: '', // String to hold raw manifest data
manifestByName: {}, // Object to hold the manifest organised by command name
manifestByCommand: {}, // Object to hold the manifest organised by command number
manifestLength: 0, // Manifest length -- zero is initial placeholder
manifestBuffer: null, // Placeholder variable for future manifest buffer
},
/** ***
* Default logging state
*/
enableLog: false, // Control logging -- default is false
logLevel: 0, // Logging message level -- default is MANDATORY
/** ***
* Default keepalive, reconnect and timeout
*/
keepAlive: false, // By default we don't keep alive
doReconnect: true, // By default we reconnect when sockets error
timeout: 0, // By default we don't time out the sockets (except the manifest)
/** ***
* State tracking: are we connected? are we waiting?
*/
isConnected: false, // Are we connected to IF?
isWaiting: false, // Are we waiting?
isPollWaiting: false, // Are we waiting for a poll result?,
isCallback: false, // Are we using callbacks?
/** ***
* Command queues
*/
q: [], // Queue for processing one-off requests
pollQ: [], // Queue for recurring poll requests
pollCurrent: 0, // Position in poll queue,
pollWaiting: 0, // Place holder for poll command currently pending data from IF
callbacks: {}, // Holds callback functions for when callbacks are enabled
/** ***
* Timeout placeholder for slow polling handler
*/
pollTimeout: null,
/** ***
*
* Queue buffers
*
*/
qBuffer: null,
pollBuffer: null,
/** ***
* List to keep track of the commands pending responses from IF
*/
waitList: [],
/** ***
* Event emitter for return events to client
*/
eventEmitter: new events.EventEmitter(),
/** ***
* Default empty infoCallback function
*/
infoCallback: () => {},
/** ***
* Default polling throttle (0ms)
*/
pollThrottle: 0,
/** ***
* Object to hold last value fetched for all states that have been fetched from API
*/
ifData: {},
/** ***
* Logging function
*/
log: (msg, level = IFC2.logLevel) => {
// generic logging function
if (IFC2.enableLog) {
if (level <= IFC2.logLevel) {
console.log(msg);
}
}
},
/** ***
* Function to allow client to define listener for events emitted by module
*/
on: (event, listener) => {
IFC2.log(`Setting listener for: ${event}`);
IFC2.eventEmitter.on(event, listener);
},
/** ***
* Returns command formatted to send on TCP socket to API for getState commands
*/
getCommand: (cmd, args) => {
// Prepare command ready to send to IF
IFC2.log(`getCommand: ${cmd}`);
let argsLength = 0;
if (args) {
argsLength = 4;
for (let i = 0; i < args.length; i++) {
const arg = args[i];
argsLength += 4 + arg.name.length + 4 + arg.value.length;
}
}
const abCommand = new ArrayBuffer(5 + argsLength);
const dvCommand = new DataView(abCommand);
dvCommand.setInt32(0, cmd, IFC2.LE); // Encode the command itself
dvCommand.setInt8(4, args ? IFC2.SETCMD : IFC2.GETCMD, IFC2.LE); // Encode get marker
if (args) {
let offset = 5;
dvCommand.setInt32(offset, args.length, IFC2.LE); // Encode number of arguments
offset += 4;
for (let i = 0; i < args.length; i++) {
const arg = args[i];
dvCommand.setInt32(offset, arg.name.length, IFC2.LE); // Encode length of argument name
offset += 4;
for (let j = 0; j < arg.name.length; j++) {
dvCommand.setInt8(offset, arg.name.charCodeAt(j), IFC2.LE); // Encode argument name
offset++;
}
dvCommand.setInt32(offset, arg.value.length, IFC2.LE); // Encode length of argument value
offset += 4;
for (let j = 0; j < arg.value.length; j++) {
dvCommand.setInt8(offset, arg.value.charCodeAt(j), IFC2.LE); // Encode argument value
offset++;
}
}
}
const u8Command = new Uint8Array(abCommand);
IFC2.log(`getCommand: ${u8Command}`);
return u8Command;
},
/** ***
* Sends command formatted to send on TCP socket to API for setState commands
*/
setCommand: (cmd, val) => {
// Prepare command ready to send to IF
IFC2.log(`setCommand: ${cmd},${val}`, IFC2.MANDATORY);
const cmdType = IFC2.infiniteFlight.manifestByCommand[cmd].type;
let dataLength = 1;
switch (cmdType) {
case IFC2.INTEGER:
dataLength = 4;
break;
case IFC2.FLOAT:
dataLength = 4;
break;
case IFC2.DOUBLE:
dataLength = 4;
break;
case IFC2.STRING:
dataLength = 4 + val.length; // length is 4 for string length + string length
break;
case IFC2.LONG:
dataLength = 8;
break;
default:
return;
}
const abCommand = new ArrayBuffer(5 + dataLength); // 5 is command + true/false divider + value to be sent
const dvCommand = new DataView(abCommand);
dvCommand.setInt32(0, cmd, IFC2.LE); // Encode the command itself
dvCommand.setInt8(4, IFC2.SETCMD, IFC2.LE); // Encode set marker
switch (cmdType) {
case IFC2.BOOLEAN:
dvCommand.setInt8(5, val, true);
break;
case IFC2.INTEGER:
dvCommand.setInt32(5, val, true);
break;
case IFC2.FLOAT:
dvCommand.setFloat32(5, val, true);
break;
case IFC2.DOUBLE:
dvCommand.setFloat64(5, val, true);
break;
case IFC2.STRING:
dvCommand.setInt32(5, val.length, true);
dvCommand.setString(9, val);
break;
case IFC2.LONG:
dvCommand.setBigInt64(5, val, true);
break;
default:
return;
}
const u8Command = new Uint8Array(abCommand);
IFC2.log(`setCommand u8Command: ${u8Command}`, IFC2.MANDATORY);
IFC2.log(dvCommand, IFC2.MANDATORY);
return u8Command;
},
/** ***
* Process next command in one-off command queue (if any commands are pending)
*/
processQueue: () => {
IFC2.log(`processQueue: isConnected: ${IFC2.isConnected}`);
IFC2.log(`processQueue: isWaiting: ${IFC2.isWaiting}`);
if (IFC2.isConnected && !IFC2.isWaiting) {
// only send if connected and not already waiting for a response
IFC2.log(`Q length: ${IFC2.q.length}`);
if (IFC2.q.length > 0) {
// only send if there is a command in the queue
const cmdObj = IFC2.q.shift(); // grab the next command from the queue
if (IFC2.infiniteFlight.manifestByName[cmdObj.cmd]) {
// only send if the command is in the manifest
IFC2.isWaiting = true; // indicate we are now waiting for a response
IFC2.log(`Sending command: ${cmdObj.cmdCode}`);
IFC2.infiniteFlight.clientSocket.write(
cmdObj.cmdBuf,
() => {
// Send the command
IFC2.waitList.push(cmdObj.cmdCode); // Add the command to the wait list
IFC2.log(`Command sent: ${cmdObj.cmdCode}`);
}
);
}
} else {
// eslint-disable-next-line @typescript-eslint/no-implied-eval
setTimeout(IFC2.processQueue, 250); // No command in queue -- try again in 250ms
}
}
},
/** **
* Add a one-off command to the command queue
*/
enqueueCommand: (cmd, action = IFC2.GETCMD, val) => {
IFC2.log(`Enqueueing: ${cmd},${action}`);
const cmdCode = IFC2.infiniteFlight.manifestByName[cmd].command; // Get the command code
const cmdBuf =
action == IFC2.GETCMD
? IFC2.getCommand(cmdCode)
: action == IFC2.RUNCMD
? IFC2.getCommand(cmdCode, val)
: IFC2.setCommand(cmdCode, val);
if (action == IFC2.GETCMD) {
IFC2.q.push({ cmd, cmdCode, cmdBuf }); // Push the command into the queue
IFC2.log(IFC2.q);
if (IFC2.q.length > 0 && !IFC2.isWaiting) {
IFC2.processQueue();
} // If not currently waiting for a response, start processing the queue
} else if (action == IFC2.SETCMD) {
IFC2.infiniteFlight.clientSocket.write(cmdBuf, () => {
// Send the command
IFC2.log(`SetState Command sent: ${cmdBuf}`);
});
} else if (action == IFC2.RUNCMD) {
IFC2.infiniteFlight.clientSocket.write(cmdBuf, () => {
// Send the command
IFC2.log(`Run Command sent: ${cmdBuf}`);
});
}
},
/** ***
* Function for client to request a one-off get command
*/
get: (cmd, callback) => {
IFC2.log(`Processing get request: ${cmd}`);
if (IFC2.isConnected) {
// Only enqueue if connected
if (IFC2.isCallback) {
// Save the callback function if we are using it
IFC2.callbacks[cmd] = callback;
}
IFC2.enqueueCommand(cmd, IFC2.GETCMD);
}
},
/** ***
* Function for client to request a one-off get command
*/
set: (cmd, val) => {
IFC2.log(`Processing set request: ${cmd},${val}`);
if (IFC2.isConnected) {
// Only enqueue if connected
IFC2.enqueueCommand(cmd, IFC2.SETCMD, val);
}
},
/** ***
* Function run an Infinite Flight command
*/
run: (cmd, args) => {
IFC2.log(`Processing run request: ${cmd}`);
if (IFC2.isConnected) {
// Only enqueue if connected
IFC2.enqueueCommand(cmd, IFC2.RUNCMD, args);
}
},
/** ***
* Process the manifest after fetching it
*/
processManifest: () => {
IFC2.log('Processing manifest into objects');
const manifestLines = IFC2.infiniteFlight.manifestData.split('\n'); // Split the data into lines
for (const key in manifestLines) {
// Loop through the lines
const line = manifestLines[key];
const lineData = line.split(','); // Split the line at commas
const command = parseInt(lineData[0]); // Get the command
const type = parseInt(lineData[1]); // Get the command data type
const name = lineData[2]; // Get the command name
if (!Number.isNaN(command)) {
// Save the manifest data for this command
IFC2.infiniteFlight.manifestByCommand[command] = {
name,
type,
};
IFC2.infiniteFlight.manifestByName[name] = {
command,
type,
};
}
}
// Emit Event
IFC2.eventEmitter.emit(
'IFC2manifest',
IFC2.infiniteFlight.manifestByName
); // Return data to calling script through an event
// Move on to post-manifest actions
IFC2.postManifest();
},
/** ***
* Return the manifest by name
*/
manifestByName: () => {
return IFC2.infiniteFlight.manifestByName;
},
/** ***
* Return the manifest by command
*/
manifestByCommand: () => {
return IFC2.infiniteFlight.manifestByCommand;
},
/** ***
* Get the manifest
*/
getManifest: () => {
IFC2.log(`Getting manifest from: ${IFC2.infiniteFlight.serverAddress}`);
// Reset manifest data variables
IFC2.infiniteFlight.manifestData = '';
IFC2.infiniteFlight.manifestByName = {};
IFC2.infiniteFlight.manifestByCommand = {};
IFC2.infiniteFlight.manifestLength = 0;
IFC2.infiniteFlight.manifestBuffer = null;
// Set up connection to the manifest socket
IFC2.infiniteFlight.manifestSocket.on('data', (data) => {
// Handle "data" event
IFC2.log('Receiving Manifest Data');
if (IFC2.infiniteFlight.manifestBuffer == null) {
// We haven't stored any buffer data yet
// Store the first batch of data in the buffer
IFC2.infiniteFlight.manifestBuffer = data;
} else {
// We already have buffer data
// Concat the new buffer data into the main manifest buffer
const bufArr = [IFC2.infiniteFlight.manifestBuffer, data];
IFC2.infiniteFlight.manifestBuffer = Buffer.concat(bufArr);
}
IFC2.log(
`Buffer length: ${IFC2.infiniteFlight.manifestBuffer.length}`
);
if (
IFC2.infiniteFlight.manifestLength <= 0 &&
IFC2.infiniteFlight.manifestBuffer.length >= 12
) {
// The first 12 bytes of the manifest are:
//
// 4 bytes: Int32 (-10 to specify the manifest command
// 4 bytes: Int32 Specify the length of all data to follow
// 4 bytes: Int32 specifying the length of the manifest data string to follow (so this is always four less than the preceding Int 32 value)
// If we don't have a manifest length and we have at least three Int32s in the buffer, get the manifest length from bytes 9-12
IFC2.infiniteFlight.manifestLength =
IFC2.infiniteFlight.manifestBuffer.readInt32LE(8);
IFC2.log(
`Manifest length: ${IFC2.infiniteFlight.manifestLength}`
);
} else if (
IFC2.infiniteFlight.manifestBuffer.length >=
IFC2.infiniteFlight.manifestLength + 12
) {
// Convert buffer to a string
IFC2.infiniteFlight.manifestData =
IFC2.infiniteFlight.manifestBuffer.toString('utf8', 12);
IFC2.log(IFC2.infiniteFlight.manifestData);
// Close the manifest socket
IFC2.infiniteFlight.manifestSocket.destroy();
// Process the manifest
IFC2.processManifest();
}
IFC2.log('-----');
});
IFC2.infiniteFlight.manifestSocket.on('timeout', () => {
// Handle "timeout" evenet
IFC2.log('Manifest data done/timed out');
IFC2.eventEmitter.emit('IFC2msg', {
type: 'error',
code: 'timeout',
context: 'manifest',
msg: 'Manifest socket connection to Infinite Flight timed out',
}); // Return data to calling script through an event
IFC2.infiniteFlight.manifestSocket.destroy(); // Destroy the socket
});
IFC2.infiniteFlight.manifestSocket.on('close', () => {
// Handle "close" event
IFC2.log('Manifest Connection closed');
IFC2.eventEmitter.emit('IFC2msg', {
type: 'info',
code: 'close',
context: 'manifest',
msg: 'Manifest socket connection to Infinite Flight closed',
}); // Return data to calling script through an event
});
// IFC2.infiniteFlight.manifestSocket.on('connect', () => { // Handle "connect" event
// });
IFC2.infiniteFlight.manifestSocket.on('error', function (data) {
IFC2.log(`Error: ${data}`, IFC2.INFO);
IFC2.eventEmitter.emit('IFC2msg', {
type: 'error',
code: 'error',
context: 'manifest',
msg: 'Error on Infinite Flight manifest socket',
}); // Return data to calling script through an event
});
IFC2.infiniteFlight.manifestSocket.on('drain', function (data) {
IFC2.log(`Drain: ${data}`, IFC2.INFO);
IFC2.eventEmitter.emit('IFC2msg', {
type: 'info',
code: 'drain',
context: 'manifest',
msg: 'Manifest socket connection to Infinite Flight drained',
}); // Return data to calling script through an event
});
IFC2.infiniteFlight.manifestSocket.on('end', function (data) {
IFC2.log(`End: ${data}`, IFC2.WARN);
IFC2.eventEmitter.emit('IFC2msg', {
type: 'info',
code: 'end',
context: 'manifest',
msg: 'Manifest socket connection to Infinite Flight ended',
}); // Return data to calling script through an event
});
IFC2.infiniteFlight.manifestSocket.on('lookup', function (data) {
IFC2.log(`Lookup: ${data}`, IFC2.INFO);
});
IFC2.infiniteFlight.manifestSocket.connect(
IFC2.infiniteFlight.serverPort,
IFC2.infiniteFlight.serverAddress,
() => {
IFC2.log('Manifest Connected');
IFC2.eventEmitter.emit('IFC2msg', {
type: 'info',
code: 'connect',
context: 'manifest',
msg: 'Manifest socket connection to Infinite Flight created',
}); // Return data to calling script through an event
IFC2.infiniteFlight.manifestSocket.setTimeout(
IFC2.infiniteFlight.manifestTimeout
); // Set the socket timeout
IFC2.infiniteFlight.manifestSocket.write(
IFC2.getCommand(IFC2.MANIFESTCMD),
() => {}
); // Issue the get manifest command (-1)
}
);
},
/** ***
* Place holder to hold success callback function provided by client
*/
successCallback: () => {},
/** ***
* Process the poll queue
*/
processPoll: () => {
IFC2.log('Processing poll Q');
if (IFC2.pollQ.length > 0 && !IFC2.isPollWaiting) {
// Only process if the queue has entries and we are not waiting for data from IF
IFC2.log(IFC2.pollQ);
// Get current command to process
const cmd = IFC2.pollQ[IFC2.pollCurrent];
const cmdCode = IFC2.infiniteFlight.manifestByName[cmd].command; // Get the command code
IFC2.log(`Polling command: ${cmdCode}`);
// Prep for next poll
IFC2.pollCurrent =
IFC2.pollCurrent + 1 == IFC2.pollQ.length
? 0
: IFC2.pollCurrent + 1;
// Set isPollWaiting
IFC2.isPollWaiting = true;
// Send the command
if (IFC2.pollThrottle > 0) {
// Wait before polling
setTimeout(() => {
IFC2.infiniteFlight.pollSocket.write(
IFC2.getCommand(cmdCode),
() => {
IFC2.log(`Poll command sent: ${cmdCode}`);
if (IFC2.waitList.indexOf(cmdCode) < 0) {
// Check if we are already waiting for this command
IFC2.waitList.push(cmdCode); // Add the command to the wait list
IFC2.pollWaiting = cmdCode;
}
}
);
}, IFC2.pollThrottle);
} else if (IFC2.waitList.indexOf(cmdCode) < 0) {
// Check if we are already waiting for this command
IFC2.infiniteFlight.pollSocket.write(
IFC2.getCommand(cmdCode),
() => {
IFC2.log(`Poll command sent: ${cmdCode}`);
IFC2.waitList.push(cmdCode); // Add the command to the wait list
IFC2.pollWaiting = cmdCode;
}
);
}
} else {
// There was nothing in the queue
IFC2.log('Set poll timeout');
}
},
/** ***
* Register a command into the poll queue
*/
pollRegister: (cmd, callback) => {
if (!IFC2.pollQ.hasOwnProperty(cmd)) {
if (IFC2.isCallback) {
// Save callback function if we are using callbacks
IFC2.callbacks[cmd] = callback;
}
IFC2.pollQ.push(cmd);
if (!IFC2.isPollWaiting) {
IFC2.processPoll();
}
}
},
/** ***
* Deregister a command from the poll queue
*/
pollDeregister: (cmd) => {
const index = IFC2.pollQ.indexOf(cmd);
IFC2.pollQ.splice(index, 1);
if (IFC2.pollCurrent >= IFC2.pollQ.length) {
IFC2.pollCurrent = 0;
}
if (IFC2.pollQ.length == 0) {
IFC2.isPollWaiting = false;
}
},
/** ***
* Process command data returned by the API
*
* nextFN is a function to call after data processing is done
*/
processData: (source, nextFN) => {
IFC2.log(`processData: Processing data source: ${source}`, IFC2.INFO);
const data = source == 'client' ? IFC2.qBuffer : IFC2.pollBuffer;
const command = data.readInt32LE(0); // Get the command from the data
IFC2.log(`processData: Got data for command: ${command}`);
const inManifest =
IFC2.infiniteFlight.manifestByCommand.hasOwnProperty(command); // See if command is in manifest
IFC2.log(`processData: inManifest: ${inManifest}`);
if (inManifest) {
// Only proceed if we have the command in the manifest
const waitIndex = IFC2.waitList.indexOf(command); // See if the command is in the waitList
IFC2.log(`processData: waitList: ${JSON.stringify(IFC2.waitList)}`);
IFC2.log(`processData: In waitList: ${waitIndex}`);
if (waitIndex >= 0) {
// Only proceed if command is in the waitList
IFC2.log(`processData: Waiting for command: ${command}`);
IFC2.log(`processData: data length: ${data.length}`);
if (data.length > 4) {
// See if we have a data length greater than 4
IFC2.log('processData: data length gt 4');
const bufLength = data.readInt32LE(4);
if (data.length >= bufLength + 8) {
// Do we have the full command data?
IFC2.log('processData: data is complete so process');
IFC2.log(data);
IFC2.log(
`processData: waitList before splice: ${JSON.stringify(
IFC2.waitList
)}`
);
IFC2.waitList.splice(waitIndex, 1);
IFC2.log(
`processData: waitList after splice: ${JSON.stringify(
IFC2.waitList
)}`
);
let strLen;
switch (
IFC2.infiniteFlight.manifestByCommand[command].type
) {
case IFC2.BOOLEAN:
IFC2.processResult(
command,
data.readUInt8(8) == 1
);
break;
case IFC2.INTEGER:
IFC2.processResult(
command,
data.readInt32LE(8)
);
break;
case IFC2.FLOAT:
IFC2.processResult(
command,
data.readFloatLE(8)
);
break;
case IFC2.DOUBLE:
IFC2.processResult(
command,
data.readDoubleLE(8)
);
break;
case IFC2.STRING:
strLen = data.readUInt32LE(8);
IFC2.processResult(
command,
data.toString('utf8', 12, strLen + 12)
);
break;
case IFC2.LONG:
IFC2.processResult(
command,
data.readBigInt64LE(8)
);
break;
default:
return;
}
// remove data from buffer
if (source == 'client') {
if (data.length > bufLength + 8) {
IFC2.qBuffer = IFC2.qBuffer.slice(
bufLength + 8,
IFC2.qBuffer.length
);
} else {
IFC2.qBuffer = null;
if (IFC2.waitList.length == 0) {
IFC2.isWaiting = false; // No longer waiting
}
}
} else if (data.length > bufLength + 8) {
IFC2.pollBuffer = IFC2.pollBuffer.slice(
bufLength + 8,
IFC2.pollBuffer.length
);
} else {
IFC2.pollBuffer = null;
IFC2.isPollWaiting = false; // No longer waiting
}
nextFN();
} else {
nextFN();
}
} else {
nextFN();
}
} else {
nextFN();
}
} else {
nextFN();
}
},
/** ***
* After processing the manifest, connect to IF Connect v2 API
*/
postManifest() {
IFC2.infiniteFlight.clientSocket.connect(
IFC2.infiniteFlight.serverPort,
IFC2.infiniteFlight.serverAddress,
function () {
IFC2.infiniteFlight.clientSocket.setTimeout(IFC2.timeout);
IFC2.infiniteFlight.clientSocket.setKeepAlive(IFC2.keepAlive);
}
);
IFC2.infiniteFlight.clientSocket.on('data', function (data) {
IFC2.log(`***** Received: ${data}`, IFC2.INFO);
if (IFC2.qBuffer == null) {
// We haven't stored any buffer data yet
// Store the first batch of data in the buffer
IFC2.qBuffer = data;
} else {
// We already have buffer data
// Concat the new buffer data into the main manifest buffer
const bufArr = [IFC2.qBuffer, data];
IFC2.qBuffer = Buffer.concat(bufArr);
}
IFC2.processData('client', IFC2.processQueue);
});
IFC2.infiniteFlight.clientSocket.on('error', function (data) {
IFC2.log(`Client: Error: ${JSON.stringify(data)}`, IFC2.INFO);
if (IFC2.isConnected && IFC2.doReconnect) {
IFC2.log('Client: Trying to reconnect');
IFC2.eventEmitter.emit('IFC2msg', {
type: 'info',
code: 'reconnect',
context: 'client',
msg: 'Reconnecting for general queries',
}); // Return data to calling script through an event
IFC2.infiniteFlight.clientSocket.destroy();
// IFC2.infiniteFlight.pollSocket = new net.Socket();
IFC2.infiniteFlight.clientSocket.connect(
IFC2.infiniteFlight.serverPort,
IFC2.infiniteFlight.serverAddress,
function () {
IFC2.infiniteFlight.clientSocket.setTimeout(
IFC2.timeout
);
IFC2.infiniteFlight.clientSocket.setKeepAlive(
IFC2.keepAlive
);
IFC2.eventEmitter.emit('IFC2msg', {
type: 'info',
code: 'reconnected',
context: 'client',
msg: 'Reconnected for general queries',
}); // Return data to calling script through an event
}
);
}
IFC2.eventEmitter.emit('IFC2msg', {
type: 'error',
code: 'error',
context: 'client',
msg: 'Error on Infinite Flight socket',
}); // Return data to calling script through an event
});
IFC2.infiniteFlight.clientSocket.on('timeout', function (data) {
IFC2.log(`Client: Timeout: ${JSON.stringify(data)}`, IFC2.INFO);
IFC2.eventEmitter.emit('IFC2msg', {
type: 'error',
code: 'timeout',
context: 'client',
msg: 'Timeout on socket connection to Infinite Flight',
}); // Return data to calling script through an event
});
IFC2.infiniteFlight.clientSocket.on('close', function (data) {
IFC2.log(`Client: Closer: ${JSON.stringify(data)}`, IFC2.INFO);
IFC2.eventEmitter.emit('IFC2msg', {
type: 'info',
code: 'close',
context: 'client',
msg: 'Socket connection to Infinite Flight closed',
}); // Return data to calling script through an event
});
IFC2.infiniteFlight.clientSocket.on('connect', function (data) {
IFC2.log(
`Connected to IF server ${IFC2.infiniteFlight.serverAddress}`,
IFC2.MANDATORY
);
/* if (IFC2.isConnected && IFC2.infiniteFlight.keepAlive) {
IFC2.infiniteFlight.clientSocket.connect(IFC2.infiniteFlight.serverPort, IFC2.infiniteFlight.serverAddress, function() {
IFC2.infiniteFlight.clientSocket.setTimeout(IFC2.timeout);
IFC2.infiniteFlight.clientSocket.setKeepAlive(IFC2.keepAlive);
});
} */
IFC2.eventEmitter.emit('IFC2msg', {
type: 'info',
code: 'connect',
context: 'client',
msg: 'Socket connection to Infinite Flight created',
}); // Return data to calling script through an event
if (!IFC2.isConnected) {
IFC2.postConnect();
}
});
IFC2.infiniteFlight.clientSocket.on('drain', function (data) {
IFC2.log(`Client: Drain: ${JSON.stringify(data)}`, IFC2.INFO);
IFC2.eventEmitter.emit('IFC2msg', {
type: 'info',
code: 'drain',
context: 'client',
msg: 'Socket connection to Infinite Flight drained',