NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

# -*- coding: UTF-8 -*-
#******************************************************************************#
# COPYRIGHT (C) Schaeffler Automotive Buehl GmbH & Co. KG #
# ALL RIGHTS RESERVED. #
# #
# The reproduction, transmission or use of this document or its #
# contents is not permitted without express written authority. #
# Offenders will be liable for damages. All rights, including rights #
# created by patent grant or registration of a utility model or design, #
# are reserved. #
#******************************************************************************#

# $ProjectName: /eMob/PL/Software/TestAutomation/HIL_MODEL_2018/Main/hil_x20/2023/dSPACE/L01_cmn/L01_cmn.pj $
# $ProjectRevision: Last Checkpoint: 1.24 $
#
# $RCSfile: 05_tools/ConfigurationDesk/create_configuration_desk_project.py $
# $Revision: 1.11 $
# $Author: Narender Singh, Mohit (ext.) AE/PUN-RM133 (NARENMHI) $
# $Date: 2024/06/17 09:59:49CEST $

# python imports
import re
import sys
import os
import shutil
sys.path.extend(['C:\Program Files\dSPACE RCPHIL 2021-A\ConfigurationDesk\Implementation\bin', 'C:\Program Files\dSPACE RCPHIL 2021-A\ConfigurationDesk\Implementation\bin', 'C:\Program Files\Python39\python39.zip', 'C:\Program Files\Python39\DLLs', 'C:\Program Files\Python39\lib', 'C:\Program Files\Python39', 'C:\Program Files\Python39\lib\site-packages', 'C:\Program Files\Python39\lib\site-packages\dSPACECommon', 'C:\Program Files\Python39\lib\site-packages\win32', 'C:\Program Files\Python39\lib\site-packages\win32\lib', 'C:\Program Files\Python39\lib\site-packages\Pythonwin'])
from win32com.client import Dispatch
from dspace.com import Enums
from tkinter import *
from tkinter import filedialog, messagebox

#-------------------------------------------------------------------------
# class automation
# This is the main class that controls and runs the script
#-------------------------------------------------------------------------

class automation:
#---------------------------------------------------------------------
# Method: __init__
# Initializing Automation class attributes
#---------------------------------------------------------------------
def __init__(self):

# Creating a Dispatch object for ConfigurationDesk application
self.ConfigDesk=Dispatch('ConfigurationDesk.Application')

# Creating an Enums object using ConfigurationDesk instance
self.Enums = Enums(self.ConfigDesk)

# Setting ConfigurationDesk application window visibility
self.ConfigDesk.MainWindow.Visible=True

# Initializing attributes for ConfigurationDesk application components
self.ActiveApplication= None
self.ModelTopology=None
self.IOFunctionLib=None
self.HardwareTopology=None
self.HardwareRequirements=None
self.GlobalView=None
self.CustomInformation=None


# List to store model port blocks
self.ModelPortBlockList=[]

# List to store function blocks
self.FunctionBlockList=[]


def CheckifOpen(self):
ActiveProject=self.ConfigDesk.ActiveProject
if ActiveProject:
project=os.path.dirname(ActiveProject.FullPath)
projectpath,projectname=os.path.split(project)
if self.ConfigDesk.ActiveApplication:
applicationname=self.ConfigDesk.ActiveApplication.Application.Name
return projectpath,projectname,applicationname
return projectpath,projectname,'TQ250'
return None,None,None


#-----------------------------------------------------------------
# Method: Initialize
# Initializing project-specific paths and names
#-----------------------------------------------------------------
def Initialize(self,project_name,project_root,app_name,model_path,ini_file):
try:
self.project_name=project_name
self.project_root=project_root
self.model_paths=model_path
file="hardware_resource_x20.htfx"
currentDir=os.getcwd()
self.htfx_path=os.path.join(currentDir,file)
# self.htfx_path=r"C:UsersLXSHILX1Documentsnarenmhi2_Draftcreate_configuration_desk_projectImport_Fileshardware_resource_x20.htfx"
self.application_name=app_name
self.inifile_path=ini_file
except Exception as exc:
messagebox.showerror('Error',"Exception in script :" + str(exc))
sys.exit()

