public bool DisassembleFile(IECUFile m_trionicFile, string inputfile, string outputfile/*, long startaddress*/, SymbolCollection symbols)
        {
            // recursive method when jsr was found
            mnemonics = new MNemonicCollection();
            labels = new MNemonicCollection();

            /*labels = */findLabels(m_trionicFile, inputfile);

            _passOne = false;

            uint i, t, seg, adr;
            long addr, endaddr, adrcntr, trgaddr, trgaddr1, trgaddr2, trgaddr3, offaddr;

            byte ch1, ch2, ch3, ch4, ch5, ch6, ch7, ch8, ch9, ch10;
            //byte n1, n2, n3, n4;
            //uint infile = 0, outfile = 0,
            uint addoff = 0;
            string inname, outname, offsetval;
            //byte inname[80], outname[80], offsetval[40];
            //byte str[80],cmd[80];
            string str, cmd;
            str = string.Empty;
            for (int temp = 0; temp < 8; temp++)
            {
                A_reg.SetValue(0, temp);
                D_reg.SetValue(0, temp);
            }
            m_symbols = symbols;
            swap = 0;
            addr = offaddr = 0;

            inname = inputfile;
            //infile = 1;
            //            outname = outputfile;
            //outfile = 1;
            //addr = startaddress;
            /********************* DISASSEMBLY STARTS HERE *********************/
            /* Read all the preceding words first */
            adrcntr = 0L;
            //StreamWriter sw = new StreamWriter(outname, false);
            FileStream fsbr = new FileStream(inname, FileMode.Open, FileAccess.Read);
            if (fsbr == null) return false;
            BinaryReader br = new BinaryReader(fsbr);
            if (br == null)
            {
                fsbr.Close();
                //sw.Close();
                return false;
            }
            //fsbr.Position = addr;
            adrcntr = addr;
            // iterate through all functions
            // first get all the pointers to work from
            func_count = 0;
            FileInfo fi = new FileInfo(inputfile);
            CastProgressEvent("Starting disassembly", 0, ProgressType.DisassemblingVectors);
            for (int vec = 1; vec <= 127; vec++)
            {
                int percentage = (vec * 100) / 127;
                CastProgressEvent("Disassembling vectors", percentage, ProgressType.DisassemblingVectors);
                long vector = m_trionicFile.GetStartVectorAddress(inputfile, vec);

                long len = fi.Length;
                if (len == 0x20000) len = 0x60000;

                if (vector != 0 && vector < len * 2)
                {
                    //Console.WriteLine("Vector: " + vec.ToString() + " addr: " + vector.ToString("X8"));
                    try
                    {
                        DisassembleFunction(vector, symbols, fsbr, br, len);
                    }
                    catch (Exception E)
                    {
                        Console.WriteLine("Failed to handle vector: " + E.Message);
                    }
                }
            }

            CastProgressEvent("Translating vector labels", 0, ProgressType.TranslatingVectors);
            //Console.WriteLine("Translating vector labels");
            long[] vectors = m_trionicFile.GetVectorAddresses(m_trionicFile.GetFileInfo().Filename);
            int lblcount = 0;
            foreach (MNemonicHelper label in labels)
            {
                int percentage = (lblcount++ * 100) / labels.Count;
                CastProgressEvent("Translating vector labels", percentage, ProgressType.TranslatingVectors);
                for (i = 0; i < 128; i++)
                {
                    if (label.Address == /*m_trionicFile.GetStartVectorAddress(m_trionicFileInformation.Filename, i)*/ Convert.ToInt64(vectors.GetValue(i)))
                    {
                        switch (i)
                        {
                            case 1:
                                label.Mnemonic = "INIT_PROGRAM:";
                                break;
                            case 2:
                                label.Mnemonic = "BUS_ERROR:";
                                break;
                            case 3:
                                label.Mnemonic = "ADDRESS_ERROR:";
                                break;
                            case 4:
                                label.Mnemonic = "ILLEGAL_INSTRUCTION:";
                                break;
                            case 5:
                                label.Mnemonic = "DIVIDE_BY_ZERO:";
                                break;
                            case 6:
                                label.Mnemonic = "CHK12_INSTR:";
                                break;
                            case 7:
                                label.Mnemonic = "TRAPx_INSTR:";
                                break;
                            case 8:
                                label.Mnemonic = "PRIV_VIOLATION:";
                                break;
                            case 9:
                                label.Mnemonic = "TRACE:";
                                break;
                            case 10:
                                label.Mnemonic = "L1010_EMUL:";
                                break;
                            case 11:
                                label.Mnemonic = "L1111_EMUL:";
                                break;
                            case 12:
                                label.Mnemonic = "HW_BREAKPOINT:";
                                break;
                            case 13:
                                label.Mnemonic = "RESERVED:";
                                break;
                            case 14:
                                label.Mnemonic = "FMT_ERR1:";
                                break;
                            case 15:
                            case 16:
                            case 17:
                            case 18:
                            case 19:
                            case 20:
                            case 21:
                            case 22:
                                label.Mnemonic = "UNASSIGNED:";
                                break;
                            case 23:
                                label.Mnemonic = "FFFFFFFF:";
                                break;
                            case 24:
                                label.Mnemonic = "SPURIOUS_INTERRUPT:";
                                break;
                            case 25:
                                label.Mnemonic = "LEVEL1_INTERUPT_AUTOVECTOR:";
                                break;
                            case 26:
                                label.Mnemonic = "LEVEL2_INTERUPT_AUTOVECTOR:";
                                break;
                            case 27:
                                label.Mnemonic = "LEVEL3_INTERUPT_AUTOVECTOR:";
                                break;
                            case 28:
                                label.Mnemonic = "LEVEL4_INTERUPT_AUTOVECTOR:";
                                break;
                            case 29:
                                label.Mnemonic = "LEVEL5_INTERUPT_AUTOVECTOR:";
                                break;
                            case 30:
                                label.Mnemonic = "LEVEL6_INTERUPT_AUTOVECTOR:";
                                break;
                            case 31:
                                label.Mnemonic = "LEVEL7_INTERUPT_AUTOVECTOR:";
                                break;
                            case 32:
                                label.Mnemonic = "TAP0_INSTRUCTION_VECTOR:";
                                break;
                            case 33:
                                label.Mnemonic = "TAP1_INSTRUCTION_VECTOR:";
                                break;
                            case 34:
                                label.Mnemonic = "TAP2_INSTRUCTION_VECTOR:";
                                break;
                            case 35:
                                label.Mnemonic = "TAP3_INSTRUCTION_VECTOR:";
                                break;
                            case 36:
                                label.Mnemonic = "TAP4_INSTRUCTION_VECTOR:";
                                break;
                            case 37:
                                label.Mnemonic = "TAP5_INSTRUCTION_VECTOR:";
                                break;
                            case 38:
                                label.Mnemonic = "TAP6_INSTRUCTION_VECTOR:";
                                break;
                            case 39:
                                label.Mnemonic = "TAP7_INSTRUCTION_VECTOR:";
                                break;
                            case 40:
                                label.Mnemonic = "TAP8_INSTRUCTION_VECTOR:";
                                break;
                            case 41:
                                label.Mnemonic = "TAP9_INSTRUCTION_VECTOR:";
                                break;
                            case 42:
                                label.Mnemonic = "TAP10_INSTRUCTION_VECTOR:";
                                break;
                            case 43:
                                label.Mnemonic = "TAP11_INSTRUCTION_VECTOR:";
                                break;
                            case 44:
                                label.Mnemonic = "TAP12_INSTRUCTION_VECTOR:";
                                break;
                            case 45:
                                label.Mnemonic = "TAP13_INSTRUCTION_VECTOR:";
                                break;
                            case 46:
                                label.Mnemonic = "TAP14_INSTRUCTION_VECTOR:";
                                break;
                            case 47:
                                label.Mnemonic = "TAP15_INSTRUCTION_VECTOR:";
                                break;
                            default:
                                label.Mnemonic = "VECTOR_" + i.ToString() + ":";
                                break;
                        }

                        break;
                    }
                }
            }
            /*
            Console.WriteLine("Translating known functions");
            CastProgressEvent("Translating known functions", 0, ProgressType.TranslatingLabels);
            lblcount = 0;
            foreach (MNemonicHelper label in labels)
            {
                int percentage = (lblcount++ * 100) / labels.Count;
                CastProgressEvent("Translating known functions", percentage, ProgressType.TranslatingLabels);
                foreach (MNemonicHelper mnemonic in mnemonics)
                {
                    if (mnemonic.Mnemonic.Contains("JSR") && mnemonic.Mnemonic.Contains(label.Address.ToString("X8")))
                    {
                        mnemonic.Mnemonic = mnemonic.Mnemonic.Replace(label.Address.ToString("X8"), label.Mnemonic.Replace(":", ""));
                        //    break;
                    }
                    else if (mnemonic.Mnemonic.Contains("BEQ") && mnemonic.Mnemonic.Contains(label.Address.ToString("X8")))
                    {
                        mnemonic.Mnemonic = mnemonic.Mnemonic.Replace(label.Address.ToString("X8"), label.Mnemonic.Replace(":", ""));
                    }
                    else if (mnemonic.Mnemonic.Contains("BRA") && mnemonic.Mnemonic.Contains(label.Address.ToString("X8")))
                    {
                        mnemonic.Mnemonic = mnemonic.Mnemonic.Replace(label.Address.ToString("X8"), label.Mnemonic.Replace(":", ""));
                    }
                    else if (mnemonic.Mnemonic.Contains("BLS") && mnemonic.Mnemonic.Contains(label.Address.ToString("X8")))
                    {
                        mnemonic.Mnemonic = mnemonic.Mnemonic.Replace(label.Address.ToString("X8"), label.Mnemonic.Replace(":", ""));
                    }
                    else if (mnemonic.Mnemonic.Contains("BNE") && mnemonic.Mnemonic.Contains(label.Address.ToString("X8")))
                    {
                        mnemonic.Mnemonic = mnemonic.Mnemonic.Replace(label.Address.ToString("X8"), label.Mnemonic.Replace(":", ""));
                    }
                    else if (mnemonic.Mnemonic.Contains("BHI") && mnemonic.Mnemonic.Contains(label.Address.ToString("X8")))
                    {
                        mnemonic.Mnemonic = mnemonic.Mnemonic.Replace(label.Address.ToString("X8"), label.Mnemonic.Replace(":", ""));
                    }
                    else if (mnemonic.Mnemonic.Contains("BCS") && mnemonic.Mnemonic.Contains(label.Address.ToString("X8")))
                    {
                        mnemonic.Mnemonic = mnemonic.Mnemonic.Replace(label.Address.ToString("X8"), label.Mnemonic.Replace(":", ""));
                    }
                    else if (mnemonic.Mnemonic.Contains("BCC") && mnemonic.Mnemonic.Contains(label.Address.ToString("X8")))
                    {
                        mnemonic.Mnemonic = mnemonic.Mnemonic.Replace(label.Address.ToString("X8"), label.Mnemonic.Replace(":", ""));
                    }
                    else if (mnemonic.Mnemonic.Contains("BGE") && mnemonic.Mnemonic.Contains(label.Address.ToString("X8")))
                    {
                        mnemonic.Mnemonic = mnemonic.Mnemonic.Replace(label.Address.ToString("X8"), label.Mnemonic.Replace(":", ""));
                    }
                    else if (mnemonic.Mnemonic.Contains("BLT") && mnemonic.Mnemonic.Contains(label.Address.ToString("X8")))
                    {
                        mnemonic.Mnemonic = mnemonic.Mnemonic.Replace(label.Address.ToString("X8"), label.Mnemonic.Replace(":", ""));
                    }
                    else if (mnemonic.Mnemonic.Contains("BGT") && mnemonic.Mnemonic.Contains(label.Address.ToString("X8")))
                    {
                        mnemonic.Mnemonic = mnemonic.Mnemonic.Replace(label.Address.ToString("X8"), label.Mnemonic.Replace(":", ""));
                    }
                    else if (mnemonic.Mnemonic.Contains("BLE") && mnemonic.Mnemonic.Contains(label.Address.ToString("X8")))
                    {
                        mnemonic.Mnemonic = mnemonic.Mnemonic.Replace(label.Address.ToString("X8"), label.Mnemonic.Replace(":", ""));
                    }
                }
            }*/
            CastProgressEvent("Adding labels", 0, ProgressType.AddingLabels);
            //Console.WriteLine("Adding labels");
            lblcount = 0;
            foreach (MNemonicHelper label in labels)
            {
                int percentage = (lblcount++ * 100) / labels.Count;
                CastProgressEvent("Adding labels", percentage, ProgressType.AddingLabels);

                label.Address--; // for sequencing
                mnemonics.Add(label);
            }

            //Console.WriteLine("Sorting data");
            CastProgressEvent("Sorting mnemonics", 0, ProgressType.SortingData);
            mnemonics.SortColumn = "Address";
            mnemonics.SortingOrder = Trionic5Controls.GenericComparer.SortOrder.Ascending;
            mnemonics.Sort();
            CastProgressEvent("Sorting mnemonics", 100, ProgressType.SortingData);
            return true;
        }
