py_canoe.core.application.Application

Main interface to CANoe via COM automation.

The Application class automatically registers an IMessageFilter that suppresses 'Server Busy' dialogs when CANoe is temporarily unable to process COM calls (e.g., during report generation after measurement stop). Rejected calls are retried automatically with exponential backoff up to 60 seconds.

Source code in src\py_canoe\core\application.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def __init__(self, enable_events: bool = True) -> None:
    self._enable_events = enable_events
    self.bus_types = {'CAN': 1, 'J1939': 2, 'FLEXRAY': 3, 'TTP': 4, 'LIN': 5, 'MOST': 6, 'ETH': 7, 'Kline': 14}
    self.com_object = None
    self.application_events = None
    self.bus: Bus = None
    self.capl: Capl = None
    self.configuration: Configuration = None
    self.environment: Environment = None
    self.measurement: Measurement = None
    self.system: System = None
    self.ui: Ui = None
    self.version: Version = None
    self.capl_function_objects = object()
    self.user_capl_functions = tuple()
    # Register IMessageFilter to suppress "Server Busy" dialogs and auto-retry
    # rejected COM calls. The filter stays active for the Application's lifetime.
    self._message_filter = COMRetryMessageFilter()
    self._message_filter.register()

attach_to_active_application()

Attach to a active instance of the CANoe application.

Source code in src\py_canoe\core\application.py
254
255
256
257
258
259
260
261
262
263
264
265
266
267
def attach_to_active_application(self) -> bool:
    """Attach to a active instance of the CANoe application."""
    try:
        self._launch_application()
        if self.com_object:
            logger.info("Successfully attached to active CANoe application ")
            self._setup_post_configuration_loading()
            return True
        else:
            logger.error("Failed to attach to active CANoe application")
            return False
    except Exception as e:
        logger.error(f"Error attaching to active CANoe application: {e}")
        return False

new(auto_save=False, prompt_user=False, timeout=5)

Create a new empty CANoe configuration.

Source code in src\py_canoe\core\application.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
def new(self, auto_save: bool = False, prompt_user: bool = False, timeout: int = 5) -> bool:
    """Create a new empty CANoe configuration."""
    self._launch_application()
    status = False
    try:
        logger.info("Opening new empty CANoe configuration...")
        self.com_object.New(auto_save, prompt_user)
        if self._enable_events:
            cond = lambda: self.application_events.OPENED
        else:
            cond = lambda: self.com_object.FullName != ""
        status = DoEventsUntil(cond, timeout, "New CANoe configuration")
        if status:
            logger.info("New empty CANoe configuration Opened")
            self._setup_post_configuration_loading()
        return status
    except Exception as e:
        logger.error(f"Error creating new configuration: {e}")
        status = False
        return status

open(canoe_cfg, visible=True, auto_save=True, prompt_user=False, timeout=5)

Open an existing CANoe configuration.

Source code in src\py_canoe\core\application.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
def open(self, canoe_cfg: str | Path, visible: bool = True, auto_save: bool = True, prompt_user: bool = False, timeout: int = 5) -> bool:
    """Open an existing CANoe configuration."""
    self._launch_application()
    status = False
    try:
        self.visible = visible
        logger.info("Opening CANoe configuration ...")
        canoe_cfg_str = str(Path(canoe_cfg).resolve())
        self.com_object.Open(canoe_cfg_str, auto_save, prompt_user)
        if self._enable_events:
            cond = lambda: self.application_events.OPENED
        else:
            cond = lambda: self.com_object.FullName.lower() == canoe_cfg_str.lower()
        status = DoEventsUntil(cond, timeout, "Open CANoe configuration")
        if status:
            logger.info(f"CANoe Configuration {canoe_cfg} Opened")
            self._setup_post_configuration_loading()
        return status
    except Exception as e:
        logger.error(f"Error opening configuration: {e}")
        status = False
        return status

open_config(canoe_cfg, auto_save=True, prompt_user=False, timeout=60)

Switch to a different CANoe configuration without restarting CANoe.

This method switches configurations in an already-running CANoe instance. Use this when CANoe is already running and you want to load a different .cfg file.

For starting CANoe with a configuration from scratch, use open() instead.

