General Python .NET interfacing

In this chapter, a general functionality is elaborated, which is needed to interface with PMP.

Operations on objects

Methods

methods() can be defined to obtain all methods of an object.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def methods(object, full=False):
    for method in list(object.GetType().GetMethods()):
        if "_" not in method.Name:
            if full:
                print(
                    "{name} {params} returns {ret}".format(
                        name=method.Name,
                        params=[parameter.Name for parameter in method.GetParameters()],
                        ret=method.ReturnType,
                    )
                )
            else:
                print(method.Name)

For example, obtain the methods of a controller topController:

>>> methods(topController)
CreateAxisControl
CreateAxisControlGroup
...
Equals
GetHashCode

Properties

The function properties() can be defined to list all properties of an object, e.g.

1
2
3
def properties(object):
    for property in list(object.GetType().GetProperties()):
        print(property.Name)

For example, obtain the properties of topController:

>>> properties(topController)
State
Time
...
Children
Events

Enumeration

1
2
3
4
from System import Enum
def enum_type(object):
    for type in list(Enum.GetNames(object)):
        print(type)

For example, show all available axis control states:

>>> enum_type(Pmp.AxisControlState)
NotReadyToSwitchOn
SwitchOnDisabled
ReadyToSwitchOn
SwitchedOn
OperationEnabled
QuickStopActive
FaultReactionActive
Fault

Dictionaries

If the key of a value in a dictionary is known, the value can be obtained directly. For example, obtain the controller with the name Arcas 5EG-1 from dictionary controllers:

topController = controllers['Arcas 5EG-1']

To see the content of a dictionary the keys can be converted to a list, for example, get the available sub-controllers of topController:

>>> list(topController.Controllers.Keys)
['Arcas FPGA']

List and Tuple

PMP requires lists or tuples as inputs for some methods. To create .NET tuple and list, they first need to be imported from System. Due to C# List initialization problem on Python, where all parameters passed to a List constructor is ignored (see https://github.com/pythonnet/pythonnet/issues/97), a list of a specific <type> with entries <entry1> .. <entryN> can be created via the following syntax:

>>> from System.Collections.Generic import List
>>> lst = List[<type>]()
>>> for entry in [<entry1>, ..., <entryN>]:
... lst.Add(entry)

A Tuple, similar to a List, is a collection of Python objects separated by commas. However, unlike a list, a tuple is immutable.

And a tuple {entry1, entry2} of type {type1, type2} can be created via the following syntax:

>>> from System import Tuple
>>> Tuple[<type1>, <type2>](<entry1>, <entry2>)