Exemple #2
0
        public override void LoadSymbol(string symbolname, IECUFile trionic_file)
        {
            // autonomous
            m_trionic_file = trionic_file;
            m_trionic_file.LibraryPath = Application.StartupPath + "\\Binaries";
            this.IsUpsideDown = true; // always?
            foreach (SymbolHelper sh in m_trionic_file.GetFileInfo().SymbolCollection)
            {
                if (sh.Varname == symbolname)
                {
                    // get data from it
                    IECUFile file = new Trionic5File();
                    file.LibraryPath = Application.StartupPath + "\\Binaries";
                    file.SetAutoUpdateChecksum(m_autoUpdateChecksum);
                    file.SelectFile(m_trionic_file.GetFileInfo().Filename);
                    byte[] symboldata = file.ReadData((uint)sh.Flash_start_address, (uint)sh.Length);
                    //byte[] symboldata = file.readdatafromfile(m_trionic_file.GetFileInfo().Filename, sh.Flash_start_address, sh.Length);
                    this.Map_content = symboldata;
                    this.Map_length = symboldata.Length;
                    this.Filename = m_trionic_file.GetFileInfo().Filename;
                    if (m_trionic_file.IsTableSixteenBits(symbolname))
                    {
                        //this.Map_length /= 2;
                    }
                    this.Map_name = symbolname;
                    this.Correction_factor = m_trionic_file.GetCorrectionFactorForMap(symbolname);
                    this.correction_offset = m_trionic_file.GetOffsetForMap(symbolname);
                    this.SetViewSize(ViewSize.NormalView);
                    //this.Viewtype = Trionic5Tools.ViewType.Easy;
                    // set axis information
                    SymbolAxesTranslator sat = new SymbolAxesTranslator();
                    sat.GetXaxisSymbol(symbolname);
                    sat.GetYaxisSymbol(symbolname);
                    this.X_axisvalues = m_trionic_file.GetMapXaxisValues(symbolname);
                    this.Y_axisvalues = m_trionic_file.GetMapYaxisValues(symbolname);
                    string x = string.Empty;
                    string y = string.Empty;
                    string z = string.Empty;

                    m_trionic_file.GetMapAxisDescriptions(symbolname, out x, out y, out z);

                    this.X_axis_name = x;
                    this.Y_axis_name = y;
                    this.Z_axis_name = z;
                    int columns = 1;
                    int rows = 1;
                    m_trionic_file.GetMapMatrixWitdhByName(symbolname, out columns, out rows);
                    this.ShowTable(columns, m_trionic_file.IsTableSixteenBits(symbolname));

                    break;
                }
            }
            
        }
        public TuningResult TuneFileToStage(int stage, string filename, IECUFile m_TrionicFile, IECUFileInformation trionicFileInformation, bool SilentMode)
        {
            //<COPY FROM HERE>
            m_fileInformation = trionicFileInformation;
            m_resume = new Trionic5Resume();
            TuningResult retval = TuningResult.TuningFailed;
            string enginetp = readenginetype(filename);
            string partnumber = readpartnumber(filename);
            PartNumberConverter pnc = new PartNumberConverter();
            ECUInformation ecuinfo = pnc.GetECUInfo(partnumber, enginetp);
            bool isLpt = false;
            if (ReadTunedToStageMarker(filename) > 0 && !SilentMode)
            {
                retval = TuningResult.TuningFailedAlreadyTuned;
            }
            else if (ReadThreeBarConversionMarker(filename) > 0 && !SilentMode)
            {
                retval = TuningResult.TuningFailedThreebarSensor;
            }
            else if (SilentMode)
            {
                Trionic5Properties t5p = m_TrionicFile.GetTrionicProperties();
                if (stage == 1)
                {
                    TuneToStage(filename, stage, ecuinfo.Stage1boost, 0.72, 1.54, 0.62, ecuinfo.Stage1boost, 90, isLpt, t5p.TurboType, t5p.InjectorType, t5p.MapSensorType);
                    retval = TuningResult.TuningSuccess;
                }
                else if (stage == 2)
                {
                    TuneToStage(filename, stage, ecuinfo.Stage2boost, 0.72, 1.54, 0.62, ecuinfo.Stage2boost, 90, isLpt, t5p.TurboType, t5p.InjectorType, t5p.MapSensorType);
                    retval = TuningResult.TuningSuccess;
                }
                else if (stage == 3)
                {
                    TuneToStage(filename, stage, ecuinfo.Stage3boost, 0.72, 1.54, 0.62, ecuinfo.Stage3boost, 90, isLpt, t5p.TurboType, t5p.InjectorType, t5p.MapSensorType);
                    retval = TuningResult.TuningSuccess;
                }
            }
            else
            {
                Trionic5Properties t5p = m_TrionicFile.GetTrionicProperties();
                string msg = string.Empty;
                if (ecuinfo.Valid)
                {
                    msg = "Tuning your: " + ecuinfo.Bhp.ToString() + " bhp ";
                    msg += ecuinfo.Carmodel.ToString() + " (" + ecuinfo.Enginetype.ToString() + ") ";
                    if (ecuinfo.Is2point3liter) msg += " 2.3 liter ";
                    else msg += " 2.0 liter ";
                    if (ecuinfo.Isaero)
                    {
                        t5p.TurboType = TurboType.TD0415T;
                        msg += " Aero binary";
                    }
                    else if (ecuinfo.Isfpt) msg += " Full pressure turbo binary";
                    else if (ecuinfo.Isturbo)
                    {
                        msg += " Low pressure turbo, you'll have to modify hardware (solenoid valve, hoses etc.) to get this working!";
                        isLpt = true;
                    }
                    else msg += " non turbo car to stage, you'll have to modify hardware to get this working!";
                }
                else
                {
                    msg = "Partnumber not recognized, tuning will continue anyway, please verify settings afterwards";
                }
                PSTaskDialog.cTaskDialog.ForceEmulationMode = false;
                PSTaskDialog.cTaskDialog.EmulatedFormWidth = 600;
                PSTaskDialog.cTaskDialog.UseToolWindowOnXP = false;
                PSTaskDialog.cTaskDialog.VerificationChecked = true;
                string stageDescription = ConvertToStageDescription(stage);
                PSTaskDialog.cTaskDialog.ShowTaskDialogBox("Tune me up™ to stage " + stageDescription + " wizard", "This wizard will tune your binary to a stage " + stageDescription + " equivalent.", "Boost request map, fuel injection and ignition tables will be altered" + Environment.NewLine + msg, "Happy driving!!!\nDilemma © 2009", "The author does not take responsibility for any damage done to your car or other objects in any form!", "Show me a summary after tuning", "", "Yes, tune me to stage " + stageDescription + "|No thanks!", PSTaskDialog.eTaskDialogButtons.None, PSTaskDialog.eSysIcons.Information, PSTaskDialog.eSysIcons.Warning);
                switch (PSTaskDialog.cTaskDialog.CommandButtonResult)
                {
                    case 0:
                        // tune to stage 1
                        if (stage == 1)
                        {
                            TuneToStage(filename, stage, ecuinfo.Stage1boost, 0.72, 1.54, 0.62, ecuinfo.Stage1boost, 90, isLpt, t5p.TurboType, t5p.InjectorType, t5p.MapSensorType);
                        }
                        else if (stage == 2)
                        {
                            TuneToStage(filename, stage, ecuinfo.Stage2boost, 0.72, 1.54, 0.62, ecuinfo.Stage2boost, 90, isLpt, t5p.TurboType, t5p.InjectorType, t5p.MapSensorType);
                        }
                        else if (stage == 3)
                        {
                            TuneToStage(filename, stage, ecuinfo.Stage3boost, 0.72, 1.54, 0.62, ecuinfo.Stage3boost, 90, isLpt, t5p.TurboType, t5p.InjectorType, t5p.MapSensorType);
                        }
                        else if (stage == 99) // stage X
                        {
                            // get parameters from user:
                            // max boost, turbo type, injector type, rpm limit etc etc
                            frmTuningSettings tunset = new frmTuningSettings();
                            tunset.Turbo = t5p.TurboType;
                            tunset.Injectors = t5p.InjectorType;
                            tunset.MapSensor = t5p.MapSensorType;
                            if (t5p.MapSensorType != MapSensorType.MapSensor25)
                            {
                                // set max boost etc
                                //tunset.PeakBoost = 1.75;
                                //tunset.BoostFuelcut = 2.05;
                            }
                            if (tunset.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                            {
                                // write details to the file

                                if (t5p.MapSensorType != tunset.MapSensor)
                                {
                                    ConvertFileToThreeBarMapSensor(m_fileInformation, t5p.MapSensorType, tunset.MapSensor);
                                }
                                // check injector type
                                if (t5p.InjectorType != tunset.Injectors)
                                {
                                    int inj_konst_diff = DetermineDifferenceInInjectorConstant(t5p.InjectorType, tunset.Injectors);
                                    AddToInjectorConstant(filename, inj_konst_diff);
                                    // roughly set inj_konst
                                    // Stock = 21
                                    // Green giants = 20 (minus 1)
                                    // Siemens 630 = 16 (minus 5)
                                    // Siemens 875 = 13 (minus 8)
                                    // Siemens 1000 = 10 (minus 11)

                                    // set battery correction voltage maps

                                    SetInjectorBatteryCorrectionMap(m_TrionicFile, tunset.Injectors);
                                }
                                t5p.TurboType = tunset.Turbo;
                                t5p.InjectorType = tunset.Injectors;
                                t5p.MapSensorType = tunset.MapSensor;
                                // determine stage??
                                if (tunset.PeakBoost < 1.2) stage = 1;
                                else if (tunset.PeakBoost < 1.3) stage = 2;
                                else if (tunset.PeakBoost < 1.4) stage = 3;
                                else if (tunset.PeakBoost < 1.5) stage = 4;
                                else if (tunset.PeakBoost < 1.6) stage = 5;
                                else if (tunset.PeakBoost < 1.7) stage = 6;
                                else if (tunset.PeakBoost < 1.8) stage = 7;
                                else if (tunset.PeakBoost < 1.9) stage = 8;
                                else stage = 9;
                                if (tunset.MapSensor == MapSensorType.MapSensor30)
                                {
                                    // set correct values

                                    double conversion = CalculateConversionFactor(MapSensorType.MapSensor25, tunset.MapSensor);
                                    tunset.PeakBoost = (((((tunset.PeakBoost + 1) * 100) / conversion) / 100) - 1);
                                    tunset.BoostFirstGear = (((((tunset.BoostFirstGear + 1) * 100) / conversion) / 100) - 1);
                                    tunset.BoostSecondGear = (((((tunset.BoostSecondGear + 1) * 100) / conversion) / 100) - 1);
                                    tunset.BoostFuelcut = (((((tunset.BoostFuelcut + 1) * 100) / conversion) / 100) - 1);
                                }
                                else if (tunset.MapSensor == MapSensorType.MapSensor35)
                                {
                                    // set correct values
                                    double conversion = CalculateConversionFactor(MapSensorType.MapSensor25, tunset.MapSensor);
                                    tunset.PeakBoost = (((((tunset.PeakBoost + 1) * 100) / conversion) / 100) - 1);
                                    tunset.BoostFirstGear = (((((tunset.BoostFirstGear + 1) * 100) / conversion) / 100) - 1);
                                    tunset.BoostSecondGear = (((((tunset.BoostSecondGear + 1) * 100) / conversion) / 100) - 1);
                                    tunset.BoostFuelcut = (((((tunset.BoostFuelcut + 1) * 100) / conversion) / 100) - 1);
                                }
                                else if (tunset.MapSensor == MapSensorType.MapSensor40)
                                {
                                    // set correct values
                                    double conversion = CalculateConversionFactor(MapSensorType.MapSensor25, tunset.MapSensor);
                                    tunset.PeakBoost = (((((tunset.PeakBoost + 1) * 100) / conversion) / 100) - 1);
                                    tunset.BoostFirstGear = (((((tunset.BoostFirstGear + 1) * 100) / conversion) / 100) - 1);
                                    tunset.BoostSecondGear = (((((tunset.BoostSecondGear + 1) * 100) / conversion) / 100) - 1);
                                    tunset.BoostFuelcut = (((((tunset.BoostFuelcut + 1) * 100) / conversion) / 100) - 1);
                                }
                                else if (tunset.MapSensor == MapSensorType.MapSensor50)
                                {
                                    // set correct values
                                    double conversion = CalculateConversionFactor(MapSensorType.MapSensor25, tunset.MapSensor);
                                    tunset.PeakBoost = (((((tunset.PeakBoost + 1) * 100) / conversion) / 100) - 1);
                                    tunset.BoostFirstGear = (((((tunset.BoostFirstGear + 1) * 100) / conversion) / 100) - 1);
                                    tunset.BoostSecondGear = (((((tunset.BoostSecondGear + 1) * 100) / conversion) / 100) - 1);
                                    tunset.BoostFuelcut = (((((tunset.BoostFuelcut + 1) * 100) / conversion) / 100) - 1);
                                }
                                m_TrionicFile.SetTrionicOptions(t5p);
                                TuneToStage(filename, stage, tunset.PeakBoost, tunset.BoostFirstGear, tunset.BoostSecondGear, tunset.BoostFirstGear, tunset.BoostFuelcut, 90, /*isLpt*/ true, t5p.TurboType, t5p.InjectorType, t5p.MapSensorType);
                            }
                            else
                            {
                                retval = TuningResult.TuningCancelled;
                                return retval;
                            }

                        }
                        retval = TuningResult.TuningSuccess;
                        break;
                    /*                        case 1:
                                                // tune to stage 2
                                                TuneToStage(2, ecuinfo.Stage2boost, 0.72, 1.54, 0.62, 1.54, 90, isLpt);
                                                break;
                                            case 2:
                                                // tune to stage 3
                                                TuneToStage(3, ecuinfo.Stage3boost, 0.72, 1.54, 0.62, 1.54, 90, isLpt);
                                                break;*/
                    case 1:
                        // cancel
                        retval = TuningResult.TuningCancelled;
                        break;
                }
            }
            return retval;
        }
        private MNemonicCollection findLabels(IECUFile m_trionicFile, string inputfile)
        {
            _labels = new MNemonicCollection();
            uint i, t, seg, adr;
            long addr, endaddr, adrcntr, trgaddr, trgaddr1, trgaddr2, trgaddr3, offaddr;

            byte ch1, ch2, ch3, ch4, ch5, ch6, ch7, ch8, ch9, ch10;
            //byte n1, n2, n3, n4;
            //uint infile = 0, outfile = 0,
            uint addoff = 0;
            string inname, outname, offsetval;
            //byte inname[80], outname[80], offsetval[40];
            //byte str[80],cmd[80];
            string str, cmd;
            str = string.Empty;
            for (int temp = 0; temp < 8; temp++)
            {
                A_reg.SetValue(0, temp);
                D_reg.SetValue(0, temp);
            }
            swap = 0;
            addr = offaddr = 0;

            inname = inputfile;
            adrcntr = 0L;
            FileStream fsbr = new FileStream(inname, FileMode.Open, FileAccess.Read);
            if (fsbr == null) return _labels;
            BinaryReader br = new BinaryReader(fsbr);
            if (br == null)
            {
                fsbr.Close();
                return _labels;
            }
            fsbr.Position = addr;
            adrcntr = addr;
            // iterate through all functions
            // first get all the pointers to work from
            func_count = 0;
            FileInfo fi = new FileInfo(inputfile);
            CastProgressEvent("Start analyzing", 0, ProgressType.PassOne);
            for (int vec = 1; vec <= 127; vec++)
            {
                int percentage = (vec * 100) / 127;
                CastProgressEvent("Analyzing", percentage, ProgressType.PassOne);
                long vector = m_trionicFile.GetStartVectorAddress(inputfile, vec);
                long len = fi.Length;
                if (len == 0x20000) len = 0x60000;

                if (vector != 0 && vector < len * 2)
                {
                    try
                    {
                        LoadLabels(vector, fsbr, br, len);
                    }
                    catch (Exception E)
                    {
                        Console.WriteLine("Failed to handle vector: " + E.Message);
                    }
                }
            }
            Console.WriteLine("Found " + _labels.Count.ToString() + " in pass one");
            return _labels;
        }
        /* public byte[] GetBatteryCorrectionMap(float[] correctionFactors)
        {
            byte[] retval = new byte[22];
            int bcount = 0;
            for (int i = 0; i < 11; i++)
            {
                float val = GetBatteryCorrection(i) / 0.004F;
                int ival = Convert.ToInt32(val);
                byte b1 = (byte)(ival / 256);
                byte b2 = (byte)(ival - (int)b1 * 256);
                retval[bcount++] = b1;
                retval[bcount++] = b2;
            }
            return retval;

        }*/
        private void SetInjectorBatteryCorrectionMap(IECUFile m_file, InjectorType injectorType)
        {
            byte[] batt_korr_tab = new byte[22]; // 11 values, first one is for 15 volt
            float tempvalue = 0;
            switch (injectorType)
            {
                case InjectorType.Stock:
                case InjectorType.Siemens875Dekas:
                case InjectorType.Siemens1000cc:
                    batt_korr_tab.SetValue((byte)0x00, 0); // 15 volt = 0.59
                    batt_korr_tab.SetValue((byte)0x93, 1);
                    batt_korr_tab.SetValue((byte)0x00, 2); // 14 volt = 0.77
                    batt_korr_tab.SetValue((byte)0xC0, 3);
                    batt_korr_tab.SetValue((byte)0x00, 4); // 13 volt = 0.78
                    batt_korr_tab.SetValue((byte)0xC3, 5);
                    batt_korr_tab.SetValue((byte)0x00, 6); // 12 volt = 0.94
                    batt_korr_tab.SetValue((byte)0xEB, 7);
                    batt_korr_tab.SetValue((byte)0x01, 8); // 11 volt = 1.28
                    batt_korr_tab.SetValue((byte)0x40, 9);
                    batt_korr_tab.SetValue((byte)0x01, 10); // 10 volt = 1.50
                    batt_korr_tab.SetValue((byte)0x77, 11);
                    batt_korr_tab.SetValue((byte)0x01, 12); // 9 volt = 1.85
                    batt_korr_tab.SetValue((byte)0xCE, 13);
                    batt_korr_tab.SetValue((byte)0x02, 14); // 8 volt = 2.32
                    batt_korr_tab.SetValue((byte)0x44, 15);
                    batt_korr_tab.SetValue((byte)0x03, 16); // 7 volt = 3.73
                    batt_korr_tab.SetValue((byte)0xA4, 17);
                    batt_korr_tab.SetValue((byte)0x03, 18); // 6 volt = 3.73
                    batt_korr_tab.SetValue((byte)0xA4, 19);
                    batt_korr_tab.SetValue((byte)0x03, 20); // 5 volt = 3.73
                    batt_korr_tab.SetValue((byte)0xA4, 21);
                    break;
                case InjectorType.GreenGiants:
                    batt_korr_tab.SetValue((byte)0x00, 0); // 15 volt = 0.894
                    batt_korr_tab.SetValue((byte)0xDF, 1);
                    batt_korr_tab.SetValue((byte)0x00, 2); // 14 volt = 1.003
                    batt_korr_tab.SetValue((byte)0xFA, 3);
                    batt_korr_tab.SetValue((byte)0x01, 4); // 13 volt = 1.15
                    batt_korr_tab.SetValue((byte)0x1F, 5);
                    batt_korr_tab.SetValue((byte)0x01, 6); // 12 volt = 1.308
                    batt_korr_tab.SetValue((byte)0x47, 7);
                    batt_korr_tab.SetValue((byte)0x01, 8); // 11 volt = 1.521
                    batt_korr_tab.SetValue((byte)0x7C, 9);
                    batt_korr_tab.SetValue((byte)0x01, 10); // 10 volt = 1.768
                    batt_korr_tab.SetValue((byte)0xBA, 11);
                    batt_korr_tab.SetValue((byte)0x02, 12); // 9 volt = 2.102
                    batt_korr_tab.SetValue((byte)0x0D, 13);
                    batt_korr_tab.SetValue((byte)0x02, 14); // 8 volt = 2.545
                    batt_korr_tab.SetValue((byte)0x7C, 15);
                    batt_korr_tab.SetValue((byte)0x03, 16); // 7 volt = 3.216
                    batt_korr_tab.SetValue((byte)0x24, 17);
                    batt_korr_tab.SetValue((byte)0x04, 18); // 6 volt = 4.142
                    batt_korr_tab.SetValue((byte)0x0B, 19);
                    batt_korr_tab.SetValue((byte)0x05, 20); // 5 volt = 5.45
                    batt_korr_tab.SetValue((byte)0x52, 21);
                    break;
                case InjectorType.Siemens630Dekas:
                    batt_korr_tab.SetValue((byte)0x00, 0); // 15 volt = 0.33
                    batt_korr_tab.SetValue((byte)0x52, 1);
                    batt_korr_tab.SetValue((byte)0x00, 2); // 14 volt = 0.433
                    batt_korr_tab.SetValue((byte)0x6C, 3);
                    batt_korr_tab.SetValue((byte)0x00, 4); // 13 volt = 0.548
                    batt_korr_tab.SetValue((byte)0x89, 5);
                    batt_korr_tab.SetValue((byte)0x00, 6); // 12 volt = 0.673
                    batt_korr_tab.SetValue((byte)0xA8, 7);
                    batt_korr_tab.SetValue((byte)0x00, 8); // 11 volt = 0.802
                    batt_korr_tab.SetValue((byte)0xC8, 9);
                    batt_korr_tab.SetValue((byte)0x00, 10); // 10 volt = 0.974
                    batt_korr_tab.SetValue((byte)0xF3, 11);
                    batt_korr_tab.SetValue((byte)0x01, 12); // 9 volt = 1.208
                    batt_korr_tab.SetValue((byte)0x2E, 13);
                    batt_korr_tab.SetValue((byte)0x01, 14); // 8 volt = 1.524
                    batt_korr_tab.SetValue((byte)0x7D, 15);
                    batt_korr_tab.SetValue((byte)0x01, 16); // 7 volt = 2.023
                    batt_korr_tab.SetValue((byte)0xF9, 17);
                    batt_korr_tab.SetValue((byte)0x02, 18); // 6 volt = 2.74
                    batt_korr_tab.SetValue((byte)0xAD, 19);
                    batt_korr_tab.SetValue((byte)0x03, 20); // 5 volt = 3.6
                    batt_korr_tab.SetValue((byte)0x84, 21);
                    break;

            }
            // write to batt_korr_tab
            m_file.WriteData(batt_korr_tab, (uint)m_file.GetFileInfo().GetSymbolAddressFlash("Batt_korr_tab!"));
        }
        public TuningResult FreeTuneBinary(IECUFile m_File, double peakTorque, double peakBoost, bool tuneBasedOnTorque, MapSensorType mapType, TurboType turboType, InjectorType injectorType, BPCType valve, int rpmlimiter, int knockTime)
        {
            Trionic5Resume _localResume = new Trionic5Resume();
            m_fileInformation = m_File.GetFileInfo();
            string filename = m_fileInformation.Filename;
            // first set things right by running the tunetostagex wizard
            // generate a nice x_scale for ignition map (18 long)
            PressureToTorque ptt = new PressureToTorque();
            double peak_boost = ptt.CalculatePressureFromTorque(peakTorque, turboType);
            if (!tuneBasedOnTorque) peak_boost = peakBoost;
            double peak_boost_request = peak_boost;
            double correction = 1.0;
            if (mapType == MapSensorType.MapSensor30) correction = 1.2;
            if (mapType == MapSensorType.MapSensor35) correction = 1.4;
            if (mapType == MapSensorType.MapSensor40) correction = 1.6;
            if (mapType == MapSensorType.MapSensor50) correction = 2.0;
            peak_boost_request *= 100;
            peak_boost_request += 100;
            peak_boost_request /= correction;
            peak_boost_request -= 100;
            peak_boost_request /= 100;

            double min_pressure = -1;
            double max_pressure = peak_boost;

            #region preparation

            /********* start of prepare phase *********/
            string enginetp = readenginetype(filename);
            string partnumber = readpartnumber(filename);
            PartNumberConverter pnc = new PartNumberConverter();
            ECUInformation ecuinfo = pnc.GetECUInfo(partnumber, enginetp);
            bool isLpt = true;
            if (ReadTunedToStageMarker(filename) > 0)
            {
                return TuningResult.TuningFailedAlreadyTuned;
            }
            else if (ReadThreeBarConversionMarker(filename) > 0)
            {
                return TuningResult.TuningFailedThreebarSensor;
            }
            Trionic5Properties t5p = m_File.GetTrionicProperties();
            if (ecuinfo.Valid)
            {
                if (ecuinfo.Isaero || ecuinfo.Isfpt)
                {
                    isLpt = false;
                }
            }

            if (t5p.MapSensorType != mapType)
            {
                ConvertFileToThreeBarMapSensor(m_fileInformation, t5p.MapSensorType, mapType);
            }
            // check injector type
            if (t5p.InjectorType != injectorType)
            {
                int inj_konst_diff = DetermineDifferenceInInjectorConstant(t5p.InjectorType, injectorType);
                AddToInjectorConstant(filename, inj_konst_diff);
                SetInjectorBatteryCorrectionMap(m_File, injectorType); //TODO: check this function for correctness!
            }
            /*if (injectorType == InjectorType.Stock) writebyteinfile(filename, GetSymbolAddress("Inj_konst!"), 19);
            else if (injectorType == InjectorType.GreenGiants) writebyteinfile(filename, GetSymbolAddress("Inj_konst!"), 18);
            else if (injectorType == InjectorType.Siemens630Dekas) writebyteinfile(filename, GetSymbolAddress("Inj_konst!"), 15);
            else if (injectorType == InjectorType.Siemens875Dekas) writebyteinfile(filename, GetSymbolAddress("Inj_konst!"), 13);
            else if (injectorType == InjectorType.Siemens875Dekas) writebyteinfile(filename, GetSymbolAddress("Inj_konst!"), 13);*/
            t5p.TurboType = turboType;
            t5p.InjectorType = injectorType;
            t5p.MapSensorType = mapType;
            // determine stage??
            int stage = 0;
            if (peak_boost < 1.2) stage = 1;
            else if (peak_boost < 1.3) stage = 2;
            else if (peak_boost < 1.4) stage = 3;
            else if (peak_boost < 1.5) stage = 4;
            else if (peak_boost < 1.6) stage = 5;
            else if (peak_boost < 1.7) stage = 6;
            else if (peak_boost < 1.8) stage = 7;
            else if (peak_boost < 1.9) stage = 8;
            else stage = 9;

            m_File.SetTrionicOptions(t5p);
            TuneToStage(filename, stage, peak_boost_request, 0.52, 1.0, 0.52, 1.54, 90, isLpt, turboType, injectorType, mapType);
            _localResume.ResumeTuning = m_resume.ResumeTuning.Copy();
            /*********** end of prepare phase **************/

            // set limiter, bpc valve type and knock time
            SetBPCValveType(filename, valve);
            _localResume.AddToResumeTable("Set BPC driving frequencies");
            SetRPMLimiter(filename, rpmlimiter);
            _localResume.AddToResumeTable("Set RPM limiter");
            SetKnockTime(filename, knockTime);
            _localResume.AddToResumeTable("Set knock time value");

            #endregion

            // if mapsensor != stock and injectors are 630 cc or bigger
            if (mapType != MapSensorType.MapSensor25 && (injectorType == InjectorType.Siemens630Dekas || injectorType == InjectorType.Siemens875Dekas || injectorType == InjectorType.Siemens1000cc))
            {
                // now scale it
                double step = (max_pressure - min_pressure) / 17;
                double[] axisforIgnitionMap = new double[18];
                for (int i = 0; i < 18; i++)
                {
                    axisforIgnitionMap.SetValue(min_pressure + (i * step), i);
                }
                byte[] actualAxis = new byte[36];
                int j = 0;
                for (int i = 0; i < 18; i++)
                {
                    double currValue = Convert.ToDouble(axisforIgnitionMap.GetValue(i));
                    currValue *= 100;
                    currValue += 100;
                    if (mapType == MapSensorType.MapSensor30) currValue /= 1.2;
                    else if (mapType == MapSensorType.MapSensor35) currValue /= 1.4;
                    else if (mapType == MapSensorType.MapSensor40) currValue /= 1.6;
                    else if (mapType == MapSensorType.MapSensor50) currValue /= 2.0;
                    int ival = Convert.ToInt32(currValue);
                    byte v1 = (byte)(ival / 256);
                    byte v2 = (byte)(ival - (int)v1 * 256);

                    actualAxis.SetValue(v1, j++);
                    actualAxis.SetValue(v2, j++);
                }
                m_File.WriteData(actualAxis, (uint)m_File.GetFileInfo().GetSymbolAddressFlash("Ign_map_0_x_axis!"));
                _localResume.AddToResumeTable("Generated and saved new ignition map x axis");
                //Generate the ignition map based on the axis values
                GenerateAndSaveNewIgnitionMap(m_File, false);
                _localResume.AddToResumeTable("Generated and saved new ignition map");
                min_pressure = -0.8;
                step = (max_pressure - min_pressure) / 15;
                // now setup x axis for fuel map
                double[] axisforFuelMap = new double[16];
                for (int i = 0; i < 16; i++)
                {
                    axisforFuelMap.SetValue(min_pressure + (i * step), i);
                }
                byte[] actualFuelAxis = new byte[16];
                for (int i = 0; i < 16; i++)
                {
                    double currValue = Convert.ToDouble(axisforFuelMap.GetValue(i));
                    currValue *= 100;
                    currValue += 100;
                    if (mapType == MapSensorType.MapSensor30) currValue /= 1.2;
                    else if (mapType == MapSensorType.MapSensor35) currValue /= 1.4;
                    else if (mapType == MapSensorType.MapSensor40) currValue /= 1.6;
                    else if (mapType == MapSensorType.MapSensor50) currValue /= 2.0;
                    int ival = Convert.ToInt32(currValue);
                    if (ival > 255) ival = 255;
                    actualFuelAxis.SetValue((byte)ival, i);
                }
                m_File.WriteData(actualFuelAxis, (uint)m_File.GetFileInfo().GetSymbolAddressFlash("Fuel_map_xaxis!"));
                _localResume.AddToResumeTable("Generated and saved new fuel map x axis");

                //Generate the ignition map based on the axis values
                GenerateAndSaveNewFuelMap(m_File);
                _localResume.AddToResumeTable("Generated and saved new fuel map");

                min_pressure = -0.3;
                step = (max_pressure - min_pressure) / 11;
                // now setup x axis for fuel map
                double[] axisforFuelKnockMap = new double[12];
                for (int i = 0; i < 12; i++)
                {
                    axisforFuelKnockMap.SetValue(min_pressure + (i * step), i);
                }
                byte[] actualFuelKnockAxis = new byte[12];
                for (int i = 0; i < 12; i++)
                {
                    double currValue = Convert.ToDouble(axisforFuelKnockMap.GetValue(i));
                    currValue *= 100;
                    currValue += 100;
                    if (mapType == MapSensorType.MapSensor30) currValue /= 1.2;
                    else if (mapType == MapSensorType.MapSensor35) currValue /= 1.4;
                    else if (mapType == MapSensorType.MapSensor40) currValue /= 1.6;
                    else if (mapType == MapSensorType.MapSensor50) currValue /= 2.0;
                    int ival = Convert.ToInt32(currValue);
                    if (ival > 255) ival = 255;
                    actualFuelKnockAxis.SetValue((byte)ival, i);
                }
                m_File.WriteData(actualFuelKnockAxis, (uint)m_File.GetFileInfo().GetSymbolAddressFlash("Fuel_knock_xaxis!"));
                _localResume.AddToResumeTable("Generated and saved new fuel knock map x axis");

                //Generate the ignition map based on the axis values
                GenerateAndSaveNewFuelKnockMap(m_File);
                _localResume.AddToResumeTable("Generated and saved new fuel knock map");

                // mesh up a boost request map for this.. already possible
                // adjust peak boost to be scaled for the mapsensor type

                SetBoostRequestMaps(turboType, injectorType, mapType, m_File.GetFileInfo().Filename, peak_boost_request, 100, isLpt);
                _localResume.AddToResumeTable("Generated boost request maps");

            }
            m_resume.ResumeTuning = _localResume.ResumeTuning.Copy();
            return TuningResult.TuningSuccess;
        }
        public void ConvertToE85(IECUFile m_File)
        {
            m_resume = new Trionic5Resume();

            m_resume.AddToResumeTable("Start tuning for E85");
            GenerateAndSaveNewIgnitionMap(m_File, true);
            m_resume.AddToResumeTable("Generated and saved ignition map for E85 use");
            // now set fuelling enrichment
            IncreaseByteVariableWith140Percent(m_File, "Inj_konst!");
            m_resume.AddToResumeTable("Increased injector constant by 40%");
            IncreaseByteVariableWith140Percent(m_File, "Eftersta_fak!");
            IncreaseByteVariableWith140Percent(m_File, "Eftersta_fak2!");
            m_resume.AddToResumeTable("Increased afterstart factors by 40%");
            GenerateStartVevFak(m_File);
            m_resume.AddToResumeTable("Generated starting enrichment factors");
        }
 private void IncreaseByteVariableWith140Percent(IECUFile m_File, string symbol)
 {
     // read value
     byte[] data = m_File.ReadData((uint)m_File.GetFileInfo().GetSymbolAddressFlash(symbol), (uint)m_File.GetFileInfo().GetSymbolLength(symbol));
     for (int t = 0; t < data.Length; t++)
     {
         double dval = Convert.ToDouble(data[t]);
         dval *= 1.4;
         data[t] = Convert.ToByte(dval);
     }
     m_File.WriteData(data, (uint)m_File.GetFileInfo().GetSymbolAddressFlash(symbol));
 }
        private void GenerateAndSaveNewIgnitionMap(IECUFile m_File, bool runsE85)
        {
            //TODO: Implement
            // get the axis
            TuningReferenceMaps _referenceMaps = new TuningReferenceMaps();
            byte[] pressure_axis = m_File.ReadData((uint)m_File.GetFileInfo().GetSymbolAddressFlash("Ign_map_0_x_axis!"), (uint)m_File.GetFileInfo().GetSymbolLength("Ign_map_0_x_axis!"));
            byte[] rpm_axis = m_File.ReadData((uint)m_File.GetFileInfo().GetSymbolAddressFlash("Ign_map_0_y_axis!"), (uint)m_File.GetFileInfo().GetSymbolLength("Ign_map_0_y_axis!"));
            byte[] new_ignition_map = new byte[16 * 18 * 2];
            int ign_map_index = 0;
            for (int rpm_index = rpm_axis.Length-2; rpm_index >=0; rpm_index -= 2)
            {
                for (int pressure_index = 0; pressure_index < pressure_axis.Length; pressure_index += 2)
                {

                    int irpm = Convert.ToInt32(rpm_axis[rpm_index]) * 256;
                    irpm += Convert.ToInt32(rpm_axis[rpm_index+1]);
                    int ipressure = Convert.ToInt32(pressure_axis[pressure_index]) * 256;
                    ipressure += Convert.ToInt32(pressure_axis[pressure_index + 1]);
                    double correctionFactor = 1;
                    double pressure = ipressure;
                    MapSensorType mapsensor = m_File.GetMapSensorType(false);
                    if (mapsensor == MapSensorType.MapSensor30) correctionFactor = 1.2;
                    else if (mapsensor == MapSensorType.MapSensor35) correctionFactor = 1.4;
                    else if (mapsensor == MapSensorType.MapSensor40) correctionFactor = 1.6;
                    else if (mapsensor == MapSensorType.MapSensor50) correctionFactor = 2.0;
                    pressure *= correctionFactor;
                    pressure -= 100;
                    pressure /= 100;
                    double ignition_advance = _referenceMaps.GetIgnitionAdvanceForPressureRpm(pressure, (double)irpm);
                    if (runsE85) ignition_advance = _referenceMaps.GetIgnitionAdvanceE85ForPressureRpm(pressure, (double)irpm);
                    // write ignition advance into the map
                    ignition_advance *= 10; // correction factor
                    Int32 iAdvance = Convert.ToInt32(ignition_advance);
                    byte v1 = (byte)(iAdvance / 256);
                    byte v2 = (byte)(iAdvance - (int)v1 * 256);
                    //Console.WriteLine("Writing data rpmidx : " + rpm_index.ToString() + " mapidx: " + pressure_index.ToString() + " ignidx: " + ign_map_index.ToString());
                    new_ignition_map[ign_map_index++] = v1;
                    new_ignition_map[ign_map_index++] = v2;
                }
            }
            // now save the map
            m_File.WriteData(new_ignition_map, (uint)m_File.GetFileInfo().GetSymbolAddressFlash("Ign_map_0!"));
            m_File.WriteData(new_ignition_map, (uint)m_File.GetFileInfo().GetSymbolAddressFlash("Ign_map_4!")); // save as warmup map as well
        }
 private void GenerateStartVevFak(IECUFile m_File)
 {
     byte[] vev_fak = new byte[15] { 8, 12, 16, 20, 23, 32, 36, 45, 60, 104, 128, 168, 208, 254, 255 };
     m_File.WriteData(vev_fak, (uint)m_File.GetFileInfo().GetSymbolAddressFlash("Startvev_fak!"));
 }
        private void GenerateAndSaveNewFuelMap(IECUFile m_File)
        {
            TuningReferenceMaps _referenceMaps = new TuningReferenceMaps();
            byte[] pressure_axis = m_File.ReadData((uint)m_File.GetFileInfo().GetSymbolAddressFlash("Fuel_map_xaxis!"), (uint)m_File.GetFileInfo().GetSymbolLength("Fuel_map_xaxis!"));
            byte[] rpm_axis = m_File.ReadData((uint)m_File.GetFileInfo().GetSymbolAddressFlash("Fuel_map_yaxis!"), (uint)m_File.GetFileInfo().GetSymbolLength("Fuel_map_yaxis!"));
            byte[] new_fuel_map = new byte[16 * 16];
            int fuel_map_index = 0;
            for (int rpm_index = rpm_axis.Length - 2; rpm_index >= 0; rpm_index -= 2)
            {
                for (int pressure_index = 0; pressure_index < pressure_axis.Length; pressure_index ++)
                {

                    int irpm = Convert.ToInt32(rpm_axis[rpm_index]) * 256;
                    irpm += Convert.ToInt32(rpm_axis[rpm_index + 1]);
                    irpm *= 10;
                    int ipressure = Convert.ToInt32(pressure_axis[pressure_index]);
                    double correctionFactor = 1;
                    double pressure = ipressure;
                    MapSensorType mapsensor = m_File.GetMapSensorType(false);
                    if (mapsensor == MapSensorType.MapSensor30) correctionFactor = 1.2;
                    else if (mapsensor == MapSensorType.MapSensor35) correctionFactor = 1.4;
                    else if (mapsensor == MapSensorType.MapSensor40) correctionFactor = 1.6;
                    else if (mapsensor == MapSensorType.MapSensor50) correctionFactor = 2.0;
                    pressure *= correctionFactor;
                    pressure -= 100;
                    pressure /= 100;
                    double fuel_correction = _referenceMaps.FuelCorrectionForPressureRpm(pressure, (double)irpm);
                    // write ignition advance into the map
                    fuel_correction -= 0.5;
                    fuel_correction /= 0.00390625;

                    Int32 icorrection = Convert.ToInt32(fuel_correction);
                    if (icorrection > 255) icorrection = 255;
                    new_fuel_map[fuel_map_index++] = (byte)icorrection;
                }
            }
            // now save the map
            m_File.WriteData(new_fuel_map, (uint)m_File.GetFileInfo().GetSymbolAddressFlash("Insp_mat!"));
        }
Exemple #12
0
 private void RollForwardOnFile(IECUFile file2Rollback, TransactionEntry entry)
 {
     int addressToWrite = entry.SymbolAddress;
     while (addressToWrite > file2Rollback.GetFileInfo().Filelength) addressToWrite -= file2Rollback.GetFileInfo().Filelength;
     file2Rollback.WriteDataNoLog(entry.DataAfter, (uint)addressToWrite);
 }
Exemple #13
0
        private bool OpenWorkingFile(string filename)
        {
            bool retval = false;
            if (File.Exists(filename))
            {
                m_trionicFile = new Trionic5File();

                m_trionicFile.LibraryPath = Application.StartupPath + "\\Binaries";

                m_trionicFile.SetAutoUpdateChecksum(m_appSettings.AutoChecksum);

                FileInfo fi = new FileInfo(filename); //<GS-07102010> remove read only flag if possible
                try
                {
                    fi.IsReadOnly = false;
                    btnReadOnly.Caption = "File access OK";
                }
                catch (Exception E)
                {
                    Console.WriteLine("Failed to remove read only flag: " + E.Message);
                    btnReadOnly.Caption = "File is READ ONLY";
                }

                m_trionicFile.onDecodeProgress += new IECUFile.DecodeProgress(m_trionicFile_onDecodeProgress);
                m_trionicFile.onTransactionLogChanged += new IECUFile.TransactionLogChanged(m_trionicFile_onTransactionLogChanged);
                m_trionicFile.SelectFile(filename);
                //m_trionicFileInformation = m_trionicFile.ParseTrionicFile(ofd.FileName);
                m_trionicFileInformation = m_trionicFile.ParseFile();
                props = m_trionicFile.GetTrionicProperties();
                // set indicators and menu items accoring to the file that has been opened
                if (props.IsTrionic55)
                {
                    barECUType.Caption = "T5.5";
                    // enable T5.5 maps
                    EnableT55Maps(true);
                }
                else
                {
                    barECUType.Caption = "T5.2";
                    EnableT55Maps(false);
                    // disable T5.5 maps
                }
                barECUSpeed.Caption = props.CPUspeed;
                if (props.RAMlocked)
                {
                    barECULocked.Caption = "RAM locked";
                }
                else
                {
                    barECULocked.Caption = "RAM unlocked";
                }
                if (CheckFileInLibrary(props.Partnumber))
                {
                    btnCompareToOriginalFile.Enabled = true;
                }
                else
                {
                    btnCompareToOriginalFile.Enabled = false;
                }
                _ecuConnection.MapSensorType = m_trionicFile.GetMapSensorType(m_appSettings.AutoDetectMapsensorType);
                gridSymbols.DataSource = m_trionicFileInformation.SymbolCollection;
                barStaticItem2.Caption = "File: " + Path.GetFileName(m_trionicFileInformation.Filename);
                this.Text = "T5Suite Professional 2.0 [" + Path.GetFileName(m_trionicFileInformation.Filename) + "]";
                OpenGridViewGroups(gridSymbols, 0);
                // enable buttons
                barButtonItem4.Enabled = true;
                btnConnectECU.Enabled = true;
                btnSwitchMode.Enabled = true;
                //btnSynchronizeMaps.Enabled = true;
                btnTuneForE85Fuel.Enabled = true; //<GS-06042010> todo
                btnTuneToLargerInjectors.Enabled = true; //<GS-06042010> todo
                btnTuneToStage1.Enabled = true;
                btnTuneToStage2.Enabled = true;
                btnTuneToStage3.Enabled = true;
                btnTuneToStageX.Enabled = true;

                //            btnTuneToThreeBarSensor.Enabled = true;
                barConvertMapSensor.Enabled = true;
                btnBoostAdaptionWizard.Enabled = true;
                btnHardcodedRPMLimit.Enabled = true;
                if (m_trionicFileInformation.Has2DRegKonMat())
                {
                    btnChangeRegkonMatRange.Enabled = true;
                }
                else
                {
                    btnChangeRegkonMatRange.Enabled = false;
                }

                m_appSettings.Lastfilename = filename;
                ctrlRealtime1.Currentfile = filename;

                if (m_AFRMaps != null)
                {
                    m_AFRMaps.SaveMaps(); // first save changes that might have been done
                }

                m_AFRMaps = null;
                if (m_AFRMaps == null && m_appSettings.AlwaysCreateAFRMaps)
                {
                    m_AFRMaps = new AFRMaps();
                    m_AFRMaps.onFuelmapCellChanged += new AFRMaps.FuelmapCellChanged(m_AFRMaps_onFuelmapCellChanged);
                    m_AFRMaps.onIdleFuelmapCellChanged += new AFRMaps.IdleFuelmapCellChanged(m_AFRMaps_onIdleFuelmapCellChanged);
                    m_AFRMaps.onCellLocked += new AFRMaps.CellLocked(m_AFRMaps_onCellLocked);
                    m_AFRMaps.TrionicFile = m_trionicFile;
                    m_AFRMaps.InitializeMaps();
                }
                // add realtime symbollist to ctrlRealtime1
                Trionic5Tools.SymbolCollection _rtSymbols = new Trionic5Tools.SymbolCollection();
                foreach (Trionic5Tools.SymbolHelper symh in m_trionicFileInformation.SymbolCollection)
                {
                    if (symh.Start_address > 0 && (symh.Length >= 1 && symh.Length <= 4)) // <GS-29072010> was 1 & 2 only
                    {
                        _rtSymbols.Add(symh);
                    }
                }
                ctrlRealtime1.RealtimeSymbolCollection = _rtSymbols;
                try
                {
                    LoadUserDefinedRealtimeSymbols(); // try to load it
                }
                catch (Exception E)
                {
                    Console.WriteLine(E.Message);
                }
                LoadKnockMaps();
                SetTaskProgress(0, false);
                retval = true;
            }
            return retval;
        }
Exemple #14
0
 private void CopySymbol(string symbolname, string fromfilename, IECUFile FileToTransferTo, int fromflashaddress, int fromlength, string targetfilename, int targetflashaddress, int targetlength, Trionic5Resume resume)
 {
     if (fromlength != targetlength)
     {
         resume.AddToResumeTable("Unable to transfer symbol " + symbolname + " because source and target lengths don't match!");
     }
     else
     {
         try
         {
             while (fromflashaddress > m_trionicFileInformation.Filelength) fromflashaddress -= m_trionicFileInformation.Filelength;
             FileInfo fi = new FileInfo(targetfilename);
             while (targetflashaddress > fi.Length) targetflashaddress -= (int)fi.Length;
             byte[] mapdata = m_trionicFile.ReadDataFromFile(fromfilename, (uint)fromflashaddress, (uint)fromlength);
             FileToTransferTo.WriteData(mapdata, (uint)targetflashaddress);
             resume.AddToResumeTable("Transferred symbol " + symbolname + " successfully");
         }
         catch (Exception E)
         {
             resume.AddToResumeTable("Failed to transfer symbol " + symbolname + ": " + E.Message);
         }
     }
 }
Exemple #15
0
        private void CloseProject()
        {
            if (_ecuConnection.Opened) StopOnlineMode();// StopECUConnection();
            if (m_CurrentWorkingProject != "")
            {
                if (m_AFRMaps != null)
                {
                    m_AFRMaps.SaveMaps();
                    m_AFRMaps.SaveIdleMaps();
                }
            }
            m_CurrentWorkingProject = string.Empty;
            // unload the current file
            m_trionicFile = null;
            m_trionicFileInformation = null;
            barECUType.Caption = "--";
            barECUSpeed.Caption = "--";
            barECULocked.Caption = "--";
            gridSymbols.DataSource = null;
            barStaticItem2.Caption = "No file";
            barButtonItem4.Enabled = false;
            btnConnectECU.Enabled = false;
            btnSynchronizeMaps.Enabled = false;
            btnWriteLogMarker.Enabled = false;
            btnClearKnockCounters.Enabled = false;
            btnErrorCodes.Enabled = false;
            btnSwitchMode.Enabled = false;
            btnTuneForE85Fuel.Enabled = false;
            btnTuneToLargerInjectors.Enabled = false;
            btnTuneToStage1.Enabled = false;
            btnTuneToStage2.Enabled = false;
            btnTuneToStage3.Enabled = false;
            btnTuneToStageX.Enabled = false;

            //            btnTuneToThreeBarSensor.Enabled = false;
            barConvertMapSensor.Enabled = false;

            btnHardcodedRPMLimit.Enabled = false;
            btnBoostAdaptionWizard.Enabled = false;
            btnChangeRegkonMatRange.Enabled = false;
            m_appSettings.Lastfilename = string.Empty;
            btnCloseProject.Enabled = false;
            btnShowProjectLogbook.Enabled = false;
            btnProduceBinaryFromProject.Enabled = false;
            btnProjectNote.Enabled = false;
            btnEditProject.Enabled = false;
            btnRecreateFile.Enabled = false;
            btnRollback.Enabled = false;
            btnRollForward.Enabled = false;
            btnShowTransactionLog.Enabled = false;
            this.Text = "T5Suite Professional 2.0";
        }