首页 > 编程语言 >python脚本调用CANoe COM Server接口

python脚本调用CANoe COM Server接口

时间:2023-01-04 18:56:08浏览次数:48  
标签:CANoe python self Server tm test app tc def

《CANoe开发入门到精通》源码:

# -----------------------------------------------------------------------------
# Example: Test Feature Set via Python
# 
# This sample demonstrates how to start the test modules and test 
# configurations via COM API using a Python script.
# The script uses the included PythonBasicEmpty.cfg configuration but is  
# working also with any other CANoe configuration containing test modules  
# and test configurations. 
# 
# Limitations:
#  - only the first test environment is supported. If the configuration 
#    contains more than one test environment, the other test environments 
#    are ignored
#  - the script does not wait for test reports to be finished. If the test
#    reports are enabled, they may run in the background after the test is 
#    finished
# -----------------------------------------------------------------------------
# Copyright (c) 2017 by Vector Informatik GmbH.  All rights reserved.
# -----------------------------------------------------------------------------

import time, os, msvcrt
from win32com.client import *
from win32com.client.connect import *

def DoEvents():
    pythoncom.PumpWaitingMessages()
    time.sleep(.1)
def DoEventsUntil(cond):
    while not cond():
        DoEvents()

class CanoeSync(object):
    """Wrapper class for CANoe Application object"""
    Started = False
    Stopped = False
    ConfigPath = ""
    def __init__(self):
        app = DispatchEx('CANoe.Application')    
        app.Configuration.Modified = False
        ver = app.Version
        print('Loaded CANoe version ', 
            ver.major, '.', 
            ver.minor, '.', 
            ver.Build, '...', sep='')
        self.App = app
        self.Measurement = app.Measurement  
        self.Running = lambda : self.Measurement.Running
        self.WaitForStart = lambda: DoEventsUntil(lambda: CanoeSync.Started)
        self.WaitForStop = lambda: DoEventsUntil(lambda: CanoeSync.Stopped)
        WithEvents(self.App.Measurement, CanoeMeasurementEvents)

    def Load(self, cfgPath):
        # current dir must point to the script file
        cfg = os.path.join(os.curdir, cfgPath)
        cfg = os.path.abspath(cfg)
        print('Opening: ', cfg)
        self.ConfigPath = os.path.dirname(cfg)
        self.Configuration = self.App.Configuration
        self.App.Open(cfg)

    def LoadTestSetup(self, testsetup):
        self.TestSetup = self.App.Configuration.TestSetup
        path = os.path.join(self.ConfigPath, testsetup)
        testenv = self.TestSetup.TestEnvironments.Add(path)
        testenv = CastTo(testenv, "ITestEnvironment2")
         # TestModules property to access the test modules
        self.TestModules = []
        self.TraverseTestItem(testenv, lambda tm: self.TestModules.append(CanoeTestModule(tm)))
    
    def LoadTestConfiguration(self, testcfgname, testunits):
        """ Adds a test configuration and initialize it with a list of existing test units """
        tc = self.App.Configuration.TestConfigurations.Add()
        tc.Name = testcfgname
        tus = CastTo(tc.TestUnits, "ITestUnits2")
        for tu in testunits:
            tus.Add(tu)
        # TestConfigs property to access the test configuration
        self.TestConfigs = [CanoeTestConfiguration(tc)]

    def Start(self): 
        if not self.Running():
            self.Measurement.Start()
            self.WaitForStart()

    def Stop(self):
        if self.Running():
            self.Measurement.Stop()
            self.WaitForStop()
       

    def RunTestModules(self):
        """ starts all test modules and waits for all of them to finish"""
        # start all test modules
        for tm in self.TestModules:
            tm.Start()
    
        # wait for test modules to stop
        while not all([not tm.Enabled or tm.IsDone() for tm in app.TestModules]):
            DoEvents()

    def RunTestConfigs(self):
        """ starts all test configurations and waits for all of them to finish"""
        # start all test configurations
        for tc in self.TestConfigs:
            tc.Start()
    
        # wait for test modules to stop
        while not all([not tc.Enabled or tc.IsDone() for tc in app.TestConfigs]):
            DoEvents()

    def TraverseTestItem(self, parent, testf):
        for test in parent.TestModules: 
            testf(test)
        for folder in parent.Folders: 
            found = self.TraverseTestItem(folder, testf)

class CanoeMeasurementEvents(object):
    """Handler for CANoe measurement events"""
    def OnStart(self): 
        CanoeSync.Started = True
        CanoeSync.Stopped = False
        print("< measurement started >")
    def OnStop(self) : 
        CanoeSync.Started = False
        CanoeSync.Stopped = True
        print("< measurement stopped >")

class CanoeTestModule:
    """Wrapper class for CANoe TestModule object"""
    def __init__(self, tm):
        self.tm = tm
        self.Events = DispatchWithEvents(tm, CanoeTestEvents)
        self.Name = tm.Name
        self.IsDone = lambda: self.Events.stopped
        self.Enabled = tm.Enabled
    def Start(self):
        if self.tm.Enabled:
            self.tm.Start()
            self.Events.WaitForStart()

