def acUpdate(deltaT): try: global app pygame.event.pump() app.update(deltaT) except Exception as e: ac.log("Error in acUpdate: {}".format(str(e)))
def announcePenalty(driver_name, lap, detail): if SERVERS and any(ac.getServerName().startswith(x) for x in SERVERS): try: ac.sendChatMessage(APP_NAME + " %s : %s penalty on Lap: %d: %s" % (VERSION, driver_name, lap, detail)) except Exception as e: ac.log(APP_NAME + ": Error in announce penalty: %s" % e)
def read_and_validate_config(): config = ConfigParser(defaults=DEFAULT_CONFIG_DICT, default_section=INI_SECTION) if not os.path.isfile(INI_FILE): with open(INI_FILE, 'w') as f: config.write(f) with open(INI_FILE) as f: config.read_file(f) bt_forward = config.get(INI_SECTION, BUTTON_FORWARD, fallback=DEFAULT_CONFIG_DICT[BUTTON_FORWARD]) bt_back = config.get(INI_SECTION, BUTTON_BACK, fallback=DEFAULT_CONFIG_DICT[BUTTON_BACK]) raspberry_ip = config.get(INI_SECTION, RASPBERRY_IP, fallback=DEFAULT_CONFIG_DICT[RASPBERRY_IP]) raspberry_udp_port = config.get(INI_SECTION, RASPBERRY_UDP_PORT, fallback=DEFAULT_CONFIG_DICT[RASPBERRY_UDP_PORT]) hz = config.get(INI_SECTION, HZ, fallback=DEFAULT_CONFIG_DICT[HZ]) show_debug_window = config.getboolean(INI_SECTION, SHOW_DEBUG_WINDOW, fallback=False) try: bt_forward = int(bt_forward) bt_back = int(bt_back) raspberry_udp_port = int(raspberry_udp_port) hz = int(hz) if not validate_ip(raspberry_ip): raise Exception('IP for Raspberry PI is not valid') if not 1024 < raspberry_udp_port <= 65535: raise Exception('UDP Port for Raspberry PI is not valid') except Exception as e: ac.log(str(e)) ac.console(str(e)) return DEFAULT_CONFIG_DICT, False return dict(button_forward=bt_forward, button_back=bt_back, raspberry_ip=raspberry_ip, raspberry_udp_port=raspberry_udp_port, hz=hz, show_debug_window=show_debug_window), True
def requestMinoratingData(): global requestPending if requestPending == False: ac.log("helipicapew::FetchPage.Start(): " + urlstr) requestPending = True FetchPage().start()
def onFormRender(deltaT): global showWindowTitle, appWindowActivated, appWindow, dbgLabel, running if not running: return #Important: Other apps can alter the global ac.gl Color and Alpha; let's reset this to White ac.glColor4f(1, 1, 1, 1) #Show/Hide the title shortly after the app became visible if showWindowTitle: if (time.clock() - appWindowActivated > showTitle): showWindowTitle = False ac.setBackgroundOpacity(appWindow, 0) ac.setIconPosition(appWindow, -7000, -3000) ac.setTitle(appWindow, "") try: #we won't do all the calculations every time, so we have to sort out some frames. #But: We'll need the graphics stuff every single time, or we'll have flickering. But no worry, opengl is fast if timeForCalculationCame(): doCalculationStuff() #Now we draw the current cars on the minimap drawCars() except Exception as e: ac.log("helipicapew::onFormRender() %s" % e) #Important: We'll clean the color again, so we might not affect other apps ac.glColor4f(1, 1, 1, 1)
def acMain(ac_version): #app window init; global variables for later updating go here global appWindow appWindow = ac.newApp(appName) ac.setTitle(appWindow, appName) ac.setSize(appWindow, width, height) ac.log("z3D Gauge loaded") ac.console("z3D Gauge console test") ####################################################declaring gauge elements # gonna need new textures like # rpm_bar = ac.newTexture(app_path + theme_path + "rpm_bar.png") global l_kmph, l_rpm, l_gear, acceleration global ascii_RPM l_kmph = ac.addLabel(appWindow, "KMPH") l_rpm = ac.addLabel(appWindow, "RPM") l_gear = ac.addLabel(appWindow, "Current gear") ascii_RPM = ac.addLabel(appWindow, "") acceleration = ac.addLabel(appWindow, "") #l_TC = ac.addLabel(appWindow, "TC on/off") #non-functional #l_ABS = ac.addLabel(appWindow, "ABS on/off") #non-functional ac.setPosition(l_kmph, 3, 30) ac.setPosition(l_rpm, 3, 60) ac.setPosition(l_gear, 3, 80) ac.setPosition(ascii_RPM, 3, 160) ac.setPosition(acceleration, 3, 580) ac.addRenderCallback(appWindow, appGL) # -> links this app's window to an OpenGL render function return appName
def loadCarData(): global CarData carName = ac.getCarName(0) try: carsFile = os.path.join(os.path.dirname(__file__), "cardata.json") with open(carsFile, "r") as f: jsonData = json.load(f) except OSError: ac.log("Reventach ERROR: loadCarData cardata.json not found") else: try: CarData["totalGears"] = jsonData[carName]["gears"] CarData["maxRPM"] = jsonData[carName]["maxRPM"] ac.console("Car data found for " + carName) except KeyError: # Doesn't exist in official, look for custom data try: carsFile = os.path.join(os.path.dirname(__file__), "cardata-custom.json") with open(carsFile, "r") as f: jsonData = json.load(f) CarData["totalGears"] = jsonData[carName]["gears"] CarData["maxRPM"] = jsonData[carName]["maxRPM"] except (OSError, KeyError) as e: ac.log( "Reventach ERROR: loadCarData: No custom car data found for this car" ) else: ac.console("Custom car data found for " + carName)
def WriteSection(): global Car, FixBody, FixEngine, FixSuspen, Preset, Tires, Gas def NewSection(NewPreset): PresetConfig = configparser.ConfigParser() PresetConfig.read('apps\python\BoxRadio\BoxRadio.ini') PresetConfig.add_section('PRESET' + str(NewPreset) + '_' + ac.getCarName(0)) PresetConfig.set('PRESET' + str(NewPreset) + '_' + ac.getCarName(0), 'car', ac.getCarName(0)) PresetConfig.set('PRESET' + str(NewPreset) + '_' + ac.getCarName(0), 'tyre', Tires) PresetConfig.set('PRESET' + str(NewPreset) + '_' + ac.getCarName(0), 'fuel', str(Gas)) PresetConfig.set('PRESET' + str(NewPreset) + '_' + ac.getCarName(0), 'body', FixBody) PresetConfig.set('PRESET' + str(NewPreset) + '_' + ac.getCarName(0), 'engine', FixEngine) PresetConfig.set('PRESET' + str(NewPreset) + '_' + ac.getCarName(0), 'suspen', FixSuspen) with open('apps\python\BoxRadio\BoxRadio.ini', 'w') as configfile: configfile.write( ';Set "FUEL / add" to "1" to ADD the fuel to the amount already in the tank or set to "0" to fill the tank up to the amount selected on the app.' + '\n') configfile.write( ';UI Size example: Set "UI / sizemultiplier" to "1.2" in order to increase UI size in 20% (min: 1.0, max: 3.0)' + '\n' + '\n') PresetConfig.write(configfile) NewSection(1) NewSection(2) NewSection(3) NewSection(4) ac.log("BoxRadio: Preset section added")
def acUpdate(delta_t): global error, timer, day_offset, gWrapDebugText, gAppsize, gHideBG, gHideWeather timer += delta_t day_offset += speed * delta_t if timer > 0.075: timer = 0.0 if abs(day_offset) > 1: try: ac.ext_weatherTimeOffset(24 * 60 * 60 * day_offset / abs(day_offset)) except: ac.log("AccExtWeatherFX: Unexpected error:" + traceback.format_exc()) day_offset = 0 if error < 1: try: if not gHideWeather: s = ac.ext_weatherDebugText() s = s.replace('current day:', ' > current day: ') if gWrapDebugText==True: s = '\n'.join(s.strip() for s in re.findall(r'.{1,80}(?:\s+|$)', s)) s = s.replace('>>> Sol weather: v', '\n>>> Sol weather: v') ac.setText(label, s) if gHideBG==True: ac.setBackgroundOpacity(app,0) ac.drawBorder(app,0) except: error = error + 1 ac.log("AccExtWeatherFX: Unexpected error:" + traceback.format_exc()) ac.setText(label, "Shaders patch not installed? Error: \n" + traceback.format_exc())
def acMain(ac_version): global updater, appHeight, appWidth, appWindow, numSecondsSpinner appWindow = ac.newApp("Traction Circle") ac.setSize(appWindow, appWidth, appHeight) ac.drawBorder(appWindow, 0) try: model = TractionCircleModel() assetto_corsa = AssettoCorsa() maxTimeSpan = 3 numSecondsSpinner = ac.addSpinner(appWindow, 'Time Span(s)') ac.setPosition(numSecondsSpinner, 0, appHeight - 20) ac.setSize(numSecondsSpinner, 100, 20) ac.setRange(numSecondsSpinner, 1, 10) ac.setValue(numSecondsSpinner, maxTimeSpan) ac.addOnValueChangeListener(numSecondsSpinner, updateMaxTimeRange) gPlotter = GPlotter(appWidth, appHeight, maxG, maxG) view = TractionCircleView(appWindow, model, gPlotter, MovingAveragePlotter(10) ) updater = TractionCircleUpdater(assetto_corsa, view, model, maxTimeRange=maxTimeSpan) ac.addRenderCallback(appWindow, doUpdate) except Exception as e: ac.log(str(traceback.format_exc())) return "Traction Circle"
def onRenderCallback(deltaT): try: multiLapsApp.onRenderCallback(deltaT) configApp.onRenderCallback(deltaT) except Exception as e: ac.log("MultiLaps: Error in onRenderCallback: %s" % e)
def connect(self): self.sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) handshake_data = Handshaker(4,1,0) ctypes.string_at(ctypes.addressof(handshake_data),ctypes.sizeof(handshake_data)) self.sock.sendto(handshake_data,self.address) ac.log("Sent :-)") self.connected = True
def driverToggle(*args): global isDriverVisible try: isDriverVisible = not isDriverVisible ac.ext_setDriverVisible(isDriverVisible) except: ac.log("Unexpected error:" + traceback.format_exc())
def setValue(self, value, deltaT, optimal): global Options try: self.value = value deg = math.degrees(self.value) #~ otherdeg = math.degrees(othervalue) #~ diff = deg - otherdeg ac.setText(self.valueLabel, "{0:.3f}°".format(deg)) #~ text = getGripFactor(Options["dcamber0"], Options["dcamber1"], value) #~ ac.setText(self.valueLabel,"{0:.1f}%".format(text) self.color = getColor(deg, optimal) self.serie.append({"value": deg, "color": self.color}) serieSum = 0 for s in self.serie: serieSum += s["value"] self.avgValue = serieSum / len(self.serie) ac.setFontColor(self.avgValueLabel, self.color['r'], self.color['g'], self.color['b'], self.color['a']) ac.setText(self.avgValueLabel, "{0:.3f}°".format(self.avgValue)) except Exception: ac.log("CamberExtravaganza ERROR: setValue(): %s" % traceback.format_exc())
def writeParameters(): try: config.set("SETTINGS", "showHeader", str(showHeader)) config.set("SETTINGS", "fontSize", str(fontSize)) config.set("SETTINGS", "opacity", str(opacity)) config.set("SETTINGS", "showBorder", str(showBorder)) config.set("SETTINGS", "lapDisplayedCount", str(lapDisplayedCount)) config.set("SETTINGS", "showDelta", str(showDelta)) config.set("SETTINGS", "deltaColor", str(deltaColor)) config.set("SETTINGS", "redAt", str(redAt)) config.set("SETTINGS", "greenAt", str(greenAt)) config.set("SETTINGS", "reference", str(reference)) config.set("SETTINGS", "showCurrent", str(showCurrent)) config.set("SETTINGS", "showTotal", str(showTotal)) config.set("SETTINGS", "showReference", str(showReference)) config.set("SETTINGS", "updateTime", str(updateTime)) config.set("SETTINGS", "logLaps", str(logLaps)) config.set("SETTINGS", "logBest", str(logBest)) config.set("SETTINGS", "lockBest", str(lockBest)) configFile = open("apps/python/MultiLaps/MultiLaps_config/config.ini", 'w') config.write(configFile) configFile.close() except Exception as e: ac.log("MultiLaps: Error in writeParameters while writing the file: %s" % e)
def printExceptionInfo(contextName=''): global logPrefix ac.console( logPrefix + "Exception[{}]: {}".format(contextName, traceback.format_exc(1))) ac.log(logPrefix + "Exception[{}]: {}".format(contextName, traceback.format_exc()))
def acMain(ac_version): global TYREINFO, optimal_spinner_id, optimal_spinner_shown appWindow = ac.newApp("Tyre Temperatures") ac.drawBackground(appWindow, background) ac.drawBorder(appWindow, background) ac.setBackgroundOpacity(appWindow, background) ac.setSize(appWindow, x_app_size, y_app_size) TYREINFO = Tyre_Info(appWindow, x_start, y_start) ac.addRenderCallback(appWindow, onFormRender) TYREINFO.optimal_temp = d_optimal_temp TYREINFO.carinifilepath = inidir + getValidFileName(ac.getCarName(0)) + ".ini" TYREINFO.needwriteini = 1 if os.path.exists(TYREINFO.carinifilepath): f = open(TYREINFO.carinifilepath, "r") TYREINFO.optimal_temp = int(f.readline()[8:]) f.close() TYREINFO.needwriteini = 0 optimal_spinner_id = ac.addSpinner(appWindow, "optimal") ac.setPosition(optimal_spinner_id, 0, y_app_size + 28) ac.setStep(optimal_spinner_id, 1) if inFahrenheit: ac.setRange(optimal_spinner_id, int(CelsiusToFahrenheit(50)), int(CelsiusToFahrenheit(150))) ac.setValue(optimal_spinner_id, int(CelsiusToFahrenheit(TYREINFO.optimal_temp))) else: ac.setRange(optimal_spinner_id, 50, 150) ac.setValue(optimal_spinner_id, TYREINFO.optimal_temp) ac.addOnValueChangeListener(optimal_spinner_id, onValueChanged) optimal_spinner_shown = 1 ac.log("Danny Giusa Tyre Temperatures loaded") return "Danny Giusa Tyre Temperatures"
def load(self): config = configparser.SafeConfigParser() try: config.read(appFolder + "/config.ini") self.enable = config.get(appName, "enable") == "1" ac.log(logPrefix + "Config loaded!") except Exception as e: ac.log(logPrefix + "Config load ERROR. type=%s" % (type(e)), 1)
def acMain(acVersion): # do something with serial library global ser ac.log("called acMain()") time.sleep(3) #ser.write("1:0;".encode()) ser.write("3:5000;".encode()) return "Arduino Serial"
def acMain(ac_version): try: appReadSettings() appCreateMyself() # ac.setVisible(app,1) # todo debug out except: ac.log("AccExtWeatherFX: Unexpected error:" + traceback.format_exc()) return "AccExtWeather"
def onAppActivated(*args): global appWindowActivated, showWindowTitle ac.log("helipicapew::onAppActivated({0})".format(args)) appWindowActivated = time.clock() showWindowTitle = True ac.setBackgroundOpacity(appWindow, 0.5) ac.setIconPosition(appWindow, 0, 0) ac.setTitle(appWindow, "helipicapew v{}".format(version))
def acShutdown(): try: if info.graphics.status != 1: multiLapsApp.writeSession() multiLapsApp.writeBestLap() except Exception as e: ac.log("MultiLaps: Error in acShutdown: %s" % e)
def acMain(acVersion): # do something with serial library global ser ac.log("called acMain()") time.sleep(3) #ser.write("1:0;".encode()) ser.write("3:17000;".encode()) return "Arduino Serial"
def vaoToggle(*args): global isVaoActive, currentVaoDebugMode try: isVaoActive = not isVaoActive currentVaoDebugMode = 0 ac.ext_setVaoActive(isVaoActive) except: ac.log("Unexpected error:" + traceback.format_exc())
def acMain(ac_version): try: global multiLapsApp, configApp, config global showHeader, fontSize, opacity, showBorder global lapDisplayedCount, showDelta, deltaColor, redAt, greenAt global reference, showCurrent, showReference, showTotal global updateTime, logLaps, logBest, lockBest global trackName, trackConf, carName, bestLapFile global nurbTourist if ac_version < 1.0: return "MultiLaps" config = configparser.ConfigParser() config.read("apps/python/MultiLaps/MultiLaps_config/config.ini") showHeader = config.getint("SETTINGS", "showHeader") fontSize = config.getint("SETTINGS", "fontSize") opacity = config.getint("SETTINGS", "opacity") showBorder = config.getint("SETTINGS", "showBorder") lapDisplayedCount = config.getint("SETTINGS", "lapDisplayedCount") showDelta = config.getint("SETTINGS", "showDelta") deltaColor = config.get("SETTINGS", "deltaColor") redAt = config.getint("SETTINGS", "redAt") greenAt = config.getint("SETTINGS", "greenAt") reference = config.get("SETTINGS", "reference") showCurrent = config.getint("SETTINGS", "showCurrent") showTotal = config.getint("SETTINGS", "showTotal") showReference = config.getint("SETTINGS", "showReference") updateTime = config.getint("SETTINGS", "updateTime") logLaps = config.getint("SETTINGS", "logLaps") logBest = config.get("SETTINGS", "logBest") lockBest = config.getint("SETTINGS", "lockBest") trackName = ac.getTrackName(0) trackConf = ac.getTrackConfiguration(0) carName = ac.getCarName(0) if trackConf == "": bestLapFile = "apps/python/MultiLaps/MultiLaps_bestlap/{0} - {1}.ini".format( trackName, carName) else: bestLapFile = "apps/python/MultiLaps/MultiLaps_bestlap/{0} [{1}] - {2}.ini".format( trackName, trackConf, carName) if trackName == "ks_nordschleife" and trackConf == "touristenfahrten": nurbTourist = True multiLapsApp = MultiLaps("MultiLaps", "Laps") multiLapsApp.refreshParameters() ac.addRenderCallback(multiLapsApp.window, onRenderCallback) configApp = MultiLaps_config("MultiLaps_config", "MultiLaps config", fontSizeConfig, 0) configApp.updateView() return "MultiLaps" except Exception as e: ac.log("MultiLaps: Error in acMain: %s" % e)
def drawTire(self, suspX, suspY, suspH, flip=False): global Options try: x = self.xPosition + 25 y = self.yPosition #~ rad = self.value * Options["radScale"] #~ rad = self.value * Options["radScale"] / (2 * -Options["targetCamber"]) rad = self.value if flip: #~ x = self.xPosition + 50 rad = math.pi - rad ac.glColor4f(self.color['r'], self.color['g'], self.color['b'], self.color['a']) h = Options["tireHeight"] w = h / 2 cosrad = math.cos(rad) sinrad = math.sin(rad) halfpi = math.pi / 2 if flip: cosradnorm = math.cos(rad + halfpi) sinradnorm = math.sin(rad + halfpi) # Have to draw counterclockwise ac.glBegin(acsys.GL.Quads) ac.glVertex2f(x, y) ac.glVertex2f(x + h * cosradnorm, y + h * sinradnorm) ac.glVertex2f(x + w * cosrad + h * cosradnorm, y + w * sinrad + h * sinradnorm) ac.glVertex2f(x + w * cosrad, y + w * sinrad) ac.glEnd() else: cosradnorm = math.cos(rad - halfpi) sinradnorm = math.sin(rad - halfpi) # Have to draw counterclockwise ac.glBegin(acsys.GL.Quads) ac.glVertex2f(x, y) ac.glVertex2f(x + w * cosrad, y + w * sinrad) ac.glVertex2f(x + w * cosrad + h * cosradnorm, y + w * sinrad + h * sinradnorm) ac.glVertex2f(x + h * cosradnorm, y + h * sinradnorm) ac.glEnd() # Suspension bits ac.glColor4f(0.9, 0.9, 0.9, 0.9) ac.glBegin(acsys.GL.Lines) ac.glVertex2f(x + (h / 2 - suspH) * cosradnorm, y + (h / 2 - suspH) * sinradnorm) ac.glVertex2f(suspX, suspY + suspH) ac.glVertex2f(x + (h / 2 + suspH) * cosradnorm, y + (h / 2 + suspH) * sinradnorm) ac.glVertex2f(suspX, suspY - suspH) ac.glEnd() except Exception: ac.log("CamberExtravaganza ERROR: drawTire(): %s" % traceback.format_exc())
def getTrackLength(): try: trackLengthFloat = ac.getTrackLength(0) return trackLengthFloat except Exception as e: ac.console(APP_NAME + ": Error in getTrackLength: %s" % e) ac.log(APP_NAME + ": Error in getTrackLength: %s" % e) return 0
def doorToggle(*args): global areDoorsOpen try: areDoorsOpen = not areDoorsOpen ac.ext_setDoorsOpen(areDoorsOpen) ac.ext_setTrackConditionInput('CAR_DOORS_OPENED', 1.0 if areDoorsOpen else 0.0) except: ac.log("Unexpected error:" + traceback.format_exc())
def getOrSetDefaultFloat(config, key, default): global update try: return config.getfloat(section, key) except Exception as e: ac.log('helipicapew::getOrSetDefaultFloat error {}'.format(e)) config.set(section, key, str(default)) update=True return default
def getNotification(): global Notify, NotificationLabel, StatusLabel try: Notify = box.notification('243075740:AAEuscXHE-VaQCwZuWpytMzmC3Iwhopub6E') ac.setText(NotificationLabel, Notify) except: ac.log('BoxRadio: No internet connection') Status = "No internet connection" ac.setText(StatusLabel, Status)
def CheckNewUpdate(): global Status, StatusLabel, branch try: Status = box.github_newupdate('Marocco2/BoxRadio', branch) ac.setText(StatusLabel, Status) except: ac.log('BoxRadio: No internet connection') Status = "No internet connection" ac.setText(StatusLabel, Status)
def onFormRender(deltaT): try: global ov1_info # init on_render function ov1_info.on_render() except Exception as e: ac.console("OV1: Error in function onFormRender(): %s" % e) ac.log("OV1: Error in function onFormRender(): %s" % e)
def acUpdate(deltaT): try: global ov1_info # init the app updates ov1_info.on_update(deltaT) except Exception as e: ac.console("OV1: Error in function acUpate(): %s" % e) ac.log("OV1: Error in function acUpate(): %s" % e)
def acShutdown(): try: global ov1_info # init on_render function ov1_info.on_shutdown() except Exception as e: ac.console("OV1: Error in function acShutdown(): %s" % e) ac.log("OV1: Error in function acShutdown(): %s" % e)
def getNotification(): global Notify, NotificationLabel, StatusLabel try: Notify = box.notification('186810231:AAGvhq85_lqUb3wPOStvazULUsmN5ET37gM') ac.setText(NotificationLabel, Notify) except: ac.log('EpicRace: No internet connection') Status = "No internet connection" ac.setText(StatusLabel, Status)
def timeToString(time): try: if time <= 0: return "-:--.---" else: return "{:d}:{:0>2d}.{:0>3d}".format(int(time/60000), int((time%60000)/1000), int(time%1000)) except Exception as e: ac.log("MultiLaps: Error in timeToString: %s" % e) return "-:--.---"
def acMain(ac_version): global app, APPNAME try: """ Must init Pygame now and must be first before trying to access the gamedevice.device object""" pygame.init() app = PDU1800DataProvider(APPNAME) return APPNAME except Exception as e: ac.log("Error in acMain: {}".format(str(e))) ac.console("Error in acMain: {}".format(str(e)))
def onAppActivated(*args): global appWindowActivated, showWindowTitle ac.log("3secondz_xyro::onAppActivated({0})".format(args)) appWindowActivated = time.clock() showWindowTitle = True ac.setBackgroundOpacity(appWindow, 0.5) ac.setIconPosition(appWindow, 0, 0) ac.setTitle(appWindow, '3secondz_xyro') running = True
def save(self): config = configparser.SafeConfigParser() try: config.add_section(appName) config.set(appName, "enable", self.enable) with open(appFolder + "/config.ini", "w") as config_file: config.write(config_file) ac.log(logPrefix + "Config saved!") except Exception as e: ac.log(logPrefix + "Config save ERROR. type=%s" % (type(e)), 1)
def resetBestLap(self): try: self.bestLapTime = 0 self.bestLapData = [] if os.path.exists(bestLapFile): os.remove(bestLapFile) except Exception as e: ac.log("MultiLaps class: Error in resetBestLap: %s" % e)
def acShutdown(): global memFile global tick tick = tick + 1 buf = struct.pack("?if", False, tick, 0); memFile.seek(0) memFile.write(buf) memFile.close() ac.log("shutdown")
def refreshAndWriteParameters(): try: multiLapsApp.refreshParameters() multiLapsApp.updateData() multiLapsApp.updateView() configApp.updateView() writeParameters() except Exception as e: ac.log("MultiLaps: Error in refreshAndWriteParameters: %s" % e)
def queue(location): try: global sound_player global isPlayingStartRace, isPlayingBeforeRace, isPlayingSuspense, isPlayingAfterRace, isPlayingOvertake global overflow # new fmod audio: sound_player.queueSong(location) overflow += 1 except: ac.log('EpicRace: error loading song ' + traceback.format_exc())
def getNotification(): global Notify, NotificationLabel, StatusLabel try: Notify = box.notification( '243075740:AAEuscXHE-VaQCwZuWpytMzmC3Iwhopub6E') ac.setText(NotificationLabel, Notify) except: ac.log('BoxRadio: No internet connection') Status = "No internet connection" ac.setText(StatusLabel, Status)
def debug(message): global appName fileDebug = False consoleDebug = False if fileDebug: ac.log(appName + ": " + message) if consoleDebug: ac.console(appName + ": " + message)
def log(message, console=True, app_log=True): """ Logs a message on the log and console. """ time_str = datetime.utcnow().strftime("%H:%M:%S.%f") formated = "[LT][{}] {}".format(time_str, message) if console: ac.console(formated) if app_log: ac.log(formated)
def VirtChange(dsize, dx, dy): global smart_mirrorini, xoffset, yoffset, smart_mirrorini try: configDocs = configparser.ConfigParser( empty_lines_in_values=False, inline_comment_prefixes=(";", "/", "#", "\\"), strict=False) configDocs.optionxform = str # keep case if not os.path.isfile(smart_mirrorini): with codecs.open(smart_mirrorini, 'w', 'utf_8', errors='ignore') as f: f.write('') else: configDocs.read(smart_mirrorini) # defaults swO = '0.1185' shO = '0.1185' sxoffset = str(xoffset) syoffset = str(yoffset) if not configDocs.has_section('PIECE_0'): configDocs.add_section('PIECE_0') syoffset = '85 + ' + str(round(float(shO) + dsize, 4)) + ' * screen.height / 2' else: if configDocs.has_option('PIECE_0', 'WIDTH'): swO = configDocs['PIECE_0']['WIDTH'].split('*')[0].strip() if configDocs.has_option('PIECE_0', 'HEIGHT'): shO = configDocs['PIECE_0']['HEIGHT'].split('*')[0].strip() if configDocs.has_option('PIECE_0', 'APP_VIRTYOFFSET'): yoffset = configDocs['PIECE_0']['APP_VIRTYOFFSET'] if configDocs.has_option('PIECE_0', 'APP_VIRTXOFFSET'): xoffset = configDocs['PIECE_0']['APP_VIRTXOFFSET'] sxoffset = '0.5 * screen.width + ' + str( round(float(xoffset) + float(dx), 4)) syoffset = str(float(yoffset) + float(dy)) + ' + ' + str( round(float(shO) + dsize, 4)) + ' * screen.height / 2' configDocs.set( 'PIECE_0', 'WIDTH', str(round(float(swO) + dsize, 4)) + ' * screen.height * 4') configDocs.set('PIECE_0', 'HEIGHT', str(round(float(shO) + dsize, 4)) + ' * screen.height') configDocs.set('PIECE_0', 'CENTER_X', sxoffset) configDocs.set('PIECE_0', 'CENTER_Y', syoffset) configDocs.set('PIECE_0', 'OPACITY', '1') configDocs.set('PIECE_0', 'APP_VIRTXOFFSET', str(float(xoffset) + float(dx))) configDocs.set('PIECE_0', 'APP_VIRTYOFFSET', str(float(yoffset) + float(dy))) with open(smart_mirrorini, 'w') as configfile: configDocs.write(configfile, space_around_delimiters=False) except: ac.log('AccExtMirrors main: \n' + traceback.format_exc())
def acMain(ac_version): ac.log("AC Main / OpenSimwheel") global memFile global tick tick = tick + 1 memFile = mmap.mmap(-1, 50, filename, access=mmap.ACCESS_WRITE) buf = struct.pack("?if", True, tick,0) memFile.seek(0) memFile.write(buf) return "OpenSimwheel v0.1"
def WriteData(): ac.console("[PV]Tires:" + Tires + ",Fuel:" + Gas + "Fix body:" + FixBody + "Fix engine:" + FixEngine + "Fix suspension:" + FixSuspension) ac.log("[PV]Tires:" + Tires + ",Fuel:" + Gas + "Fix body:" + FixBody + "Fix engine:" + FixEngine + "Fix suspension:" + FixSuspension) with open('apps/python/PitVoice/Pit.txt', 'w') as f: f.write(Tires + "\n") f.write(Gas + "\n") f.write(FixBody + "\n") f.write(FixEngine + "\n") f.write(FixSuspension) f.close()
def listen_key(): try: ctypes.windll.user32.RegisterHotKey(None, 1, 0, win32con.VK_F10) msg = ctypes.wintypes.MSG() while listen_active: if ctypes.windll.user32.GetMessageA(ctypes.byref(msg), None, 0, 0) != 0: if msg.message == win32con.WM_HOTKEY: hotkey_pressed() ctypes.windll.user32.TranslateMessage(ctypes.byref(msg)) ctypes.windll.user32.DispatchMessageA(ctypes.byref(msg)) except: ac.log('BoxRadio: Hotkey fail')
def acMain(ac_version): global fuelUsage appWindow = ac.newApp("Fuel Usage") ac.drawBackground(appWindow, background) ac.drawBorder(appWindow, background) ac.setBackgroundOpacity(appWindow, background) ac.setSize(appWindow, x_app_size, y_app_size) fuelUsage = Fuel_Usage(appWindow, x_start, y_start) ac.addRenderCallback(appWindow, onFormRender) ac.log("Fuel Usage App loaded") return "Fuel Usage App"
def priority_queue(location): try: global sound_player global isPlayingStartRace, isPlayingBeforeRace, isPlayingSuspense, isPlayingAfterRace, isPlayingOvertake global overflow # priority clip cancels other audio. stopPlaying() # new fmod audio: sound_player.queueSong(location) overflow += 2 except: ac.log('EpicRace: error loading song ' + traceback.format_exc())
def w(message): exc_type, exc_value, exc_traceback = sys.exc_info() lines = traceback.format_exception(exc_type, exc_value, exc_traceback) ac.console(message + ":") for line in lines: ac.log(line) for line in lines: if line.find("Traceback")>=0: continue s = line.replace("\n"," -> ") s = s.replace(" ","") if s[-4:] == " -> ": s=s[:-4] ac.console(s)
def acMain(ac_version): try: global ov1_info # initialize the app ov1_info = App() # create the app objects ov1_info.start_up() # add render callback ov1_info.window.onRenderCallback(onFormRender) # return the app's ID return "OV1Info" except Exception as e: ac.console("OV1: Error in function acMain(): %s" % e) ac.log("OV1: Error in function acMain(): %s" % e)