-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathirsdk-node.ts
More file actions
557 lines (494 loc) · 14.9 KB
/
Copy pathirsdk-node.ts
File metadata and controls
557 lines (494 loc) · 14.9 KB
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
import * as yaml from 'js-yaml';
import {
BroadcastMessages,
CameraState,
ChatCommand,
FFBCommand,
PitCommand,
ReloadTexturesCommand,
ReplayPositionCommand,
ReplaySearchCommand,
ReplayStateCommand,
TelemetryCommand,
VideoCaptureCommand,
TelemetryVariable,
TelemetryVarList,
CameraInfo,
CarSetupInfo,
DriverInfo,
RadioInfo,
SessionList,
SplitTimeInfo,
WeekendInfo,
SessionData,
} from '../types';
import type { INativeSDK } from '../native';
import { getSimStatus } from './utils';
import { getSdkOrMock } from './get-sdk';
import logger from '../../logger';
function copyTelemData<
K extends keyof TelemetryVarList = keyof TelemetryVarList,
T extends TelemetryVarList[K] = TelemetryVarList[K],
>(
src: T,
key: K,
dest: TelemetryVarList,
cache?: Partial<TelemetryVarList>
): void {
// Check if we have a cached entry to reuse
const cached = cache?.[key];
const useCache = cached && cached.value && Array.isArray(cached.value);
if (!useCache) {
dest[key] = { value: src?.value ?? [] } as TelemetryVarList[K];
} else {
dest[key] = cached;
}
// bool
if (src.varType === 1) {
const arr = new Int8Array(src.value as number[]);
const targetArray = useCache ? (dest[key].value as boolean[]) : [];
if (!useCache) {
dest[key].value = targetArray;
}
// Reuse array by updating in-place
for (let i = 0; i < arr.length; i++) {
targetArray[i] = !!arr[i];
}
return;
}
// numbers
if (src.varType === 2 || src.varType === 3) {
// int
const srcArray = new Int32Array(src.value as number[]);
if (useCache) {
const targetArray = dest[key].value as number[];
for (let i = 0; i < srcArray.length; i++) {
targetArray[i] = srcArray[i];
}
} else {
dest[key].value = [...srcArray];
}
} else if (src.varType === 4) {
// float
const srcArray = new Float32Array(src.value as number[]);
if (useCache) {
const targetArray = dest[key].value as number[];
for (let i = 0; i < srcArray.length; i++) {
targetArray[i] = srcArray[i];
}
} else {
dest[key].value = [...srcArray];
}
} else if (src.varType === 5) {
// double
const srcArray = new Float64Array(src.value as number[]);
if (useCache) {
const targetArray = dest[key].value as number[];
for (let i = 0; i < srcArray.length; i++) {
targetArray[i] = srcArray[i];
}
} else {
dest[key].value = [...srcArray];
}
}
}
export class IRacingSDK {
// Public
/**
* Enable attempting to auto-start telemetry when starting the SDK (if it is not running).
* @default false
*/
public autoEnableTelemetry = false;
// Private
private _dataVer = -1;
private _sessionData: SessionData | null = null;
private _sdk?: INativeSDK;
private _sdkReq: Promise<void>;
// Cache for telemetry data to avoid repeated array allocations
private _telemetryCache: Partial<TelemetryVarList> = {};
constructor() {
this._sdkReq = this._loadSDK();
}
private async _loadSDK(): Promise<void> {
const sdk = await getSdkOrMock();
this._sdk = sdk;
this._sdk.startSDK();
}
public async ready(): Promise<boolean> {
await this._sdkReq;
return true;
}
/**
* The current version number of the session data. Increments internally every time data changes.
* @property {number}
* @readonly
*/
public get currDataVersion(): number {
return this._sdk?.currDataVersion ?? -1;
}
/** Whether or not to enable verbose logging in the SDK.
* @property {boolean}
*/
public get enableLogging(): boolean {
return this._sdk?.enableLogging ?? false;
}
public set enableLogging(value: boolean) {
if (this._sdk) this._sdk.enableLogging = value;
}
// @todo: add getter for current session string version
/**
* Checks whether the simulation service is running.
* @returns {boolean} True if the service is running.
*/
public static async IsSimRunning(): Promise<boolean> {
try {
const result = await getSimStatus();
return result;
} catch (e) {
logger.error('Could not successfully determine sim status:', e);
}
return false;
}
public get sessionStatusOK(): boolean {
return this._sdk?.isRunning() ?? false;
}
/**
* Merges continuation lines back into the preceding key's value. iRacing
* occasionally emits values that contain a literal newline (e.g. a
* DriverSetupName built from a path with `\n` in a folder name), which
* produces YAML that fails to parse. We detect lines that don't look like
* a valid key, list item, or document marker and fold them into the prior
* key's value as a single-quoted scalar.
*/
private static fixMultilineValues(yamlText: string): string {
const lines = yamlText.split('\n');
const keyLine = /^\s*(?:-\s+)?\w+:(?:\s|$)/;
const otherValid = /^\s*$|^\s*#|^\.\.\.\s*$|^---\s*$|^\s*-\s+\S/;
let lastKeyIdx = -1;
let changed = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (keyLine.test(line)) {
lastKeyIdx = i;
} else if (otherValid.test(line)) {
// structurally valid, nothing to merge
} else if (lastKeyIdx >= 0) {
const match = lines[lastKeyIdx].match(/^(\s*(?:-\s+)?\w+:\s*)(.*)$/);
if (match) {
const [, keyPart, existing] = match;
const unquoted = existing
.replace(/^'(.*)'$/, '$1')
.replace(/''/g, "'");
const merged = `${unquoted.trimEnd()} ${line.trim()}`.replace(
/'/g,
"''"
);
lines[lastKeyIdx] = `${keyPart}'${merged}'`;
lines[i] = '';
changed = true;
}
}
}
return changed ? lines.join('\n') : yamlText;
}
/**
* Quotes scalar values that iRacing emits with a leading YAML mapping or
* sequence indicator. For example, `UserName: ? ?` and
* `TeamName: - BLACKSUIT` are not valid as unquoted scalars.
*/
private static fixIndicatorValues(yamlText: string): string {
return yamlText.replace(
/^([^\S\r\n]*(?:-[^\S\r\n]+)?\w+:[^\S\r\n]*)([?-](?:[^\S\r\n]+[^\r\n]*)?)\r?$/gm,
(_line, keyPart: string, value: string) =>
`${keyPart}'${value.replace(/'/g, "''")}'`
);
}
/**
* Starts the native iRacing SDK and begins subscribing for data.
* @returns {boolean} If the SDK started successfully.
*/
public startSDK(): boolean {
if (!this._sdk?.isRunning()) {
const successful = this._sdk?.startSDK() ?? false;
if (this.autoEnableTelemetry) {
this.enableTelemetry(true);
}
return successful;
}
return true;
}
/**
* Stops the SDK from running and resets the data version.
*/
public stopSDK(): void {
this._sdk?.stopSDK();
this._dataVer = -1;
}
/**
* Wait for new data from the sdk.
* @param {number} timeout Timeout (in ms). Max is 60fps (1/60)
*/
public waitForData(timeout?: number): boolean {
const result = this._sdk?.waitForData(timeout) ?? false;
if (!result && this._sdk?.currDataVersion === -1) {
this._dataVer = -1;
this._sessionData = null;
}
return result;
}
/**
* Gets the current session data (from yaml format).
* @returns {SessionData}
*/
public getSessionData(): SessionData | null {
if (!this._sdk) return null;
try {
const seshString = this._sdk?.getSessionData();
// currDataVersion is only updated after getSessionData is called
if (this._sessionData && this._dataVer === this.currDataVersion)
return this._sessionData;
// Handle leading commas in YAML values.
// First regex will drop the comma if no values follow (e.g. 'field: ,' => 'field: ')
// Second regex will put value in quotes, if leading comma is followed by values (e.g. 'field: ,data' => 'field: ",data"')
// The multiline-value pass handles iRacing setup names that contain a literal
// newline (e.g. corrupted DriverSetupName paths), which YAML would otherwise reject.
const fixedYaml = seshString
? IRacingSDK.fixIndicatorValues(
IRacingSDK.fixMultilineValues(seshString)
)
.replace(/(\w+: ) *, *\n/g, '$1 \n')
.replace(/(\w+: )(,.*)/g, '$1"$2" \n')
: seshString;
this._sessionData = yaml.load(fixedYaml, { json: true }) as SessionData;
this._dataVer = this.currDataVersion;
return this._sessionData;
} catch (err) {
logger.error('There was an error getting session data:', err);
}
return null;
}
/**
* Gets the current weekend info from the session data
* @returns {WeekendInfo}
*/
public getWeekendInfo(): WeekendInfo | null {
const session = this.getSessionData();
return session?.WeekendInfo ?? null;
}
/**
* Gets the current session info from the session data.
* @returns {SessionInfo}
*/
public getSessionInfo(): SessionList | null {
const session = this.getSessionData();
return session?.SessionInfo ?? null;
}
/**
* Gets the current camera info from the session data.
* @returns {CameraInfo}
*/
public getCameraInfo(): CameraInfo | null {
const session = this.getSessionData();
return session?.CameraInfo ?? null;
}
/**
* Gets the current radio info from the session data.
* @returns {RadioInfo}
*/
public getRadioInfo(): RadioInfo | null {
const session = this.getSessionData();
return session?.RadioInfo ?? null;
}
/**
* Gets the current driver info from the session data.
* @returns {DriverInfo}
*/
public getDriverInfo(): DriverInfo | null {
const session = this.getSessionData();
return session?.DriverInfo ?? null;
}
/**
* Gets the current split time info from the session data.
* @returns {SplitTimeInfo}
*/
public getSplitInfo(): SplitTimeInfo | null {
const session = this.getSessionData();
return session?.SplitTimeInfo ?? null;
}
/**
* Gets the current session info from the session data.
* @returns {CarSetupInfo}
*/
public getCarSetupInfo(): CarSetupInfo | null {
const session = this.getSessionData();
return session?.CarSetup ?? null;
}
/**
* Get the current value of the telemetry variables.
*/
public getTelemetry(): TelemetryVarList {
const rawData = this._sdk?.getTelemetryData();
const data: Partial<TelemetryVarList> = {};
if (rawData) {
Object.keys(rawData).forEach((dataKey) => {
copyTelemData(
rawData[dataKey as keyof TelemetryVarList],
dataKey as keyof TelemetryVarList,
data as TelemetryVarList,
this._telemetryCache
);
});
// Update cache with the new data
this._telemetryCache = data;
}
return data as TelemetryVarList;
}
/**
* Request the value of the given telemetry variable.
* @param telemVar The variable name or numeric index (use index only if you know what you are doing!)
*/
public getTelemetryVariable<T extends boolean | number | string>(
telemVar: number | keyof TelemetryVarList
): TelemetryVariable<T[]> | null {
if (!this._sdk) return null;
const rawData = this._sdk?.getTelemetryVariable(telemVar as string);
const parsed: Partial<TelemetryVarList> = {};
copyTelemData(
rawData as TelemetryVariable,
rawData.name as keyof TelemetryVarList,
parsed as TelemetryVarList
);
return parsed[rawData.name as keyof TelemetryVarList] as TelemetryVariable<
T[]
>;
}
// Broadcast commands
public enableTelemetry(enabled: boolean): void {
const command = enabled ? TelemetryCommand.Start : TelemetryCommand.Stop;
this._sdk?.broadcast(BroadcastMessages.TelemCommand, command);
}
public restartTelemetry(): void {
this._sdk?.broadcast(
BroadcastMessages.TelemCommand,
TelemetryCommand.Restart
);
}
public changeCameraPosition(
position: number,
group: number,
camera: number
): void {
this._sdk?.broadcast(
BroadcastMessages.CameraSwitchPos,
position,
group,
camera
);
}
// @todo: needs to be padded
public changeCameraNumber(
driver: number,
group: number,
camera: number
): void {
this._sdk?.broadcast(
BroadcastMessages.CameraSwitchNum,
driver,
group,
camera
);
}
public changeCameraState(state: CameraState): void {
this._sdk?.broadcast(BroadcastMessages.CameraSetState, state);
}
public changeReplaySpeed(speed: number, slowMotion: boolean): void {
this._sdk?.broadcast(
BroadcastMessages.ReplaySetPlaySpeed,
speed,
slowMotion ? 1 : 0
);
}
public changeReplayPosition(
position: ReplayPositionCommand,
frame: number
): void {
this._sdk?.broadcast(
BroadcastMessages.ReplaySetPlayPosition,
position,
frame
);
}
public searchReplay(command: ReplaySearchCommand): void {
this._sdk?.broadcast(BroadcastMessages.ReplaySearch, command);
}
public changeReplayState(state: ReplayStateCommand): void {
this._sdk?.broadcast(BroadcastMessages.ReplaySetState, state);
}
public triggerReplaySessionSearch(session: number, time: number): void {
this._sdk?.broadcast(
BroadcastMessages.ReplaySearchSessionTime,
session,
time
);
}
public reloadAllTextures(): void {
this._sdk?.broadcast(
BroadcastMessages.ReloadTextures,
ReloadTexturesCommand.All,
0
);
}
public reloadCarTextures(car: number): void {
this._sdk?.broadcast(
BroadcastMessages.ReloadTextures,
ReloadTexturesCommand.CarIndex,
car
);
}
public triggerChatState(
state: ChatCommand.BeginChat | ChatCommand.Cancel | ChatCommand.Reply
): void {
this._sdk?.broadcast(BroadcastMessages.ChatCommand, state, 1);
}
/**
* @param {number} macro Between 1 - 15
*/
public triggerChatMacro(macro: number): void {
const clamped = Math.min(15, Math.max(1, macro));
this._sdk?.broadcast(
BroadcastMessages.ChatCommand,
ChatCommand.Macro,
clamped
);
}
public triggerPitClearCommand(
command:
| PitCommand.Clear
| PitCommand.ClearTires
| PitCommand.ClearWS
| PitCommand.ClearFR
| PitCommand.ClearFuel
): void {
this._sdk?.broadcast(BroadcastMessages.PitCommand, command);
}
public triggerPitCommand(command: PitCommand.WS | PitCommand.FR): void {
this._sdk?.broadcast(BroadcastMessages.PitCommand, command);
}
public triggerPitChange(
command:
| PitCommand.Fuel
| PitCommand.LF
| PitCommand.RF
| PitCommand.LR
| PitCommand.RR,
amount: number
): void {
this._sdk?.broadcast(BroadcastMessages.PitCommand, command, amount);
}
public changeFFB(mode: FFBCommand, amount: number): void {
this._sdk?.broadcast(BroadcastMessages.FFBCommand, mode, amount);
}
public triggerVideoCapture(command: VideoCaptureCommand): void {
this._sdk?.broadcast(BroadcastMessages.VideoCapture, command);
}
}