#-----------------------------------------------------------------
# Method: CreateProject
# Creating a new project in ConfigurationDesk
#-----------------------------------------------------------------
def CreateProject(self):
try:
if not self.ConfigDesk.ProjectRoots.Contains(self.project_root):
projectroot=self.ConfigDesk.ProjectRoots.Add(self.project_root)
else:
projectroot=self.ConfigDesk.ProjectRoots.Item(self.project_root)
projectroot.Activate()

if self.ConfigDesk.Projects.Contains(self.project_name):
# sys.exit('Another project already exists in the root directory.Please choose a different name.nExiting...')
# Project Already exist give warning
messagebox.showwarning('_Overwrite!!!','A project with the same name already exists. Files will be overwritten')
project=self.ConfigDesk.Projects.Item(self.project_name)
project=project.Open(True)
if project.Applications.Contains(self.application_name):
Application=project.Applications.Item(self.application_name)
Application.Activate()
else:
Application=project.Applications.Add(self.application_name)
else:
project=self.ConfigDesk.Projects.Add(self.project_name)
Application=project.Applications.Add(self.application_name)
self.importIni()
# Initializing project-related attributes
self.ActiveApplication=self.ConfigDesk.ActiveApplication
self.HardwareTopology=self.ActiveApplication.Components.HardwareTopology
self.ModelTopology=self.ActiveApplication.Components.ModelTopology
self.IOFunctionLib=self.ActiveApplication.Components.IOFunctionLib.Item(0)
self.HardwareRequirements=self.ActiveApplication.Relations.HardwareRequirements
except Exception as exc:
messagebox.showerror('Error',"Exception in script :" + str(exc))
sys.exit()

def importIni(self):
self.ConfigDesk.SetCustomInformation(["ImportCustomFunctions"],[self.inifile_path,True])

def CreateApplication(self):
# Add a loop for multiple Model files
self.ConfigureHardwareTopology()
self.TraverseModel()

def TraverseModel(self):
try:
for modelpath in self.model_paths:
self.FunctionBlockList=[]
self.ModelPortBlockList=[]
FileName=os.path.splitext(os.path.basename(modelpath))
if FileName[1]=='.slx':
WorkingView=FileName[0]
self.GlobalView=self.ActiveApplication.WorkingViews.Add('',WorkingView)
if not os.path.isfile(os.path.join(self.project_root,self.project_name,'Models',FileName[0]+'.slx')):
modelpath=shutil.copy(modelpath,os.path.join(self.project_root,self.project_name,'Models'))
self.ConfigureModelTopology(modelpath)
model=self.ModelTopology.Item(self.ModelTopology.Count-1)
# clear function block list and model block lists here
self.TraversingTopologies(model)
self.ConnectBlocks()
else:
if not os.path.isfile(os.path.join(self.project_root,self.project_name,'Models',FileName[0]+'.m')):
shutil.copy(modelpath,os.path.join(self.project_root,self.project_name,'Models'))
except Exception as exc:
messagebox.showerror('Error',"Exception in script :" + str(exc))
sys.exit()

def ConfigureModelTopology(self,modelpath):
try:
Args=[]
Args.append(modelpath)
Args.append(True)
Args.append('')
Args.append(True)

# Configuring model topology
self.ModelTopology.Configure("AddModel",Args)

except Exception as exc:
messagebox.showerror('Error',"Exception in script :" + str(exc))
sys.exit()

