Automatic Constraints in assembly for Ipart

Automatic Constraints in assembly for Ipart

dparmarF6BDE
Enthusiast Enthusiast
265 Views
1 Reply
Message 1 of 2

Automatic Constraints in assembly for Ipart

dparmarF6BDE
Enthusiast
Enthusiast

Hello All,
I am trying to place the parts and constraint them based on the excel file that I have created. I will walk you through the workflow to have a better understanding of what I am trying to achieve here.


1. There is an excel file located at a defined path and it has the file name in one column, the rule goes through each of the line in excel and search that file name in a defined directory, upon finding the part it is placing the part in to the active assembly. Now after placing the part in the assembly it records the model name of that part and updates the excel cell values to reflect the model name. refer to the first script.

Sub Main()
    ' Define paths and constants
    Dim excelFilePath As String = "C:run.xlsx"
    Dim searchFolder As String = "C:"
    Dim row As Integer = 3 ' Start reading from row 3

    ' Create a new Excel application
    Dim excelApp As Object = CreateObject("Excel.Application")
    Dim workbook As Object = excelApp.Workbooks.Open(excelFilePath)
    Dim worksheet As Object = workbook.Sheets(1)

    ' Loop through the Excel file
    While True
        ' Read the file name from column A
        Dim fileName As String = worksheet.Cells(row, 1).Value
        If fileName = "" Then Exit While ' Exit the loop if the cell is empty

        ' Define the full path to the part file
        Dim partFilePath As String = System.IO.Path.Combine(searchFolder, fileName & ".ipt")

        ' Check if the file exists
        If System.IO.File.Exists(partFilePath) Then
            ' Insert the part into the assembly
            Dim partDoc As Document = ThisApplication.Documents.Open(partFilePath, False) ' Open in read-only mode
            Dim asmDoc As AssemblyDocument = ThisApplication.ActiveDocument
            Dim asmCompDef As AssemblyComponentDefinition = asmDoc.ComponentDefinition
            Dim oMatrix As Matrix = ThisApplication.TransientGeometry.CreateMatrix()
            Dim occurrence As ComponentOccurrence = asmCompDef.Occurrences.Add(partFilePath, oMatrix)

            ' Get the model browser name
            Dim modelName As String = occurrence.Name

            ' Display message box with the latest component placed and its model browser name
            'MessageBox.Show("Placed part: " & fileName & vbCrLf & "Model Browser Name: " & modelName, "Component Placed", MessageBoxButtons.OK)

            ' Update the Excel file with the model browser name
            worksheet.Cells(row, 2).Value = modelName ' Assuming the model name should be written in column B
        End If

        ' Move to the next row
        row += 1
    End While

    ' Save and close the Excel file
    workbook.Save()
    workbook.Close(False)
    excelApp.Quit()
    System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp)
    excelApp = Nothing

    MsgBox("Finished processing Excel file.")
End Sub

 

2. Now the excel has been updated and all the parts have been placed and we have access to the model names for each of them. I want to apply flush or mate constraints based on the defined plane names for example "YZ Plane" I am also attaching the excel file that has been used to help understand the data structure. the origin plane is for the initial trial, I want to use the user planes that are visible in the image. 

Sub Main()
    ' Define paths and constants
    Dim excelFilePath As String = "C:\run.xlsx"
    Dim row As Integer = 3 ' Start reading from row 3

    ' Create a new Excel application
    Dim excelApp As Object = CreateObject("Excel.Application")
    Dim workbook As Object = excelApp.Workbooks.Open(excelFilePath)
    Dim worksheet As Object = workbook.Sheets(1)

    ' Get the active assembly document
    Dim asmDoc As AssemblyDocument = ThisApplication.ActiveDocument
    
    ' Check if the active document is an assembly
    If asmDoc.DocumentType <> DocumentTypeEnum.kAssemblyDocumentObject Then
        MsgBox("This script should be run on an assembly document.")
        Exit Sub
    End If
    
    ' Get the assembly component definition
    Dim asmCompDef As AssemblyComponentDefinition = asmDoc.ComponentDefinition
    
    ' Loop through the Excel file
    While True
        ' Read the part names from columns B and C
        Dim partNameB As String = worksheet.Cells(row, 2).Value
        Dim partNameC As String = worksheet.Cells(row, 3).Value
        If partNameB = "" Or partNameC = "" Then Exit While ' Exit the loop if either cell is empty

        ' Find the occurrences in the assembly
        Dim occurrenceB As ComponentOccurrence = FindOccurrenceByName(asmCompDef, partNameB)
        Dim occurrenceC As ComponentOccurrence = FindOccurrenceByName(asmCompDef, partNameC)
        
        If occurrenceB Is Nothing Or occurrenceC Is Nothing Then
            MsgBox("Could not find the parts in the assembly: " & partNameB & " or " & partNameC)
            Exit Sub
        End If

        ' Get the planes
        Dim leftFacePlane As WorkPlane = GetPlane(occurrenceB, "YZ Plane")
        Dim rightFacePlane As WorkPlane = GetPlane(occurrenceC, "YZ Plane")

        ' Apply mate constraint
        If leftFacePlane IsNot Nothing AndAlso rightFacePlane IsNot Nothing Then
            Try
                asmCompDef.Constraints.AddMateConstraint(leftFacePlane, rightFacePlane, 0)
                MsgBox("Mate constraint applied between parts: " & partNameB & " and " & partNameC)
            Catch ex As Exception
                MsgBox("Error applying mate constraint: " & ex.Message)
            End Try
        Else
            MsgBox("Could not find the planes 'YZ Plane' or 'YZ Plane' in the parts: " & partNameB & " or " & partNameC)
        End If

        ' Move to the next row
        row += 1
    End While

    ' Close the Excel file and clean up
    workbook.Close(False)
    excelApp.Quit()
    System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp)
    excelApp = Nothing

    MsgBox("Finished processing Excel file.")