class CanoeTestConfiguration:
    """Wrapper class for a CANoe Test Configuration object"""
    def __init__(self, tc):        
        self.tc = tc
        self.Name = tc.Name
        self.Events = DispatchWithEvents(tc, CanoeTestEvents)
        self.IsDone = lambda: self.Events.stopped
        self.Enabled = tc.Enabled
    def Start(self):
        if self.tc.Enabled:
            self.tc.Start()
            self.Events.WaitForStart()

class CanoeTestEvents:
    """Utility class to handle the test events"""
    def __init__(self):
        self.started = False
        self.stopped = False
        self.WaitForStart = lambda: DoEventsUntil(lambda: self.started)
        self.WaitForStop = lambda: DoEventsUntil(lambda: self.stopped)
    def OnStart(self):
        self.started = True
        self.stopped = False        
        print("<", self.Name, " started >")
    def OnStop(self, reason):
        self.started = False
        self.stopped = True 
        print("<", self.Name, " stopped >")

# -----------------------------------------------------------------------------
# main
# -----------------------------------------------------------------------------
app = CanoeSync()

# loads the sample configuration
app.Load('CANoeConfig\PythonBasicEmpty.cfg')

# add test modules to the configuration
app.LoadTestSetup('TestEnvironments\Test Environment.tse')

# add a test configuration and a list of test units
app.LoadTestConfiguration('TestConfiguration', ['TestConfiguration\EasyTest\EasyTest.vtuexe'])

# start the measurement
app.Start()    

# runs the test modules
app.RunTestModules()

# runs the test configurations
app.RunTestConfigs()

# wait for a keypress to end the program
print("Press any key to exit ...")
while not msvcrt.kbhit():
    DoEvents()

# stops the measurement
app.Stop()
View Code

 

标签:CANoe,python,self,Server,tm,test,app,tc,def
From: https://www.cnblogs.com/aplmmy49y/p/17025740.html

相关文章

  • (15)Python识别文字,tesseract包
    使用python提供的tesseract包识别图片中的文字,但效果一般我的是在arch中实现的文章目录​​1、安装tesseract和英文和中文语言包​​​​2、安装必要的第三方库​​​​3、......
  • python爬取银行存款利率数据
    三年疫情让各行各业的经济都下滑了很多,手里有钱的人都会很谨慎地进行一些投资项目。2023新年来临,银行存款利率也出现一波调整,近期多家中小银行对定期存款挂牌利率进行下调。......
  • Python内置方法
    开胃菜(小例子、用法):help(method)查看帮助,按space或enter继续显示多的行数(--More--),按ctrl+c退出。如果想要查看有哪些方法,比如list有哪些方法,可以:dir(list)输出:>......
  • 【Azure 应用服务】Azure Function Python函数部署到Azure后遇见 Value cannot be nul
    问题描述使用VSCode创建PythonFunction,处理EventHub中的数据。当部署到AzureFunctionApp后,函数无法执行,查看Function日志出现 Valuecannotbenull.(Parameter......
  • python常识系列07-->python利用xlwt写入excel文件
     前言读书之法,在循序而渐进,熟读而精思。——朱熹抽空又来写一篇,毕竟知识在于分享!一、xlwt模块是什么python第三方工具包,用于往excel中写入数据;(ps:只能创建新表格,不能修......
  • CentOS7下搭建JumpServer
    JumpServer部署架构图JumpServer功能架构图JumpServer是广受欢迎的开源堡垒机,是符合4A规范的专业运维安全审计系统。JumpServer使用Python开发,配备了业界......
  • 网上一个哥们写的,使用Python写一个m3u8多线程下载器 -- 没用起来
    文章目录I.挖坑缘由II.功能/更新记录III.代码1.GUI2.下载工具类3.逻辑代码IV.下载地址I.挖坑缘由现在很多在线观看的视频为了防盗链使用了M3u8格式,想要下载的话比较麻烦,如果......
  • 万万没想到,除了香农计划,Python3.11竟还有这么多性能提升!
    众所周知,Python3.11版本带来了较大的性能提升,但是,它具体在哪些方面上得到了优化呢?除了著名的“香农计划”外,它还包含哪些与性能相关的优化呢?本文将带你一探究竟!作者:Beshr......
  • 谷歌、微软、Meta?谁才是 Python 最大的金主?
    你知道维护Python这个大规模的开源项目,每年需要多少资金吗?答案是:约200万美元!​​PSF​​​(Python软件基金会)在2022年6月发布了2021的​​年度报告​​,其中披露了......
  • UniPush FCM 需要的Legancy server key官方已经停用了
    在使用unipush功能时发现:Firebase官方已经停用了CloudMessagingAPI(Legacy),统一用新的FirebaseCloudMessagingAPI(V1)了,然后UniPushFCM需要的Legancyserve......