What's new

Script Triggers

Lingeswaran M

New Member
I have script to activate the configuration based on changes in values of parameter. But I couldn't find the option to triggers this script whenever there are changes in value of parameter. my requirement is simple like, if change value of parameter, the configuration should change automatically without pressing script run option. Please help me on this.

my current script is:

Prt = CurrentPart()
Stl1 = Prt.GetConfiguration("Style1")
Stl2 = Prt.GetConfiguration("Style2")
Style = Prt.GetParameter('Style1')
if Style.Value == 1:
Stl1.Activate()
if Style.Value == 0:
Stl2.Activate()
 

stepalibre

Alibre Super User
Are you thinking of a sensor or event listener? It's not good practice to tie a parameter change directly to configurations as you described. I have sensors that are triggered if a calculated value (limit, mass, area, min, max, etc.) is matched. A volume sensor, if the part volume =100, the sensor will trigger, and a message will say that the part volume has exceeded design requirements. I got the sensor idea from SolidWorks.

From your code it looks like you're missing a loop or a mechanism to keep running while checking if Style.Value == 1.
 

EPowIPi

Senior Member
@stepalibre, can you please elaborate on this, this sounds super interesting! So, is it possible to automatically trigger scripts based on parameter or configuration changes? That would be very useful, indeed! (Edit: I mean event based, polling in a loop with busy wait would be a little crude :) )
 

stepalibre

Alibre Super User
Yes. You can have a program that runs outside of the Alibre Design process (.exe) that can perform any task you want. Alibre's APIs and the program itself it not designed to allow for true non-blocking code execution. The shared session state is a problem when trying to exit early or stop the process while doing work. I often need to kill Alibre Design.exe and relaunch it even when code is not blocking the UI thread because COM gets confused or a part in an assembly was open. My Python shell addon allow you to run non-blocking code that can be triggered on a parameter change, but it is still very difficult to not crash Alibre Design.exe. The reason for crashes is that transactions must close prior to any other API method is called to prevent Alibre Design from exploding. You can have error handling and checks in place to minimize this. You need a command to send to the program so it safely closes all transactions and cleans up COM before it exits. But still you need to address any other edge cases. If the program you make is intended for automation without any human getting in the way, then it should work perfectly fine.

I can share an example that switches configurations on a timer when I return to my desk. The AlibreScript addon can run non-blocking async code but it needs to be loaded inside the window and is outdated, which is not what I want. I need access to all sessions and documents while being in a separate window. So I ported the Python shell to Alibre Design.

I can't recall them but addons have access to events that can be used to trigger code. It's common to have system, document, application and window events.
 

EPowIPi

Senior Member
That would be great! I have two immediate usages in mind:
1) That way one could e.g. implement a copy-on-change mechanism, where a part could have a parameter "template" which is the name of another part. When that template part changes, all changes on the geometry are copied over to the current part. And the current part could have parameters named "local_*" which are always kept instance specific and non-local parameters that are overwritten when they change in the template. That way one wouldn't have to have a potentially really large global parameter file to orchestrate all changes in all parts of an assembly but could keep parameters local to the related parts and still have a template-instance concept.
The sync script should then monitor changes of the template part - either the geometry or some non-"local" parameters, to automatically update the instances.
Currently one would have to manually call the script when the instances should be updated.

2) A "feature-script" script would monitor the creation of dummy sketches or parts with a certain name. E.g. looking for parts or sketches that follow this naming schema: "scripted_<script_name>_<instance_name>". When such a sketch or part is found the script "script_name" should automatically be started, expecting an "update" function that gets the current sketch or part as parameter. This script would then look up the local formula editor-defined parameters for this local sketch or part, would programmatically delete the content and redraw the sketch or part programmatically.
Additionally the feature-script script would monitor the formula-editor parameters of such scripted parts or sketches. When those change the "script name" update script would automatically be called, updating the part or sketch. That way one would have scriptable parts or sketches that can be placed in the construction graph, using the part-local formula editor-defined parameters as changable per-instance script parameters.

Having monitoring / event-triggering when the scripts have to be called would be very convenient of course, otherwise it's still possible but in order to trigger an update one would always have to manually call the script. Or, when no eventing but at least async parallel execution is possible, polling inside a loop with some sleep would be an alternative, so the change might not be instantaneous but after the next poll cycle - less elegant but still an option.
 