End Sub

' Function to find an occurrence in the assembly by its name
Function FindOccurrenceByName(compDef As AssemblyComponentDefinition, partName As String) As ComponentOccurrence
    For Each occurrence As ComponentOccurrence In compDef.Occurrences
        If occurrence.Name = partName Then
            Return occurrence
        End If
    Next
    Return Nothing
End Function

' Function to get a work plane from an occurrence based on the plane name
Function GetPlane(occurrence As ComponentOccurrence, planeName As String) As WorkPlane
    Dim compDef As ComponentDefinition = occurrence.Definition
    For Each workPlane As WorkPlane In compDef.WorkPlanes
        If WorkPlane.Name = planeName Then
            Return WorkPlane
        End If
    Next
    Return Nothing
End Function

Note: the parts that I am using are Ipart factory parts, they have been generated and the link has been broken between child parts and the parent part. even though I have included my user planes in Itable  while making these parts so the necessary user planes are present in all the child parts, I cannot access them in the assembly model browser even though they are visible in the image and in the assembly. I do not have that much of the experience so I would not know if this is the reason why it is not working or something else.

 

dparmarF6BDE_0-1715615474043.png

I am getting this error while running the second script so I am posting this here to get a solution. Thank you!

dparmarF6BDE_1-1715615736149.png

 

 

 

 

0 Likes
266 Views
1 Reply
Reply (1)
Message 2 of 2

A.Acheson
Mentor
Mentor

Hi @dparmarF6BDE 

 

Judging by the error message which isn't specific the error occurs in the try catch statement. I would suggest to switch off this try catch statement in order to generate a system message. Look then at the more info tab and see if the message makes sense. 

AAcheson_0-1715650418552.png

If you further need to debug I  would suggest you go line by line on each object and return a property of the object to ensure it is correct. example would be the name of the workplane. Also ensure you can manually carry out the workplane constraints. This will ensure it is possible to do the operation. For the custom workplanes they should be available in the model tab.

 

You can also use another method to figure out the path to write the correct code. After  manually constraining use  the capture tool in the ilogic editor to capture the ilogic API code used. This will show if there what construction is needed. 

 

Here is a 2 part constraint method from the API help which uses proxy workplanes.

Sub Main
	MateConstraintOfWorkPlanes()
End Sub

Public Sub MateConstraintOfWorkPlanes()
    Dim oAsmCompDef As AssemblyComponentDefinition
    oAsmCompDef = ThisApplication.ActiveDocument.ComponentDefinition

    ' Get references to the two occurrences to constrain.
    ' This arbitrarily gets the first and second occurrence.
    Dim oOcc1 As ComponentOccurrence
    oOcc1 = oAsmCompDef.Occurrences.Item(1)

    Dim oOcc2 As ComponentOccurrence
    oOcc2 = oAsmCompDef.Occurrences.Item(2)

    ' Get the XY plane from each occurrence.  This goes to the
    ' component definition of the part to get this information.
    ' This is the same as accessing the part document directly.
    ' The work plane obtained is in the context of the part,
    ' not the assembly.
    Dim oPartPlane1 As WorkPlane
    oPartPlane1 = oOcc1.Definition.WorkPlanes.Item(3)

    Dim oPartPlane2 As WorkPlane
    oPartPlane2 = oOcc2.Definition.WorkPlanes.Item(3)

    ' Because we need the work plane in the context of the assembly
    ' we need to create proxies for the work planes.  The proxies
    ' represent the work planes in the context of the assembly.
    Dim oAsmPlane1 As WorkPlaneProxy
    Call oOcc1.CreateGeometryProxy(oPartPlane1, oAsmPlane1)

    Dim oAsmPlane2 As WorkPlaneProxy
    Call oOcc2.CreateGeometryProxy(oPartPlane2, oAsmPlane2)

    ' Create the constraint using the work plane proxies.
    Call oAsmCompDef.Constraints.AddMateConstraint(oAsmPlane1, oAsmPlane2, 0)
End Sub

 

 

If this solved a problem, please click (accept) as solution.‌‌‌‌
Or if this helped you, please, click (like)‌‌
Regards
Alan
0 Likes