#-----------------------------------------------------------------
# Method: ConfigureTopologies
# Configuring model and hardware topologies
#-----------------------------------------------------------------
def ConfigureHardwareTopology(self):
try:
Args=[]
# self.HardwareTopology.Configure("Remove",Args)
Args.append(self.Enums.HardwareTopologyCreateMode.FileImportHtf)
Args.append('Hardware Topology')
Args.append(self.htfx_path)

# Configuring hardware topology
self.HardwareTopology.Configure("Create",Args)
except Exception as exc:
messagebox.showerror('Error',"Exception in script :" + str(exc))
sys.exit()

#-----------------------------------------------------------------
# Method: TraversingTopologies
# Recursively traversing model topology elements
#-----------------------------------------------------------------
def TraversingTopologies(self,RootObject):
try:
for i in range(RootObject.GetCount()):
if RootObject.Item(i).GetCount()>0 and not RootObject.Item(i).IsOfRole('ModelPortBlock'):
self.TraversingTopologies(RootObject.Item(i))
elif RootObject.Item(i).IsOfRole('ModelPortBlock'):

# Adding model port block to list
self.ModelPortBlockList.append(RootObject.Item(i))
ModelPortBlock=RootObject.Item(i)

# Adding model port block to view
self.AddToView(ModelPortBlock)

# Finding corresponding function block
FunctionName=self.FindFunctionBlock(ModelPortBlock)
if FunctionName:

# Creating function block
FunctionBlock=self.CreateFunctionBlock(FunctionName,ModelPortBlock)

self.AddToView(FunctionBlock)

# Adding function block to list
self.FunctionBlockList.append(FunctionBlock)

# Finding channel set
ChannelSet=self.FindChannelSet(FunctionBlock,ModelPortBlock)

# Assigning channel set
if ChannelSet:
self.AssignChannelSet(FunctionBlock,ChannelSet)
# Finding channel
ChannelRequirement,Channel=self.FindChannel(FunctionBlock,ModelPortBlock)
if Channel:
# Assigning channel
self.AssignChannel(ChannelRequirement,Channel,FunctionBlock)
else:
print('The Channel is unavailable')
else:
print('This ChannelSet is unavailable')

print('-'*30)
except Exception as exc:
messagebox.showerror('Error',"Exception in script :" + str(exc))
sys.exit()

#-----------------------------------------------------------------
# Method: AddToView
# Adding model port block to the global working view
#-----------------------------------------------------------------
def AddToView(self,Block):
self.GlobalView.Add(Block)
print(f'{Block.Name} added to Working View')