Lingeswaran M

New Member
Are you thinking of a sensor or event listener? It's not good practice to tie a parameter change directly to configurations as you described. I have sensors that are triggered if a calculated value (limit, mass, area, min, max, etc.) is matched. A volume sensor, if the part volume =100, the sensor will trigger, and a message will say that the part volume has exceeded design requirements. I got the sensor idea from SolidWorks.

From your code it looks like you're missing a loop or a mechanism to keep running while checking if Style.Value == 1.
Hi Stepalibre, I'm looking for event trigger or something to change configuration whenever changes made on style value
 

Lingeswaran M

New Member
Are you thinking of a sensor or event listener? It's not good practice to tie a parameter change directly to configurations as you described. I have sensors that are triggered if a calculated value (limit, mass, area, min, max, etc.) is matched. A volume sensor, if the part volume =100, the sensor will trigger, and a message will say that the part volume has exceeded design requirements. I got the sensor idea from SolidWorks.

From your code it looks like you're missing a loop or a mechanism to keep running while checking if Style.Value == 1.
Can you suggest missing loop or mechanism to keep running while checking if Style.Value == 1
 

stepalibre

Alibre Super User
This code is a mix of my example AlibreX and AlibreScript IronPython code (I've shared here before) and my sensor/trigger code from VB.NET, simplified and converted to IronPython 2.7. This is only a demo and is not a ready-to-use solution. This is an advanced topic, you should understand the code, test it using test files not anything important. Paste the code into an AI to aid in your understanding.

That was my disclaimer...

I stopped using the AlibreScript addon after making Alibre Python shell. There are differences between my addon and the AlibreScript addon. The short story is related to module importing and preloading. AlibreScript addon is in a panel docked inside the window, my addon is in its own window. The addon is a generic Python shell without any preloaded Alibre APIs. You need to import modules and libraries manually. It does run inside the Alibre Design process so it can access libraries and modules the are loaded inside Alibre Design. I would need to update the addon to fully support this.

My addon does not stop or release objects after the window is closed. If you have a window that is modeless with non-blocking code or code running async it will continue to run even with the window closed. This is how my sensors work. I have code running in the background checking property values. To stop a sensor I have commands that set a Boolean value and clean up the objects.

To stop the example code just close the window. I made a quick video demo in case my writing is confusing. If you would rather use the AlibreScript addon the code should work with minor tweaks.

Code: AI added the comments
Python:
import sys
import clr
import time
from System import TimeSpan
from System.Threading import Thread, ThreadStart
# Update script paths to the new version
sys.path.append("C:\\Program Files\\Alibre Design 28.0.2.28126\\Program")
sys.path.append("C:\\Program Files\\Alibre Design 28.0.2.28126\\Program\\Addons\\AlibreScript")
clr.AddReference("AlibreX")
clr.AddReference("AlibreScriptAddOn")
clr.AddReference("System.Windows.Forms")
clr.AddReference("System.Drawing")
import AlibreX
# Update PythonLib paths
sys.path.append("C:\\Program Files\\Alibre Design 28.0.2.28126\\Program\\Addons\\AlibreScript\\PythonLib")
sys.path.append("C:\\Program Files\\Alibre Design 28.0.2.28126\\Program\\Addons\\AlibreScript")
sys.path.append("C:\\Program Files\\Alibre Design 28.0.2.28126\\Program\\Addons\\AlibreScript\\PythonLib\\site-packages")
import AlibreScript
from AlibreScript.API import *
clr.AddReference('System.Runtime.InteropServices')
from System.Runtime.InteropServices import Marshal
# Automation hook and object handling
alibre = Marshal.GetActiveObject("AlibreX.AutomationHook")
root = alibre.Root
myPart = Part(root.TopmostSession)
session = root.Sessions.Item(0)
objADPartSession = session
# Print session and body information
print session.FilePath
print objADPartSession.Bodies.Count
b = objADPartSession.Bodies
verts = b.Item(0).Vertices
print verts.Count
# Print vertex points
def printpoint(x, y, z):
    print "{0} , {1} , {2}".format(x, y, z)
for i in range(verts.Count):
    vert = verts.Item(i)
    point = vert.Point
    printpoint(point.X, point.Y, point.Z)
# Configuration handling
ConfigurationStep = session
config_count = ConfigurationStep.Configurations.Count
ConfigurationStep.ActiveConfiguration = ConfigurationStep.Configurations.Item(0)
# Configuration switching function
def switch_configurations():
    i = 0
    while True:
        item = ConfigurationStep.Configurations.Item(i % config_count)
        ConfigurationStep.ActiveConfiguration = item
        print "Switched to Configuration:", item.Name
        time.sleep(5)  # Switch every 5 seconds
        i += 1
# Start a .NET thread for non-blocking configuration switching
thread = Thread(ThreadStart(switch_configurations))
thread.IsBackground = True  # Ensure the thread exits with the script
thread.Start()
# Windows dialog handling
Win = Windows()
Win.InfoDialog('This code is from Alibre Script.', myPart.FileName)
Win.ErrorDialog('This code is from Alibre Script!', myPart.LastAuthor)
print Win.QuestionDialog('This code is from Alibre Script?', myPart.CreatedBy)
# Keep the script alive to allow the background thread to run
while True:
    time.sleep(1)  # Prevent the script from exiting immediately
Demo and uninstalling Revit:

I forgot to mention the example is not interactive. You cannot edit features or use any commands that use transactions or touch features, configurations, parameters, etc. I have logic in my project that checks the state and only runs code when AD is idle. If you try to create or edit a feature AD will crash. You need to handle this in your code if you want an interactive tool.
{edit}
After thinking about this, it is possible to edit and create features while the code is running. But It's dangerous without something handling this to do it safely. So I don't recommend it.
 
Last edited:

Lingeswaran M

New Member
This code is a mix of my example AlibreX and AlibreScript IronPython code (I've shared here before) and my sensor/trigger code from VB.NET, simplified and converted to IronPython 2.7. This is only a demo and is not a ready-to-use solution. This is an advanced topic, you should understand the code, test it using test files not anything important. Paste the code into an AI to aid in your understanding.

That was my disclaimer...

I stopped using the AlibreScript addon after making Alibre Python shell. There are differences between my addon and the AlibreScript addon. The short story is related to module importing and preloading. AlibreScript addon is in a panel docked inside the window, my addon is in its own window. The addon is a generic Python shell without any preloaded Alibre APIs. You need to import modules and libraries manually. It does run inside the Alibre Design process so it can access libraries and modules the are loaded inside Alibre Design. I would need to update the addon to fully support this.

My addon does not stop or release objects after the window is closed. If you have a window that is modeless with non-blocking code or code running async it will continue to run even with the window closed. This is how my sensors work. I have code running in the background checking property values. To stop a sensor I have commands that set a Boolean value and clean up the objects.

To stop the example code just close the window. I made a quick video demo in case my writing is confusing. If you would rather use the AlibreScript addon the code should work with minor tweaks.

Code: AI added the comments
Python:
import sys
import clr
import time
from System import TimeSpan
from System.Threading import Thread, ThreadStart
# Update script paths to the new version
sys.path.append("C:\\Program Files\\Alibre Design 28.0.2.28126\\Program")
sys.path.append("C:\\Program Files\\Alibre Design 28.0.2.28126\\Program\\Addons\\AlibreScript")
clr.AddReference("AlibreX")
clr.AddReference("AlibreScriptAddOn")
clr.AddReference("System.Windows.Forms")
clr.AddReference("System.Drawing")
import AlibreX
# Update PythonLib paths
sys.path.append("C:\\Program Files\\Alibre Design 28.0.2.28126\\Program\\Addons\\AlibreScript\\PythonLib")
sys.path.append("C:\\Program Files\\Alibre Design 28.0.2.28126\\Program\\Addons\\AlibreScript")
sys.path.append("C:\\Program Files\\Alibre Design 28.0.2.28126\\Program\\Addons\\AlibreScript\\PythonLib\\site-packages")
import AlibreScript
from AlibreScript.API import *
clr.AddReference('System.Runtime.InteropServices')
from System.Runtime.InteropServices import Marshal
# Automation hook and object handling
alibre = Marshal.GetActiveObject("AlibreX.AutomationHook")
root = alibre.Root
myPart = Part(root.TopmostSession)
session = root.Sessions.Item(0)
objADPartSession = session
# Print session and body information
print session.FilePath
print objADPartSession.Bodies.Count
b = objADPartSession.Bodies
verts = b.Item(0).Vertices
print verts.Count
# Print vertex points
def printpoint(x, y, z):
    print "{0} , {1} , {2}".format(x, y, z)
for i in range(verts.Count):
    vert = verts.Item(i)
    point = vert.Point
    printpoint(point.X, point.Y, point.Z)
# Configuration handling
ConfigurationStep = session
config_count = ConfigurationStep.Configurations.Count
ConfigurationStep.ActiveConfiguration = ConfigurationStep.Configurations.Item(0)
# Configuration switching function
def switch_configurations():
    i = 0
    while True:
        item = ConfigurationStep.Configurations.Item(i % config_count)
        ConfigurationStep.ActiveConfiguration = item
        print "Switched to Configuration:", item.Name
        time.sleep(5)  # Switch every 5 seconds
        i += 1
# Start a .NET thread for non-blocking configuration switching
thread = Thread(ThreadStart(switch_configurations))
thread.IsBackground = True  # Ensure the thread exits with the script
thread.Start()
# Windows dialog handling
Win = Windows()
Win.InfoDialog('This code is from Alibre Script.', myPart.FileName)
Win.ErrorDialog('This code is from Alibre Script!', myPart.LastAuthor)
print Win.QuestionDialog('This code is from Alibre Script?', myPart.CreatedBy)
# Keep the script alive to allow the background thread to run
while True:
    time.sleep(1)  # Prevent the script from exiting immediately
Demo and uninstalling Revit:

I forgot to mention the example is not interactive. You cannot edit features or use any commands that use transactions or touch features, configurations, parameters, etc. I have logic in my project that checks the state and only runs code when AD is idle. If you try to create or edit a feature AD will crash. You need to handle this in your code if you want an interactive tool.
{edit}
After thinking about this, it is possible to edit and create features while the code is running. But It's dangerous without something handling this to do it safely. So, I don't recommend it.
I think, this code is switching the configuration like animation, but my requirement is different.
Actually, I created one bolt with two thread configurations (Schematic & Cosmetic), and I have added this part on the toolbox (this part created by using add part from spreadsheet option)
Now, I tried to insert part from, I have option to select configuration but on the real fact selected configuration not activated at part level. (Look on the SolidWorks how toolbox parts are can insert and configure on the assembly)
I have tried with previously mentioned code but it not working automatically. (But it works when I click run button in part level)
I hope now you're understand my problem.
 

Attachments

  • image (4).png
    image (4).png
    281.9 KB · Views: 9

stepalibre

Alibre Super User
That example is to show how to have code run on its own. It can be used to detect a change and perform some task automatically the same as my sensors. It's possible to read feature or component names and if something contains "Hex Bolt", automatically trigger code.
 

stepalibre

Alibre Super User
I believe I answered your original question and provided an example loop you asked for. What I provided should help you develop the script you want. You have to write the script, unless someone posts their solution.

Share your code someone can assist you.

1) That way one could e.g. implement a copy-on-change mechanism, where a part could have a parameter "template" which is the name of another part. When that template part changes, all changes on the geometry are copied over to the current part. And the current part could have parameters named "local_*" which are always kept instance specific and non-local parameters that are overwritten when they change in the template. That way one wouldn't have to have a potentially really large global parameter file to orchestrate all changes in all parts of an assembly but could keep parameters local to the related parts and still have a template-instance concept.
The sync script should then monitor changes of the template part - either the geometry or some non-"local" parameters, to automatically update the instances.
Currently one would have to manually call the script when the instances should be updated.

2) A "feature-script" script would monitor the creation of dummy sketches or parts with a certain name. E.g. looking for parts or sketches that follow this naming schema: "scripted_<script_name>_<instance_name>". When such a sketch or part is found the script "script_name" should automatically be started, expecting an "update" function that gets the current sketch or part as parameter. This script would then look up the local formula editor-defined parameters for this local sketch or part, would programmatically delete the content and redraw the sketch or part programmatically.
Additionally the feature-script script would monitor the formula-editor parameters of such scripted parts or sketches. When those change the "script name" update script would automatically be called, updating the part or sketch. That way one would have scriptable parts or sketches that can be placed in the construction graph, using the part-local formula editor-defined parameters as changable per-instance script parameters.
This should be possible with Alibre APIs.
 
Top