-
Notifications
You must be signed in to change notification settings - Fork 0
/
exporter.py
252 lines (229 loc) · 8.31 KB
/
exporter.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
import irsdk
import time
import random
from os import path
import yaml
from prometheus_client.core import GaugeMetricFamily, REGISTRY, CounterMetricFamily, InfoMetricFamily
from prometheus_client import start_http_server
totalRandomNumber = 0
metrics_dict = {
"AirDensity": "",
"AirPressure": "",
"AirTemp": "",
"BrakeRaw": "",
"EngineWarnings": "",
"FastRepairAvailable": "",
"FastRepairUsed": "",
"FogLevel": "",
"FrameRate": "",
"FuelLevel": "",
"FuelLevelPct": "",
"FuelUsePerHour": "",
"Gear": "",
"Lap": "",
"LapBestLap": "",
"LapBestLapTime": "",
"LapCompleted": "",
"LapCurrentLapTime": "",
"LapDeltaToBestLap_DD": "",
"LapDeltaToBestLap": "",
"LapDeltaToOptimalLap_DD": "",
"LapDeltaToOptimalLap": "",
"LapDeltaToSessionBestLap_DD": "",
"LapDeltaToSessionBestLap": "",
"LapDeltaToSessionLastlLap_DD": "",
"LapDeltaToSessionLastlLap": "",
"LapDeltaToSessionOptimalLap_DD": "",
"LapDeltaToSessionOptimalLap": "",
"LapDist": "",
"LapDistPct": "",
"LapLasNLapSeq": "",
"LapLastLapTime": "",
"LapLastNLapTime": "",
"LFtempCL": "",
"LFtempCM": "",
"LFtempCR": "",
"LFwearL": "",
"LFwearM": "",
"LFwearR": "",
"LRtempCL": "",
"LRtempCM": "",
"LRtempCR": "",
"LRwearL": "",
"LRwearM": "",
"LRwearR": "",
"OilLevel": "",
"OilPress": "",
"OilTemp": "",
"PlayerCarClassPosition": "",
"PlayerCarDriverIncidentCount": "",
"PlayerCarIdx": "",
"PlayerCarMyIncidentCount": "",
"PlayerCarPosition": "",
"PlayerCarTeamIncidentCount": "",
"PlayerCarTowTime": "",
"PlayerTireCompound": "",
"PlayerTrackSurface": "",
"PlayerTrackSurfaceMaterial": "",
"RaceLaps": "",
"RelativeHumidity": "",
"RFtempCL": "",
"RFtempCM": "",
"RFtempCR": "",
"RFwearL": "",
"RFwearM": "",
"RFwearR": "",
"Roll": "",
"RollRate": "",
"RPM": "",
"RRtempCL": "",
"RRtempCM": "",
"RRtempCR": "",
"RRwearL": "",
"RRwearM": "",
"RRwearR": "",
"SessionFlags": "",
"SessionLapsRemain": "",
"SessionNum": "",
"SessionState": "",
"SessionTime": "",
"SessionTimeRemain": "",
"SessionUniqueID": "",
"ShiftGrindRPM": "",
"ShiftIndicatorPct": "",
"ShiftPowerPct": "",
"Skies": "",
"Speed": "",
"SteeringWheelAngle": "",
"SteeringWheelAngleMax": "",
"SteeringWheelPctDamper": "",
"SteeringWheelPctTorque": "",
"SteeringWheelPctTorqueSign": "",
"SteeringWheelPctTorqueSignStops": "",
"SteeringWheelPeakForceNm": "",
"SteeringWheelTorque": "",
"ThrottleRaw": "",
"TireSetsAvailable": "",
"TireSetsUsed": "",
"TrackTemp": "",
"TrackTempCrew": "",
"WeatherType": "",
"WindDir": "",
"WindVel": "",
"@Timestamp": "",
}
# this is our State class, with some helpful variables
class State:
ir_connected = False
last_car_setup_tick = -1
# hold driver data for the current session
class Driver():
def __init__(self, driver_name, incident_count) -> None:
self.driver_name = driver_name
self.incident_count = incident_count
class Track():
def __init__(self, name) -> None:
self.name = name
class IracingMetricsCollector(object):
def __init__(self):
self.ir = irsdk.IRSDK()
self.state = State()
# here we check if we are connected to iracing
# so we can retrieve some data
def check_iracing(self):
if self.state.ir_connected and not (self.ir.is_initialized and self.ir.is_connected):
self.state.ir_connected = False
# don't forget to reset your State variables
self.state.last_car_setup_tick = -1
# we are shutting down ir library (clearing all internal variables)
self.ir.shutdown()
print('irsdk disconnected')
elif not self.state.ir_connected and self.ir.startup() and self.ir.is_initialized and self.ir.is_connected:
self.state.ir_connected = True
print('irsdk connected')
# our main loop, where we retrieve data
# and do something useful with it
def get_metrics(self, metrics_dict):
# on each tick we freeze buffer with live telemetry
# it is optional, but useful if you use vars like CarIdxXXX
# this way you will have consistent data from those vars inside one tick
# because sometimes while you retrieve one CarIdxXXX variable
# another one in next line of code could change
# to the next iracing internal tick_count
# and you will get incosistent data
self.ir.freeze_var_buffer_latest()
print(self.ir['SessionInfo'])
for key, value in metrics_dict.items():
value = self.ir[key]
metrics_dict.update({key: value})
return metrics_dict
# # retrieve live telemetry data
# # check here for list of available variables
# # https://github.com/kutu/pyirsdk/blob/master/vars.txt
# # this is not full list, because some cars has additional
# # specific variables, like break bias, wings adjustment, etc
# t = self.ir['SessionTime']
# fuel_level = ir['FuelLevel']
# time_remaining = ir['SessionTimeRemain']
# print('session time:', t)
# # retrieve CarSetup from session data
# # we also check if CarSetup data has been updated
# # with ir.get_session_info_update_by_key(key)
# # but first you need to request data, before checking if its updated
# car_setup = ir['CarSetup']
# if car_setup:
# car_setup_tick = ir.get_session_info_update_by_key('CarSetup')
# if car_setup_tick != state.last_car_setup_tick:
# state.last_car_setup_tick = car_setup_tick
# print('car setup update count:', car_setup['UpdateCount'])
# # now you can go to garage, and do some changes with your setup
# # this line will be printed, only when you change something
# # and press apply button, but not every 1 sec
# # note about session info data
# # you should always check if data exists first
# # before do something like ir['WeekendInfo']['TeamRacing']
# # so do like this:
# # if ir['WeekendInfo']:
# # print(ir['WeekendInfo']['TeamRacing'])
def collect(self):
self.check_iracing()
if self.state.ir_connected:
metrics = self.get_metrics(metrics_dict)
print(metrics)
# gauge = GaugeMetricFamily("fuel_level", "percentage of fuel available", labels=[self.ir['Lap']])
# gauge.add_metric(['fuel_level'], metrics['FuelLevel']).add
# yield gauge
# gauge = GaugeMetricFamily("time_remaining", "time remaining in the current sessions", labels=["time"])
# gauge.add_metric(['time_remaining'], metrics['SessionTimeRemain'])
# yield gauge
# gauge = GaugeMetricFamily("last_laptime", "last lap time", labels=["time"])
# gauge.add_metric(['last_laptime'], metrics['LapLastLapTime'])
# yield gauge
# gauge = GaugeMetricFamily("race_laps", "Laps completed in race", labels=["laps"])
# gauge.add_metric(['race_laps'], metrics['RaceLaps'])
# yield gauge
# count = CounterMetricFamily("laps_completed", "number of laps completed", labels=['laps'])
# count.add_metric(['laps_completed'], metrics['LapCompleted'])
# yield count
gauge = GaugeMetricFamily("fuel_level", "percentage of fuel available", labels='lap')
gauge.add_metric([self.ir['lap']], metrics['FuelLevel'])
yield gauge
if __name__ == "__main__":
# ir = irsdk.IRSDK()
# state = State()
port = 9001
frequency = 1
if path.exists('config.yml'):
with open('config.yml', 'r') as config_file:
try:
config = yaml.safe_load(config_file)
port = int(config['port'])
frequency = config['scrape_frequency']
except yaml.YAMLError as error:
print(error)
start_http_server(port)
REGISTRY.register(IracingMetricsCollector())
while True:
# period between collection
print("sleep")
time.sleep(frequency)