def setup(self): self.ir = irsdk.IRSDK() self.bot.ir_connected = False self.bot.hero = None self.bot.heroidx = None self.bot.add_cog(Announcer(self.bot, self.ir)) @self.bot.event async def on_ready(): logging.info("[+] Connected as " + self.bot.user.name) logging.info("[+] Listening commands in channel #" + self.args.channel) self.bot.channel = discord.utils.get(self.bot.get_all_channels(), name=self.args.channel) await self.bot.change_presence(status=discord.Status.online) @self.bot.event async def on_message(message): # Only listen on the single channel specified on the command line if message.channel.name == self.args.channel: # Ignore messages by bots (including self) if message.author.bot: return if message.content.startswith(self.prefix): msg = message.content.strip("".join(list(self.prefix))) if msg.startswith("help"): return # Pass on to rest of the client commands await self.bot.process_commands(message)
def __init__(self): self.api = irsdk.IRSDK() self.__connected = False # Shift Light Information self.__shift_rpm = 6000 self.__shift_rpm_min = 0 self.__shift_rpm_max = 6000 self.__shift_rpm_max_blink = 6250 self.api.startup()
def __init__(self): super().__init__() self.ir = irsdk.IRSDK() self.driver_lib = {} # lib for drivers and their idx self.racer_info = [ ] # a list of the Racer() class which contains the driver info self.avg_fuel_list = [] # list of drivers avg fuel use self.avgfuellaps = 5 # num of laps to average fuel over self.settings = QSettings( 'settings.ini', QSettings.IniFormat) # create .ini file to save settings self.settings.setFallbacksEnabled( False) # never use registry, only .ini file
def start(self, test_file=None): """ Connect to iRacing and start streaming data """ self.ir = irsdk.IRSDK() if test_file: self.ir.startup(test_file) else: self.ir.startup() if self.ir.is_initialized and self.ir.is_connected: self.is_active = True self.get_startup_info()
def testLapData(self): ir = irsdk.IRSDK() ir.startup(test_file='data/monzasunset.dump') syncState = SyncState() syncState.sessionId = 'session' syncState.subSessionId = 'subsession' syncState.sessionNum = 0 lapData = LapData(syncState, ir) print(syncState.toDict()) print(lapData.lapDataMessage()) ir.shutdown()
def main_thread(): config = configparser.ConfigParser() config.read('config.ini') ir = irsdk.IRSDK() ir_running = False leftright_state = LeftRightState() fastclassbehind_state = FastClassBehindState() while program_active: ir_running = iracing_update_connection_state(ir, ir_running) if ir_running: ir.freeze_var_buffer_latest() if config['leftright']['enabled'] == 'true': leftright_handler(ir, config['leftright'], leftright_state) if config['fastclassbehind']['enabled'] == 'true': fastclassbehind_handler(ir, config['fastclassbehind'], fastclassbehind_state) time.sleep(float(config['general']['update_interval'])) # iracing updates at 60hz, but 20hz will be enough, 0.05s between updates
def create_app(config='config.ProdConfig'): """Initialize the core application.""" app = Flask(__name__, instance_relative_config=False, static_folder=None) app.config.from_object(config) with app.app_context(): # Import application components from .api import api_routes from .charts import charts_routes app.register_blueprint(api_routes.api) app.register_blueprint(charts_routes.charts) ir = irsdk.IRSDK() ir.startup()#test_file='./before_green.bin') app.config['IR'] = ir return app
globalConfig.merge(**cfg['server']) except IOError as e: print(f'WARN: Could not open {configFilename}: {e}. continuing...') if args.url: globalConfig.url = args.url print(f'Using this url: {globalConfig.url}') #exit(1) with open('logging.yaml', 'r') as f: config = yaml.safe_load(f.read()) logging.config.dictConfig(config) # initializing ir and state logger = logging.getLogger("racelog") ir = irsdk.IRSDK() state = State() try: # infinite loop while True: # check if we are connected to iracing check_iracing() # if we are, then process data if state.ir_connected: loop() # sleep for 1 second # maximum you can use is 1/60 # cause iracing updates data with 60 fps time.sleep(1/60) except KeyboardInterrupt:
# print(brake_val) # if throttle_val > brake_val: # set_color(green_safe) # else: # set_color(red_safe) # for l in all_lights: # l.brightness = int(max(throttle_val, brake_val)) if __name__ == '__main__': config = configparser.ConfigParser(inline_comment_prefixes=(";", )) config.read('settings.ini') ir = irsdk.IRSDK(parse_yaml_async=True) state = State() # Get variables from settings.ini dim_lights_after_green = bool(int( config['DEFAULT']['DimLightsAfterGreen'])) pedal_input = bool(int(config['DEFAULT']['PedalInput'])) light_group = config['DEFAULT']['GroupName'] ip = config['DEFAULT']['BridgeIP'] print( "\nWelcome to irHUE: A small Python application for controlling Phillips Hue lights via iRacing.\nPress Ctrl-C at any time to exit the program\n" ) #Check if a default IP address has been specified in settings.ini if not ip:
def __init__(self): super().__init__() self.ir = irsdk.IRSDK()
class IDDUItem: db = 0 pygame = pygame pygame.init() myJoystick = None joystickList = [] white = (255, 255, 255) red = (255, 0, 0) green = (0, 255, 0) blue = (0, 0, 255) yellow = (255, 255, 0) orange = (255, 133, 13) grey = (141, 141, 141) black = (0, 0, 0) cyan = (0, 255, 255) purple = (255, 0, 255) GTE = (255, 88, 136) LMP1 = (255, 218, 89) LMP2 = (51, 206, 255) ir = irsdk.IRSDK() vjoy = pyvjoy.VJoyDevice(2) LogFilePath = os.path.abspath( os.path.join((os.getcwd()).split('iDDU')[0], 'iDDU', 'data', 'iDDU.log')) logger = MyLogger() def __init__(self): pass @staticmethod def setDB(rtdb): IDDUItem.db = rtdb def getJoystickList(self): pygame.joystick.init() self.logger.info( str(pygame.joystick.get_count()) + ' joysticks detected:') for i in range(pygame.joystick.get_count()): self.joystickList.append(pygame.joystick.Joystick(i).get_name()) self.logger.info('Joystick {}: {}'.format( i, pygame.joystick.Joystick(i).get_name())) def initJoystick(self, name): desiredJoystick = None for i in range(len(self.joystickList)): if pygame.joystick.Joystick(i).get_name() == name: desiredJoystick = i for i in range(pygame.joystick.get_count()): if pygame.joystick.Joystick(i).get_name() == name: desiredJoystick = i self.logger.info('Attempting to connect to {}'.format(name)) if desiredJoystick: IDDUItem.myJoystick = pygame.joystick.Joystick(desiredJoystick) IDDUItem.myJoystick.get_name() IDDUItem.myJoystick.init() self.logger.info('Successfully connected to {} !'.format(name)) else: self.logger.error('{} not found!'.format(name)) def pressButton(self, ID, t): self.vjoy.set_button(ID, 1) time.sleep(t) self.vjoy.set_button(ID, 0)
import eventlet eventlet.monkey_patch() from iR_state import IRState from iR_telemetry import start_iR_telemetry from flask import Flask, render_template from flask_socketio import SocketIO, emit app = Flask(__name__) # Flask app has now become a Flask-SocketIO app socketio = SocketIO(app, async_mode='eventlet') iR_sdk = irsdk.IRSDK() iR_state = IRState() thread = None @app.route('/') def index(): return render_template('index.html') def send_iR_data_to_client(): """ Send iRacing data to the client. """
def importIBT(ibtPath, channels=None, lap=None, channelMapPath='iRacingChannelMap.csv'): # read in metadata c = dict() ir = irsdk.IRSDK() ir.startup(test_file=ibtPath) c['CarSetup'] = ir['CarSetup'] c['DriverInfo'] = ir['DriverInfo'] c['WeekendInfo'] = ir['WeekendInfo'] c['carPath'] = c['DriverInfo']['Drivers'][c['DriverInfo'] ['DriverCarIdx']]['CarPath'] ir.shutdown() # read in telemetry channels ir_ibt = irsdk.IBT() ir_ibt.open(ibtPath) var_headers_names = ir_ibt.var_headers_names temp = dict() s = dict() # load channel map channelMap = importExport.loadCSV(channelMapPath) # define telemetry channels to import channelsExport = [] if channels is None: channelsExport = var_headers_names else: for i in range(0, len(channels)): if channels[i] in var_headers_names: channelsExport.append(channels[i]) elif channels[i] in channelMap['ChannelName']: index = channelMap['ChannelName'].index(channels[i]) channelsExport.append(channelMap['iRacingChannelName'][index]) else: print( 'Error: <{}> neihter in list of iRacing channels nor in channel map! - Skipping this channel!' .format(channels[i])) channelsExport.extend(defaultChannels) channelsExport = list(set(channelsExport)) # import channels for i in range(0, len(channelsExport)): if channelsExport[i] in var_headers_names: temp[channelsExport[i]] = np.array( ir_ibt.get_all(channelsExport[i])) else: print('Error: <{}> not in the list of available channels'.format( channelsExport[i])) varNames = list(temp.keys()) # cut data if lap is None or lap in [ 'a', 'A', 'all', 'ALL', 'All', 'w', 'W', 'whole', 'WHOLE' ]: # complete file for i in range(0, len(varNames)): s[varNames[i]] = temp[varNames[i]] else: indices = [] if lap in ['f', 'F', 'fastest', 'Fastest', 'FASTERST']: # fastest lap only # find the fastest lap print('\tImporting fastest lap.') NLapStartIndex = scipy.signal.find_peaks( 1 - np.array(temp['LapDistPct']), height=(0.98, 1.02), distance=600) if len(NLapStartIndex[0]) > 1: print('\tFound following laps:') tLap = [] NLap = [] sLap = [] VFuelLap = [] for q in range(0, len(NLapStartIndex[0]) - 1): tLap.append(temp['SessionTime'][NLapStartIndex[0][q + 1] - 1] - temp['SessionTime'][NLapStartIndex[0][q]]) sLap.append(temp['LapDist'][NLapStartIndex[0][q + 1] - 1]) NLap.append(temp['Lap'][NLapStartIndex[0][q]]) VFuelLap.append( temp['FuelLevel'][NLapStartIndex[0][q]] - temp['FuelLevel'][NLapStartIndex[0][q + 1] - 1]) print('\t{0}\t{1} min\t{2} l'.format( NLap[q], convertString.convertTimeMMSSsss(tLap[q]), convertString.convertTimeMMSSsss(VFuelLap[q]))) for r in range(0, len(tLap)): if sLap[r] < float(c['WeekendInfo']['TrackLength'].split( ' ')[0]) * 1000 * 0.95: tLap.pop(r) # tLap[r] = tLap[r] + 1000 NLapFastest = NLap[np.argmin(tLap)] # get all indices for the fastest lap indices = np.argwhere(temp['Lap'] == NLapFastest)[:, 0] print('\tImporting Lap {} ({})'.format( NLapFastest, convertString.convertTimeMMSSsss(min(tLap)))) else: print('\tNo valid lap found!') return None, None # lap number elif isinstance(lap, int): if lap < np.min(temp['Lap']) or lap > np.max(np.array( temp['Lap'])): print( 'Error: Lap number {} is out of bounds! File contains laps {} to {}' .format(lap, np.min(temp['Lap']), np.max(np.array(temp['Lap'])))) return indices = np.argwhere(temp['Lap'] == lap)[:, 0] # actually cut the data for i in range(0, len(varNames)): s[varNames[i]] = temp[varNames[i]][indices] ir_ibt.close() # channel mapping for i in range(0, len(channelsExport)): if channelsExport[i] in channelMap['iRacingChannelName']: index = channelMap['iRacingChannelName'].index(channelsExport[i]) c[channelMap['ChannelName'][index]] = np.array( s[channelsExport[i]]) * float( channelMap['ConverstionFactor'][index]) else: c[channelsExport[i]] = s[channelsExport[i]] # fuel calcs if 'QFuel' in channels or 'dmFuel' in channels: c['QFuel'] = c['dmFuel'] / 1000 / c['DriverInfo'][ 'DriverCarFuelKgPerLtr'] # l/s # replacing tLap with SessionTime derivative c['dt'] = np.diff(c['SessionTime']) c['tLap'] = np.append(0, np.cumsum([c['dt']])) c['VFuelLap'] = c['VFuel'][0] - c['VFuel'][-1] # setting start and end value for LapDistPct c['LapDistPct'][0] = 0 c['LapDistPct'][-1] = 1 return c, list(c.keys())
# import packages import irsdk from pygame import * import winsound fname = "Beep.wav" # path to beep soundfile ir = irsdk.IRSDK() # initialize iRacing SDK wasRunning = 0 # flag to check if iRacing was running print('Waiting for iRacing...') # initialisation message # shut down programme if iRacing is not found within one minute while not ir.startup(): time.wait(6000) print('iRacing not detected. Shutting down...') break # initialisaiton if iRacing is detected if ir.startup(): wasRunning = 1 print('iRacing detected! :-)') # play three beep sounds as notification winsound.PlaySound(fname, winsound.SND_FILENAME) time.wait(300) winsound.PlaySound(fname, winsound.SND_FILENAME) time.wait(300) winsound.PlaySound(fname, winsound.SND_FILENAME)
def createCar(self, db, var_headers_names=None): DriverCarIdx = db.DriverInfo['DriverCarIdx'] self.name = db.DriverInfo['Drivers'][DriverCarIdx][ 'CarScreenNameShort'] self.iRShiftRPM = [ db.DriverInfo['DriverCarSLFirstRPM'], db.DriverInfo['DriverCarSLShiftRPM'], db.DriverInfo['DriverCarSLLastRPM'], db.DriverInfo['DriverCarSLBlinkRPM'] ] DRSList = [ 'formularenault35', # TODO: shouldn't be here 'mclarenmp430' ] if any(self.name in s for s in DRSList): self.BDRS = True else: self.BDRS = False P2PList = [ 'dallaradw12', # TODO: shouldn't be here 'dallarair18' ] if any(self.name in s for s in P2PList): self.BP2P = True else: self.BP2P = False dcIgnoreList = [ 'dcHeadlightFlash', 'dcPitSpeedLimiterToggle', 'dcStarter', 'dcTractionControlToggle', 'dcTearOffVisor', 'dcPushToPass', 'dcDashPage', 'dcToggleWindshieldWipers', 'dcTriggerWindshieldWipers' ] # TODO: shouldn't be here dcNotInt = ['dcBrakeBias'] # TODO: shouldn't be here keys = [] if var_headers_names is None: ir = irsdk.IRSDK() if ir.startup(): keys = ir.var_headers_names ir.shutdown() else: keys = var_headers_names for i in range(0, len(keys)): temp = keys[i] if temp.startswith('dc'): if not (temp.endswith('Change') or temp.endswith('Old') or temp.endswith('Str') or temp.endswith('Time')): if not keys[i] is None: if keys[i] in dcIgnoreList: self.dcList[keys[i]] = (keys[i].split('dc')[1], False, 0) else: if any(keys[i] in s for s in dcNotInt): self.dcList[keys[i]] = (keys[i].split('dc')[1], True, 1) else: self.dcList[keys[i]] = (keys[i].split('dc')[1], True, 0) self.setUserShiftRPM(db) self.tLap = {} db.BMultiInitRequest = True