Wednesday, July 6, 2011

Adding Scripting Functions

So, you have a handy method available in one of your Java classes, and you wish you could use it in your jython script? Now you can!

The full list of items that are available from Python 2.5 are available here: http://docs.python.org/release/2.5/modindex.html

If we want to convert radians to degrees, let's say, there's no method in Python 2.5 to do it, but there is one in Java. And it couldn't be easier. java.lang.Math has a method called toDegrees(). Lets expose java.lang.Math straight to jython.

In your designer hook class, just add the following code:

 @Override
 public void initializeScriptManager(ScriptManager manager) {
  manager.addScriptModule("playground.math", java.lang.Math.class);
 }

Notice "java.lang.Math.class" in the last line. Giving the Class of an object will expose any static methods.

Now, open your designer, open up your script playground, and enter the following.

 import playground
 print playground.math.toRadians(.5)

And voila, we have full access!

If you want to expose any instance methods, just pass addScriptModule() an Object, and it takes care of the rest.

Of course, you can (and probably will) use your own classes and objects to create whatever scripting functions you need.

You'll want to run addScriptModule() in the client hook too, in order to have the same scripting functions available in both client and designer. If you need to run any of the scripting functions from a gateway script, be sure to add the lines to the gateway hook as well.

And that's it, easy as pie! (Maybe easier)

Note: As of Ignition 7.5.1, there's no way to "clean up" your scripting functions when your module is shut down. The Ignition developers have informed me that new methods (like manager.removeScriptModule(), for example) are planned to be added to Ignition in a future version.


Ignition Version: 7.5 (7.5.1)

2 comments:

Unknown said...
This comment has been removed by the author.
Unknown said...

I tried the same method but every time I am getting following error
Traceback (most recent call last):
File "", line 1, in
ImportError: No module named playground

Post a Comment