forked from kutu/pyirsdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
irsdk.py
794 lines (669 loc) · 29 KB
/
irsdk.py
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
#!python3
import re
import argparse
import mmap
import struct
import ctypes
import yaml
from threading import Thread
from urllib import request, error
from yaml.reader import Reader as YamlReader
try:
from yaml.cyaml import CSafeLoader as YamlSafeLoader
except ImportError:
from yaml import SafeLoader as YamlSafeLoader
VERSION = '1.3.5'
SIM_STATUS_URL = 'http://127.0.0.1:32034/get_sim_status?object=simStatus'
DATAVALIDEVENTNAME = 'Local\\IRSDKDataValidEvent'
MEMMAPFILE = 'Local\\IRSDKMemMapFileName'
MEMMAPFILESIZE = 1164 * 1024
BROADCASTMSGNAME = 'IRSDK_BROADCASTMSG'
VAR_TYPE_MAP = ['c', '?', 'i', 'I', 'f', 'd']
YAML_TRANSLATER = bytes.maketrans(b'\x81\x8D\x8F\x90\x9D', b' ')
YAML_CODE_PAGE = 'cp1252'
class StatusField:
status_connected = 1
class EngineWarnings:
water_temp_warning = 0x01
fuel_pressure_warning = 0x02
oil_pressure_warning = 0x04
engine_stalled = 0x08
pit_speed_limiter = 0x10
rev_limiter_active = 0x20
oil_temp_warning = 0x40
class Flags:
# global flags
checkered = 0x0001
white = 0x0002
green = 0x0004
yellow = 0x0008
red = 0x0010
blue = 0x0020
debris = 0x0040
crossed = 0x0080
yellow_waving = 0x0100
one_lap_to_green = 0x0200
green_held = 0x0400
ten_to_go = 0x0800
five_to_go = 0x1000
random_waving = 0x2000
caution = 0x4000
caution_waving = 0x8000
# drivers black flags
black = 0x010000
disqualify = 0x020000
servicible = 0x040000 # car is allowed service (not a flag)
furled = 0x080000
repair = 0x100000
# start lights
start_hidden = 0x10000000
start_ready = 0x20000000
start_set = 0x40000000
start_go = 0x80000000
class TrkLoc:
not_in_world = -1
off_track = 0
in_pit_stall = 1
aproaching_pits = 2
on_track = 3
class TrkSurf:
not_in_world = -1
undefined = 0
asphalt_1 = 1
asphalt_2 = 2
asphalt_3 = 3
asphalt_4 = 4
concrete_1 = 5
concrete_2 = 6
racing_dirt_1 = 7
racing_dirt_2 = 8
paint_1 = 9
paint_2 = 10
rumble_1 = 11
rumble_2 = 12
rumble_3 = 13
rumble_4 = 14
grass_1 = 15
grass_2 = 16
grass_3 = 17
grass_4 = 18
dirt_1 = 19
dirt_2 = 20
dirt_3 = 21
dirt_4 = 22
sand = 23
gravel_1 = 24
gravel_2 = 25
grasscrete = 26
astroturf = 27
class SessionState:
invalid = 0
get_in_car = 1
warmup = 2
parade_laps = 3
racing = 4
checkered = 5
cool_down = 6
class CameraState:
is_session_screen = 0x0001 # the camera tool can only be activated if viewing the session screen (out of car)
is_scenic_active = 0x0002 # the scenic camera is active (no focus car)
# these can be changed with a broadcast message
cam_tool_active = 0x0004
ui_hidden = 0x0008
use_auto_shot_selection = 0x0010
use_temporary_edits = 0x0020
use_key_acceleration = 0x0040
use_key10x_acceleration = 0x0080
use_mouse_aim_mode = 0x0100
class BroadcastMsg:
cam_switch_pos = 0 # car position, group, camera
cam_switch_num = 1 # driver #, group, camera
cam_set_state = 2 # CameraState, unused, unused
replay_set_play_speed = 3 # speed, slowMotion, unused
replay_set_play_position = 4 # RpyPosMode, Frame Number (high, low)
replay_search = 5 # RpySrchMode, unused, unused
replay_set_state = 6 # RpyStateMode, unused, unused
reload_textures = 7 # ReloadTexturesMode, carIdx, unused
chat_command = 8 # ChatCommandMode, subCommand, unused
pit_command = 9 # PitCommandMode, parameter
telem_command = 10 # irsdk_TelemCommandMode, unused, unused
ffb_command = 11 # irsdk_FFBCommandMode, value (float, high, low)
replay_search_session_time = 12 # sessionNum, sessionTimeMS (high, low)
video_capture = 13 # irsdk_VideoCaptureMode, unused, unused
class ChatCommandMode:
macro = 0 # pass in a number from 1-15 representing the chat macro to launch
begin_chat = 1 # Open up a new chat window
reply = 2 # Reply to last private chat
cancel = 3 # Close chat window
class PitCommandMode: # this only works when the driver is in the car
clear = 0 # Clear all pit checkboxes
ws = 1 # Clean the winshield, using one tear off
fuel = 2 # Add fuel, optionally specify the amount to add in liters or pass '0' to use existing amount
lf = 3 # Change the left front tire, optionally specifying the pressure in KPa or pass '0' to use existing pressure
rf = 4 # right front
lr = 5 # left rear
rr = 6 # right rear
clear_tires = 7 # Clear tire pit checkboxes
fr = 8 # Request a fast repair
clear_ws = 9 # Uncheck Clean the winshield checkbox
clear_fr = 10 # Uncheck request a fast repair
clear_fuel = 11 # Uncheck add fuel
class TelemCommandMode: # You can call this any time, but telemtry only records when driver is in there car
stop = 0 # Turn telemetry recording off
start = 1 # Turn telemetry recording on
restart = 2 # Write current file to disk and start a new one
class RpyStateMode:
erase_tape = 0 # clear any data in the replay tape
class ReloadTexturesMode:
all = 0 # reload all textuers
car_idx = 1 # reload only textures for the specific carIdx
class RpySrchMode:
to_start = 0
to_end = 1
prev_session = 2
next_session = 3
prev_lap = 4
next_lap = 5
prev_frame = 6
next_frame = 7
prev_incident = 8
next_incident = 9
class RpyPosMode:
begin = 0
current = 1
end = 2
class csMode:
at_incident = -3
at_leader = -2
at_exciting = -1
class PitSvFlags:
lf_tire_change = 0x01
rf_tire_change = 0x02
lr_tire_change = 0x04
rr_tire_change = 0x08
fuel_fill = 0x10
windshield_tearoff = 0x20
fast_repair = 0x40
class PitSvStatus:
# status
none = 0
in_progress = 1
complete = 2
# errors
too_far_left = 100
too_far_right = 101
too_far_forward = 102
too_far_back = 103
bad_angle = 104
cant_fix_that = 105
class PaceMode:
single_file_start = 0
double_file_start = 1
single_file_restart = 2
double_file_restart = 3
not_pacing = 4
class PaceFlags:
end_of_line = 0x0001
free_pass = 0x0002
waved_around = 0x0004
class CarLeftRight:
off = 0
clear = 1 # no cars around us.
car_left = 2 # there is a car to our left.
car_right = 3 # there is a car to our right.
car_left_right = 4 # there are cars on each side.
two_cars_left = 5 # there are two cars to our left.
two_cars_right = 6 # there are two cars to our right.
class FFBCommandMode: # You can call this any time
ffb_command_max_force = 0 # Set the maximum force when mapping steering torque force to direct input units (float in Nm)
class VideoCaptureMode:
trigger_screen_shot = 0 # save a screenshot to disk
start_video_capture = 1 # start capturing video
end_video_capture = 2 # stop capturing video
toggle_video_capture = 3 # toggle video capture on/off
show_video_timer = 4 # show video timer in upper left corner of display
hide_video_timer = 5 # hide video timer
class TrackWetness:
unknown = 0
dry = 1
mostly_dry = 2
very_lightly_wet = 3
lightly_wet = 4
moderately_wet = 5
very_wet = 6
extremely_wet = 7
class IRSDKStruct:
@classmethod
def property_value(cls, offset, var_type):
struct_type = struct.Struct(var_type)
return property(lambda self: self.get(offset, struct_type))
@classmethod
def property_value_str(cls, offset, var_type):
struct_type = struct.Struct(var_type)
return property(lambda self: self.get(offset, struct_type).strip(b'\x00').decode('latin-1'))
def __init__(self, shared_mem, offset=0):
self._shared_mem = shared_mem
self._offset = offset
def __repr__(self):
return f'''<{self.__class__.__module__}.{self.__class__.__name__} {', '.join(
f'{k}={getattr(self, k)!r}'
for k, p in vars(self.__class__).items()
if not k.startswith('_') and isinstance(p, property)
)}>'''
def get(self, offset, struct_type):
return struct_type.unpack_from(self._shared_mem, self._offset + offset)[0]
class Header(IRSDKStruct):
version = IRSDKStruct.property_value(0, 'i')
status = IRSDKStruct.property_value(4, 'i')
tick_rate = IRSDKStruct.property_value(8, 'i')
session_info_update = IRSDKStruct.property_value(12, 'i')
session_info_len = IRSDKStruct.property_value(16, 'i')
session_info_offset = IRSDKStruct.property_value(20, 'i')
num_vars = IRSDKStruct.property_value(24, 'i')
var_header_offset = IRSDKStruct.property_value(28, 'i')
num_buf = IRSDKStruct.property_value(32, 'i')
buf_len = IRSDKStruct.property_value(36, 'i')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.var_buf = [
VarBuffer(self._shared_mem, 48 + i * 16, buf_len=self.buf_len)
for i in range(self.num_buf)
]
class VarBuffer(IRSDKStruct):
tick_count = IRSDKStruct.property_value(0, 'i')
_buf_offset = IRSDKStruct.property_value(4, 'i')
def __init__(self, *args, buf_len, **kwargs):
super().__init__(*args, **kwargs)
self.is_memory_frozen = False
self._frozen_memory = None
self._buf_len = buf_len
def freeze(self):
self._frozen_memory = self._shared_mem[self._buf_offset : self._buf_offset + self._buf_len]
self.is_memory_frozen = True
def unfreeze(self):
self._frozen_memory = None
self.is_memory_frozen = False
def get_memory(self):
return self._frozen_memory if self.is_memory_frozen else self._shared_mem
@property
def buf_offset(self):
return 0 if self.is_memory_frozen else self._buf_offset
class VarHeader(IRSDKStruct):
type = IRSDKStruct.property_value(0, 'i')
offset = IRSDKStruct.property_value(4, 'i')
count = IRSDKStruct.property_value(8, 'i')
count_as_time = IRSDKStruct.property_value(12, '?')
name = IRSDKStruct.property_value_str(16, '32s')
desc = IRSDKStruct.property_value_str(48, '64s')
unit = IRSDKStruct.property_value_str(112, '32s')
class DiskSubHeader(IRSDKStruct):
session_start_date = IRSDKStruct.property_value(0, 'Q')
session_start_time = IRSDKStruct.property_value(8, 'd')
session_end_time = IRSDKStruct.property_value(16, 'd')
session_lap_count = IRSDKStruct.property_value(24, 'i')
session_record_count = IRSDKStruct.property_value(28, 'i')
class IRSDK:
def __init__(self, parse_yaml_async=False):
self.parse_yaml_async = parse_yaml_async
self.is_initialized = False
self.last_session_info_update = 0
self._shared_mem = None
self._header = None
self._data_valid_event = None
self.__var_headers = None
self.__var_headers_dict = None
self.__var_headers_names = None
self.__var_buffer_latest = None
self.__session_info_dict = {}
self.__broadcast_msg_id = None
self.__test_file = None
self.__workaround_connected_state = 0
def __getitem__(self, key):
if key in self._var_headers_dict:
var_header = self._var_headers_dict[key]
var_buf_latest = self._var_buffer_latest
res = struct.unpack_from(
VAR_TYPE_MAP[var_header.type] * var_header.count,
var_buf_latest.get_memory(),
var_buf_latest.buf_offset + var_header.offset)
return res[0] if var_header.count == 1 else list(res)
return self._get_session_info(key)
@property
def is_connected(self):
if self._header:
if self._header.status == StatusField.status_connected:
self.__workaround_connected_state = 0
if self.__workaround_connected_state == 0 and self._header.status != StatusField.status_connected:
self.__workaround_connected_state = 1
if self.__workaround_connected_state == 1 and (self['SessionNum'] is None or self.__test_file):
self.__workaround_connected_state = 2
if self.__workaround_connected_state == 2 and self['SessionNum'] is not None:
self.__workaround_connected_state = 3
return self._header is not None and \
(self.__test_file or self._data_valid_event) and \
(self._header.status == StatusField.status_connected or self.__workaround_connected_state == 3)
@property
def session_info_update(self):
return self._header.session_info_update
@property
def var_headers_names(self):
if self.__var_headers_names is None:
self.__var_headers_names = [var_header.name for var_header in self._var_headers]
return self.__var_headers_names
def startup(self, test_file=None, dump_to=None):
if test_file is None:
if not self._check_sim_status():
return False
self._data_valid_event = ctypes.windll.kernel32.OpenEventW(0x00100000, False, DATAVALIDEVENTNAME)
if not self._wait_valid_data_event():
self._data_valid_event = None
return False
if self._shared_mem is None:
if test_file:
self.__test_file = open(test_file, 'rb')
self._shared_mem = mmap.mmap(self.__test_file.fileno(), 0, access=mmap.ACCESS_READ)
else:
self._shared_mem = mmap.mmap(0, MEMMAPFILESIZE, MEMMAPFILE, access=mmap.ACCESS_READ)
if self._shared_mem:
if dump_to:
with open(dump_to, 'wb') as f:
f.write(self._shared_mem)
self._header = Header(self._shared_mem)
self.is_initialized = self._header.version >= 1 and len(self._header.var_buf) > 0
return self.is_initialized
def shutdown(self):
self.is_initialized = False
self.last_session_info_update = 0
if self._shared_mem:
self._shared_mem.close()
self._shared_mem = None
self._header = None
self._data_valid_event = None
self.__var_headers = None
self.__var_headers_dict = None
self.__var_headers_names = None
self.__var_buffer_latest = None
self.__session_info_dict = {}
self.__broadcast_msg_id = None
if self.__test_file:
self.__test_file.close()
self.__test_file = None
def parse_to(self, to_file):
if not self.is_initialized:
return
f = open(to_file, 'w', encoding='utf-8')
f.write(self._shared_mem[self._header.session_info_offset:self._header.session_info_len].rstrip(b'\x00').decode(YAML_CODE_PAGE))
f.write('\n'.join([
'{:32}{}'.format(i, self[i])
for i in sorted(self._var_headers_dict.keys(), key=str.lower)
]))
f.close()
def cam_switch_pos(self, position=0, group=1, camera=0):
return self._broadcast_msg(BroadcastMsg.cam_switch_pos, position, group, camera)
def cam_switch_num(self, car_number='1', group=1, camera=0):
return self._broadcast_msg(BroadcastMsg.cam_switch_num, self._pad_car_num(car_number), group, camera)
def cam_set_state(self, camera_state=CameraState.cam_tool_active):
return self._broadcast_msg(BroadcastMsg.cam_set_state, camera_state)
def replay_set_play_speed(self, speed=0, slow_motion=False):
return self._broadcast_msg(BroadcastMsg.replay_set_play_speed, speed, 1 if slow_motion else 0)
def replay_set_play_position(self, pos_mode=RpyPosMode.begin, frame_num=0):
return self._broadcast_msg(BroadcastMsg.replay_set_play_position, pos_mode, frame_num)
def replay_search(self, search_mode=RpySrchMode.to_start):
return self._broadcast_msg(BroadcastMsg.replay_search, search_mode)
def replay_set_state(self, state_mode=RpyStateMode.erase_tape):
return self._broadcast_msg(BroadcastMsg.replay_set_state, state_mode)
def reload_all_textures(self):
return self._broadcast_msg(BroadcastMsg.reload_textures, ReloadTexturesMode.all)
def reload_texture(self, car_idx=0):
return self._broadcast_msg(BroadcastMsg.reload_textures, ReloadTexturesMode.car_idx, car_idx)
def chat_command(self, chat_command_mode=ChatCommandMode.begin_chat):
return self._broadcast_msg(BroadcastMsg.chat_command, chat_command_mode)
def chat_command_macro(self, macro_num=0):
return self._broadcast_msg(BroadcastMsg.chat_command, ChatCommandMode.macro, macro_num)
def pit_command(self, pit_command_mode=PitCommandMode.clear, var=0):
return self._broadcast_msg(BroadcastMsg.pit_command, pit_command_mode, var)
def telem_command(self, telem_command_mode=TelemCommandMode.stop):
return self._broadcast_msg(BroadcastMsg.telem_command, telem_command_mode)
def ffb_command(self, ffb_command_mode=FFBCommandMode.ffb_command_max_force, value=0):
return self._broadcast_msg(BroadcastMsg.ffb_command, ffb_command_mode, int(value * 65536))
def replay_search_session_time(self, session_num=0, session_time_ms=0):
return self._broadcast_msg(BroadcastMsg.replay_search_session_time, session_num, session_time_ms)
def video_capture(self, video_capture_mode=VideoCaptureMode.trigger_screen_shot):
return self._broadcast_msg(BroadcastMsg.video_capture, video_capture_mode)
def _check_sim_status(self):
try:
return 'running:1' in request.urlopen(SIM_STATUS_URL).read().decode('utf-8')
except error.URLError as e:
print("Failed to connect to sim: {}".format(e.reason))
return False
@property
def _var_buffer_latest(self):
# return 2nd most recent var buffer
# because it might be a situation (with most recent var buffer)
# that half of var buffer written with new data
# and other half still old
return sorted(self._header.var_buf, key=lambda v: v.tick_count, reverse=True)[1]
@property
def _var_headers(self):
if self.__var_headers is None:
self.__var_headers = []
for i in range(self._header.num_vars):
var_header = VarHeader(self._shared_mem, self._header.var_header_offset + i * 144)
self._var_headers.append(var_header)
return self.__var_headers
@property
def _var_headers_dict(self):
if self.__var_headers_dict is None:
self.__var_headers_dict = {}
for var_header in self._var_headers:
self.__var_headers_dict[var_header.name] = var_header
return self.__var_headers_dict
def freeze_var_buffer_latest(self):
self.unfreeze_var_buffer_latest()
self._wait_valid_data_event()
self.__var_buffer_latest = sorted(self._header.var_buf, key=lambda v: v.tick_count, reverse=True)[0]
self.__var_buffer_latest.freeze()
def unfreeze_var_buffer_latest(self):
if self.__var_buffer_latest:
self.__var_buffer_latest.unfreeze()
self.__var_buffer_latest = None
def get_session_info_update_by_key(self, key):
if key in self.__session_info_dict:
return self.__session_info_dict[key]['update']
return None
def _wait_valid_data_event(self):
if self._data_valid_event is not None:
return ctypes.windll.kernel32.WaitForSingleObject(self._data_valid_event, 32) == 0 if self._data_valid_event else False
else:
return True
def _get_session_info(self, key):
if self.last_session_info_update < self._header.session_info_update:
self.last_session_info_update = self._header.session_info_update
for session_data in self.__session_info_dict.values():
# keep previous parsed data, in case binary data not changed
if session_data['data']:
session_data['data_last'] = session_data['data']
session_data['data'] = None
if key not in self.__session_info_dict:
self.__session_info_dict[key] = dict(data=None)
session_data = self.__session_info_dict[key]
# already have and parsed
if session_data['data']:
return session_data['data']
if self.parse_yaml_async:
if 'async_session_info_update' not in session_data or session_data['async_session_info_update'] < self.last_session_info_update:
session_data['async_session_info_update'] = self.last_session_info_update
Thread(target=self._parse_yaml, args=(key, session_data)).start()
else:
self._parse_yaml(key, session_data)
return session_data['data']
def _get_session_info_binary(self, key):
start = self._header.session_info_offset
end = start + self._header.session_info_len
# search section by key
match_start = re.compile(('\n%s:\n' % key).encode(YAML_CODE_PAGE)).search(self._shared_mem, start, end)
if not match_start:
return None
match_end = re.compile(b'\n\n').search(self._shared_mem, match_start.start() + 1, end)
if not match_end:
return None
return self._shared_mem[match_start.start() + 1 : match_end.start()]
def _parse_yaml(self, key, session_data):
session_info_update = self.last_session_info_update
data_binary = self._get_session_info_binary(key)
# section not found
if not data_binary:
if 'data_last' in session_data:
return session_data['data_last']
else:
return None
# is binary data the same as last time?
if 'data_binary' in session_data and data_binary == session_data['data_binary'] and 'data_last' in session_data:
session_data['data'] = session_data['data_last']
return session_data['data']
session_data['data_binary'] = data_binary
# parsing
yaml_src = re.sub(YamlReader.NON_PRINTABLE, '', data_binary.translate(YAML_TRANSLATER).rstrip(b'\x00').decode(YAML_CODE_PAGE))
if key == 'DriverInfo':
def name_replace(m):
return m.group(1) + '"%s"' % re.sub(r'(["\\])', r'\\\1', m.group(2))
yaml_src = re.sub(r'((?:DriverSetupName|UserName|TeamName|AbbrevName|Initials): )(.*)', name_replace, yaml_src)
yaml_src = re.sub(r'(\w+: )(,.*)', r'\1"\2"', yaml_src)
result = yaml.load(yaml_src, Loader=CustomYamlSafeLoader)
# check if result is available, and yaml data is not updated while we were parsing it in async mode
if result and (not self.parse_yaml_async or self.last_session_info_update == session_info_update):
session_data['data'] = result[key]
if session_data['data']:
session_data['update'] = session_info_update
elif 'data_last' in session_data:
session_data['data'] = session_data['data_last']
@property
def _broadcast_msg_id(self):
if self.__broadcast_msg_id is None:
self.__broadcast_msg_id = ctypes.windll.user32.RegisterWindowMessageW(BROADCASTMSGNAME)
return self.__broadcast_msg_id
def _broadcast_msg(self, broadcast_type=0, var1=0, var2=0, var3=0):
return ctypes.windll.user32.SendNotifyMessageW(0xFFFF, self._broadcast_msg_id,
broadcast_type | var1 << 16, var2 | var3 << 16)
def _pad_car_num(self, num):
num = str(num)
num_len = len(num)
zero = num_len - len(num.lstrip("0"))
if zero > 0 and num_len == zero:
zero -= 1
num = int(num)
if zero:
num_place = 3 if num > 99 else 2 if num > 9 else 1
return num + 1000 * (num_place + zero)
return num
class IBT:
def __init__(self):
self._ibt_file = None
self._shared_mem = None
self._header = None
self._disk_header = None
self.__var_headers = None
self.__var_headers_dict = None
self.__var_headers_names = None
self.__session_info_dict = None
def __getitem__(self, key):
return self.get(self._disk_header.session_record_count - 1, key)
@property
def file_name(self):
return self._ibt_file and self._ibt_file.name
@property
def var_header_buffer_tick(self):
return self._header and self._header.var_buf[0].tick_count
@property
def var_headers_names(self):
if not self._header:
return None
if self.__var_headers_names is None:
self.__var_headers_names = [var_header.name for var_header in self._var_headers]
return self.__var_headers_names
def open(self, ibt_file):
self._ibt_file = open(ibt_file, 'rb')
self._shared_mem = mmap.mmap(self._ibt_file.fileno(), 0, access=mmap.ACCESS_READ)
self._header = Header(self._shared_mem)
self._disk_header = DiskSubHeader(self._shared_mem, 112)
def close(self):
if self._shared_mem:
self._shared_mem.close()
if self._ibt_file:
self._ibt_file.close()
self._ibt_file = None
self._shared_mem = None
self._header = None
self._disk_header = None
self.__var_headers = None
self.__var_headers_dict = None
self.__var_headers_names = None
self.__session_info_dict = None
def get(self, index, key):
if not self._header:
return None
if 0 > index >= self._disk_header.session_record_count:
return None
if key in self._var_headers_dict:
var_header = self._var_headers_dict[key]
fmt = VAR_TYPE_MAP[var_header.type] * var_header.count
var_offset = var_header.offset + self._header.var_buf[0].buf_offset + index * self._header.buf_len
res = struct.unpack_from(fmt, self._shared_mem, var_offset)
return list(res) if var_header.count > 1 else res[0]
return None
def get_all(self, key):
if not self._header:
return None
if key in self._var_headers_dict:
var_header = self._var_headers_dict[key]
fmt = VAR_TYPE_MAP[var_header.type] * var_header.count
var_offset = var_header.offset + self._header.var_buf[0].buf_offset
buf_len = self._header.buf_len
is_array = var_header.count > 1
results = []
for i in range(self._disk_header.session_record_count):
res = struct.unpack_from(fmt, self._shared_mem, var_offset + i * buf_len)
results.append(list(res) if is_array else res[0])
return results
return None
@property
def _var_headers(self):
if not self._header:
return None
if self.__var_headers is None:
self.__var_headers = []
for i in range(self._header.num_vars):
var_header = VarHeader(self._shared_mem, self._header.var_header_offset + i * 144)
self._var_headers.append(var_header)
return self.__var_headers
@property
def _var_headers_dict(self):
if not self._header:
return None
if self.__var_headers_dict is None:
self.__var_headers_dict = {}
for var_header in self._var_headers:
self.__var_headers_dict[var_header.name] = var_header
return self.__var_headers_dict
# https://stackoverflow.com/a/37958106/1034242
class CustomYamlSafeLoader(YamlSafeLoader):
@classmethod
def remove_implicit_resolver(cls, tag_to_remove):
if not 'yaml_implicit_resolvers' in cls.__dict__:
cls.yaml_implicit_resolvers = cls.yaml_implicit_resolvers.copy()
for first_letter, mappings in cls.yaml_implicit_resolvers.items():
cls.yaml_implicit_resolvers[first_letter] = [(tag, regexp) for tag, regexp in mappings if tag != tag_to_remove]
CustomYamlSafeLoader.remove_implicit_resolver('tag:yaml.org,2002:timestamp')
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-v', '--version', action='version', version='Python iRacing SDK %s' % VERSION, help='show version and exit')
parser.add_argument('--test', help='use test file as irsdk mmap')
parser.add_argument('--dump', help='dump irsdk mmap to file')
parser.add_argument('--parse', help='parse current irsdk mmap to file')
args = parser.parse_args()
ir = IRSDK()
ir.startup(test_file=args.test, dump_to=args.dump)
if args.parse:
ir.parse_to(args.parse)
if __name__ == '__main__':
main()