#-----------------------------------------------------------------
# Method: FindFunctionBlock
# Finding the corresponding function block for a model port block
#-----------------------------------------------------------------
def FindFunctionBlock(self,ModelPortBlock):
if "Inport" in ModelPortBlock.Name:
print(f'No Function Block created for {ModelPortBlock.Name}')
elif "Trigger" in ModelPortBlock.Name:
print(f'No Function Block created for {ModelPortBlock.Name}')
elif "Outport" in ModelPortBlock.Name:
ModelPortBlockName=ModelPortBlock.Name.replace("_Outport",'')
for FunctionBlock in self.IOFunctionLib:
if CheckName(FunctionBlock.Name,ModelPortBlockName):
return FunctionBlock
else:
for FunctionBlock in self.IOFunctionLib:
if CheckName(FunctionBlock.Name,ModelPortBlock.Name):
return FunctionBlock
#-----------------------------------------------------------------
# Method: CreateFunctionBlock
# Creating a function block corresponding to a model port block
#-----------------------------------------------------------------
def CreateFunctionBlock(self,FunctionName,ModelPortBlock):
try:
FunctionBlock=FunctionName.CreateChild(FunctionName.DataObjectTypes.Item(0),ModelPortBlock.Name.replace("_Outport",''))
print(f'{FunctionName.Name} sucessfully created for {ModelPortBlock.Name}')
return FunctionBlock
except Exception as exc:
messagebox.showerror('Error',"Exception in script :" + str(exc))
sys.exit()
#-----------------------------------------------------------------
# Method: FindChannelSet
# Finding the channel set for a function block and model port block pair
#-----------------------------------------------------------------
def FindChannelSet(self,FunctionBlock,ModelPortBlock):
try:
ChannelSets=self.ActiveApplication.Algorithms.GetAssignableChannelSets(FunctionBlock)
for i in range(ChannelSets.count):
if CheckName(ChannelSets.Item(i).Name,ModelPortBlock.Name):
return ChannelSets.Item(i)
return None
except Exception as exc:
messagebox.showerror('Error',"Exception in script :" + str(exc))
sys.exit()
#-----------------------------------------------------------------
# Method:AssignChannelSet
# Assigning a channel set to a function block
#-----------------------------------------------------------------
def AssignChannelSet(self,FunctionBlock,ChannelSet):
try:
self.ActiveApplication.Relations.ChannelSets.SetElements(FunctionBlock,[ChannelSet])
print(f'{ChannelSet.Name} assigned sucessfully for {FunctionBlock.Name}')
except Exception as exc:
messagebox.showerror('Error',"Exception in script :" + str(exc))
sys.exit()
#-----------------------------------------------------------------
# Method:FindChannel
# Finding a channel for a function block and model port block pair
#-----------------------------------------------------------------
def FindChannel(self,FunctionBlock,ModelPortBlock):
try:
ChannelRequirements=self.HardwareRequirements.GetElements(FunctionBlock.Item(0))
Channels=self.ActiveApplication.Relations.ApplicableChannels.GetElements(ChannelRequirements.Item(0))
SetChannel=re.search(r'(?<=Ch)([0]?)([1-9]?[0-9])',ModelPortBlock.Name)
SetChannel='Channel '+SetChannel.group(2)
for Channel in Channels:
if SetChannel == Channel.Name:
return ChannelRequirements,Channel
return ChannelRequirements,None
except Exception as exc:
messagebox.showerror('Error',"Exception in script :" + str(exc))
sys.exit()
#-----------------------------------------------------------------
# Method: AssignChannel
# Assigning a channel to a function block
#-----------------------------------------------------------------
def AssignChannel(self,ChannelRequirements,Channel,FunctionBlock):
try:
self.ActiveApplication.Relations.AssignedChannels.SetElements(ChannelRequirements.Item(0),[Channel])
print(f'{Channel.Name} assigned sucessfully for {FunctionBlock.Name}')
except Exception as exc:
messagebox.showerror('Error',"Exception in script :" + str(exc))
sys.exit()
#-----------------------------------------------------------------
# Method: ConnectBlocks
# Connecting model port blocks to function blocks
#-----------------------------------------------------------------
def ConnectBlocks(self):
print('*'*100)
try:
for ModelPortBlock in self.ModelPortBlockList:
if 'Trigger' in ModelPortBlock.Name:
for FunctionBlock in self.FunctionBlockList:
if ModelPortBlock.Name.replace('_Trigger','')==FunctionBlock.Name:
# Enable Event Generation for the Function Block
FunctionBlockEventGeneration=FunctionBlock.Properties.Item('IsEventGenerationEnabled')
FunctionBlockEventGeneration.Value=True
ModelPort=ModelPortBlock.Item(0)
EventPort=re.search('(?<=/).*',ModelPort.Name)
self.FunctionPorts=[]
self.GetFunctionPort(FunctionBlock.Item(1))
for FunctionPort in self.FunctionPorts:
if FunctionPort.Name.replace(' ','')==EventPort.group():
self.ActiveApplication.ConnectObjects(ModelPort,FunctionPort)