Parameters:
  • canoe_cfg (str | Path) –

    Path to the CANoe configuration (.cfg) file.

  • auto_save (bool, default: True ) –

    If True, automatically save the current configuration before switching.

  • prompt_user (bool, default: False ) –

    If True, prompt user for confirmation before switching.

  • timeout (int, default: 60 ) –

    Maximum time to wait for configuration to load (seconds).

Returns:
  • bool

    True if configuration was successfully loaded, False otherwise.

Source code in src\py_canoe\core\application.py
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
def open_config(self, canoe_cfg: str | Path, auto_save: bool = True, prompt_user: bool = False, timeout: int = 60) -> bool:
    """Switch to a different CANoe configuration without restarting CANoe.

    This method switches configurations in an already-running CANoe instance.
    Use this when CANoe is already running and you want to load a different .cfg file.

    For starting CANoe with a configuration from scratch, use open() instead.

    Args:
        canoe_cfg: Path to the CANoe configuration (.cfg) file.
        auto_save: If True, automatically save the current configuration before switching.
        prompt_user: If True, prompt user for confirmation before switching.
        timeout: Maximum time to wait for configuration to load (seconds).

    Returns:
        True if configuration was successfully loaded, False otherwise.
    """
    import time as _time
    status = False
    try:
        abs_path = str(Path(canoe_cfg).resolve())
        logger.info(f"Switching to CANoe configuration: {abs_path}")

        # Reset OPENED flag before calling Open
        self.application_events.OPENED = False

        # Call COM Open() to switch configuration
        self.com_object.Open(abs_path, auto_save, prompt_user)

        if self._enable_events:
            status = DoEventsUntil(
                lambda: self.application_events.OPENED and self.configuration.full_name.lower() == abs_path.lower(),
                timeout,
                f"Switch to configuration {canoe_cfg}"
            )
        else:
            # Poll FullName without PumpWaitingMessages
            poll_deadline = _time.monotonic() + timeout
            while _time.monotonic() < poll_deadline:
                try:
                    if self.configuration.full_name.lower() == abs_path.lower():
                        status = True
                        break
                except Exception:
                    pass
                _time.sleep(0.2)

        if status:
            logger.info(f"Configuration switched successfully to {canoe_cfg}")
            self._setup_post_configuration_loading()
        else:
            logger.warning(f"Configuration switch timed out after {timeout}s")

        return status
    except Exception as e:
        logger.error(f"Error switching configuration: {e}")
        return False

pump_messages()

Pump COM messages to prevent blocking.

This is a thin wrapper around pythoncom.PumpWaitingMessages(). Use this in custom wait loops to keep COM responsive.

Example

while not ready(): app.pump_messages() time.sleep(0.1)

Source code in src\py_canoe\core\application.py
327
328
329
330
331
332
333
334
335
336
337
338
def pump_messages(self) -> None:
    """Pump COM messages to prevent blocking.

    This is a thin wrapper around pythoncom.PumpWaitingMessages().
    Use this in custom wait loops to keep COM responsive.

    Example:
        >>> while not ready():
        >>>     app.pump_messages()
        >>>     time.sleep(0.1)
    """
    pythoncom.PumpWaitingMessages()

quit(timeout=5)

Quit CANoe and clean up COM references.

Source code in src\py_canoe\core\application.py
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
def quit(self, timeout: int = 5) -> bool:
    """Quit CANoe and clean up COM references."""
    status = False
    try:
        if self.configuration is not None and self.configuration.modified:
            self.configuration.modified = False
        # Do NOT release event sinks before Quit(). CANoe fires OnExit (and
        # potentially OnStop) as part of its internal shutdown sequence after
        # Quit() is called. Releasing sinks beforehand leaves CANoe with a
        # dangling vtable pointer → access violation → crash dialog.
        # Sinks are released in the finally block after CANoe has shut down.
        self.com_object.Quit()
        status = DoEventsUntil(lambda: self.application_events.QUIT, timeout, "Quit CANoe application")
        if status:
            logger.info("CANoe Application Quit Successfully.")
        return status
    except Exception as e:
        logger.error(f"Error during CANoe quit: {e}")
        status = False
        return status
    finally:
        self._release_event_sinks()