public bool ReindexAddresses(LadderProgram program) { foreach (Line line in program.Lines) { foreach (Instruction instruction in line.Instructions) { switch (instruction.OpCode) { case OperationCode.None: case OperationCode.LineBegin: case OperationCode.LineEnd: case OperationCode.ParallelBranchBegin: case OperationCode.ParallelBranchEnd: case OperationCode.ParallelBranchNext: break; default: instruction.SetOperand(0, Find((Address)instruction.GetOperand(0))); break; } } foreach (Instruction instruction in line.Outputs) { switch (instruction.OpCode) { case OperationCode.None: case OperationCode.LineBegin: case OperationCode.LineEnd: case OperationCode.ParallelBranchBegin: case OperationCode.ParallelBranchEnd: case OperationCode.ParallelBranchNext: break; default: instruction.SetOperand(0, Find((Address)instruction.GetOperand(0))); //if (instruction.IsAllOperandsOk()) //{ if (instruction.OpCode == OperationCode.Counter) { CounterInstruction counter = (CounterInstruction)instruction; counter.Counter.Type = (int)instruction.GetOperand(1); counter.Counter.Preset = (int)instruction.GetOperand(2); counter.Counter.Accumulated = (int)instruction.GetOperand(3); } if (instruction.OpCode == OperationCode.Timer) { ((Address)instruction.GetOperand(0)).Timer.Type = (Int32)instruction.GetOperand(1); ((Address)instruction.GetOperand(0)).Timer.Preset = (Int32)instruction.GetOperand(2); ((Address)instruction.GetOperand(0)).Timer.Accumulated = (Int32)instruction.GetOperand(3); ((Address)instruction.GetOperand(0)).Timer.TimeBase = (Int32)instruction.GetOperand(4); } //} break; } } } return(true); }
private void IndicateAddressUsed(LadderProgram program, AddressTypeEnum addressType) { CleanUsedIndication(); foreach (Line line in program.Lines) { line.Instructions.AddRange(line.Outputs); foreach (Instruction instruction in line.Instructions) { switch (instruction.OpCode) { /// TODO: Why this is this way? case OperationCode.NormallyOpenContact: case OperationCode.NormallyClosedContact: case OperationCode.OutputCoil: case OperationCode.Timer: case OperationCode.Counter: case OperationCode.Reset: if (instruction.IsAllOperandsOk()) { Address address = (Address)instruction.GetOperand(0); if (address.AddressType == addressType) { address.Used = true; } } break; } } line.Instructions.RemoveRange(line.Instructions.Count - line.Outputs.Count, line.Outputs.Count); } }
//public int AlocateMemoryAddressing(Device device, List<Address> addresses, AddressTypeEnum addressType, int numberOfAddress) //{ // int currentNumberOfAddress = addresses.Count; // if ((currentNumberOfAddress == 0) || (currentNumberOfAddress < numberOfAddress)) // { // for (int i = currentNumberOfAddress + 1; i <= numberOfAddress; i++) // { // addresses.Add(new Address(addressType, i, device.NumberBitsByPort)); // } // } // else if (currentNumberOfAddress > numberOfAddress) // { // for (int i = (currentNumberOfAddress - 1); i >= numberOfAddress; i--) // { // if (!addresses[i].Used) // { // addresses[i] = null; // addresses.RemoveAt(i); // } // else // { // break; // } // } // } // return 0; //} public int AlocateAddressingMemoryAndTimerAndCounter(LadderProgram program, List <Address> addresses, AddressTypeEnum type, int numberOfAddresses) { IndicateAddressUsed(program, type); int currentNumberOfAddress = addresses.Count; if (currentNumberOfAddress == 0 || currentNumberOfAddress < numberOfAddresses) { for (int i = currentNumberOfAddress + 1; i <= numberOfAddresses; i++) { //if (type.Equals(AddressTypeEnum.DigitalMemoryCounter)) //{ // addresses.Add(new InternalCounter(i, program.device.NumberBitsByPort)); //} //else addresses.Add(new Address(type, i, program.device.NumberBitsByPort)); } } else if (currentNumberOfAddress > numberOfAddresses) { for (int i = (currentNumberOfAddress - 1); i >= numberOfAddresses; i--) { if (!addresses[i].Used) { addresses[i] = null; addresses.RemoveAt(i); } else { break; } } } return(0); }
private void OpenFile(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal); openFileDialog.Filter = "LadderApp files (*.xml;*.a43)|*.xml;*.a43|XML files (*.xml)|*.xml|MSP430 Executable files (*.a43)|*.a43"; if (openFileDialog.ShowDialog(this) == DialogResult.OK) { string fileName = openFileDialog.FileName; switch (Path.GetExtension(fileName).ToLower()) { case ".xml": try { XmlReader fileReader = new XmlTextReader(new FileStream(fileName, FileMode.Open)); XmlSerializer xmlSerializer = new XmlSerializer(typeof(LadderProgram)); if (xmlSerializer.CanDeserialize(fileReader)) { LadderProgram ladderProgram = (LadderProgram)xmlSerializer.Deserialize(fileReader); projectForm = new ProjectForm(ladderProgram, AddressingServices.Instance); projectForm.Status = ProjectForm.ProgramStatus.Open; projectForm.PathFile = fileName; projectForm.Program.Name = Path.GetFileNameWithoutExtension(fileName); projectForm.MdiParent = this; projectForm.Show(); projectForm.SetText(); } fileReader.Close(); } catch (Exception ex) { MessageBox.Show("Error reading file! " + ex.InnerException.Message, "Open files ...", MessageBoxButtons.OK, MessageBoxIcon.Error); } break; case ".a43": try { MicIntegrationServices p = new MicIntegrationServices(); String readContent = p.ConvertHex2String(fileName); if (CheckPassword(readContent)) { ReadExecutable(readContent, fileName.Substring(fileName.LastIndexOf(@"\") + 1, fileName.Length - fileName.LastIndexOf(@"\") - 1)); } } catch { MessageBox.Show("Unknown file format!", "Open files ...", MessageBoxButtons.OK, MessageBoxIcon.Error); } break; default: MessageBox.Show("Unknown file format!", "Open files ...", MessageBoxButtons.OK, MessageBoxIcon.Error); break; } } }
public LadderForm(LadderProgram program) { InitializeComponent(); this.VScroll = false; this.HScroll = false; visualProgram = new VisualProgram(program, this); }
public bool VerifyProgram(LadderProgram program) { usedCounters.Clear(); usedTimers.Clear(); foreach (Line line in program.Lines) { if (!VerifyLine(line)) { return(false); } } return(true); }
public VisualProgram(LadderProgram program, LadderForm ladderForm) { this.program = program; this.ladderForm = ladderForm; if (this.program.Lines.Count > 0) { foreach (Line line in this.program.Lines) { VisualLine visualLine = CreateVisualLine(line); InsertLineAtEnd(visualLine); } } }
private void ReadExecutable(string content, string projectName) { try { ExecutableReaderService executableReaderService = new ExecutableReaderService(); LadderProgram program = executableReaderService.ReadExecutable(content, projectName); projectForm = new ProjectForm(program, AddressingServices.Instance); projectForm.MdiParent = this; projectForm.Show(); projectForm.SetText(); } catch (Exception ex) { MessageBox.Show(ex.Message, "ReadExecutable ...", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public ProjectForm(LadderProgram program, AddressingServices addressingServices) : this() { this.Program = program; this.addressingServices = addressingServices; this.addressingServices.SetAddressing(program.addressing); if (Status == ProgramStatus.NotInitialized && Program.device == null) { Program.device = DeviceFactory.CreateNewDevice(); addressingServices.AlocateIOAddressing(Program.device); addressingServices.AlocateAddressingMemoryAndTimerAndCounter(Program, Program.addressing.ListMemoryAddress, AddressTypeEnum.DigitalMemory, 10); addressingServices.AlocateAddressingMemoryAndTimerAndCounter(Program, Program.addressing.ListTimerAddress, AddressTypeEnum.DigitalMemoryTimer, 10); addressingServices.AlocateAddressingMemoryAndTimerAndCounter(Program, Program.addressing.ListCounterAddress, AddressTypeEnum.DigitalMemoryCounter, 10); } else { Status = ProgramStatus.Open; if (Program.device == null) { Program.device = DeviceFactory.CreateNewDevice(); } addressingServices.AlocateIOAddressing(Program.device); addressingServices.AlocateAddressingMemoryAndTimerAndCounter(Program, Program.addressing.ListMemoryAddress, AddressTypeEnum.DigitalMemory, Program.addressing.ListMemoryAddress.Count); addressingServices.AlocateAddressingMemoryAndTimerAndCounter(Program, Program.addressing.ListTimerAddress, AddressTypeEnum.DigitalMemoryTimer, Program.addressing.ListTimerAddress.Count); addressingServices.AlocateAddressingMemoryAndTimerAndCounter(Program, Program.addressing.ListCounterAddress, AddressTypeEnum.DigitalMemoryCounter, Program.addressing.ListCounterAddress.Count); addressingServices.ReindexAddresses(Program); } }
public LadderProgram ReadExecutable(string content, string projectName) { if (content.IndexOf("@laddermic.com") == -1) { throw new Exception("Executable has no Ladder content!"); } OperationCode opCode = OperationCode.None; int countOfEnds = 0; int lineIndex = 0; Address address; AddressTypeEnum addressType; int index = 0; LadderProgram program = new LadderProgram(); program.Name = projectName; program.device = DeviceFactory.CreateNewDevice(); addressingServices.AlocateIOAddressing(program.device); addressingServices.AlocateAddressingMemoryAndTimerAndCounter(program, program.addressing.ListMemoryAddress, AddressTypeEnum.DigitalMemory, 10); addressingServices.AlocateAddressingMemoryAndTimerAndCounter(program, program.addressing.ListTimerAddress, AddressTypeEnum.DigitalMemoryTimer, 10); addressingServices.AlocateAddressingMemoryAndTimerAndCounter(program, program.addressing.ListCounterAddress, AddressTypeEnum.DigitalMemoryCounter, 10); lineIndex = program.InsertLineAtEnd(new Line()); for (int position = content.IndexOf("@laddermic.com") + 15; position < content.Length; position++) { opCode = (OperationCode)Convert.ToChar(content.Substring(position, 1)); switch (opCode) { case OperationCode.None: countOfEnds++; break; case OperationCode.LineEnd: countOfEnds++; if ((OperationCode)Convert.ToChar(content.Substring(position + 1, 1)) != OperationCode.None) { lineIndex = program.InsertLineAtEnd(new Line()); } break; case OperationCode.NormallyOpenContact: case OperationCode.NormallyClosedContact: countOfEnds = 0; //Instruction instruction = new Instruction((OperationCode)opCode); Instruction instruction = InstructionFactory.createInstruction(opCode); addressType = (AddressTypeEnum)Convert.ToChar(content.Substring(position + 1, 1)); index = (Int32)Convert.ToChar(content.Substring(position + 2, 1)); address = addressingServices.Find(addressType, index); if (address == null) { program.device.Pins[index - 1].Type = addressType; addressingServices.RealocatePinAddressesByPinTypesFromDevice(program.device); addressingServices.AlocateIOAddressing(program.device); address = addressingServices.Find(addressType, index); } instruction.SetOperand(0, address); position += 2; program.Lines[lineIndex].Instructions.Add(instruction); break; case OperationCode.OutputCoil: case OperationCode.Reset: countOfEnds = 0; { InstructionList instructions = new InstructionList(); instructions.Add(InstructionFactory.createInstruction(opCode)); addressType = (AddressTypeEnum)Convert.ToChar(content.Substring(position + 1, 1)); index = (Int32)Convert.ToChar(content.Substring(position + 2, 1)); address = addressingServices.Find(addressType, index); if (address == null) { program.device.Pins[index - 1].Type = addressType; addressingServices.RealocatePinAddressesByPinTypesFromDevice(program.device); addressingServices.AlocateIOAddressing(program.device); address = addressingServices.Find(addressType, index); } instructions[instructions.Count - 1].SetOperand(0, address); position += 2; lineServices.InsertToOutputs(program.Lines[lineIndex], instructions); instructions.Clear(); } break; case OperationCode.ParallelBranchBegin: case OperationCode.ParallelBranchEnd: case OperationCode.ParallelBranchNext: countOfEnds = 0; program.Lines[lineIndex].Instructions.Add(InstructionFactory.createInstruction(opCode)); break; case OperationCode.Counter: countOfEnds = 0; { InstructionList instructions = new InstructionList(); CounterInstruction counter = (CounterInstruction)InstructionFactory.createInstruction(opCode); counter.SetAddress(addressingServices.Find(AddressTypeEnum.DigitalMemoryCounter, (Int32)Convert.ToChar(content.Substring(position + 1, 1)))); counter.setBoxType((int)Convert.ToChar(content.Substring(position + 2, 1))); counter.setPreset((int)Convert.ToChar(content.Substring(position + 3, 1))); instructions.Add(counter); //instructions.Add(InstructionFactory.createInstruction(opCode)); //instructions[instructions.Count - 1].SetOperand(0, addressingServices.Find(AddressTypeEnum.DigitalMemoryCounter, (Int32)Convert.ToChar(content.Substring(position + 1, 1)))); //((Address)instructions[instructions.Count - 1].GetOperand(0)).Counter.Type = (Int32)Convert.ToChar(content.Substring(position + 2, 1)); //((Address)instructions[instructions.Count - 1].GetOperand(0)).Counter.Preset = (Int32)Convert.ToChar(content.Substring(position + 3, 1)); //instructions[instructions.Count - 1].SetOperand(1, ((Address)instructions[instructions.Count - 1].GetOperand(0)).Counter.Type); //instructions[instructions.Count - 1].SetOperand(2, ((Address)instructions[instructions.Count - 1].GetOperand(0)).Counter.Preset); position += 3; lineServices.InsertToOutputs(program.Lines[lineIndex], instructions); instructions.Clear(); } break; case OperationCode.Timer: countOfEnds = 0; { InstructionList instructions = new InstructionList(); instructions.Add(InstructionFactory.createInstruction(opCode)); instructions[instructions.Count - 1].SetOperand(0, addressingServices.Find(AddressTypeEnum.DigitalMemoryTimer, (Int32)Convert.ToChar(content.Substring(position + 1, 1)))); ((Address)instructions[instructions.Count - 1].GetOperand(0)).Timer.Type = (Int32)Convert.ToChar(content.Substring(position + 2, 1)); ((Address)instructions[instructions.Count - 1].GetOperand(0)).Timer.TimeBase = (Int32)Convert.ToChar(content.Substring(position + 3, 1)); ((Address)instructions[instructions.Count - 1].GetOperand(0)).Timer.Preset = (Int32)Convert.ToChar(content.Substring(position + 4, 1)); instructions[instructions.Count - 1].SetOperand(1, ((Address)instructions[instructions.Count - 1].GetOperand(0)).Timer.Type); instructions[instructions.Count - 1].SetOperand(2, ((Address)instructions[instructions.Count - 1].GetOperand(0)).Timer.Preset); instructions[instructions.Count - 1].SetOperand(4, ((Address)instructions[instructions.Count - 1].GetOperand(0)).Timer.TimeBase); position += 4; lineServices.InsertToOutputs(program.Lines[lineIndex], instructions); instructions.Clear(); } break; } /// end of codes if (countOfEnds >= 2) { MicIntegrationServices p = new MicIntegrationServices(); //p.CreateFile("opcode.txt", content.Substring(content.IndexOf("@laddermic.com"), i - content.IndexOf("@laddermic.com") + 1)); //position = content.Length; break; } } return(program); }
public bool SimulateLadder(LadderProgram program, Address auxToggleBitPulse) { if (!verificationServices.VerifyProgram(program)) { return(false); } SimulateTimers(program); List <LineStretchSummary> lineStretchSummary = new List <LineStretchSummary>(); foreach (Line line in program.Lines) { lineStretchSummary.Add(new LineStretchSummary()); foreach (Instruction instruction in line.Instructions) { switch (instruction.OpCode) { case OperationCode.ParallelBranchBegin: lineStretchSummary.Add(new LineStretchSummary()); break; case OperationCode.ParallelBranchEnd: MakeOrLogicOverParallelBranchTwoLastLineStretchAndRemoveLastOne(lineStretchSummary); MakeAndLogicOverTwoLastLineStreatchAndRemoveLastOne(lineStretchSummary); break; case OperationCode.ParallelBranchNext: lineStretchSummary.Add(new LineStretchSummary()); break; default: if (lineStretchSummary[lineStretchSummary.Count - 1].Initiated) { lineStretchSummary[lineStretchSummary.Count - 1].LineValue = lineStretchSummary[lineStretchSummary.Count - 1].LineValue && instruction.GetValue(); } else { lineStretchSummary[lineStretchSummary.Count - 1].LineValue = instruction.GetValue(); } break; } } foreach (FirstOperandAddressDigitalInstruction instruction in line.Outputs.FindAll(i => i is IDigitalAddressable)) { switch (instruction.OpCode) { case OperationCode.OutputCoil: case OperationCode.Timer: case OperationCode.Counter: case OperationCode.Reset: if (instruction.OpCode == OperationCode.OutputCoil) { instruction.GetAddress().Value = lineStretchSummary[lineStretchSummary.Count - 1].LineValue; } if (instruction.OpCode == OperationCode.Timer) { instruction.GetAddress().Timer.Enable = lineStretchSummary[lineStretchSummary.Count - 1].LineValue; } if (instruction.OpCode == OperationCode.Counter) { CounterInstruction counter = (CounterInstruction)instruction; counter.Counter.Enable = lineStretchSummary[lineStretchSummary.Count - 1].LineValue; ExecuteCountersSimulator(instruction); } if (instruction.OpCode == OperationCode.Reset) { if (lineStretchSummary[lineStretchSummary.Count - 1].LineValue) { switch (instruction.GetAddress().AddressType) { case AddressTypeEnum.DigitalMemoryCounter: FirstOperandAddressDigitalInstruction reset = (FirstOperandAddressDigitalInstruction)instruction; // TODO RETIRAR ESTA LINGUIÇA DEPOIS CounterInstruction counter = program.Lines.SelectMany(l => l.Outputs).Where(o => o is CounterInstruction).Cast <CounterInstruction>().Where(c => c.GetAddress().Equals(reset.GetAddress())).First(); counter.Counter.Reset = true; ExecuteCountersSimulator(counter); break; case AddressTypeEnum.DigitalMemoryTimer: instruction.GetAddress().Timer.Reset = true; break; default: break; } } } break; default: break; } } lineStretchSummary.RemoveAt(lineStretchSummary.Count - 1); } if (auxToggleBitPulse != null) { auxToggleBitPulse.Value = auxToggleBitPulse.Value == true ? false : true; auxToggleBitPulse = null; } return(true); }
public bool SimulateLadder(LadderProgram program) { return(SimulateLadder(program, null)); }
public void SimulateTimers(LadderProgram program) { int parcialPreset = -1; foreach (Address address in program.addressing.ListTimerAddress) { if (address.Timer.Reset == true) { address.Timer.Accumulated = 0; address.Value = false; address.Timer.Reset = false; } switch (address.Timer.Type) { case 0: // TON if (address.Timer.Enable && !address.Timer.Reset) { address.Timer.ParcialAccumulated++; if (address.Timer.ParcialAccumulated >= address.Timer.ParcialPreset) { address.Timer.ParcialAccumulated = 0; address.Timer.Accumulated++; if (address.Timer.Accumulated >= address.Timer.Preset) { address.Value = true; /// DONE = true address.Timer.Accumulated = address.Timer.Preset; } } } else { address.Value = false; address.Timer.Accumulated = 0; address.Timer.ParcialAccumulated = 0; address.Timer.Reset = false; } break; case 1: // TOF if (address.Timer.Enable || address.Timer.Reset) { address.Value = true; /// DONE = true address.Timer.Accumulated = 0; address.Timer.ParcialAccumulated = 0; address.Timer.Reset = false; } else { if (address.Value) // Done enabled - timer counting { address.Timer.ParcialAccumulated++; } if (address.Timer.ParcialAccumulated >= address.Timer.ParcialPreset) { address.Timer.ParcialAccumulated = 0; address.Timer.Accumulated++; } if (address.Timer.Accumulated >= address.Timer.Preset) { address.Value = false; /// DONE = false address.Timer.Accumulated = 0; address.Timer.ParcialAccumulated = 0; } } break; case 2: // RTO if (address.Timer.Reset) { address.Value = false; /// DONE = false address.Timer.Accumulated = 0; address.Timer.ParcialAccumulated = 0; } if (address.Timer.Enable) { address.Timer.ParcialAccumulated++; if (address.Timer.ParcialAccumulated == parcialPreset) { address.Timer.ParcialAccumulated = 0; if (address.Timer.Accumulated <= Int32.MaxValue) { if (address.Timer.Accumulated < address.Timer.Preset) { address.Timer.Accumulated++; } else { address.Timer.Accumulated = address.Timer.Preset; } if (address.Timer.Accumulated >= address.Timer.Preset) { address.Value = true; /// DONE = true } else { address.Value = false; /// DONE = false } } } } break; default: break; } /// switch } }
public bool GenerateExecutable(LadderProgram program, bool saveProgramInsideExecutable, bool savePassword, string password, bool writeProgram) { SetAddressing(program.addressing); addressingServices.SetAddressing(program.addressing); String doc = "", lineText = "", lineTestText = "", outputLastOperand = ""; bool operandInLine = false; List <String> outputOperands = new List <string>(); List <String> operandsToReset = new List <string>(); String functionsAfterLine = ""; DialogResult result; bool initiated = false; if (!verificationServices.VerifyProgram(program)) { return(false); } opCode2TextServices.Add(OperationCode.None); if (saveProgramInsideExecutable && savePassword && !String.IsNullOrEmpty(password)) { opCode2TextServices.AddHeader(); opCode2TextServices.Header.Add(OperationCode.HeadPassword0); opCode2TextServices.Header.Add(password.Length); opCode2TextServices.Header.Add(password); } addressingServices.CleanUsedIndication(); lineText += Environment.NewLine; doc += lineText; foreach (Line line in program.Lines) { lineText = ""; foreach (Instruction instruction in line.Instructions) { switch (instruction.OpCode) { case OperationCode.ParallelBranchBegin: if (initiated) { lineText += " && "; } initiated = false; lineText += "(("; break; case OperationCode.ParallelBranchEnd: lineText += "))"; break; case OperationCode.ParallelBranchNext: initiated = false; lineText += ") || ("; break; default: if (initiated) { lineText += " && "; } switch (instruction.OpCode) { case OperationCode.NormallyOpenContact: lineText += ((Address)instruction.GetOperand(0)).GetBitVariableName(); ((Address)instruction.GetOperand(0)).Used = true; break; case OperationCode.NormallyClosedContact: lineText += "!" + ((Address)instruction.GetOperand(0)).GetBitVariableName(); ((Address)instruction.GetOperand(0)).Used = true; break; } initiated = true; break; } opCode2TextServices.Add(instruction); } initiated = false; if (lineText == "") { lineText = "1"; } lineText = "(" + lineText + ")"; lineTestText = lineText; outputOperands.Clear(); operandsToReset.Clear(); foreach (FirstOperandAddressDigitalInstruction instruction in line.Outputs.FindAll(i => i is IDigitalAddressable)) { switch (instruction.OpCode) { case OperationCode.OutputCoil: case OperationCode.Timer: case OperationCode.Counter: outputOperands.Add(((IOutput)instruction).GetOutputDeclaration()); goto case OperationCode.Reset; case OperationCode.Reset: opCode2TextServices.Add((Instruction)instruction); instruction.SetUsed(); if (instruction.OpCode == OperationCode.Counter) { functionsAfterLine += " ExecuteCounter(&" + instruction.GetAddress().GetName() + ");"; } if (instruction.OpCode == OperationCode.Reset) { operandsToReset.Add(((IOutput)instruction).GetOutputDeclaration()); switch (instruction.GetAddress().AddressType) { case AddressTypeEnum.DigitalMemoryCounter: operandsToReset.Add("ExecuteCounter(&" + instruction.GetAddress().GetName() + ");"); break; default: break; } } break; default: break; } } if (outputOperands.Count > 0) { operandInLine = true; lineText = ""; foreach (String outputOperand in outputOperands) { lineText += outputOperand + " = "; outputLastOperand = outputOperand; } lineText += lineTestText + ";"; if (functionsAfterLine != "") { lineText += Environment.NewLine + functionsAfterLine; } functionsAfterLine = ""; doc += lineText + Environment.NewLine; } if (operandsToReset.Count > 0) { if (operandInLine) { lineTestText = outputLastOperand; } lineText = "if (" + lineTestText + ") {" + Environment.NewLine; foreach (String maybeOutpustOfLine in operandsToReset) { lineText += maybeOutpustOfLine + Environment.NewLine; } lineText += "}"; doc += lineText + Environment.NewLine; } operandInLine = false; doc += Environment.NewLine; opCode2TextServices.Add(OperationCode.LineEnd); } opCode2TextServices.Add(OperationCode.None); result = MessageBox.Show("Do you want to generate the .C file below? " + Environment.NewLine + doc, "Confirmation: Generate .C file?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question); if (result == DialogResult.OK) { string contentLadderProgramDotHFile = ""; string contentLadderProgramDotCFile = ""; string contentFunctionsDotHFile = ""; string contentFunctionsDotCFile = ""; string contentAddressesDotHFile = ""; string contentHardwareSetupDotCFile = ""; string contentMainDotCFile = ""; string contentIOSetup = ""; string contentReadInputs = ""; string contentWriteOutputs = ""; string contentParameterization = ""; string contentVariableDeclarations = ""; string contentOpCodes = ""; string contentTimers = ""; bool counterPresent = false; bool timerPresent = false; bool inputsPresent = false; bool outputsPresent = false; List <string> usedVariableNames = new List <string>(); List <string> usedPorts = new List <string>(); List <int> usedTimerTypes = new List <int>(); List <int> usedCounterTypes = new List <int>(); PrepareParameterizationForInputPorts(ref contentParameterization, ref inputsPresent, usedPorts); PrepareParameterizationForOutputAddress(ref contentParameterization, ref outputsPresent, usedPorts); PrepareVariableDeclarationForInputOrOutPutUsedInProgram(usedVariableNames, usedPorts); for (int i = 0; i < usedPorts.Count; i++) { contentIOSetup += usedPorts[i] + "OUT = 0; // Init Output data of port" + Environment.NewLine; contentIOSetup += usedPorts[i] + "DIR = " + usedPorts[i] + "_DIR.Byte; // Init of Port1 Data-Direction Reg (Out=1 / Inp=0)" + Environment.NewLine; contentIOSetup += usedPorts[i] + "SEL = 0; // Port-Modules:" + Environment.NewLine; contentIOSetup += usedPorts[i] + "IE = 0; // Interrupt Enable (0=dis 1=enabled)" + Environment.NewLine; contentIOSetup += usedPorts[i] + "IES = 0; // Interrupt Edge Select (0=pos 1=neg)" + Environment.NewLine; contentIOSetup += Environment.NewLine; if (inputsPresent) { contentReadInputs += usedPorts[i] + "_IN.Byte = " + usedPorts[i] + "IN;" + Environment.NewLine; } if (outputsPresent) { contentWriteOutputs += usedPorts[i] + "OUT = " + usedPorts[i] + "_OUT.Byte; // Write Output data of port1" + Environment.NewLine; } } foreach (Address address in GetAddressing().ListMemoryAddress) { if (address.Used) { if (!usedVariableNames.Contains(address.GetStructVariable())) { usedVariableNames.Add(address.GetStructVariable()); } } } if (usedVariableNames.Count > 0) { contentVariableDeclarations += "TPort "; foreach (String variableName in usedVariableNames) { contentVariableDeclarations += variableName + ", "; } contentVariableDeclarations = contentVariableDeclarations.Substring(0, contentVariableDeclarations.Length - 2) + ";" + Environment.NewLine; usedVariableNames.Clear(); } /// timer contentParameterization += "// timer parameters" + Environment.NewLine; foreach (Address address in GetAddressing().ListTimerAddress) { if (address.Used) { timerPresent = true; contentParameterization += "\t" + address.GetName() + ".Type = " + address.Timer.Type.ToString() + ";" + Environment.NewLine; contentParameterization += "\t" + address.GetName() + ".TimeBase = " + address.Timer.TimeBase.ToString() + ";" + Environment.NewLine; contentParameterization += "\t" + address.GetName() + ".Preset = " + address.Timer.Preset.ToString() + ";" + Environment.NewLine; contentParameterization += "\t" + address.GetName() + ".Accumulated = 0;" + Environment.NewLine; contentParameterization += Environment.NewLine; /// prepare variable declaration if (!usedVariableNames.Contains(address.GetStructVariable())) { usedVariableNames.Add(address.GetStructVariable()); } if (!usedTimerTypes.Contains(address.Timer.Type)) { usedTimerTypes.Add(address.Timer.Type); } } } /// timers if (usedVariableNames.Count > 0) { contentVariableDeclarations += "TTimer "; foreach (String variableName in usedVariableNames) { contentVariableDeclarations += variableName + ", "; contentTimers += "ExecuteTimer(&" + variableName + ");" + Environment.NewLine; } contentVariableDeclarations = contentVariableDeclarations.Substring(0, contentVariableDeclarations.Length - 2) + ";" + Environment.NewLine; usedVariableNames.Clear(); } /// counters foreach (CounterInstruction counter in program.Lines.SelectMany(l => l.Outputs).Where(i => i is CounterInstruction)) { if (counter.GetAddress().Used) { counterPresent = true; contentParameterization += $"\t{counter.GetName()}.Type = {counter.GetBoxType()};{Environment.NewLine}"; contentParameterization += $"\t{counter.GetName()}.Preset = {counter.GetPreset()};{Environment.NewLine}"; contentParameterization += $"\t{counter.GetName()}.Accumulated = 0;{Environment.NewLine}"; contentParameterization += Environment.NewLine; /// prepare variable declaration if (!usedVariableNames.Contains(counter.GetAddress().GetStructVariable())) { usedVariableNames.Add(counter.GetAddress().GetStructVariable()); } if (!usedCounterTypes.Contains(counter.GetBoxType())) { usedCounterTypes.Add(counter.GetBoxType()); } } } /// Prepare TCounter to be declared if (usedVariableNames.Count > 0) { contentVariableDeclarations += "TCounter "; foreach (String variableDeclaration in usedVariableNames) { contentVariableDeclarations += variableDeclaration + ", "; } contentVariableDeclarations = contentVariableDeclarations.Substring(0, contentVariableDeclarations.Length - 2) + ";" + Environment.NewLine; usedVariableNames.Clear(); } //MSP430IntegrationServices msp430gcc = new MSP430IntegrationServices(false); /// Prepara ENDERECOS contentAddressesDotHFile = MicrocontrollersBaseCodeFilesResource.addressesH; contentAddressesDotHFile = contentAddressesDotHFile.Replace("#VARIABLE_DECLARATIONS#", contentVariableDeclarations); contentAddressesDotHFile.Trim(); micIntegrationServices.CreateFile("addresses.h", contentAddressesDotHFile); micIntegrationServices.CreateFile("definitions.h", MicrocontrollersBaseCodeFilesResource.definitionsH); micIntegrationServices.CreateFile("hardwaresetup.h", MicrocontrollersBaseCodeFilesResource.hardwaresetupH); if (counterPresent) { contentFunctionsDotHFile = MicrocontrollersBaseCodeFilesResource.functionsH.Replace("#EXECCOUNTER_FUNCTION_H#", MicrocontrollersBaseCodeFilesResource.execcounter_functionsH); } else { contentFunctionsDotHFile = MicrocontrollersBaseCodeFilesResource.functionsH.Replace("#EXECCOUNTER_FUNCTION_H#", ""); } if (timerPresent) { contentFunctionsDotHFile = contentFunctionsDotHFile.Replace("#EXECTIMER_FUNCTION_H#", MicrocontrollersBaseCodeFilesResource.exectimer_functionsH); } else { contentFunctionsDotHFile = contentFunctionsDotHFile.Replace("#EXECTIMER_FUNCTION_H#", ""); } micIntegrationServices.CreateFile("functions.h", contentFunctionsDotHFile); if (timerPresent) { contentLadderProgramDotHFile = MicrocontrollersBaseCodeFilesResource.ladderprogramH.Replace("#EXEC_TIMERS_LADDERPROGRAM_H#", MicrocontrollersBaseCodeFilesResource.exectimer_functions_ladderprogramH); } else { contentLadderProgramDotHFile = MicrocontrollersBaseCodeFilesResource.ladderprogramH.Replace("#EXEC_TIMERS_LADDERPROGRAM_H#", ""); } micIntegrationServices.CreateFile("ladderprogram.h", contentLadderProgramDotHFile); contentLadderProgramDotCFile = MicrocontrollersBaseCodeFilesResource.ladderprogramC; if (timerPresent) { contentLadderProgramDotCFile = contentLadderProgramDotCFile.Replace("#EXEC_TIMERS_LADDERPROGRAM_C#", MicrocontrollersBaseCodeFilesResource.exectimer_functions_ladderprogramC); contentLadderProgramDotCFile = contentLadderProgramDotCFile.Replace("#TIMERS_LADDERPROGRAM_C#", contentTimers); } else { contentLadderProgramDotCFile = contentLadderProgramDotCFile.Replace("#EXEC_TIMERS_LADDERPROGRAM_C#", ""); } contentLadderProgramDotCFile = contentLadderProgramDotCFile.Replace("#LADDER#", doc); contentLadderProgramDotCFile = contentLadderProgramDotCFile.Replace("#PARAMETERIZATION#", contentParameterization); contentLadderProgramDotCFile.Trim(); micIntegrationServices.CreateFile("ladderprogram.c", contentLadderProgramDotCFile); micIntegrationServices.CompilesMsp430ViaGcc("ladderprogram"); contentMainDotCFile = MicrocontrollersBaseCodeFilesResource.mainC; if (saveProgramInsideExecutable) { opCode2TextServices.FinalizeHeader(); contentOpCodes = "const unsigned char ladderInstructions[" + opCode2TextServices.Length + "] = {" + opCode2TextServices + "};"; contentMainDotCFile = contentMainDotCFile.Replace("#LADDER_INSTRUCTIONS#", contentOpCodes); } else { contentMainDotCFile = contentMainDotCFile.Replace("#LADDER_INSTRUCTIONS#", ""); } contentMainDotCFile.Trim(); //msp430gcc.CreateFile("opcodes.txt", contentOpCodes); if (timerPresent) { contentMainDotCFile = contentMainDotCFile.Replace("#EXEC_TIMERS_CALL#", "ExecuteTimers();"); } else { contentMainDotCFile = contentMainDotCFile.Replace("#EXEC_TIMERS_CALL#", ""); } micIntegrationServices.CreateFile("main.c", contentMainDotCFile); micIntegrationServices.CompilesMsp430ViaGcc("main"); if (counterPresent) { contentFunctionsDotCFile = MicrocontrollersBaseCodeFilesResource.functionsC.Replace("#EXEC_COUNTER_FUNCTION_C#", MicrocontrollersBaseCodeFilesResource.execcounter_functionsC); if (usedCounterTypes.Contains(0)) { contentFunctionsDotCFile = contentFunctionsDotCFile.Replace("#EXEC_COUNTER_TYPE_0_FUNCTION_C#", MicrocontrollersBaseCodeFilesResource.execcounter_ctu_type0_functionsC); } else { contentFunctionsDotCFile = contentFunctionsDotCFile.Replace("#EXEC_COUNTER_TYPE_0_FUNCTION_C#", ""); } if (usedCounterTypes.Contains(1)) { contentFunctionsDotCFile = contentFunctionsDotCFile.Replace("#EXEC_COUNTER_TYPE_1_FUNCTION_C#", MicrocontrollersBaseCodeFilesResource.execcounter_ctd_type1_functionsC); } else { contentFunctionsDotCFile = contentFunctionsDotCFile.Replace("#EXEC_COUNTER_TYPE_1_FUNCTION_C#", ""); } } else { contentFunctionsDotCFile = MicrocontrollersBaseCodeFilesResource.functionsC.Replace("#EXEC_COUNTER_FUNCTION_C#", ""); } if (timerPresent) { contentFunctionsDotCFile = contentFunctionsDotCFile.Replace("#EXEC_TIMER_FUNCTION_C#", MicrocontrollersBaseCodeFilesResource.exectimer_functionsC); if (usedTimerTypes.Contains(0)) { contentFunctionsDotCFile = contentFunctionsDotCFile.Replace("#EXEC_TIMER_TYPE_0_FUNCTION_C#", MicrocontrollersBaseCodeFilesResource.exectimer_ton_type0_functions); } else { contentFunctionsDotCFile = contentFunctionsDotCFile.Replace("#EXEC_TIMER_TYPE_0_FUNCTION_C#", ""); } if (usedTimerTypes.Contains(1)) { contentFunctionsDotCFile = contentFunctionsDotCFile.Replace("#EXEC_TIMER_TYPE_1_FUNCTION_C#", MicrocontrollersBaseCodeFilesResource.exectimer_tof_type1_functions); } else { contentFunctionsDotCFile = contentFunctionsDotCFile.Replace("#EXEC_TIMER_TYPE_1_FUNCTION_C#", ""); } } else { contentFunctionsDotCFile = contentFunctionsDotCFile.Replace("#EXEC_TIMER_FUNCTION_C#", ""); } micIntegrationServices.CreateFile("functions.c", contentFunctionsDotCFile); micIntegrationServices.CompilesMsp430ViaGcc("functions"); contentHardwareSetupDotCFile = MicrocontrollersBaseCodeFilesResource.hardwaresetupC.Replace("#IO_HARDWARE_SETUP_C#", contentIOSetup); contentHardwareSetupDotCFile = contentHardwareSetupDotCFile.Replace("#READ_INPUTS#", contentReadInputs); contentHardwareSetupDotCFile = contentHardwareSetupDotCFile.Replace("#WRITE_OUTPUTS#", contentWriteOutputs); micIntegrationServices.CreateFile("hardwaresetup.c", contentHardwareSetupDotCFile); micIntegrationServices.CompilesMsp430ViaGcc("hardwaresetup"); micIntegrationServices.CreateFile("interruption.c", MicrocontrollersBaseCodeFilesResource.interruptionC); micIntegrationServices.CompilesMsp430ViaGcc("interruption"); micIntegrationServices.CompileELF(program.Name); micIntegrationServices.CompilationStepMergeAllDotOFilesAndGenerateElfFile(program.Name); if (writeProgram) { micIntegrationServices.DownloadViaUSB(program.Name); } } return(true); }