else:
for FunctionBlock in self.FunctionBlockList:
if ModelPortBlock.Name.replace('_Inport','').replace('_Outport','')==FunctionBlock.Name:
print(f'Connecting {ModelPortBlock.Name} to {FunctionBlock.Name}')
if FunctionBlock.Item(1).GetCount()==1 and FunctionBlock.Item(1).Item(0).IsOfRole('Port'):
FunctionPort=FunctionBlock.Item(1).Item(0)
if ModelPortBlock.GetCount()==1 and ModelPortBlock.Item(0).IsOfRole('Port'):
ModelPort=ModelPortBlock.Item(0)
self.ActiveApplication.ConnectObjects(ModelPort,FunctionPort)
else:
self.FunctionPorts=[]
self.ModelPorts=[]
self.GetFunctionPort(FunctionBlock.Item(1))
self.GetModelPort(ModelPortBlock)
for ModelPort in self.ModelPorts:
for FunctionPort in self.FunctionPorts:
if FunctionPort.Name.replace(' ','')==ModelPort.Name:
self.ActiveApplication.ConnectObjects(ModelPort,FunctionPort)
except Exception as exc:
messagebox.showerror('Error',"Exception in script :" + str(exc))
sys.exit()

#-----------------------------------------------------------------
# Method: GetFunctionPort
# Getting function ports recursively
#-----------------------------------------------------------------
def GetFunctionPort(self,RootObject):
try:
for i in range(RootObject.GetCount()):
if RootObject.Item(i).GetCount()>0:
self.GetFunctionPort(RootObject.Item(i))
elif RootObject.Item(i).IsOfRole('Port'):
self.FunctionPorts.append(RootObject.Item(i))
except Exception as exc:
messagebox.showerror('Error',"Exception in script :" + str(exc))
sys.exit()

#-----------------------------------------------------------------
# Method: GetModelPort
# Getting model ports recursively
#-----------------------------------------------------------------
def GetModelPort(self,RootObject):
try:
for i in range(RootObject.GetCount()):
if RootObject.Item(i).GetCount()>0:
self.GetModelPort(RootObject.Item(i))
elif RootObject.Item(i).IsOfRole('Port'):
self.ModelPorts.append(RootObject.Item(i))
except Exception as exc:
messagebox.showerror('Error',"Exception in script :" + str(exc))
sys.exit()
#---------------------------------------------------------------------
# Method: CheckName
# Checking if a name exists in a string
#---------------------------------------------------------------------
def CheckName(Name,String):
try:
Name=Name.replace(' ','')
if Name in String:
return True
except Exception as exc:
messagebox.showerror('Error',"Exception in script :" + str(exc))
sys.exit()
#---------------------------------------------------------------------
# Method: CheckWords
# Checking if all words in a list exist in a string
#---------------------------------------------------------------------
def CheckWords(Words,String):
try:
Words=Words.split(' ')
return all(Word in String for Word in Words)
except Exception as exc:
messagebox.showerror('Error',"Exception in script :" + str(exc))
sys.exit()
#---------------------------------------------------------------------
# Method: CreateProjectInCD
# Function to initialize and create a new project in ConfigurationDesk
#---------------------------------------------------------------------
def CreateProjectInCD(project_name,project_path,app_name,model_path,ini_file):

obj.Initialize(project_name,project_path,app_name,model_path,ini_file)
obj.CreateProject()
#---------------------------------------------------------------------
# Method: ImportFilesInCD
# Function to configure model and hardware topologies
#---------------------------------------------------------------------
def ImportFilesInCD():
obj.CreateApplication()

#---------------------------------------------------------------------
# Method: BuildSignalChain
# Function to traverse the model topology, create function blocks, and connect them
#---------------------------------------------------------------------

def selectModelfile():
ent_modelFile.delete(0,END)
modelFiles=filedialog.askopenfilenames(initialdir='L:',title='Select model and script files to be added to the application',filetypes=[('Model and script files',('*.m','*.slx'))])
for modelFile in modelFiles:
ent_modelFile.insert(ent_modelFile.index(INSERT),modelFile+',')
ent_modelFile.delete(ent_modelFile.index(END)-1,END)
# return(os.path.normpath(modelFile))

