py_canoe.core.system.System

The System object represents the system of the CANoe application. The System object offers access to the namespaces for data exchange with external applications.

Source code in src\py_canoe\core\system.py
19
20
def __init__(self, app: 'Application'):
    self.com_object = app.com_object.System

namespaces property

Return the Namespaces object for accessing system variable namespaces.

variables_files property

Return the VariablesFiles object for accessing system variable files.

add_variable(sys_var_name, value, read_only=False)

Add a new system variable to the CANoe system. If the namespace does not exist, it will be created.

Source code in src\py_canoe\core\system.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def add_variable(self, sys_var_name: str, value: Union[int, float, str], read_only: bool = False) -> Union[object, None]:
    """Add a new system variable to the CANoe system. If the namespace does not exist, it will be created."""
    new_var_com_obj = None
    try:
        parts = sys_var_name.split('::')
        if len(parts) < 2:
            logger.error(f"Invalid system variable name '{sys_var_name}'. Must be in 'namespace::variable' format.")
            return None
        namespace = '::'.join(parts[:-1])
        variable_name = parts[-1]
        try:
            namespace_obj = self.com_object.Namespaces(namespace)
        except Exception:
            logger.info(f"namespace '{namespace}' not present. Creating namespace...")
            namespaces_obj = self.com_object.Namespaces
            namespace_obj = namespaces_obj.Add(namespace)
            logger.info(f"Created new namespace: {namespace}")
        variables_obj = namespace_obj.Variables
        if read_only:
            new_var_com_obj = variables_obj.Add(variable_name, value)
        else:
            new_var_com_obj = variables_obj.AddWriteable(variable_name, value)
        logger.info(f"System Variable '{sys_var_name}' defined successfully with value: {value}")
        return new_var_com_obj
    except Exception as e:
        logger.error(f"Error defining System Variable '{sys_var_name}': {e}")
        return None

get_all_namespace_names()

Get all system variable namespace names as a list. If an error occurs, it will raise a PyCanoeError.

Source code in src\py_canoe\core\system.py
167
168
169
170
171
172
173
174
def get_all_namespace_names(self) -> list[str]:
    """Get all system variable namespace names as a list. If an error occurs, it will raise a PyCanoeError."""
    try:
        names = [ns.name for ns in self.namespaces.fetch_all()]
    except Exception as e:
        raise PyCanoeError(f"Failed to enumerate namespaces: {e}") from e
    logger.info(f'{len(names)} system variable namespace(s) found')
    return names

get_all_variables_in_namespace(namespace_name)

Get all system variables in a specific namespace as a list of dictionaries with variable names, values, and full names. If the namespace does not exist, it will raise a NamespaceNotFoundError. If an error occurs while enumerating variables, it will raise a PyCanoeError.

Source code in src\py_canoe\core\system.py
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
def get_all_variables_in_namespace(self, namespace_name: str) -> list[dict]:
    """Get all system variables in a specific namespace as a list of dictionaries with variable names, values, and full names. If the namespace does not exist, it will raise a NamespaceNotFoundError. If an error occurs while enumerating variables, it will raise a PyCanoeError."""
    try:
        ns_com = self.com_object.Namespaces(namespace_name)
    except Exception as e:
        raise NamespaceNotFoundError(f"Namespace '{namespace_name}' not found: {e}") from e
    try:
        variables_obj = Variables(ns_com.Variables)
        result = []
        for var in variables_obj.fetch_all():
            result.append({
                "name": var.name,
                "value": var.get_value(),
                "full_name": var.full_name,
            })
        logger.info(f"{len(result)} variable(s) found in '{namespace_name}'")
        return result
    except Exception as e:
        raise PyCanoeError(f"Failed to enumerate variables in '{namespace_name}': {e}") from e

get_namespaces()

Get system root namespaces as a dictionary with namespace names as keys and Namespace objects as values. If an error occurs, it will log the error and return None.

Source code in src\py_canoe\core\system.py
153
154
155
156
157
158
159
160
161
162
163
164
165
def get_namespaces(self) -> dict[str, 'Namespace'] | None:
    """Get system root namespaces as a dictionary with namespace names as keys and Namespace objects as values. If an error occurs, it will log the error and return None."""
    try:
        namespaces_dict = {}
        namespaces = self.namespaces
        for index in range(1, namespaces.count + 1):
            namespace = namespaces.item(index)
            namespaces_dict[namespace.name] = namespace
        logger.info(f"total {namespaces.count} system root namespaces found.")
        return namespaces_dict
    except Exception as e:
        logger.error(f"Error getting system namespaces: {e}")
        return None

get_variable_value(sys_var_name, return_symbolic_name=False, enable_events=True)

Get the value of a system variable. If the variable does not exist, it will log an error message and return None.

Source code in src\py_canoe\core\system.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
def get_variable_value(self, sys_var_name: str, return_symbolic_name=False, enable_events: bool = True) -> Union[int, float, str, None]:
    """Get the value of a system variable. If the variable does not exist, it will log an error message and return None."""
    # enable_events is deprecated and ignored: reading a variable never registers a COM event sink
    try:
        parts = sys_var_name.split('::')
        if len(parts) < 2:
            logger.error(f"Invalid system variable name '{sys_var_name}'. Must be in 'namespace::variable' format.")
            return None
        namespace = '::'.join(parts[:-1])
        variable_name = parts[-1]
        namespace_obj = self.com_object.Namespaces(namespace)
        variable_obj = Variable(namespace_obj.Variables(variable_name))
        value = variable_obj.get_value()
        if return_symbolic_name:
            symbolic_value = variable_obj.get_symbolic_value_name(value)
            logger.info(f"System Variable '{sys_var_name}' symbolic value: {symbolic_value}")
            return symbolic_value
        logger.info(f"System Variable '{sys_var_name}' value: {value}")
        return value
    except Exception as e:
        logger.error(f"Error retrieving System Variable '{sys_var_name}': {e}")
        return None

