From ec77140386703e6259ee46ea7e46be6653229728 Mon Sep 17 00:00:00 2001 From: bri3d Date: Sat, 14 Dec 2024 14:56:36 -0700 Subject: [PATCH] black and flake8 --- VW_Flash_GUI.py | 50 +++++---- extract_software_info.py | 12 +- extractodx.py | 1 - frf/decryptfrf.py | 3 +- lib/binfile.py | 55 +++++---- lib/checksum.py | 14 +-- lib/connections/connection_setup.py | 4 +- lib/connections/fake_connection.py | 2 - lib/connections/j2534.py | 6 +- lib/connections/j2534_connection.py | 14 +-- lib/constants.py | 4 +- lib/dq381_flash_utils.py | 7 +- lib/dsg_flash_utils.py | 6 +- lib/flash_uds.py | 14 +-- lib/haldex_checksum.py | 13 ++- lib/haldex_flash_utils.py | 11 +- lib/legacysimos.py | 2 +- lib/lzss.py | 8 +- lib/lzss_helper.py | 7 +- lib/modules/simos10.py | 2 +- lib/modules/simos12.py | 2 +- lib/modules/simos122.py | 2 +- lib/modules/simos16.py | 4 +- lib/modules/simos8.py | 2 +- lib/resource_helper.py | 5 +- lib/simos_flash_utils.py | 6 +- lib/simos_hsl.py | 166 +++++++++++++++++++--------- setup.py | 2 - 28 files changed, 249 insertions(+), 175 deletions(-) diff --git a/VW_Flash_GUI.py b/VW_Flash_GUI.py index b0af05e..5043bec 100644 --- a/VW_Flash_GUI.py +++ b/VW_Flash_GUI.py @@ -1,4 +1,3 @@ -import asyncio import glob from pathlib import Path import wx @@ -34,8 +33,7 @@ dq250mqb, dq381, simos16, - simosshared, - haldex4motion + haldex4motion, ) DEFAULT_STMIN = 350000 @@ -69,9 +67,11 @@ def module_selection_is_dq250(selection_index): def module_selection_is_dq381(selection_index): return selection_index == 3 + def module_selection_is_haldex(selected_index): return selected_index == 4 + def split_interface_name(interface_string: str): parts = interface_string.split("_", 1) interface = parts[0] @@ -323,7 +323,7 @@ def on_module_changed(self, event): simos1810.s1810_flash_info, dq250mqb.dsg_flash_info, dq381.dsg_flash_info, - haldex4motion.haldex_flash_info + haldex4motion.haldex_flash_info, ][module_number] def on_get_info(self, event): @@ -354,16 +354,23 @@ def on_read_dtcs(self, event): ] def flash_unlock(self, selected_file): - if module_selection_is_dq250( - self.module_choice.GetSelection() - ) or module_selection_is_dq381(self.module_choice.GetSelection()) or module_selection_is_haldex(self.module_choice.GetSelection()): - self.feedback_text.AppendText("SKIPPED: Unlocking is unnecessary for Haldex/DSG\n") + if ( + module_selection_is_dq250(self.module_choice.GetSelection()) + or module_selection_is_dq381(self.module_choice.GetSelection()) + or module_selection_is_haldex(self.module_choice.GetSelection()) + ): + self.feedback_text.AppendText( + "SKIPPED: Unlocking is unnecessary for Haldex/DSG\n" + ) return input_bytes = Path(selected_file).read_bytes() if str.endswith(selected_file, ".frf"): self.feedback_text.AppendText("Extracting FRF for unlock...\n") - (flash_data, allowed_boxcodes,) = extract_flash.extract_flash_from_frf( + ( + flash_data, + allowed_boxcodes, + ) = extract_flash.extract_flash_from_frf( input_bytes, self.flash_info, is_dsg=module_selection_is_dq250(self.module_choice.GetSelection()), @@ -412,7 +419,10 @@ def flash_bin_file(self, selected_file, patch_cboot=False): input_bytes = Path(self.row_obj_dict[selected_file]).read_bytes() if str.endswith(self.row_obj_dict[selected_file], ".frf"): self.feedback_text.AppendText("Extracting FRF...\n") - (flash_data, allowed_boxcodes,) = extract_flash.extract_flash_from_frf( + ( + flash_data, + allowed_boxcodes, + ) = extract_flash.extract_flash_from_frf( input_bytes, self.flash_info, is_dsg=module_selection_is_dq250(self.module_choice.GetSelection()), @@ -426,7 +436,9 @@ def flash_bin_file(self, selected_file, patch_cboot=False): self.flash_bin(get_info=False, should_patch_cboot=patch_cboot) elif len(input_bytes) == self.flash_info.binfile_size: self.input_blocks = binfile.blocks_from_bin( - self.row_obj_dict[selected_file], self.flash_info, module_selection_is_haldex(self.module_choice.GetSelection()) + self.row_obj_dict[selected_file], + self.flash_info, + module_selection_is_haldex(self.module_choice.GetSelection()), ) self.flash_bin(get_info=False, should_patch_cboot=patch_cboot) else: @@ -641,14 +653,10 @@ def prepare_file(self, selected_file, output_dir): ) output_file = Path(output_dir, "PATCHED_" + Path(selected_file).name) outfile_data = binfile.bin_from_blocks(output_blocks, self.flash_info) - output_file.write_bytes( - outfile_data - ) + output_file.write_bytes(outfile_data) self.feedback_text.AppendText( - "File prepared and saved as : " - + output_file.name - + "\n" + "File prepared and saved as : " + output_file.name + "\n" ) self.progress_bar.SetValue(0) @@ -1048,6 +1056,10 @@ def on_select_extract_frf(self, event): title = "Choose an output directory:" dlg = wx.DirDialog(self, title) if dlg.ShowModal() == wx.ID_OK: + + def callback(progress): + wx.CallAfter(progress_dialog.Update, progress) + output_dir = dlg.GetPath() progress_dialog = wx.ProgressDialog( "Extracting FRF", @@ -1056,9 +1068,6 @@ def on_select_extract_frf(self, event): parent=self, style=wx.PD_APP_MODAL | wx.PD_AUTO_HIDE, ) - callback = lambda progress: wx.CallAfter( - progress_dialog.Update, progress - ) frf_thread = threading.Thread( target=self.extract_frf_task, args=(frf_file, output_dir, callback), @@ -1067,6 +1076,7 @@ def on_select_extract_frf(self, event): progress_dialog.Pulse() progress_dialog.Show() + if __name__ == "__main__": app = wx.App(False) frame = VW_Flash_Frame() diff --git a/extract_software_info.py b/extract_software_info.py index e2d4e98..53ec426 100644 --- a/extract_software_info.py +++ b/extract_software_info.py @@ -1,5 +1,5 @@ import argparse -from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor +from concurrent.futures import ProcessPoolExecutor import csv import itertools import sys @@ -156,9 +156,13 @@ def process_data(data: bytes, is_bin=False): for block_number in flash_info.block_names_frf.keys(): flash_blocks[block_number] = constants.BlockData( block_number, - flash_data[flash_info.block_names_frf[block_number]].block_bytes - if is_bin - else flash_data[flash_info.block_names_frf[block_number]], + ( + flash_data[ + flash_info.block_names_frf[block_number] + ].block_bytes + if is_bin + else flash_data[flash_info.block_names_frf[block_number]] + ), block_name=flash_info.number_to_block_name[block_number], ) diff --git a/extractodx.py b/extractodx.py index f53f2ce..1fad76c 100644 --- a/extractodx.py +++ b/extractodx.py @@ -9,7 +9,6 @@ from lib.modules import ( simos8, simos10, - simos12, simos18, simos1810, simos184, diff --git a/frf/decryptfrf.py b/frf/decryptfrf.py index 1683bec..f28f2fb 100644 --- a/frf/decryptfrf.py +++ b/frf/decryptfrf.py @@ -1,11 +1,10 @@ import pathlib -from sys import argv from zipfile import ZipFile import argparse import io -import os from lib import constants + # Implements a goofy "recursive xor" cypher used to encrypt FRF files, which at the end of the day are ZIP files containing either SGO (binary flash data) or ODX data. def decrypt_data(key_material: bytes, encrypted_data: bytes): output_data = bytearray() diff --git a/lib/binfile.py b/lib/binfile.py index 40a2cc8..d45e5bc 100644 --- a/lib/binfile.py +++ b/lib/binfile.py @@ -120,15 +120,18 @@ def filter_blocks(input_blocks: dict[str, BlockData], flash_info: FlashInfo): return input_blocks -def blocks_from_bin(bin_path: str, flash_info: FlashInfo, haldex_hack: bool = False) -> dict[str, BlockData]: +def blocks_from_bin( + bin_path: str, flash_info: FlashInfo, haldex_hack: bool = False +) -> dict[str, BlockData]: bin_data = Path(bin_path).read_bytes() return blocks_from_data(bin_data, flash_info, haldex_hack) -def blocks_from_data(data: bytes, flash_info: FlashInfo, haldex_hack: bool = False) -> dict[str, BlockData]: +def blocks_from_data( + data: bytes, flash_info: FlashInfo, haldex_hack: bool = False +) -> dict[str, BlockData]: input_blocks = {} - for i in flash_info.block_names_frf.keys(): filename = flash_info.block_names_frf[i] block_length = flash_info.block_lengths[i] @@ -136,23 +139,35 @@ def blocks_from_data(data: bytes, flash_info: FlashInfo, haldex_hack: bool = Fal # TODO: Make this less awful if haldex_hack: - if filename == 'FD_1DATA': - logger.info('Dynamically getting CAL length for Haldex...') - length = data[ (flash_info.binfile_layout[i] + 0x14) : (flash_info.binfile_layout[i] + 0x18)] - logger.info('Set Haldex CAL length to: '+length.hex()) - block_length = struct.unpack('> 32) - data_binary_cal[ - checksum_location_cal + 4 : checksum_location_cal + 8 - ] = struct.pack("> 32) + ) + data_binary_cal[checksum_location_cal + 4 : checksum_location_cal + 8] = ( + struct.pack(" int: def internal_path(*path_parts) -> str: - __location__ = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__))) + __location__ = getattr(sys, "_MEIPASS", os.path.dirname(os.path.abspath(__file__))) if sys.platform == "win32": return os.path.join(__location__, *path_parts) else: @@ -237,7 +237,7 @@ def internal_path(*path_parts) -> str: ) -### test data for the FakeConnection +# test data for the FakeConnection testdata = { b"\x10\x03": b"\x50\x03\x12\x23\x34\x45", diff --git a/lib/dq381_flash_utils.py b/lib/dq381_flash_utils.py index 2253bcf..467112d 100644 --- a/lib/dq381_flash_utils.py +++ b/lib/dq381_flash_utils.py @@ -5,12 +5,11 @@ from . import lzss_helper as lzss from . import dq381_checksum -from .modules import dq381 from . import constants as constants from .constants import BlockData, FlashInfo, PreparedBlockData from . import flash_uds -from typing import Union +from typing import Optional cliLogger = logging.getLogger("FlashUtils") @@ -213,8 +212,8 @@ def flash_bin( callback=None, interface: str = "CAN", patch_cboot=False, - interface_path: Union[str, None] = None, - stmin_override: Union[int, None] = 900000, + interface_path: Optional[str] = None, + stmin_override: Optional[int] = 900000, ): asw_data = bytearray() cal_id = b"NONE" diff --git a/lib/dsg_flash_utils.py b/lib/dsg_flash_utils.py index f17b864..8918690 100644 --- a/lib/dsg_flash_utils.py +++ b/lib/dsg_flash_utils.py @@ -7,7 +7,7 @@ from .modules import dq250mqb from .constants import BlockData, FlashInfo, PreparedBlockData -from typing import Union +from typing import Optional cliLogger = logging.getLogger("FlashUtils") @@ -213,8 +213,8 @@ def flash_bin( callback=None, interface: str = "CAN", patch_cboot=False, - interface_path: Union[str, None] = None, - stmin_override: Union[int, None] = None, + interface_path: Optional[str] = None, + stmin_override: Optional[int] = None, ): prepared_blocks = prepare_blocks(flash_info, input_blocks, callback) flash_uds.flash_blocks( diff --git a/lib/flash_uds.py b/lib/flash_uds.py index e24deca..b0d2222 100644 --- a/lib/flash_uds.py +++ b/lib/flash_uds.py @@ -1,13 +1,11 @@ -import sys import logging import time import udsoncan from . import constants from . import dtc_handler from .connections.connection_setup import connection_setup -from datetime import date from sa2_seed_key.sa2_seed_key import Sa2SeedKey -from typing import List, Union +from typing import Optional from udsoncan.client import Client from udsoncan.client import Routine from udsoncan import configs @@ -17,11 +15,6 @@ from .workshop_code import WorkshopCodeCodec -from typing import Union - -if sys.platform == "win32": - from .connections.j2534_connection import J2534Connection - logger = logging.getLogger("SimosFlashHistory") detailedLogger = logging.getLogger("SimosUDSDetail") @@ -164,6 +157,7 @@ def flash_block( if (len(tuner_tag) > 0) and (block_number > 1): detailedLogger.info("Sending tuner ASW magic number...") + # Send Magic # In the case of a tuned CBOOT, send tune-specific magic bytes after this 3E to force-overwrite the CAL validity area. def tuner_payload(payload, tune_block_number=block_number): @@ -297,7 +291,7 @@ def flash_blocks( tuner_tag=None, callback=None, interface: str = "CAN", - interface_path: Union[str, None] = None, + interface_path: Optional[str] = None, workshop_code=bytes( [ 0x20, # Year (BCD/HexDecimal since 2000) @@ -311,7 +305,7 @@ def flash_blocks( 0x3D, ] ), - stmin_override: Union[int, None] = None, + stmin_override: Optional[int] = None, dq3xx_hack=False, ): class GenericStringCodec(udsoncan.DidCodec): diff --git a/lib/haldex_checksum.py b/lib/haldex_checksum.py index c2b2128..7791e3f 100644 --- a/lib/haldex_checksum.py +++ b/lib/haldex_checksum.py @@ -1,6 +1,5 @@ import struct import logging -import zlib from . import constants from .modules import haldex4motion @@ -14,7 +13,7 @@ def validate( should_fix=False, ): # Don't checksum the DRIVER - if(blocknum == 1): + if blocknum == 1: logger.debug("Ignoring DRIVER checksum") return (constants.ChecksumState.FIXED_CHECKSUM, data_binary) @@ -26,15 +25,19 @@ def validate( )[0] # Grab the data before and after the checksum block - checksum_data = data_binary[0:checksum_location] + (data_binary[checksum_location + 0xA:]) + checksum_data = data_binary[0:checksum_location] + ( + data_binary[checksum_location + 0xA :] + ) checksum = 0 for i in range(0, len(checksum_data), 2): # Simple 16bit adder - checksum = (checksum + struct.unpack("L", data[3:7])[0] - count = struct.unpack(">H", data[1:3])[0] + # count = struct.unpack(">H", data[1:3])[0] output_cursor = 0 offset_size = int(data[1]) dict_size = fill_bits(int(data[2])) diff --git a/lib/lzss.py b/lib/lzss.py index 15423e6..5bc0834 100644 --- a/lib/lzss.py +++ b/lib/lzss.py @@ -166,21 +166,21 @@ def decode(self): r = (self.N - self.F) - self.rless while True: c = self.getbit(1) - if c == None: + if c is None: break if c: c = self.getbit(8) - if c == None: + if c is None: break self.outfile.write(bytes((c,))) self.buffer[r] = c r = (r + 1) & (self.N - 1) else: i = self.getbit(self.EI) - if i == None: + if i is None: break j = self.getbit(self.EJ) - if j == None: + if j is None: break for k in range(0, j + 2): c = self.buffer[(i + k) & (self.N - 1)] diff --git a/lib/lzss_helper.py b/lib/lzss_helper.py index c0aeb66..28afa48 100644 --- a/lib/lzss_helper.py +++ b/lib/lzss_helper.py @@ -1,4 +1,4 @@ -import os, sys +import sys import subprocess from .resource_helper import resource_path @@ -29,8 +29,3 @@ def lzss_compress(input_data: bytes, skip_padding=False, exact_padding=False) -> output_data = p.stdout return output_data - - -def main(inputfile="", outputfile=""): - command = libdir + "/lzss/lzss -i " + inputfile + " -o " + outputfile - result = os.system(command) diff --git a/lib/modules/simos10.py b/lib/modules/simos10.py index b4615ee..4b09fed 100644 --- a/lib/modules/simos10.py +++ b/lib/modules/simos10.py @@ -1,4 +1,4 @@ -from lib.constants import FlashInfo, internal_path, ecu_control_module_identifier +from lib.constants import FlashInfo, ecu_control_module_identifier from lib.crypto import simos_xor from .simosshared import ( diff --git a/lib/modules/simos12.py b/lib/modules/simos12.py index 4711dea..7c6a2f1 100644 --- a/lib/modules/simos12.py +++ b/lib/modules/simos12.py @@ -1,4 +1,4 @@ -from lib.constants import FlashInfo, internal_path, ecu_control_module_identifier +from lib.constants import FlashInfo, ecu_control_module_identifier from lib.crypto import aes from .simosshared import ( diff --git a/lib/modules/simos122.py b/lib/modules/simos122.py index 0ebb4f4..5106b6d 100644 --- a/lib/modules/simos122.py +++ b/lib/modules/simos122.py @@ -1,4 +1,4 @@ -from lib.constants import FlashInfo, internal_path, ecu_control_module_identifier +from lib.constants import FlashInfo, ecu_control_module_identifier from lib.crypto import aes from .simosshared import ( block_identifiers_simos, diff --git a/lib/modules/simos16.py b/lib/modules/simos16.py index 84650e5..b00f429 100644 --- a/lib/modules/simos16.py +++ b/lib/modules/simos16.py @@ -1,6 +1,6 @@ -from lib.constants import FlashInfo, internal_path, ecu_control_module_identifier +from lib.constants import FlashInfo, ecu_control_module_identifier from lib.crypto import aes -from .simos18 import base_addresses_s18, block_lengths_s18 +from .simos18 import block_lengths_s18 from .simosshared import ( block_identifiers_simos, block_checksums_simos, diff --git a/lib/modules/simos8.py b/lib/modules/simos8.py index 804e9c6..31b1662 100644 --- a/lib/modules/simos8.py +++ b/lib/modules/simos8.py @@ -1,4 +1,4 @@ -from lib.constants import FlashInfo, internal_path, ecu_control_module_identifier +from lib.constants import FlashInfo, ecu_control_module_identifier from lib.crypto import simos_xor from .simosshared import ( diff --git a/lib/resource_helper.py b/lib/resource_helper.py index 9669b8c..d6d6c8b 100644 --- a/lib/resource_helper.py +++ b/lib/resource_helper.py @@ -1,6 +1,7 @@ import os import sys + def resource_path(relative_path): - base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__))) - return os.path.join(base_path, relative_path) \ No newline at end of file + base_path = getattr(sys, "_MEIPASS", os.path.dirname(os.path.abspath(__file__))) + return os.path.join(base_path, relative_path) diff --git a/lib/simos_flash_utils.py b/lib/simos_flash_utils.py index 375918f..952d20a 100644 --- a/lib/simos_flash_utils.py +++ b/lib/simos_flash_utils.py @@ -11,7 +11,7 @@ from .modules import simosshared from . import flash_uds -from typing import Union +from typing import Optional cliLogger = logging.getLogger("FlashUtils") @@ -301,8 +301,8 @@ def flash_bin( callback=None, interface: str = "CAN", patch_cboot=False, - interface_path: Union[str, None] = None, - stmin_override: Union[int, None] = None, + interface_path: Optional[str] = None, + stmin_override: Optional[int] = None, ): asw_data = bytearray() cal_id = b"NONE" diff --git a/lib/simos_hsl.py b/lib/simos_hsl.py index 006dae5..426f937 100644 --- a/lib/simos_hsl.py +++ b/lib/simos_hsl.py @@ -31,6 +31,7 @@ TQ_CONSTANT = 16.3 PI = 3.14 + class hsl_logger: def __init__( self, @@ -113,7 +114,9 @@ def __init__( self.activityLogger.info("Configuration file: " + self.CONFIGFILE) if os.path.exists(self.CONFIGFILE) and os.access(self.CONFIGFILE, os.R_OK): try: - self.activityLogger.debug("Loading configuration file: " + self.CONFIGFILE) + self.activityLogger.debug( + "Loading configuration file: " + self.CONFIGFILE + ) with open(self.CONFIGFILE, "r") as configFile: configuration = yaml.safe_load(configFile) @@ -129,7 +132,9 @@ def __init__( self.displayGauges = False if "Log Trigger" in configuration: - self.activityLogger.debug(" Log Trigger: " + str(configuration["Log Trigger"])) + self.activityLogger.debug( + " Log Trigger: " + str(configuration["Log Trigger"]) + ) self.logTrigger = str(configuration["Log Trigger"]) if "Calculate HP" in configuration: @@ -137,29 +142,49 @@ def __init__( if str(configuration["Calculate HP"]["Type"]).lower() == "none": self.activityLogger.debug(" Calculate HP: None") self.calcHP = 0 - elif str(configuration["Calculate HP"]["Type"]).lower() == "reported": + elif ( + str(configuration["Calculate HP"]["Type"]).lower() + == "reported" + ): self.activityLogger.debug(" Calculate HP: Reported TQ") self.calcHP = 1 - elif str(configuration["Calculate HP"]["Type"]).lower() == "accel": - self.activityLogger.debug(" Calculate HP: Accelerometer TQ") + elif ( + str(configuration["Calculate HP"]["Type"]).lower() + == "accel" + ): + self.activityLogger.debug( + " Calculate HP: Accelerometer TQ" + ) self.calcHP = 2 - + if "Curb Weight" in configuration["Calculate HP"]: - self.curbWeight = float(configuration["Calculate HP"]["Curb Weight"]) * KG_TO_N - + self.curbWeight = ( + float(configuration["Calculate HP"]["Curb Weight"]) + * KG_TO_N + ) + if "Tire Circumference" in configuration["Calculate HP"]: - self.tireCircumference = float(configuration["Calculate HP"]["Tire Circumference"]) * PI + self.tireCircumference = ( + float(configuration["Calculate HP"]["Tire Circumference"]) + * PI + ) if "Frontal Area" in configuration["Calculate HP"]: - self.frontalArea = float(configuration["Calculate HP"]["Frontal Area"]) + self.frontalArea = float( + configuration["Calculate HP"]["Frontal Area"] + ) if "Coefficient Of Drag" in configuration["Calculate HP"]: - self.coefficientOfDrag = float(configuration["Calculate HP"]["Coefficient Of Drag"]) + self.coefficientOfDrag = float( + configuration["Calculate HP"]["Coefficient Of Drag"] + ) for g in range(1, 8): - gearString = "Gear " + str(g) - if gearString in configuration["Calculate HP"]: - self.gearRatios[0] = float(configuration["Calculate HP"][gearString]) + gearString = "Gear " + str(g) + if gearString in configuration["Calculate HP"]: + self.gearRatios[0] = float( + configuration["Calculate HP"][gearString] + ) logType = "Mode" + logType if logType in configuration: @@ -184,7 +209,7 @@ def __init__( self.activityLogger.info("Interactive mode: " + str(self.interactive)) self.activityLogger.info("Display Gauges: " + str(self.displayGauges)) self.activityLogger.info("Log Trigger: " + str(self.logTrigger)) - + if fps < 1: self.delay = 0.0 self.activityLogger.info("Max frame rate: unlimited") @@ -200,7 +225,7 @@ def __init__( self.activityLogger.info("Calculate HP: Reported TQ") elif self.calcHP == 2: self.activityLogger.info("Calculate HP: Accelerometer TQ") - + # open params file self.PARAMFILE = self.filePath + param_file self.activityLogger.info("Parameter file: " + self.PARAMFILE) @@ -221,7 +246,9 @@ def __init__( self.logParams[pid_counter]["Name"] = param["Name"] self.logParams[pid_counter]["Address"] = param["Address"] self.logParams[pid_counter]["Length"] = int(param["Length"]) - self.logParams[pid_counter]["Equation"] = param["Equation"].lower() + self.logParams[pid_counter]["Equation"] = param[ + "Equation" + ].lower() self.logParams[pid_counter]["Signed"] = ( param["Signed"].lower() == "true" ) @@ -246,8 +273,10 @@ def __init__( ): valid = True for ch in assignTo: - if ch != '_' and (ch < 'a' or ch > 'z'): - self.activityLogger.warning("Invalid Assignment: " + assignTo) + if ch != "_" and (ch < "a" or ch > "z"): + self.activityLogger.warning( + "Invalid Assignment: " + assignTo + ) valid = false break @@ -286,7 +315,7 @@ def __init__( self.activityLogger.info("PID count: " + str(pid_counter)) self.activityLogger.info("Assignment count: " + str(assignment_counter)) - + self.activityLogger.info("CSV Header for log files will be: " + self.csvHeader) # If we're only going to be writing to a single CSV file, create that file and put the header in it @@ -419,7 +448,9 @@ def main(self, client=None, callback=None): self.drawGauges() if self.callbackFunction: - self.callbackFunction(logger_status="Logger Running", dataStream=self.dataStream) + self.callbackFunction( + logger_status="Logger Running", dataStream=self.dataStream + ) time.sleep(0.2) @@ -458,8 +489,10 @@ def checkLogging(self): if assignmentPID is not None: value = self.logParams[assignmentPID]["Value"] compare = subEquation[comparePos] - compareValue = float(subEquation[comparePos+1:].strip()) - + compareValue = float( + subEquation[comparePos + 1 :].strip() + ) + if compare == ">": if value <= compareValue: subConditionsMet = False @@ -622,27 +655,34 @@ def getParamsHSL(self): for parameter in self.logParams: if results == "": break - + if self.logParams[parameter]["Virtual"]: self.setPIDValue(parameter, self.logParams[parameter]["Value"]) else: - #get current data and remove it from the results + # get current data and remove it from the results val = results[: self.logParams[parameter]["Length"] * 2] results = results[self.logParams[parameter]["Length"] * 2 :] self.activityLogger.debug(str(parameter) + " raw from ecu: " + str(val)) - #get raw value - rawval = int.from_bytes(bytearray.fromhex(val),"little", - signed=self.logParams[parameter]["Signed"]) + # get raw value + rawval = int.from_bytes( + bytearray.fromhex(val), + "little", + signed=self.logParams[parameter]["Signed"], + ) if self.logParams[parameter]["Length"] == 4: rawval = struct.unpack("f", int(rawval).to_bytes(4, "little"))[0] - #set pid value - self.activityLogger.debug(str(parameter) + " pre-function: " + str(rawval)) + # set pid value + self.activityLogger.debug( + str(parameter) + " pre-function: " + str(rawval) + ) self.setPIDValue(parameter, rawval) - self.activityLogger.debug(str(parameter) + " scaling applied: " + str(val)) + self.activityLogger.debug( + str(parameter) + " scaling applied: " + str(val) + ) - #fill stream and log with current value + # fill stream and log with current value self.dataStreamBuffer[parameter] = { "Name": self.logParams[parameter]["Name"], "Value": str(self.logParams[parameter]["Value"]), @@ -692,7 +732,7 @@ def reqParams22(self, parameterString): else: results = "" - #clear datastream and csv row + # clear datastream and csv row def clearDataStream(self): self.dataStreamBuffer = {} self.dataStreamBuffer["Time"] = { @@ -707,7 +747,7 @@ def clearDataStream(self): def getParams22(self): self.activityLogger.debug("Getting values via 0x22") - + parameterPosition = 0 parameterString = "22" for parameter in self.logParams: @@ -720,12 +760,14 @@ def getParams22(self): else: self.reqParams22(parameterString) parameterPosition = 1 - parameterString = "22" + self.logParams[parameter]["Address"].lstrip("0x") + parameterString = "22" + self.logParams[parameter][ + "Address" + ].lstrip("0x") if parameterPosition > 0: self.reqParams22(parameterString) - #fill stream and log with current values + # fill stream and log with current values row = self.clearDataStream() for parameter in self.logParams: self.dataStreamBuffer[parameter] = { @@ -741,34 +783,58 @@ def calcTQ(self): try: gearValue = int(self.logParams[self.assignments["gear"]]["Raw"]) if gearValue in range(1, 8): - ms2Value = sqrt((self.logParams[self.assignments["accel_long"]]["Raw"] - 512.0) / 32.0) - ratioValue = sqrt(self.gearRatios[gearValue - 1] * self.gearFinal) - velValue = self.logParams[self.assignments["speed"]]["Raw"] / 100.0 - rpmValue = self.logParams[self.assignments["rpm"]]["Raw"] - dragAirValue = velValue ** 3 * 0.00001564 * self.coefficientOfDrag * self.frontalArea - dragRollValue = velValue * self.curbWeight * 0.00000464 - dragValue = (dragAirValue + dragRollValue) / rpmValue * 7127.0 - self.assignmentValues["tq"] = (self.curbWeight * ms2Value / ratioValue / self.tireCircumference / TQ_CONSTANT) + dragValue - self.assignmentValues["hp"] = self.assignmentValues["tq"] * rpmValue / 7127.0 + ms2Value = sqrt( + (self.logParams[self.assignments["accel_long"]]["Raw"] - 512.0) + / 32.0 + ) + ratioValue = sqrt(self.gearRatios[gearValue - 1] * self.gearFinal) + velValue = self.logParams[self.assignments["speed"]]["Raw"] / 100.0 + rpmValue = self.logParams[self.assignments["rpm"]]["Raw"] + dragAirValue = ( + velValue**3 + * 0.00001564 + * self.coefficientOfDrag + * self.frontalArea + ) + dragRollValue = velValue * self.curbWeight * 0.00000464 + dragValue = (dragAirValue + dragRollValue) / rpmValue * 7127.0 + self.assignmentValues["tq"] = ( + self.curbWeight + * ms2Value + / ratioValue + / self.tireCircumference + / TQ_CONSTANT + ) + dragValue + self.assignmentValues["hp"] = ( + self.assignmentValues["tq"] * rpmValue / 7127.0 + ) except: self.assignmentValues["tq"] = 0.0 self.assignmentValues["hp"] = 0.0 elif self.calcHP == 1: try: if self.mode == "22": - self.assignmentValues["tq"] = self.logParams[self.assignments["tq_rep"]]["Raw"] / 10.0 + self.assignmentValues["tq"] = ( + self.logParams[self.assignments["tq_rep"]]["Raw"] / 10.0 + ) else: - self.assignmentValues["tq"] = self.logParams[self.assignments["tq_rep"]]["Raw"] / 32.0 + self.assignmentValues["tq"] = ( + self.logParams[self.assignments["tq_rep"]]["Raw"] / 32.0 + ) - self.assignmentValues["hp"] = self.assignmentValues["tq"] * rpmValue / 7127.0 + self.assignmentValues["hp"] = ( + self.assignmentValues["tq"] * rpmValue / 7127.0 + ) except: self.assignmentValues["tq"] = 0.0 self.assignmentValues["hp"] = 0.0 def setAssignmentValues(self): for assign in self.assignments: - self.assignmentValues[assign] = self.logParams[self.assignments[assign]]["Value"] - + self.assignmentValues[assign] = self.logParams[self.assignments[assign]][ + "Value" + ] + def setPIDValue(self, parameter, raw): try: self.assignmentValues["x"] = raw diff --git a/setup.py b/setup.py index 851c558..6bb1551 100644 --- a/setup.py +++ b/setup.py @@ -1,6 +1,4 @@ from distutils.core import setup -import py2exe -import lib data_files = [ ("lib/lzss", ["lib/lzss/lzss.exe"]),