def selectinifiles():
ent_iniFile.delete(0, END)
Ini_file =filedialog.askopenfilename(initialdir='L:',title='Select INI file',filetypes=[('INI File',('*.ini'))])
ent_iniFile.insert(0,Ini_file)

def selectProjectpath():
ent_projectPath.delete(0,END)
Projectpath=filedialog.askdirectory(initialdir='L:/',title='Root directory')
ent_projectPath.insert(0,Projectpath)
# return(os.path.normpath(Projectpath))
def createProject():
projectName=ent_projectName.get()
projectPath=os.path.normpath(ent_projectPath.get())
applicationname=ent_appName.get()
modelFiles=ent_modelFile.get()
iniFile=ent_inifile.get()
if modelFiles and iniFile != '':
modelFiles=modelFiles.split(',')
iniFilepath=os.path.normpath(iniFile)
modelFilepath=[]
for modelFile in modelFiles:
modelFilepath.append(os.path.normpath(modelFile))
CreateProjectInCD(projectName,projectPath,applicationname,modelFilepath,iniFilepath)
ImportFilesInCD()
# userMsg=messagebox.askquestion("Project Created Successfully","Do you want to continue?")
# if userMsg == 'no':
messagebox.showinfo("Exiting","Project Created Successfully!!!Exiting the program.")
window.destroy()

# Main program execution
if __name__ == '__main__':
obj=automation()
window=Tk()
window.title('create_configuration_desk_project')
window.geometry('520x294')
window.resizable(width=False,height=False)
window.attributes('-topmost',True)

frame=Frame(relief='sunken',borderwidth=1,pady=10,padx=5)
frame.pack(padx=5,pady=10)

lbl_projectName=Label(master=frame,text='Project Name:')
lbl_projectPath=Label(master=frame,text='Project Path:')
lbl_appName=Label(master=frame,text='Application Name:')
lbl_modelFile=Label(master=frame,text='Model and script files:')
lbl_customFile = Label(master=frame,text='custom file:')


ent_projectName=Entry(master=frame,width=70)
ent_projectPath=Entry(master=frame,width=70)
ent_appName=Entry(master=frame,width=70)
ent_modelFile=Entry(master=frame,width=70)
ent_iniFile=Entry(master=frame,width=70)

btn_selectModelfile=Button(master=frame,text='Choose',command=selectModelfile)
btn_selectProjectpath=Button(master=frame,text='Choose',command=selectProjectpath)
btn_selectCustomfile=Button(master=frame,text='Choose',command=selectinifiles)
btn_create=Button(text='Create ',height=15,width=15,command=createProject)

lbl_projectName.grid(row=0,column=0,sticky='w')
ent_projectName.grid(row=1,column=0)
lbl_projectPath.grid(row=2,column=0,sticky='w')
ent_projectPath.grid(row=3,column=0)
lbl_appName.grid(row=4,column=0,sticky='w')
ent_appName.grid(row=5,column=0)


btn_selectProjectpath.grid(row=3,column=1,padx=5)
lbl_modelFile.grid(row=6,column=0,sticky='w')
ent_modelFile.grid(row=7,column=0)
btn_selectModelfile.grid(row=7,column=1,padx=5)
lbl_customFile.grid(row=8,column=0,sticky='w')
ent_iniFile.grid(row=9,column=0)
btn_selectCustomfile.grid(row=9,column=1,padx=5)

btn_create.pack(pady=20)

path,name,applicationname=obj.CheckifOpen()
if path:
ent_projectPath.insert(0,path)
ent_appName.insert(0,applicationname)
ent_projectName.insert(0,name)
ent_iniFile.insert(0,path)
messagebox.showinfo("Confirmation","Project Already opened!!")
# Test your code here

window.mainloop()
     
 
what is notes.io
 

Notes.io is a web-based application for taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000 notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 12 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.