[docs]classCANapeError(Exception):def__init__(self,error_code:int,error_string:str,function:str)->None:#: The error code according to :class:`~pycanape.cnp_api.cnp_constants.ErrorCodes`self.error_code=error_codesuper().__init__(f"{function} failed ({error_string})")# keep reference to args for picklingself._args=error_code,error_string,functiondef__reduce__(self)->Union[str,tuple[Any,...]]:returnCANapeError,self._args,{}
def_kill_canape_processes()->None:# search for open CANape processes and kill themforprocinpsutil.process_iter():try:proc_name=proc.name()exceptpsutil.AccessDenied:passelse:ifproc_name.lower()in("canape.exe","canape64.exe"):proc.kill()
[docs]defget_canape_versions()->list[CANapeVersion]:"""Return a list of all CANape versions, that can be found in Windows Registry."""versions:list[CANapeVersion]=[]with(contextlib.suppress(FileNotFoundError),winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,"SOFTWARE\\VECTOR\\CANape")askey,):_sub_key_count,value_count,_last_modified=winreg.QueryInfoKey(key)foridxinrange(value_count):name,_data,_type=winreg.EnumValue(key,idx)ifnotre.match(r"Path\d{3}",name):continuetry:version_number=re.sub(pattern=r"Path",repl="",string=name)versions.append(CANapeVersion(int(version_number[:2])))exceptValueError:continuereturnversions
[docs]defget_canape_path(version:Optional[CANapeVersion]=None)->Path:"""Return the path to the CANape installation from Windows registry. :param version: Select the CANape version that shall be found. If ``None``, it will usually return the version, that was installed last. :return: Path to the CANape installation. """name=f"Path{version.value}0"ifversionelse"Path"withwinreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,"SOFTWARE\\VECTOR\\CANape")askey:try:returnPath(winreg.QueryValueEx(key,name)[0])exceptFileNotFoundError:err_msg="CANape path not found in Windows registry."raiseFileNotFoundError(err_msg)fromNone
[docs]defget_canape_data_path(version:Optional[CANapeVersion]=None)->Path:"""Return the path to the CANape data folder from Windows registry. :param version: Select the CANape version that shall be found. If ``None``, it will usually return the version, that was installed last. :return: Path to the CANape data folder. """name=f"DataPath{version.value}0"ifversionelse"DataPath"withwinreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,"SOFTWARE\\VECTOR\\CANape")askey:try:returnPath(winreg.QueryValueEx(key,name)[0])exceptFileNotFoundError:err_msg="CANape data path not found in Windows registry."raiseFileNotFoundError(err_msg)fromNone
[docs]defget_canape_dll_path(version:Optional[CANapeVersion]=None)->Path:"""Return the path to the CANapAPI.dll from Windows registry or PATH. :param version: Select the CANape version that shall be found. If ``None``, it will usually return the version, that was installed last. :return: Path to the CANapAPI.dll. """dll_name="CANapAPI64"ifplatform.architecture()[0]=="64bit"else"CANapAPI"# try to find dll via registry entrywithcontextlib.suppress(FileNotFoundError):canape_path=get_canape_path(version)dll_path=canape_path/"CANapeAPI"/(dll_name+".dll")ifdll_path.exists():returndll_path# try to find dll via PATH environment variableifdll_path_string:=find_library(dll_name):returnPath(dll_path_string)err_msg="CANape DLL not found."raiseFileNotFoundError(err_msg)