get_variables_files()

Get system variables files as a dictionary with file full names as keys and VariablesFile objects as values. If an error occurs, it will log the error and return None.

Source code in src\py_canoe\core\system.py
196
197
198
199
200
201
202
203
204
205
206
207
208
def get_variables_files(self) -> dict[str, 'VariablesFile'] | None:
    """Get system variables files as a dictionary with file full names as keys and VariablesFile objects as values. If an error occurs, it will log the error and return None."""
    try:
        variables_files_dict = {}
        variables_files = self.variables_files
        for index in range(1, variables_files.count + 1):
            variables_file = variables_files.item(index)
            variables_files_dict[variables_file.full_name] = variables_file
        logger.info(f"total {variables_files.count} system variables files found.")
        return variables_files_dict
    except Exception as e:
        logger.error(f"Error getting system variables files: {e}")
        return None

remove_variable(sys_var_name)

Remove a system variable from the CANoe system. If the variable does not exist, it will log an info message and return False.

Source code in src\py_canoe\core\system.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def remove_variable(self, sys_var_name: str) -> bool:
    """Remove a system variable from the CANoe system. If the variable does not exist, it will log an info message and return False."""
    try:
        parts = sys_var_name.split('::')
        if len(parts) < 2:
            logger.error(f"Invalid system variable name '{sys_var_name}'. Must be in 'namespace::variable' format.")
            return False
        namespace = '::'.join(parts[:-1])
        variable_name = parts[-1]
        namespace_obj = self.com_object.Namespaces(namespace)
        variables_obj = namespace_obj.Variables
        for i in range(1, variables_obj.Count + 1):
            variable_obj = variables_obj.Item(i)
            if variable_obj.Name == variable_name:
                variables_obj.Remove(i)
                logger.info(f"System Variable '{sys_var_name}' removed successfully.")
                return True
        logger.info(f"System Variable '{sys_var_name}' not found.")
        return False
    except Exception as e:
        logger.error(f"Error removing System Variable '{sys_var_name}': {e}")
        return False

set_variable_array_values(sys_var_name, value, index=0, timeout=1, enable_events=True)

Set the values of a system variable array starting from a specific index. If the variable does not exist or if there is not enough space in the array, it will log an error message and return False.

Source code in src\py_canoe\core\system.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
def set_variable_array_values(self, sys_var_name: str, value: tuple, index: int = 0, timeout: Union[int, float] = 1, enable_events: bool = True) -> bool:
    """Set the values of a system variable array starting from a specific index. If the variable does not exist or if there is not enough space in the array, it will log an error message and return False."""
    try:
        parts = sys_var_name.split('::')
        if len(parts) < 2:
            logger.error(f"Invalid system variable name '{sys_var_name}'. Must be in 'namespace::variable' format.")
            return False
        namespace = '::'.join(parts[:-1])
        variable_name = parts[-1]
        namespace_obj = self.com_object.Namespaces(namespace)
        variable_obj = Variable(namespace_obj.Variables(variable_name), enable_events)
        arr = list(variable_obj.get_value())
        if index < 0 or index + len(value) > len(arr):
            logger.error(f"Not enough space in System Variable Array '{sys_var_name}' to set values.")
            return False
        value_type = type(arr[0]) if arr else type(value[0])
        arr[index:index + len(value)] = [value_type(v) for v in value]
        status = variable_obj.set_value(tuple(arr), timeout)
        return status
    except Exception as e:
        logger.error(f"Error setting System Variable Array '{sys_var_name}': {e}")
        return False

set_variable_value(sys_var_name, value, timeout=1, enable_events=True)

Set the value of a system variable. If the variable does not exist, it will log an error message and return False.

Source code in src\py_canoe\core\system.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
def set_variable_value(self, sys_var_name: str, value: Union[int, float, str], timeout: Union[int, float] = 1, enable_events: bool = True) -> bool:
    """Set the value of a system variable. If the variable does not exist, it will log an error message and return False."""
    try:
        parts = sys_var_name.split('::')
        if len(parts) < 2:
            logger.error(f"Invalid system variable name '{sys_var_name}'. Must be in 'namespace::variable' format.")
            return False
        namespace = '::'.join(parts[:-1])
        variable_name = parts[-1]
        namespace_obj = self.com_object.Namespaces(namespace)
        variable_obj = Variable(namespace_obj.Variables(variable_name), enable_events)
        var_type = type(variable_obj.get_value())
        try:
            converted_value = var_type(value)
        except Exception:
            logger.error(f"Could not convert value '{value}' to type {var_type.__name__} for '{sys_var_name}'")
            return False
        status = variable_obj.set_value(converted_value, timeout)
        return status
    except Exception as e:
        logger.error(f"Error setting System Variable '{sys_var_name}': {e}")
        return False