-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathsharedMemoryAPI.py
More file actions
336 lines (287 loc) · 11.8 KB
/
sharedMemoryAPI.py
File metadata and controls
336 lines (287 loc) · 11.8 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
"""
Inherit Python mapping of The Iron Wolf's rF2 Shared Memory Tools
and add access functions to it.
"""
# pylint: disable=invalid-name
import psutil
try:
from . import rF2data
except ImportError: # standalone, not package
import rF2data
class SimInfoAPI(rF2data.SimInfo):
"""
API for rF2 shared memory
"""
__HELP = "\nShared Memory is installed by Crew Chief or you can install it yourself.\n" \
"Please update rFactor2SharedMemoryMapPlugin64.dll, see\n" \
"https://forum.studio-397.com/index.php?threads/rf2-shared-memory-tools-for-developers.54282/"
sharedMemoryVerified = False
minimumSupportedVersionParts = ['3', '6', '0', '0']
rf2_pid = None # Once we've found rF2 running
rf2_pid_counter = 0 # Counter to check if running
rf2_running = False
def __init__(self):
rF2data.SimInfo.__init__(self)
self.versionCheckMsg = self.versionCheck()
self.__find_rf2_pid()
def versionCheck(self):
"""
Lifted from
https://gitlab.com/mr_belowski/CrewChiefV4/blob/master/CrewChiefV4/RF2/RF2GameStateMapper.cs
and translated.
"""
self.sharedMemoryVerified = False # Verify every time it is called.
versionStr = Cbytestring2Python(self.Rf2Ext.mVersion)
msg = ''
if versionStr == '':
msg = "\nrFactor 2 Shared Memory not present." + self.__HELP
return msg
versionParts = versionStr.split('.')
if len(versionParts) != 4:
msg = "Corrupt or leaked rFactor 2 Shared Memory. Version string: " \
+ versionStr + self.__HELP
return msg
smVer = 0
minVer = 0
partFactor = 1
for i in range(3, -1, -1):
versionPart = 0
try:
versionPart = int(versionParts[i])
except BaseException:
msg = "Corrupt or leaked rFactor 2 Shared Memory version. Version string: " \
+ versionStr + self.__HELP
return msg
smVer += (versionPart * partFactor)
minVer += (int(self.minimumSupportedVersionParts[i]) * partFactor)
partFactor *= 100
if smVer < minVer:
minVerStr = ".".join(self.minimumSupportedVersionParts)
msg = "Unsupported rFactor 2 Shared Memory version: " \
+ versionStr \
+ " Minimum supported version is: " \
+ minVerStr + self.__HELP
else:
msg = "\nrFactor 2 Shared Memory\nversion: " + versionStr + " 64bit."
if self.Rf2Ext.mDirectMemoryAccessEnabled:
if self.Rf2Ext.mSCRPluginEnabled:
msg += " Stock Car Rules plugin enabled. (DFT:%d" % \
self.Rf2Ext.mSCRPluginDoubleFileType
else:
msg += " DMA enabled."
if self.Rf2Ext.is64bit == 0:
msg += "\nOnly 64bit version of rFactor 2 is supported."
else:
self.sharedMemoryVerified = True
return msg
###########################################################
def __find_rf2_pid(self):
""" Find the process ID for rfactor2.exe. Takes a while """
for pid in psutil.pids():
try:
p = psutil.Process(pid)
except psutil.NoSuchProcess:
continue
if p.name().lower().startswith('rfactor2.exe'):
self.rf2_pid = pid
break
def __playersDriverNum(self):
""" Find the player's driver number """
for _player in range(50): # self.Rf2Tele.mVehicles[0].mNumVehicles:
if self.Rf2Scor.mVehicles[_player].mIsPlayer:
break
return _player
###########################################################
# Access functions
def isRF2running(self, find_counter=200, found_counter=5):
"""
Both "rFactor 2 Launcher" and "rf2" processes are found
whether it's the launcher or the game that's running BUT
rfactor2.exe is only present if the game is running.
Beacuse this takes some time, control how often it's checked using:
find_counter: how often to check if rF2 is not running
found_counter: how often to check once rF2 is running
"""
if self.rf2_pid_counter == 0: # first time
self.rf2_pid_counter = find_counter
if self.isSharedMemoryAvailable():
# No need to check if Shared Memory is OK!
self.rf2_running = True
elif self.rf2_pid:
if self.rf2_pid_counter >= found_counter:
self.rf2_pid_counter = 0
try:
p = psutil.Process(self.rf2_pid)
except psutil.NoSuchProcess:
self.rf2_pid = None
return False
if p.name().lower().startswith('rfactor2.exe'):
self.rf2_running = True
else:
if self.rf2_pid_counter >= find_counter:
self.rf2_pid_counter = 0
self.__find_rf2_pid()
self.rf2_running = False
self.rf2_pid_counter += 1
return self.rf2_running
def isSharedMemoryAvailable(self):
"""
True: The correct memory map is loaded
"""
self.versionCheck()
return self.sharedMemoryVerified
def isTrackLoaded(self):
"""
True: rF2 is running and the track is loaded
"""
started = self.Rf2Ext.mSessionStarted
return started != 0
def isOnTrack(self):
"""
True: rF2 is running and the player is on track
"""
realtime = self.Rf2Ext.mInRealtimeFC
return realtime != 0
def isAiDriving(self):
"""
True: rF2 is running and the player is on track
"""
return self.Rf2Scor.mVehicles[self.__playersDriverNum()].mControl == 1
# who's in control: -1=nobody (shouldn't get this), 0=local player,
# 1=local AI, 2=remote, 3=replay (shouldn't get this)
# didn't work self.Rf2Ext.mPhysics.mAIControl
def driverName(self):
"""
Get the player's name
"""
return Cbytestring2Python(
self.Rf2Scor.mVehicles[self.__playersDriverNum()].mDriverName)
def playersVehicleTelemetry(self):
""" Get the variable for the player's vehicle """
self.__playersDriverNum()
return self.Rf2Tele.mVehicles[self.__playersDriverNum()]
def playersVehicleScoring(self):
""" Get the variable for the player's vehicle """
self.__playersDriverNum()
return self.Rf2Scor.mVehicles[self.__playersDriverNum()]
def vehicleName(self):
"""
Get the vehicle's name
"""
return Cbytestring2Python(
self.Rf2Scor.mVehicles[self.__playersDriverNum()].mVehicleName)
def close(self):
# This didn't help with the errors
try:
self._rf2_tele.close()
self._rf2_scor.close()
self._rf2_ext.close()
except BufferError: # "cannot close exported pointers exist"
pass
def __del__(self):
self.close()
def Cbytestring2Python(bytestring):
"""
C string to Python string
"""
try:
return bytes(bytestring).partition(b'\0')[0].decode('utf_8').rstrip()
except BaseException:
pass
try: # Codepage 1252 includes Scandinavian characters
return bytes(bytestring).partition(b'\0')[0].decode('cp1252').rstrip()
except BaseException:
pass
try: # OK, struggling, just ignore errors
return bytes(bytestring).partition(b'\0')[
0].decode('utf_8', 'ignore').rstrip()
except Exception as e:
print('Trouble decoding a string')
print(e)
def test_main(): # pylint: disable=too-many-statements
""" Example usage """
info = SimInfoAPI()
if info.isRF2running():
print('rfactor2.exe is running')
print(info.versionCheckMsg, '\n')
if info.isSharedMemoryAvailable():
print('Memory map is loaded')
version = Cbytestring2Python(info.Rf2Ext.mVersion)
# 2019/04/23: 3.5.0.9
print('Shared memory version:', version)
if info.isTrackLoaded():
trackName = Cbytestring2Python(
info.Rf2Scor.mScoringInfo.mTrackName)
print('%s is loaded' % trackName)
if info.isOnTrack():
driver = Cbytestring2Python(
info.playersVehicleScoring().mDriverName)
print('Driver "%s" is on track' % driver)
clutch = info.playersVehicleTelemetry().mUnfilteredClutch
# 1.0 clutch down, 0 clutch up
driver = Cbytestring2Python(
info.playersVehicleScoring().mDriverName)
gear = info.playersVehicleTelemetry().mGear
print('Driver: "%s", Gear: %d, Clutch position: %d' %
(driver, gear, clutch))
# Test that memory map can be poked
info.playersVehicleTelemetry().mGear = 1
gear = info.playersVehicleTelemetry().mGear # -1 to 6
assert info.playersVehicleTelemetry().mGear == 1
info.playersVehicleTelemetry().mGear = 2
assert info.playersVehicleTelemetry().mGear == 2
gear = info.playersVehicleTelemetry().mGear # -1 to 6
info.playersVehicleTelemetry().mGear = 1
assert info.playersVehicleTelemetry().mGear == 1
_vehicleName = Cbytestring2Python(
info.playersVehicleScoring().mVehicleName)
_vehicleClass = Cbytestring2Python(
info.playersVehicleScoring().mVehicleClass)
print('vehicleName:', _vehicleName)
print('vehicleClass:', _vehicleClass)
started = info.Rf2Ext.mSessionStarted
print('SessionStarted:', started)
realtime = info.Rf2Ext.mInRealtimeFC
print('InRealtimeFC:', realtime)
if info.isAiDriving():
print('AI is driving the car')
else:
print('Car not under AI control')
else:
print('Driver is not on track')
else:
print('Track is not loaded')
print('\nBreaking the version string...')
info.Rf2Ext.mVersion[0] = 32
assert not info.isSharedMemoryAvailable()
print('\n' + info.versionCheck())
info.Rf2Ext.mVersion[0] = 51 # restore it
info.Rf2Ext.mVersion[0] = 50
assert not info.isSharedMemoryAvailable()
print('\n' + info.versionCheck())
info.Rf2Ext.mVersion[0] = 51 # restore it
info.Rf2Ext.mVersion[2] = 53
assert not info.isSharedMemoryAvailable()
print('\n' + info.versionCheck())
info.Rf2Ext.mVersion[2] = 54 # restore it
print('\nBreaking 64 bit info...')
info.Rf2Ext.is64bit = 0
assert not info.isSharedMemoryAvailable()
print(info.versionCheck())
info.Rf2Ext.is64bit = 1
print('\nPit Menu')
while True:
if info.Rf2PitMenu.changed:
print(Cbytestring2Python(
info.Rf2PitMenu.mCategoryName))
info.Rf2PitMenu.changed = 0
print('\nOK')
else:
print('Incorrect shared memory')
else:
print('rFactor 2 not running')
s = bytearray(range(0xA1, 0xff))
print(Cbytestring2Python(s))
return 'OK'
if __name__ == '__main__':
test_main()