diff options
author | Rahul P | 2020-03-04 16:28:15 +0530 |
---|---|---|
committer | GitHub | 2020-03-04 16:28:15 +0530 |
commit | 9ae86b144458c7a2ee3a63e6766a98368b951efd (patch) | |
tree | 70111351e857526bc637a049034d10994ab17a79 | |
parent | d086cd7d5d8a3661300868f2e6a758d0146d45ef (diff) | |
parent | c8f4f86d833c695dab9bee0f8293d83a748c196e (diff) | |
download | nghdl-9ae86b144458c7a2ee3a63e6766a98368b951efd.tar.gz nghdl-9ae86b144458c7a2ee3a63e6766a98368b951efd.tar.bz2 nghdl-9ae86b144458c7a2ee3a63e6766a98368b951efd.zip |
Merge pull request #40 from rahulp13/master
port to python3
-rw-r--r-- | ghdl-0.36.tar.gz | bin | 4333562 -> 0 bytes | |||
-rwxr-xr-x | install-nghdl.sh | 288 | ||||
-rw-r--r-- | ngspice-nghdl.tar.gz | bin | 8684202 -> 0 bytes | |||
-rw-r--r-- | ngspice-nghdl.tar.xz | bin | 0 -> 4493772 bytes | |||
-rw-r--r-- | src/Appconfig.py | 39 | ||||
-rw-r--r-- | src/createKicadLibrary.py | 148 | ||||
-rw-r--r-- | src/model_generation.py | 1857 | ||||
-rwxr-xr-x | src/ngspice_ghdl.py | 432 |
8 files changed, 1360 insertions, 1404 deletions
diff --git a/ghdl-0.36.tar.gz b/ghdl-0.36.tar.gz Binary files differdeleted file mode 100644 index 6df02cb..0000000 --- a/ghdl-0.36.tar.gz +++ /dev/null diff --git a/install-nghdl.sh b/install-nghdl.sh deleted file mode 100755 index 78adde5..0000000 --- a/install-nghdl.sh +++ /dev/null @@ -1,288 +0,0 @@ -#!/bin/bash -#=============================================================================== -# FILE: install-nghdl.sh -# -# USAGE: ./install-nghdl.sh --install -# or -# ./install-nghdl.sh --uninstall -# -# DESCRIPTION: It is installation script for ngspice and ghdl work (nghdl). -# -# OPTIONS: --- -# REQUIREMENTS: --- -# BUGS: --- -# NOTES: --- -# AUTHOR: Fahim Khan, Rahul Paknikar -# ORGANIZATION: eSim, FOSSEE group at IIT Bombay -# CREATED: Wednesday 18 December 2019 14:30 -# REVISION: --- -#=============================================================================== - -ngspice="ngspice-nghdl" -ghdl="ghdl-0.36" -config_dir="$HOME/.nghdl" -config_file="config.ini" -src_dir=`pwd` - -#Will be used to take backup of any file -sysdate="$(date)" -timestamp=`echo $sysdate|awk '{print $3"_"$2"_"$6"_"$4 }'` - - -#All functions goes here -function installDependency -{ - - echo "Updating indexes to install latest versions......" - sudo apt-get update - - echo "Installing dependencies for ghdl-0.36 LLVM......." - - echo "Installing Make.................................." - sudo apt-get install -y make - if [ $? -ne 0 ]; then - echo -e "\n\n\"Make\" dependency couldn't be installed.\nKindly resolve above \"apt-get\" errors and try again." - exit 1 - fi - - echo "Installing GNAT-5................................" - sudo apt-get install -y gnat-5 - if [ $? -ne 0 ]; then - echo -e "\n\n\"GNAT-5\" dependency couldn't be installed.\nKindly resolve above \"apt-get\" errors and try again." - exit 1 - fi - - echo "Installing LLVM.................................." - sudo apt-get install -y llvm - if [ $? -ne 0 ]; then - echo -e "\n\n\"LLVM\" dependency couldn't be installed.\nKindly resolve above \"apt-get\" errors and try again." - exit 1 - fi - - echo "Installing Clang................................." - sudo apt-get install -y clang - if [ $? -ne 0 ]; then - echo -e "\n\n\"Clang\" dependency couldn't be installed.\nKindly resolve above \"apt-get\" errors and try again." - exit 1 - fi - - echo "Installing Zlib1g-dev............................" - sudo apt-get install -y zlib1g-dev - if [ $? -ne 0 ]; then - echo -e "\n\n\"Zlib1g-dev\" dependency couldn't be installed.\nKindly resolve above \"apt-get\" errors and try again." - exit 1 - fi - - echo "Installing Xterm................................." - sudo apt-get install -y xterm - if [ $? -ne 0 ]; then - echo -e "\n\n\"Xterm\" dependency couldn't be installed.\nKindly resolve above \"apt-get\" errors and try again." - exit 1 - fi - - - echo "Installing GHDL.................................." - grep -h "ghdl" /usr/local/bin/ghdl > /dev/null - if [ $? -ne 0 ]; then - tar -xzvf ghdl-0.36.tar.gz - if [ "$?" == 0 ]; then - echo "ghdl-0.36 LLVM successfully extracted to $HOME......" - echo "Changing directory to ghdl-0.36 LLVM installation..." - cd ghdl-0.36/ - echo "Configuring ghdl-0.36 build as per requirements....." - #Other configure flags can be found at - https://github.com/ghdl/ghdl/blob/master/configure - sudo ./configure --with-llvm-config - echo "Building the install file for ghdl-0.36 LLVM....." - sudo make - echo "Installing ghdl-0.36 LLVM....." - sudo make install - echo "Removing unused part of ghdl-0.36 LLVM....." - sudo rm -rf ../ghdl-0.36 - else - echo "Unable to extract ghdl-0.36 LLVM" - echo "Exiting installation" - exit 1 - fi - else - echo "GHDL already exists....." - echo "Leaving ghdl-0.36 LLVM installation" - fi - - echo "Installing Flex.................................." - sudo apt-get install -y flex - if [ $? -ne 0 ]; then - echo -e "\n\n\"Flex\" dependency couldn't be installed.\nKindly resolve above \"apt-get\" errors and try again." - exit 1 - fi - - echo "Installing Bison................................." - sudo apt-get install -y bison - if [ $? -ne 0 ]; then - echo -e "\n\n\"Bison\" dependency couldn't be installed.\nKindly resolve above \"apt-get\" errors and try again." - exit 1 - fi - - # Specific dependency for nvidia graphic cards - echo "Installing graphics dependency for ngspice souce build" - echo "Installing libxaw7................................" - sudo apt-get install libxaw7 - if [ $? -ne 0 ]; then - echo -e "\n\n\"libxaw7\" dependency couldn't be installed.\nKindly resolve above \"apt-get\" errors and try again." - exit 1 - fi - - echo "Installing libxaw7-dev............................" - sudo apt-get install libxaw7-dev - if [ $? -ne 0 ]; then - echo -e "\n\n\"libxaw7-dev\" dependency couldn't be installed.\nKindly resolve above \"apt-get\" errors and try again." - exit 1 - fi -} - - -function installNgspice -{ - echo "Installing Ngspice................................" - #Checking if ngspice-nghdl directory is already present in Home directory - if [ -d $HOME/$ngspice ];then - echo "$ngspice directory already exists at $HOME" - echo "Leaving Ngspice installation.................." - else - #Extracting Ngspice to Home Directory - cd $src_dir - tar -xzvf $ngspice.tar.gz -C $HOME - if [ "$?" == 0 ];then - echo "Ngspice extracted sucessfuly to $HOME " - #change to ngspice-nghdl directory - cd $HOME/$ngspice - #Make local install directory - mkdir -p install_dir - #Make release directory for build - mkdir -p release - #Change to release directory - cd release - echo "Installing Ngspice....." - echo "-----------------------------------------" - sleep 5 - ../configure --enable-xspice --disable-debug --prefix=$HOME/$ngspice/install_dir/ --exec-prefix=$HOME/$ngspice/install_dir/ - - #dirty fix for adding patch to ngspice base code - cp $src_dir/src/outitf.c $HOME/$ngspice/src/frontend - - make - make install - if [ "$?" == 0 ];then - echo "Removing previously installed Ngspice (if any)......" - sudo apt-get remove -y ngspice - - echo "Ngspice installed sucessfully......" - echo "Adding softlink for the installed Ngspice......" - - sudo ln -s $HOME/$ngspice/install_dir/bin/ngspice /usr/bin/ngspice - if [ $? -ne 0 ];then - echo "Failed to add Ngspice softlink" - echo "Remove earlier installations at /usr/bin/ngspice and try again..." - exit 1 - else - echo "Added softlink for Ngspice" - fi - - else - echo "There was some error while installing Ngspice" - fi - - else - echo "Unable to extract Ngspice tar file" - exit 1; - fi - fi - -} - -function createConfigFile -{ - - #Creating config.ini file and adding configuration information - #Check if config file is present - if [ -d $config_dir ];then - rm $config_dir/$config_file && touch $config_dir/$config_file - else - mkdir $config_dir && touch $config_dir/$config_file - fi - - echo "[NGSPICE]" >> $config_dir/$config_file - echo "NGSPICE_HOME = $HOME/$ngspice" >> $config_dir/$config_file - echo "DIGITAL_MODEL = %(NGSPICE_HOME)s/src/xspice/icm/ghdl" >> $config_dir/$config_file - echo "RELEASE = %(NGSPICE_HOME)s/release" >> $config_dir/$config_file - echo "[SRC]" >> $config_dir/$config_file - echo "SRC_HOME = $src_dir" >> $config_dir/$config_file - echo "LICENSE = %(SRC_HOME)s/LICENSE" >> $config_dir/$config_file - -} - -function createSoftLink -{ - - ## Creating softlink - cd /usr/local/bin - if [[ -L nghdl ]];then - echo "Symlink was already present" - sudo unlink nghdl - sudo ln -sf $src_dir/src/ngspice_ghdl.py nghdl - else - echo "Creating symlink" - sudo ln -sf $src_dir/src/ngspice_ghdl.py nghdl - if [ $? -ne 0 ];then - echo "Failed to add NGHDL softlink" - echo "Remove earlier installations at /usr/local/bin/nghdl and try again..." - exit 1 - else - echo "Added softlink for NGHDL......" - fi - fi - cd $pwd - -} - -##################################################################### -# Script start from here # -##################################################################### - -###Checking if file is passsed as argument to script - -if [ "$#" -eq 1 ];then - option=$1 -else - echo "USAGE : " - echo "./install-nghdl.sh --install" - exit 1; -fi - -##Checking flags -if [ $option == "--install" ];then - - #Calling functions - installDependency - if [ $? -ne 0 ];then - echo -e "\n\n\nERROR: Unable to install required packages. Please check your internet connection.\n\n" - exit 0 - fi - installNgspice - createConfigFile - createSoftLink - -elif [ $option == "--uninstall" ];then - echo "Deleting Files............" - sudo rm -rf $HOME/ngspice-nghdl $HOME/.nghdl /usr/share/kicad/library/eSim_Nghdl.lib /usr/local/bin/nghdl /usr/bin/ngspice - echo "Removing GNAT-5............" - sudo apt-get remove -y gnat-5 - echo "Removing LLVM............" - sudo apt-get remove -y llvm - echo "Removing GHDL............" - sudo rm -rf /usr/local/bin/ghdl /usr/local/lib/ghdl /usr/local/bin/ghdl1-llvm /usr/local/lib/libghdlvpi.so - -else - echo "Please select the proper operation." - echo "--install" - echo "--uninstall" -fi diff --git a/ngspice-nghdl.tar.gz b/ngspice-nghdl.tar.gz Binary files differdeleted file mode 100644 index ac9262c..0000000 --- a/ngspice-nghdl.tar.gz +++ /dev/null diff --git a/ngspice-nghdl.tar.xz b/ngspice-nghdl.tar.xz Binary files differnew file mode 100644 index 0000000..f32a0a8 --- /dev/null +++ b/ngspice-nghdl.tar.xz diff --git a/src/Appconfig.py b/src/Appconfig.py index 6909c53..8cf63a2 100644 --- a/src/Appconfig.py +++ b/src/Appconfig.py @@ -1,35 +1,34 @@ import os.path -from ConfigParser import SafeConfigParser +from configparser import SafeConfigParser class Appconfig: home = os.path.expanduser("~") - #Reading all varibale from eSim config.ini + # Reading all variables from eSim config.ini parser_esim = SafeConfigParser() - parser_esim.read(os.path.join(home, os.path.join('.esim','config.ini'))) + parser_esim.read(os.path.join(home, os.path.join('.esim', 'config.ini'))) try: - src_home = parser_esim.get('eSim','eSim_HOME') - xml_loc = os.path.join(src_home,'src/modelParamXML') + src_home = parser_esim.get('eSim', 'eSim_HOME') + xml_loc = os.path.join(src_home, 'library/modelParamXML') lib_loc = os.path.expanduser('~') - except: + except BaseException: pass esimFlag = 0 - #Reading all variable from nghdl config.ini + # Reading all variables from nghdl config.ini parser_nghdl = SafeConfigParser() - parser_nghdl.read(os.path.join(home,os.path.join('.nghdl','config.ini'))) + parser_nghdl.read(os.path.join(home, os.path.join('.nghdl', 'config.ini'))) kicad_lib_template = { - "start_def":"DEF comp_name U 0 40 Y Y 1 F N", - "U_field":"F0 \"U\" 2850 1800 60 H V C CNN", - "comp_name_field":"F1 \"comp_name\" 2850 2000 60 H V C CNN", - "blank_field":["F2 blank_quotes 2850 1950 60 H V C CNN","F3 blank_quotes 2850 1950 60 H V C CNN"], - "start_draw":"DRAW", - "draw_pos":"S 2550 2100 3150 1800 0 1 0 N", - "input_port":"X in 1 2350 2000 200 R 50 50 1 1 I", - "output_port":"X out 2 3350 2000 200 L 50 50 1 1 O", - "end_draw":"ENDDRAW", - "end_def":"ENDDEF" + "start_def": "DEF comp_name U 0 40 Y Y 1 F N", + "U_field": "F0 \"U\" 2850 1800 60 H V C CNN", + "comp_name_field": "F1 \"comp_name\" 2850 2000 60 H V C CNN", + "blank_field": ["F2 blank_quotes 2850 1950 60 H V C CNN", + "F3 blank_quotes 2850 1950 60 H V C CNN"], + "start_draw": "DRAW", + "draw_pos": "S 2550 2100 3150 1800 0 1 0 N", + "input_port": "X in 1 2350 2000 200 R 50 50 1 1 I", + "output_port": "X out 2 3350 2000 200 L 50 50 1 1 O", + "end_draw": "ENDDRAW", + "end_def": "ENDDEF" } - - diff --git a/src/createKicadLibrary.py b/src/createKicadLibrary.py index a75413c..966c9d6 100644 --- a/src/createKicadLibrary.py +++ b/src/createKicadLibrary.py @@ -2,7 +2,7 @@ from Appconfig import Appconfig import re import os import xml.etree.cElementTree as ET -from PyQt4 import QtGui, QtCore +from PyQt4 import QtGui class AutoSchematic(QtGui.QWidget): @@ -15,34 +15,43 @@ class AutoSchematic(QtGui.QWidget): self.lib_loc = Appconfig.lib_loc self.kicad_nghdl_lib = '/usr/share/kicad/library/eSim_Nghdl.lib' self.parser = Appconfig.parser_nghdl - + def createKicadLibrary(self): xmlFound = None for root, dirs, files in os.walk(self.xml_loc): if (str(self.modelname) + '.xml') in files: xmlFound = root print(xmlFound) - if (xmlFound == None): + if xmlFound is None: self.getPortInformation() self.createXML() self.createLib() elif (xmlFound == self.xml_loc + '/Nghdl'): - print 'Library already exists...' - ret = QtGui.QMessageBox.warning(self, "Warning",'''<b>Library files for this model already exist. Do you want to overwrite it?</b><br/> - If yes press ok, else cancel it and change the name of your vhdl file.''', QtGui.QMessageBox.Ok, QtGui.QMessageBox.Cancel) + print('Library already exists...') + ret = QtGui.QMessageBox.warning( + self, "Warning", '''<b>Library files for this model ''' + + '''already exist. Do you want to overwrite it?</b><br/> + If yes press ok, else cancel it and ''' + + '''change the name of your vhdl file.''', + QtGui.QMessageBox.Ok, QtGui.QMessageBox.Cancel + ) if ret == QtGui.QMessageBox.Ok: - print "Overwriting existing libraries" + print("Overwriting existing libraries") self.getPortInformation() self.createXML() - self.removeOldLibrary() #Removes the exisitng library + self.removeOldLibrary() # Removes the exisitng library self.createLib() else: - print "Exiting Nghdl" + print("Exiting Nghdl") quit() else: - print 'Pre existing library...' - ret = QtGui.QMessageBox.critical(self, "Error",'''<b>A standard library already exists with this name.</b><br/> - <b>Please change the name of your vhdl file and upload it again</b>''', QtGui.QMessageBox.Ok) + print('Pre existing library...') + ret = QtGui.QMessageBox.critical( + self, "Error", '''<b>A standard library already exists ''' + + '''with this name.</b><br/><b>Please change the name ''' + + '''of your vhdl file and upload it again</b>''', + QtGui.QMessageBox.Ok + ) # quit() @@ -60,29 +69,37 @@ class AutoSchematic(QtGui.QWidget): self.splitText += bit + "-V:" self.splitText += self.portInfo[-1] + "-V" - print "changing directory to ", (xmlDestination) + print("changing directory to ", xmlDestination) os.chdir(xmlDestination) root = ET.Element("model") ET.SubElement(root, "name").text = self.modelname ET.SubElement(root, "type").text = "Nghdl" ET.SubElement(root, "node_number").text = str(len(self.portInfo)) - ET.SubElement(root, "title").text = "Add parameters for " + str(self.modelname) + ET.SubElement(root, "title").text = ( + "Add parameters for " + str(self.modelname)) ET.SubElement(root, "split").text = self.splitText param = ET.SubElement(root, "param") - ET.SubElement(param, "rise_delay", default = "1.0e-9").text = "Enter Rise Delay (default=1.0e-9)" - ET.SubElement(param ,"fall_delay", default ="1.0e-9").text = "Enter Fall Delay (default=1.0e-9)" - ET.SubElement(param ,"input_load", default ="1.0e-12").text = "Enter Input Load (default=1.0e-12)" - ET.SubElement(param ,"instance_id", default ="1").text = "Enter Instance ID (Between 0-99)" + ET.SubElement(param, "rise_delay", default="1.0e-9").text = ( + "Enter Rise Delay (default=1.0e-9)") + ET.SubElement(param, "fall_delay", default="1.0e-9").text = ( + "Enter Fall Delay (default=1.0e-9)") + ET.SubElement(param, "input_load", default="1.0e-12").text = ( + "Enter Input Load (default=1.0e-12)") + ET.SubElement(param, "instance_id", default="1").text = ( + "Enter Instance ID (Between 0-99)") tree = ET.ElementTree(root) tree.write(str(self.modelname) + '.xml') - print "Leaving the directory ", (xmlDestination) + print("Leaving the directory ", xmlDestination) os.chdir(cwd) - #Calculates the maximum between input and output ports + # Calculates the maximum between input and output ports def findBlockSize(self): ind = self.input_length - return max(self.char_sum(self.portInfo[:ind]), self.char_sum(self.portInfo[ind:])) + return max( + self.char_sum(self.portInfo[:ind]), + self.char_sum(self.portInfo[ind:]) + ) def char_sum(self, ls): return sum([int(x) for x in ls]) @@ -90,7 +107,7 @@ class AutoSchematic(QtGui.QWidget): def removeOldLibrary(self): cwd = os.getcwd() os.chdir(self.lib_loc) - print "Changing directory to ", self.lib_loc + print("Changing directory to ", self.lib_loc) f = open(self.kicad_nghdl_lib) lines = f.readlines() f.close() @@ -112,48 +129,55 @@ class AutoSchematic(QtGui.QWidget): f.write(line) os.chdir(cwd) - print "Leaving directory, ", self.lib_loc + print("Leaving directory, ", self.lib_loc) def createLib(self): - self.dist_port = 100 #distance between two ports - self.inc_size = 100 #Increment size of a block + self.dist_port = 100 # Distance between two ports + self.inc_size = 100 # Increment size of a block cwd = os.getcwd() os.chdir(self.lib_loc) - print "Changing directory to ", self.lib_loc + print("Changing directory to ", self.lib_loc) - lib_file = open(self.kicad_nghdl_lib,"a") + lib_file = open(self.kicad_nghdl_lib, "a") line1 = self.template["start_def"] line1 = line1.split() - line1 = [w.replace('comp_name', self.modelname) for w in line1] + line1 = [w.replace('comp_name', self.modelname) for w in line1] self.template["start_def"] = ' '.join(line1) if os.stat(self.kicad_nghdl_lib).st_size == 0: - lib_file.write("EESchema-LIBRARY Version 2.3"+ "\n\n") - #lib_file.write("#encoding utf-8"+ "\n"+ "#"+ "\n" + "#test_compo" + "\n"+ "#"+ "\n") - lib_file.write(self.template["start_def"]+ "\n"+self.template["U_field"]+"\n") + lib_file.write("EESchema-LIBRARY Version 2.3" + "\n\n") + # lib_file.write("#encoding utf-8"+ "\n"+ "#"+ "\n" + + # "#test_compo" + "\n"+ "#"+ "\n") + lib_file.write( + self.template["start_def"] + "\n" + self.template["U_field"]+"\n" + ) line3 = self.template["comp_name_field"] line3 = line3.split() line3 = [w.replace('comp_name', self.modelname) for w in line3] self.template["comp_name_field"] = ' '.join(line3) - lib_file.write(self.template["comp_name_field"]+ "\n") + lib_file.write(self.template["comp_name_field"] + "\n") line4 = self.template["blank_field"] line4_1 = line4[0] line4_2 = line4[1] line4_1 = line4_1.split() - line4_1 = [w.replace('blank_quotes','""') for w in line4_1] + line4_1 = [w.replace('blank_quotes', '""') for w in line4_1] line4_2 = line4_2.split() - line4_2 = [w.replace('blank_quotes','""') for w in line4_2] + line4_2 = [w.replace('blank_quotes', '""') for w in line4_2] line4[0] = ' '.join(line4_1) line4[1] = ' '.join(line4_2) self.template["blank_qoutes"] = line4 - lib_file.write(line4[0]+"\n" + line4[1]+"\n"+ self.template["start_draw"]+ "\n") + lib_file.write( + line4[0] + "\n" + line4[1] + "\n" + + self.template["start_draw"] + "\n" + ) draw_pos = self.template["draw_pos"] draw_pos = draw_pos.split() - draw_pos[4] = str(int(draw_pos[4])- self.findBlockSize() * self.inc_size) + draw_pos[4] = str( + int(draw_pos[4]) - self.findBlockSize() * self.inc_size) self.template["draw_pos"] = ' '.join(draw_pos) lib_file.write(self.template["draw_pos"]+"\n") @@ -165,39 +189,47 @@ class AutoSchematic(QtGui.QWidget): inputs = self.portInfo[0: self.input_length] outputs = self.portInfo[self.input_length:] - print "INPUTS AND OUTPUTS " - print inputs - print outputs + print("INPUTS AND OUTPUTS ") + print(inputs) + print(outputs) inputs = self.char_sum(inputs) - outputs= self.char_sum(outputs) - + outputs = self.char_sum(outputs) + total = inputs+outputs port_list = [] - for i in xrange(total): + for i in range(total): if (i < inputs): - input_port[1] = "in"+str(i+1) - input_port[2] = str(i+1) - input_port[4] = str(int(input_port[4])-self.dist_port) + input_port[1] = "in" + str(i + 1) + input_port[2] = str(i + 1) + input_port[4] = str(int(input_port[4]) - self.dist_port) input_list = ' '.join(input_port) port_list.append(input_list) else: - output_port[1] = "out"+str(i- inputs+1) - output_port[2] = str(i+1) - output_port[4] = str(int(output_port[4])-self.dist_port) + output_port[1] = "out" + str(i - inputs + 1) + output_port[2] = str(i + 1) + output_port[4] = str(int(output_port[4]) - self.dist_port) output_list = ' '.join(output_port) port_list.append(output_list) for ports in port_list: - lib_file.write(ports+"\n") - lib_file.write(self.template["end_draw"]+"\n"+ self.template["end_def"] + "\n\n\n") + lib_file.write(ports+"\n") + lib_file.write( + self.template["end_draw"] + "\n" + + self.template["end_def"] + "\n\n\n" + ) os.chdir(cwd) - print 'Leaving directory, ', self.lib_loc - QtGui.QMessageBox.information(self, "Library added", '''Library details for this model is added to the <b>eSim_Nghdl.lib</b> in the KiCad shared directory''', QtGui.QMessageBox.Ok) + print('Leaving directory, ', self.lib_loc) + QtGui.QMessageBox.information( + self, "Library added", + '''Library details for this model is added to the ''' + + '''<b>eSim_Nghdl.lib</b> in the KiCad shared directory''', + QtGui.QMessageBox.Ok + ) class PortInfo: @@ -211,16 +243,20 @@ class PortInfo: info_loc = os.path.join(self.model_loc, self.modelname+'/DUTghdl/') input_list = [] output_list = [] - read_file=open(info_loc + 'connection_info.txt','r') - data=read_file.readlines() + read_file = open(info_loc + 'connection_info.txt', 'r') + data = read_file.readlines() read_file.close() for line in data: if re.match(r'^\s*$', line): pass else: - in_items=re.findall("IN",line,re.MULTILINE|re.IGNORECASE) - out_items=re.findall("OUT",line,re.MULTILINE|re.IGNORECASE) + in_items = re.findall( + "IN", line, re.MULTILINE | re.IGNORECASE + ) + out_items = re.findall( + "OUT", line, re.MULTILINE | re.IGNORECASE + ) if in_items: input_list.append(line.split()) if out_items: diff --git a/src/model_generation.py b/src/model_generation.py index e507b55..da8e272 100644 --- a/src/model_generation.py +++ b/src/model_generation.py @@ -1,852 +1,1033 @@ -#!/usr/bin/env python +#!/usr/bin/python3 -"""#!/usr/bin/python """ import re -import sys import os -#######Script start from here -print "Arguement is :", sys.argv[1] -fname = os.path.basename(sys.argv[1]) -print "VHDL filename is :",fname -home = os.path.expanduser("~") -###########Creating connection_info.txt file from vhdl file##################### -read_vhdl = open(sys.argv[1],'r') -vhdl_data = read_vhdl.readlines() -read_vhdl.close() - -start_flag = -1 #Used for scaning part of data -scan_data=[] -#p=re.search('port(.*?)end',read_vhdl,re.M|re.I|re.DOTALL).group() - -for item in vhdl_data: - if re.search('port',item,re.I): - start_flag = 1 - - elif re.search("end",item,re.I): - start_flag = 0 - else: - pass - - if start_flag == 1: - item=re.sub("port", " ", item, flags=re.I) - item=re.sub("\(", " ", item, flags=re.I) - item=re.sub("\)", " ", item, flags=re.I) - item=re.sub(";"," ",item,flags=re.I) - - scan_data.append(item.rstrip()) - scan_data=filter(None, scan_data) - elif start_flag == 0: - break - -#print "Scan Data",scan_data -port_info=[] -port_vector_info = [] - -for item in scan_data: - print "Scan Data :",item - if re.search("in",item,flags=re.I): - if re.search("std_logic_vector",item,flags=re.I): - temp=re.compile(r"\s*std_logic_vector\s*",flags=re.I) - elif re.search("std_logic",item,flags=re.I): - temp=re.compile(r"\s*std_logic\s*",flags=re.I) - else: - print "Please check your vhdl code for datatype of input port" - sys.exit() - elif re.search("out",item,flags=re.I): - if re.search("std_logic_vector",item,flags=re.I): - temp=re.compile(r"\s*std_logic_vector\s*",flags=re.I) - elif re.search("std_logic",item,flags=re.I): - temp=re.compile(r"\s*std_logic\s*",flags=re.I) - else: - print "Please check your vhdl code for datatype of output port" - sys.exit() - else: - print "Please check the in/out direction of your port" - sys.exit() - - lhs=temp.split(item)[0] - rhs=temp.split(item)[1] - bit_info=re.compile(r"\s*downto\s*",flags=re.I).split(rhs)[0] - if bit_info: - port_info.append(lhs+":"+str(int(bit_info)+int(1))) - port_vector_info.append(1) - else: - port_info.append(lhs+":"+str(int(1))) - port_vector_info.append(0) - -print "Port Info :",port_info - -#Open connection_info.txt file - -con_ifo=open('connection_info.txt','w') - -for item in port_info: - word=item.split(':') - con_ifo.write(word[0].strip()+' '+word[1].strip()+' '+word[2].strip()) - con_ifo.write("\n") -con_ifo.close() -############### Reading connection/port information############################# - -#Declaring input and output list -input_list=[] -output_list=[] - -#Reading connection_info.txt file for port infomation -read_file=open('connection_info.txt','r') -data=read_file.readlines() -read_file.close() - -#Extracting input and output port list from data -print "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" -for line in data: - print line - if re.match(r'^\s*$', line): - pass - #print "Blank Line" - else: - in_items=re.findall("IN",line,re.MULTILINE|re.IGNORECASE) - out_items=re.findall("OUT",line,re.MULTILINE|re.IGNORECASE) - #print "Line",line - if in_items: - input_list.append(line.split()) - #print "Found IN" - else: - pass - #print "Not Found" - - if out_items: - output_list.append(line.split()) - #print "Found Out" - else: - pass - -print "Inout List :",input_list -print "Output list",output_list -input_port=[] -output_port=[] -#creating list of input and output port with its weight -for input in input_list: - input_port.append(input[0]+":"+input[2]) - #print "Input List: ",input -for output in output_list: - output_port.append(output[0]+":"+output[2]) - #print "Output List: ",output - -print "Output Port List : ",output_port -print "Input Port List : ",input_port - -######################Creating content for cfunc.mod file####################### -print "Starting With cfunc.mod file" -cfunc=open('cfunc.mod','w') - -print "Building content for cfunc.mod file" - -comment='''/* This is cfunc.mod file auto generated by gen_con_info.py -Developed by Fahim, Rahul at IIT Bombay */ \n + +class ModelGeneration: + + def __init__(self, file): + + # Script starts from here + print("Arguement is : ", file) + self.fname = os.path.basename(file) + print("VHDL filename is : ", self.fname) + self.home = os.path.expanduser("~") + + # #### Creating connection_info.txt file from vhdl file #### # + read_vhdl = open(file, 'r') + vhdl_data = read_vhdl.readlines() + read_vhdl.close() + + start_flag = -1 # Used for scaning part of data + scan_data = [] + # p=re.search('port(.*?)end',read_vhdl,re.M|re.I|re.DOTALL).group() + + for item in vhdl_data: + if re.search('port', item, re.I): + start_flag = 1 + + elif re.search("end", item, re.I): + start_flag = 0 + + if start_flag == 1: + item = re.sub("port", " ", item, flags=re.I) + item = re.sub("\(", " ", item, flags=re.I) # noqa + item = re.sub("\)", " ", item, flags=re.I) # noqa + item = re.sub(";", " ", item, flags=re.I) + + scan_data.append(item.rstrip()) + scan_data = [_f for _f in scan_data if _f] + elif start_flag == 0: + break + + port_info = [] + self.port_vector_info = [] + + for item in scan_data: + print("Scan Data :", item) + if re.search("in", item, flags=re.I): + if re.search("std_logic_vector", item, flags=re.I): + temp = re.compile(r"\s*std_logic_vector\s*", flags=re.I) + elif re.search("std_logic", item, flags=re.I): + temp = re.compile(r"\s*std_logic\s*", flags=re.I) + else: + raise ValueError("Please check your vhdl " + + "code for datatype of input port") + elif re.search("out", item, flags=re.I): + if re.search("std_logic_vector", item, flags=re.I): + temp = re.compile(r"\s*std_logic_vector\s*", flags=re.I) + elif re.search("std_logic", item, flags=re.I): + temp = re.compile(r"\s*std_logic\s*", flags=re.I) + else: + raise ValueError("Please check your vhdl " + + "code for datatype of output port") + else: + raise ValueError( + "Please check the in/out direction of your port" + ) + + lhs = temp.split(item)[0] + rhs = temp.split(item)[1] + bit_info = re.compile(r"\s*downto\s*", flags=re.I).split(rhs)[0] + if bit_info: + port_info.append(lhs + ":" + str(int(bit_info) + int(1))) + self.port_vector_info.append(1) + else: + port_info.append(lhs + ":" + str(int(1))) + self.port_vector_info.append(0) + + print("Port Info :", port_info) + + # Open connection_info.txt file + con_ifo = open('connection_info.txt', 'w') + + for item in port_info: + word = item.split(':') + con_ifo.write( + word[0].strip() + ' ' + word[1].strip() + ' ' + word[2].strip() + ) + con_ifo.write("\n") + con_ifo.close() + + def readPortInfo(self): + + # ############## Reading connection/port information ############## # + + # Declaring input and output list + input_list = [] + output_list = [] + + # Reading connection_info.txt file for port infomation + read_file = open('connection_info.txt', 'r') + data = read_file.readlines() + read_file.close() + + # Extracting input and output port list from data + print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") + for line in data: + print(line) + if re.match(r'^\s*$', line): + pass + else: + in_items = re.findall( + "IN", line, re.MULTILINE | re.IGNORECASE + ) + out_items = re.findall( + "OUT", line, re.MULTILINE | re.IGNORECASE + ) + if in_items: + input_list.append(line.split()) + + if out_items: + output_list.append(line.split()) + + print("Inout List :", input_list) + print("Output list", output_list) + + self.input_port = [] + self.output_port = [] + + # creating list of input and output port with its weight + for input in input_list: + self.input_port.append(input[0]+":"+input[2]) + for output in output_list: + self.output_port.append(output[0]+":"+output[2]) + + print("Output Port List : ", self.output_port) + print("Input Port List : ", self.input_port) + + def createCfuncModFile(self): + + # ############## Creating content for cfunc.mod file ############## # + + print("Starting With cfunc.mod file") + cfunc = open('cfunc.mod', 'w') + print("Building content for cfunc.mod file") + + comment = '''/* This is cfunc.mod file auto generated by gen_con_info.py + Developed by Fahim, Rahul at IIT Bombay */\n + ''' + + header = ''' + #include <stdio.h> + #include <math.h> + #include <string.h> + #include <time.h> + #include <sys/socket.h> + #include <sys/types.h> + #include <netinet/in.h> + #include <netdb.h> + #include <stdlib.h> + #include <unistd.h> + #include <errno.h> ''' -header=''' -#include <stdio.h> -#include <math.h> -#include <string.h> -#include <time.h> -#include <sys/socket.h> -#include <sys/types.h> -#include <netinet/in.h> -#include <netdb.h> -#include <stdlib.h> -#include <unistd.h> -#include <errno.h> -''' - -function_open='''void cm_'''+fname.split('.')[0]+'''(ARGS) \n{''' - -digital_state_output=[] -for item in output_port: - digital_state_output.append("Digital_State_t *_op_"+item.split(':')[0]+", *_op_"+item.split(':')[0]+"_old;") - - -var_section=''' - // Declaring components of Client - FILE *log_client = NULL; - log_client=fopen("client.log","a"); - int socket_fd, bytes_recieved; - char send_data[1024]; - char recv_data[1024]; - char *key_iter; - struct hostent *host; - struct sockaddr_in server_addr; - int sock_port = 5000+PARAM(instance_id); -''' - -temp_input_var=[] -for item in input_port: - temp_input_var.append("char temp_"+item.split(':')[0]+"[1024];") - -#Start of INIT function -init_start_function=''' - if(INIT) - { - /* Allocate storage for output ports.And set the load for input ports */ -''' - -cm_event_alloc=[] -cm_count_output=0 -for item in output_port: - cm_event_alloc.append("cm_event_alloc("+str(cm_count_output)+","+item.split(':')[1]+"*sizeof(Digital_State_t));") - cm_count_output=cm_count_output+1 - -load_in_port=[] -for item in input_port: - load_in_port.append("for(Ii=0;Ii<PORT_SIZE("+item.split(':')[0]+");Ii++)\n\t\t{\n\t\t\tLOAD("+item.split(':')[0]+"[Ii])=PARAM(input_load); \n\t\t}") - -cm_count_ptr=0 -cm_event_get_ptr=[] -for item in output_port: - cm_event_get_ptr.append("_op_"+item.split(':')[0]+" = _op_"+item.split(':')[0]+"_old = (Digital_State_t *) cm_event_get_ptr("+str(cm_count_ptr)+",0);") - cm_count_ptr=cm_count_ptr+1 - -systime_info=''' - /*Taking system time info for log */ - time_t systime; - systime = time(NULL); - printf(ctime(&systime)); - printf("Client-Initialising GHDL...\\n\\n"); - fprintf(log_client,"Setup Client Server Connection at %s \\n",ctime(&systime)); -''' - - - -init_else=''' - printf("Client-Inside else of INIT \\n"); - fprintf(log_client,"Inside else of INIT \\n"); - /* retrieve storage for output ports. */ -''' - -els_evt_ptr=[] -els_evt_count1=0 -els_evt_count2=0 -for item in output_port: - els_evt_ptr.append("_op_"+item.split(":")[0]+" = (Digital_State_t *) cm_event_get_ptr("+str(els_evt_count1)+","+str(els_evt_count2)+");") - els_evt_count2=els_evt_count2+1 - els_evt_ptr.append("_op_"+item.split(":")[0]+"_old"+" = (Digital_State_t *) cm_event_get_ptr("+str(els_evt_count1)+","+str(els_evt_count2)+");") - els_evt_count1=els_evt_count1+1 - - -client_setup_ip=''' - /* Client Setup IP Addr */ - FILE *fptr; - int ip_count = 0; - char* my_ip = malloc(16); - - char ip_filename[40]; - sprintf(ip_filename, "/tmp/NGHDL_COMMON_IP_%d.txt", getpid()); - - fptr = fopen(ip_filename, "r"); - if (fptr) - { - char line[20]; - while(fscanf(fptr, "%s", line) == 1) { - ip_count++; + function_open = ( + '''void cm_''' + self.fname.split('.')[0] + '''(ARGS) \n{''') + + digital_state_output = [] + for item in self.output_port: + digital_state_output.append( + "Digital_State_t *_op_" + item.split(':')[0] + + ", *_op_" + item.split(':')[0] + "_old;" + ) + + var_section = ''' + // Declaring components of Client + FILE *log_client = NULL; + log_client=fopen("client.log","a"); + int socket_fd, bytes_recieved; + char send_data[1024]; + char recv_data[1024]; + char *key_iter; + struct hostent *host; + struct sockaddr_in server_addr; + int sock_port = 5000+PARAM(instance_id); + ''' + + temp_input_var = [] + for item in self.input_port: + temp_input_var.append( + "char temp_" + item.split(':')[0] + "[1024];" + ) + + # Start of INIT function + init_start_function = ''' + if(INIT) + { + /* Allocate storage for output ports ''' \ + '''and set the load for input ports */ + ''' + + cm_event_alloc = [] + cm_count_output = 0 + for item in self.output_port: + cm_event_alloc.append( + "cm_event_alloc(" + + str(cm_count_output) + "," + item.split(':')[1] + + "*sizeof(Digital_State_t));" + ) + cm_count_output = cm_count_output + 1 + + load_in_port = [] + for item in self.input_port: + load_in_port.append( + "for(Ii=0;Ii<PORT_SIZE(" + item.split(':')[0] + + ");Ii++)\n\t\t{\n\t\t\tLOAD(" + item.split(':')[0] + + "[Ii])=PARAM(input_load); \n\t\t}" + ) + + cm_count_ptr = 0 + cm_event_get_ptr = [] + for item in self.output_port: + cm_event_get_ptr.append( + "_op_" + item.split(':')[0] + " = _op_" + + item.split(':')[0] + + "_old = (Digital_State_t *) cm_event_get_ptr(" + + str(cm_count_ptr) + ",0);" + ) + + cm_count_ptr = cm_count_ptr + 1 + + systime_info = ''' + /*Taking system time info for log */ + time_t systime; + systime = time(NULL); + printf(ctime(&systime)); + printf("Client-Initialising GHDL...\\n\\n"); + fprintf(log_client,"Setup Client Server Connection at %s \\n"''' \ + ''',ctime(&systime)); + ''' + + els_evt_ptr = [] + els_evt_count1 = 0 + els_evt_count2 = 0 + for item in self.output_port: + els_evt_ptr.append("_op_" + item.split(":")[0] + + " = (Digital_State_t *) cm_event_get_ptr(" + + str(els_evt_count1) + "," + + str(els_evt_count2) + ");") + els_evt_count2 = els_evt_count2 + 1 + els_evt_ptr.append("_op_" + item.split(":")[0] + "_old" + + " = (Digital_State_t *) cm_event_get_ptr(" + + str(els_evt_count1) + "," + + str(els_evt_count2) + ");") + els_evt_count1 = els_evt_count1 + 1 + + client_setup_ip = ''' + /* Client Setup IP Addr */ + FILE *fptr; + int ip_count = 0; + char* my_ip = malloc(16); + + char ip_filename[40]; + sprintf(ip_filename, "/tmp/NGHDL_COMMON_IP_%d.txt", getpid()); + + fptr = fopen(ip_filename, "r"); + if (fptr) + { + char line[20]; + while(fscanf(fptr, "%s", line) == 1) { + ip_count++; + } + + fclose(fptr); + } + + if (ip_count < 255) { + sprintf(my_ip, "127.0.0.%d", ip_count+1); + } else { + sprintf(my_ip, "127.0.%d.1", (ip_count+1)%256); + } + + fptr = fopen(ip_filename, "a"); + if (fptr) + { + fprintf(fptr, "%s\\n", my_ip); + fclose(fptr); + } else { + perror("Client - cannot open Common_IP file "); + exit(1); + } + + STATIC_VAR(my_ip) = my_ip; + ''' + + client_fetch_ip = ''' + /* Client Fetch IP Addr */ + + char* my_ip = STATIC_VAR(my_ip); + + host = gethostbyname(my_ip); + fprintf(log_client,"Creating client socket \\n"); + ''' + + create_socket = ''' + //Creating socket for client + if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) + { + perror("Client - Error while creating client Socket "); + fprintf(log_client,"Error while creating client socket \\n"); + exit(1); } - fclose(fptr); - } - - if (ip_count < 255) { - sprintf(my_ip, "127.0.0.%d", ip_count+1); - } else { - sprintf(my_ip, "127.0.%d.1", (ip_count+1)%256); - } - - fptr = fopen(ip_filename, "a"); - if (fptr) - { - fprintf(fptr, "%s\\n", my_ip); - fclose(fptr); - } else { - perror("Client - cannot open Common_IP file "); - exit(1); - } - - STATIC_VAR(my_ip) = my_ip; -''' - -client_fetch_ip=''' - /* Client Fetch IP Addr */ - - char* my_ip = STATIC_VAR(my_ip); - - host = gethostbyname(my_ip); - fprintf(log_client,"Creating client socket \\n"); -''' - -create_socket=''' - //Creating socket for client - if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) - { - perror("Client-Error while creating client Socket "); - fprintf(log_client,"Error while creating client socket \\n"); - exit(1); - } - - printf("Client-Socket (Id : %d) created\\n", socket_fd); - fprintf(log_client,"Client-Client Socket created successfully \\n"); - fprintf(log_client,"Client- Socket Id : %d \\n",socket_fd); - - // memset(&server_addr, 0, sizeof(server_addr)); - server_addr.sin_family = AF_INET; - server_addr.sin_port = htons(sock_port); - server_addr.sin_addr = *((struct in_addr *)host->h_addr); - bzero(&(server_addr.sin_zero),8); - -''' - -connect_server=''' - fprintf(log_client,"Client-Connecting to server \\n"); - - //Connecting to server - int try_limit=10; - while(try_limit>0) - { - if (connect(socket_fd, (struct sockaddr*)&server_addr,sizeof(struct sockaddr)) == -1) - { - sleep(1); - try_limit--; - if(try_limit==0) - { - fprintf(stderr,"Connect- Error:Tried to connect server on port , failed..giving up \\n"); - fprintf(log_client,"Connect- Error:Tried to connect server on port , failed..giving up \\n"); - exit(1); - } - } - else - { - printf("Client-Connected to server \\n"); - fprintf(log_client,"Client-Connected to server \\n"); - break; - } - } - -''' - -#Assign bit value to every input -assign_data_to_input=[] -for item in input_port: - assign_data_to_input.append("\tfor(Ii=0;Ii<PORT_SIZE("+item.split(':')[0]+");Ii++)\n\ -\t{\n\t\tif( INPUT_STATE("+item.split(':')[0]+"[Ii])==ZERO )\n\ -\t\t{\n\t\t\ttemp_"+item.split(':')[0]+"[Ii]='0';\n\t\t}\n\ -\t\telse\n\t\t{\n\t\t\ttemp_"+item.split(':')[0]+"[Ii]='1';\n\ -\t\t}\n\t}\n\ttemp_"+item.split(':')[0]+"[Ii]='\\0';\n\n") - - -snprintf_stmt=[] -snprintf_count=0 -snprintf_stmt.append("\t//Sending and receiving data to-from server \n") -snprintf_stmt.append('\tsnprintf(send_data,sizeof(send_data),"') -for item in input_port: - snprintf_count=snprintf_count+1 - snprintf_stmt.append(item.split(':')[0]+":%s") - if snprintf_count == len(input_port): - snprintf_stmt.append('",') - internal_count=0 - for item1 in input_port: - if internal_count == len(input_port): - pass - else: - snprintf_stmt.append("temp_"+item1.split(':')[0]) - internal_count=internal_count+1 - if internal_count == len(input_port): - pass - else: - snprintf_stmt.append(",") - snprintf_stmt.append(");") - else: - snprintf_stmt.append(",") - - -send_data=''' - - if ( send(socket_fd,send_data,sizeof(send_data),0)==-1) - { - fprintf(stderr, "Client-Failure Sending Message \\n"); - close(socket_fd); - exit(1); - } - else - { - printf("Client-Message sent: %s \\n",send_data); - fprintf(log_client,"Socket Id : %d & Message sent : %s \\n",socket_fd,send_data); - } - -''' - -recv_data=''' - - bytes_recieved=recv(socket_fd,recv_data,sizeof(recv_data),0); - if ( bytes_recieved <= 0 ) - { - perror("Client-Either Connection Closed or Error "); - exit(1); - } - recv_data[bytes_recieved] = '\\0'; - - printf("Client-Message Received - %s\\n\\n",recv_data); - fprintf(log_client,"Message Received From Server- %s\\n",recv_data); - -''' - -#Scheduling output event - -sch_output_event=[] - -for item in output_port: - sch_output_event.append("\t/* Scheduling event and processing them */\n\ -\tif((key_iter=strstr(recv_data, "+'"'+item.split(':')[0]+':"'")) != NULL)\n\ -\t{\n\ -\t\twhile(*key_iter++ != ':');\n\ -\t\tfor(Ii=0;*key_iter != ';';Ii++,key_iter++)\n\ -\t\t{\n\ -\t\t\tfprintf(log_client,\"Client-Bit val is %c \\n\",*key_iter);\n\ -\t\t\tif(*key_iter=='0')\n\t\t\t{\n\ -\t\t\t\t_op_"+item.split(':')[0]+"[Ii]=ZERO;\n\t\t\t}\n\ -\t\t\telse if(*key_iter=='1')\n\t\t\t{\n\ -\t\t\t\t_op_"+item.split(':')[0]+"[Ii]=ONE;\n\ -\t\t\t}\n\t\t\telse\n\t\t\t{\n\ -\t\t\t\tfprintf(log_client,\"Unknow value return from server \\n\");\n\ -\t\t\t\tprintf(\"Client-Unknown value return \\n\");\n\t\t\t}\n\n\ -\t\t\tif(ANALYSIS == DC)\n\t\t\t{\n\ -\t\t\t\tOUTPUT_STATE("+item.split(':')[0]+"[Ii]) = _op_"+item.split(':')[0]+"[Ii];\n\ -\t\t\t}\n\t\t\telse if(_op_"+item.split(':')[0]+"[Ii] != _op_"+item.split(':')[0]+"_old[Ii])\n\ -\t\t\t{\n\t\t\t\tOUTPUT_STATE("+item.split(':')[0]+"[Ii]) = _op_"+item.split(':')[0]+"[Ii];\n\ -\t\t\t\tOUTPUT_DELAY("+item.split(':')[0]+"[Ii]) = ((_op_"+item.split(':')[0]+"[Ii] == ZERO) ? PARAM(fall_delay) : PARAM(rise_delay));\n\ -\t\t\t}\n\t\t\telse\n\t\t\t{\n\ -\t\t\t\tOUTPUT_CHANGED("+item.split(':')[0]+"[Ii]) = FALSE;\n\t\t\t}\n\ -\t\t\tOUTPUT_STRENGTH("+item.split(':')[0]+"[Ii]) = STRONG;\n\ -\t\t}\n\ -\t}\n") - -#Writing content in cfunc.mod file -cfunc.write(comment) -cfunc.write(header) -cfunc.write("\n") -cfunc.write(function_open) -cfunc.write("\n") - -#Adding digital state Variable -for item in digital_state_output: - cfunc.write("\t"+item+"\n") - -#Adding variable declaration section -cfunc.write(var_section) -for item in temp_input_var: - cfunc.write("\t"+item+"\n") -cfunc.write("\n"); - -#Adding INIT portion -cfunc.write(init_start_function) -for item in cm_event_alloc: - cfunc.write(2*"\t"+item) - cfunc.write("\n") - -cfunc.write(2*"\t"+"/* set the load for input ports. */") -cfunc.write("\n") -cfunc.write(2*"\t"+"int Ii;") -cfunc.write("\n"); - -for item in load_in_port: - cfunc.write(2*"\t"+item) - cfunc.write("\n") -cfunc.write("\n") -cfunc.write(2*"\t"+"/*Retrieve Storage for output*/") -cfunc.write("\n") -for item in cm_event_get_ptr: - cfunc.write(2*"\t"+item) - cfunc.write("\n") -cfunc.write(systime_info) -cfunc.write("\n") -cfunc.write(client_setup_ip) -cfunc.write("\n") -cfunc.write("\t\tchar command[1024];\n") -cfunc.write('\t\tsnprintf(command,1024,"'+home+'/ngspice-nghdl/src/xspice/icm/ghdl/'+fname.split('.')[0]+'/DUTghdl/start_server.sh %d %s &",sock_port, my_ip);') -cfunc.write('\n\t\tsystem(command);') -cfunc.write("\n\t}") -cfunc.write("\n") -cfunc.write("\telse\n\t{\n") - -for item in els_evt_ptr: - cfunc.write(2*"\t"+item) - cfunc.write("\n") -cfunc.write("\t}") -cfunc.write("\n\n") - -cfunc.write(client_fetch_ip) -cfunc.write(create_socket) -cfunc.write(connect_server) - -cfunc.write("\t//Formating data for sending it to client\n") -cfunc.write("\tint Ii;\n\n") - -for item in assign_data_to_input: - cfunc.write(item) - -for item in snprintf_stmt: - cfunc.write(item) - -cfunc.write(send_data) -cfunc.write(recv_data) - -for item in sch_output_event: - cfunc.write(item) - -#Close socket fd -cfunc.write("\tclose(socket_fd);\n\n") - -#close log_client file -cfunc.write("\tfclose(log_client);") - -#Close cm_ function -cfunc.write("\n}") -cfunc.close() - -################Creating ifspec.ifs file######################################## -print "Starting with ifspec.ifs file" -ifspec=open('ifspec.ifs','w') - -print "Gathering Al the content for ifspec file" - -ifspec_comment=''' -/* -SUMMARY: This file is auto generated and it contains the interface specification for the -code model. */\n -''' - -name_table='NAME_TABLE:\n\ -C_Function_Name: cm_'+fname.split('.')[0]+'\n\ -Spice_Model_Name: '+fname.split('.')[0]+'\n\ -Description: "Model generated from ghdl code '+fname+'" \n' - -#Input and Output Port Table -in_port_table=[] -out_port_table=[] - -for item in input_port: - port_table = 'PORT_TABLE:\n' - port_name = 'Port_Name:\t'+item.split(':')[0]+'\n' - description = 'Description:\t"input port '+item.split(':')[0]+'"\n' - direction = 'Direction:\tin\n' - default_type = 'Default_Type:\td\n' - allowed_type = 'Allowed_Types:\t[d]\n' - vector = 'Vector:\tyes\n' - vector_bounds = 'Vector_Bounds:\t['+item.split(':')[1]+' '+item.split(":")[1]+']\n' - null_allowed = 'Null_Allowed:\tno\n' - #Insert detail in the list - in_port_table.append(port_table+port_name+description+direction+default_type+allowed_type+vector+vector_bounds+null_allowed) - - -for item in output_port: - port_table = 'PORT_TABLE:\n' - port_name = 'Port_Name:\t'+item.split(':')[0]+'\n' - description = 'Description:\t"output port '+item.split(':')[0]+'"\n' - direction = 'Direction:\tout\n' - default_type = 'Default_Type:\td\n' - allowed_type = 'Allowed_Types:\t[d]\n' - vector = 'Vector:\tyes\n' - vector_bounds = 'Vector_Bounds:\t['+item.split(':')[1]+' '+item.split(":")[1]+']\n' - null_allowed = 'Null_Allowed:\tno\n' - #Insert detail in the list - in_port_table.append(port_table+port_name+description+direction+default_type+allowed_type+vector+vector_bounds+null_allowed) - -parameter_table=''' - -PARAMETER_TABLE: -Parameter_Name: instance_id input_load -Description: "instance_id" "input load value (F)" -Data_Type: real real -Default_Value: 0 1.0e-12 -Limits: - - -Vector: no no -Vector_Bounds: - - -Null_Allowed: yes yes - -PARAMETER_TABLE: -Parameter_Name: rise_delay fall_delay -Description: "rise delay" "fall delay" -Data_Type: real real -Default_Value: 1.0e-9 1.0e-9 -Limits: [1e-12 -] [1e-12 -] -Vector: no no -Vector_Bounds: - - -Null_Allowed: yes yes - -''' - -static_table=''' - -STATIC_VAR_TABLE: - -Static_Var_Name: my_ip -Data_Type: pointer -Description: "connect to ghdlserver through this ip" - -''' - - -#Writing all the content in ifspec file -ifspec.write(ifspec_comment) -ifspec.write(name_table+"\n\n") - -for item in in_port_table: - ifspec.write(item+"\n") - -ifspec.write("\n") - -for item in out_port_table: - ifspec.write(item+"\n") - -ifspec.write("\n") -ifspec.write(parameter_table) -ifspec.write("\n") -ifspec.write(static_table) -ifspec.close() - - -########Creating testbench file ################################################ -print "Starting with testbench file" - -testbench=open(fname.split('.')[0]+'_tb.vhdl','w') -print fname.split('.')[0] + '_tb.vhdl' -#comment -comment_vhdl="--------------------------------------------------------------------------------\n" -comment_vhdl+="--This testbench has been created by Ambikeshwar Srivastava, Rahul Paknikar \n" -comment_vhdl+="--------------------------- FOSSEE, IIT Bombay ---------------------------------\n" -comment_vhdl+="--------------------------------------------------------------------------------\n" - -#Adding header, entity and architecture statement -tb_header=''' -library ieee; -use ieee.std_logic_1164.all; -use ieee.numeric_std.all; -library work; -use work.Vhpi_Foreign.all; -use work.Utility_Package.all; -use work.sock_pkg.all; - - -''' - -tb_entity="entity "+fname.split('.')[0]+"_tb is\nend entity;\n\n" - -arch="architecture "+fname.split('.')[0]+"_tb_beh of "+fname.split('.')[0]+"_tb is\n" - -#Adding components - -components=[] -components.append("\tcomponent "+fname.split('.')[0]+" is\n\t\tport(\n\t\t\t\t") - -port_vector_count = 0 - -for item in input_port: - if port_vector_info[port_vector_count]: - components.append(item.split(':')[0]+": in std_logic_vector("+str(int(item.split(':')[1])-int(1))+" downto 0);\n\t\t\t\t") - else: - components.append(item.split(':')[0]+": in std_logic;\n\t\t\t\t") - - port_vector_count += 1 - #if item.split(":")[1] != '1': - # components.append(item.split(':')[0]+": in std_logic_vector("+str(int(item.split(':')[1])-int(1))+" downto 0);\n\t\t\t\t") - #else: - # components.append(item.split(':')[0]+": in std_logic_vector("+str(int(item.split(':')[1])-int(1))+" downto 0);\n\t\t\t\t") - -for item in output_port[:-1]: - if port_vector_info[port_vector_count]: - components.append(item.split(':')[0]+": out std_logic_vector("+str(int(item.split(':')[1])-int(1))+" downto 0);\n\t\t\t\t") - else: - components.append(item.split(':')[0]+": out std_logic;\n\t\t\t\t") - - port_vector_count += 1 - -if port_vector_info[port_vector_count]: - components.append(output_port[-1].split(':')[0]+": out std_logic_vector("+str(int(output_port[-1].split(':')[1])-int(1))+" downto 0)\n\t\t\t\t") -else: - components.append(output_port[-1].split(':')[0]+": out std_logic\n\t\t\t\t") - #if item.split(":")[1] != '1': - # components.append(item.split(':')[0]+": out std_logic_vector("+str(int(item.split(':')[1])-int(1))+" downto 0)\n\t\t\t\t") - #else: - # components.append(item.split(':')[0]+": out std_logic_vector("+str(int(item.split(':')[1])-int(1))+" downto 0)\n\t\t\t\t") - -components.append(");\n") -components.append("\tend component;\n\n") + printf("Client-Socket (Id : %d) created\\n", socket_fd); + fprintf(log_client,"Client-Client Socket created ''' \ + '''successfully \\n"); + fprintf(log_client,"Client- Socket Id : %d \\n",socket_fd); -#Adding signals -signals=[] -signals.append("\tsignal clk_s : std_logic := '0';\n") - -port_vector_count = 0 - -for item in input_port: - if port_vector_info[port_vector_count]: - signals.append("\tsignal "+item.split(':')[0]+": std_logic_vector("+str(int(item.split(':')[1])-int(1))+" downto 0);\n") - else: - signals.append("\tsignal "+item.split(':')[0]+": std_logic;\n") - port_vector_count += 1 - - #if item.split(":")[1] != '1': - # signals.append("\tsignal "+item.split(':')[0]+": std_logic_vector("+str(int(item.split(':')[1])-int(1))+" downto 0);\n") - #else: - # signals.append("\tsignal "+item.split(':')[0]+": std_logic_vector("+str(int(item.split(':')[1])-int(1))+" downto 0);\n") - - -for item in output_port: - if port_vector_info[port_vector_count]: - signals.append("\tsignal "+item.split(':')[0]+": std_logic_vector("+str(int(item.split(':')[1])-int(1))+" downto 0);\n") - else: - signals.append("\tsignal "+item.split(':')[0]+": std_logic;\n") - port_vector_count += 1 - #if item.split(":")[1] != '1': - # signals.append("\tsignal "+item.split(':')[0]+": std_logic_vector("+str(int(item.split(':')[1])-int(1))+" downto 0);\n") - #else: - # signals.append("\tsignal "+item.split(':')[0]+": std_logic_vector("+str(int(item.split(':')[1])-int(1))+" downto 0);\n") + // memset(&server_addr, 0, sizeof(server_addr)); + server_addr.sin_family = AF_INET; + server_addr.sin_port = htons(sock_port); + server_addr.sin_addr = *((struct in_addr *)host->h_addr); + bzero(&(server_addr.sin_zero),8); -#Adding mapping part -map=[] -map.append("\tu1 : "+fname.split('.')[0]+" port map(\n") + ''' -for item in input_port: - map.append("\t\t\t\t"+item.split(':')[0]+" => "+item.split(':')[0]+",\n") - -for item in output_port: - if output_port.index(item) == len(output_port) - 1: - map.append("\t\t\t\t"+item.split(':')[0]+" => "+item.split(':')[0]+"\n") - else: - map.append("\t\t\t\t"+item.split(':')[0]+" => "+item.split(':')[0]+",\n") -map.append("\t\t\t);") + connect_server = ''' + fprintf(log_client,"Client-Connecting to server \\n"); + + //Connecting to server + int try_limit=10; + while(try_limit>0) + { + if (connect(socket_fd, (struct sockaddr*)&server_addr,''' \ + '''sizeof(struct sockaddr)) == -1) + { + sleep(1); + try_limit--; + if(try_limit==0) + { + fprintf(stderr,"Connect- Error:Tried to connect server on port,''' \ + '''failed...giving up \\n"); + fprintf(log_client,"Connect- Error:Tried to connect server on ''' \ + '''port, failed...giving up \\n"); + exit(1); + } + } + else + { + printf("Client-Connected to server \\n"); + fprintf(log_client,"Client-Connected to server \\n"); + break; + } + } + ''' + # Assign bit value to every input + assign_data_to_input = [] + for item in self.input_port: + assign_data_to_input.append("\tfor(Ii=0;Ii<PORT_SIZE(" + + item.split(':')[0] + ");Ii++)\n\ + \t{\n\t\tif( INPUT_STATE(" + item.split(':')[0] + "[Ii])==ZERO )\n\ + \t\t{\n\t\t\ttemp_" + item.split(':')[0] + "[Ii]='0';\n\t\t}\n\ + \t\telse\n\t\t{\n\t\t\ttemp_" + item.split(':')[0] + "[Ii]='1';\n\ + \t\t}\n\t}\n\ttemp_" + item.split(':')[0] + "[Ii]='\\0';\n\n") + + snprintf_stmt = [] + snprintf_count = 0 + snprintf_stmt.append( + "\t//Sending and receiving data to-from server \n" + ) + snprintf_stmt.append('\tsnprintf(send_data,sizeof(send_data),"') + for item in self.input_port: + snprintf_count = snprintf_count + 1 + snprintf_stmt.append(item.split(':')[0] + ":%s") + if snprintf_count == len(self.input_port): + snprintf_stmt.append('", ') + internal_count = 0 + for item1 in self.input_port: + if internal_count == len(self.input_port): + pass + else: + snprintf_stmt.append("temp_" + item1.split(':')[0]) + internal_count = internal_count + 1 + if internal_count == len(self.input_port): + pass + else: + snprintf_stmt.append(",") + snprintf_stmt.append(");") + else: + snprintf_stmt.append(",") + + send_data = ''' + + if ( send(socket_fd,send_data,sizeof(send_data),0)==-1) + { + fprintf(stderr, "Client-Failure Sending Message \\n"); + close(socket_fd); + exit(1); + } + else + { + printf("Client-Message sent: %s \\n",send_data); + fprintf(log_client,"Socket Id : %d & Message sent : %s \\n"''' \ + ''',socket_fd,send_data); + } + + ''' + + recv_data = ''' + + bytes_recieved=recv(socket_fd,recv_data,sizeof(recv_data),0); + if ( bytes_recieved <= 0 ) + { + perror("Client-Either Connection Closed or Error "); + exit(1); + } + recv_data[bytes_recieved] = '\\0'; + + printf("Client-Message Received - %s\\n\\n",recv_data); + fprintf(log_client,"Message Received From Server-''' \ + '''%s\\n",recv_data); + + ''' + + # Scheduling output event + sch_output_event = [] + + for item in self.output_port: + sch_output_event.append( + "\t/* Scheduling event and processing them */\n\ + \tif((key_iter=strstr(recv_data, " + '"' + item.split(':')[0] + ':"'")) != NULL)\n\ + \t{\n\ + \t\twhile(*key_iter++ != ':');\n\ + \t\tfor(Ii=0;*key_iter != ';';Ii++,key_iter++)\n\ + \t\t{\n\ + \t\t\tfprintf(log_client,\"Client-Bit val is %c \\n\",*key_iter);\n\ + \t\t\tif(*key_iter=='0')\n\t\t\t{\n\ + \t\t\t\t_op_" + item.split(':')[0] + "[Ii]=ZERO;\n\t\t\t}\n\ + \t\t\telse if(*key_iter=='1')\n\t\t\t{\n\ + \t\t\t\t_op_" + item.split(':')[0] + "[Ii]=ONE;\n\ + \t\t\t}\n\t\t\telse\n\t\t\t{\n\ + \t\t\t\tfprintf(log_client,\"Unknow value return from server \\n\");\n\ + \t\t\t\tprintf(\"Client-Unknown value return \\n\");\n\t\t\t}\n\n\ + \t\t\tif(ANALYSIS == DC)\n\t\t\t{\n\ + \t\t\t\tOUTPUT_STATE(" + item.split(':')[0] + "[Ii]) = _op_" + item.split(':')[0] + "[Ii];\n\ + \t\t\t}\n\t\t\telse if(_op_" + item.split(':')[0] + "[Ii] != _op_" + item.split(':')[0] + "_old[Ii])\n\ + \t\t\t{\n\t\t\t\tOUTPUT_STATE(" + item.split(':')[0] + "[Ii]) = _op_" + item.split(':')[0] + "[Ii];\n\ + \t\t\t\tOUTPUT_DELAY(" + item.split(':')[0] + "[Ii]) = ((_op_" + item.split(':')[0] + "[Ii] == ZERO) ? PARAM(fall_delay) : PARAM(rise_delay));\n\ + \t\t\t}\n\t\t\telse\n\t\t\t{\n\ + \t\t\t\tOUTPUT_CHANGED(" + item.split(':')[0] + "[Ii]) = FALSE;\n\t\t\t}\n\ + \t\t\tOUTPUT_STRENGTH(" + item.split(':')[0] + "[Ii]) = STRONG;\n\ + \t\t}\n\ + \t}\n") + + # Writing content in cfunc.mod file + cfunc.write(comment) + cfunc.write(header) + cfunc.write("\n") + cfunc.write(function_open) + cfunc.write("\n") + + # Adding digital state Variable + for item in digital_state_output: + cfunc.write("\t" + item + "\n") + + # Adding variable declaration section + cfunc.write(var_section) + for item in temp_input_var: + cfunc.write("\t" + item + "\n") + cfunc.write("\n") + + # Adding INIT portion + cfunc.write(init_start_function) + for item in cm_event_alloc: + cfunc.write(2 * "\t" + item) + cfunc.write("\n") + + cfunc.write(2 * "\t" + "/* set the load for input ports. */") + cfunc.write("\n") + cfunc.write(2 * "\t" + "int Ii;") + cfunc.write("\n") + + for item in load_in_port: + cfunc.write(2 * "\t" + item) + cfunc.write("\n") + cfunc.write("\n") + cfunc.write(2 * "\t" + "/*Retrieve Storage for output*/") + cfunc.write("\n") + for item in cm_event_get_ptr: + cfunc.write(2 * "\t" + item) + cfunc.write("\n") + cfunc.write(systime_info) + cfunc.write("\n") + cfunc.write(client_setup_ip) + cfunc.write("\n") + cfunc.write("\t\tchar command[1024];\n") + cfunc.write( + '\t\tsnprintf(command,1024,"' + self.home + + '/ngspice-nghdl/src/xspice/icm/ghdl/' + + self.fname.split('.')[0] + + '/DUTghdl/start_server.sh %d %s &",sock_port,my_ip);' + ) + cfunc.write('\n\t\tsystem(command);') + cfunc.write("\n\t}") + cfunc.write("\n") + cfunc.write("\telse\n\t{\n") + + for item in els_evt_ptr: + cfunc.write(2 * "\t" + item) + cfunc.write("\n") + cfunc.write("\t}") + cfunc.write("\n\n") + + cfunc.write(client_fetch_ip) + cfunc.write(create_socket) + cfunc.write(connect_server) + + cfunc.write("\t//Formating data for sending it to client\n") + cfunc.write("\tint Ii;\n\n") + + for item in assign_data_to_input: + cfunc.write(item) + + for item in snprintf_stmt: + cfunc.write(item) + + cfunc.write(send_data) + cfunc.write(recv_data) + + for item in sch_output_event: + cfunc.write(item) + + # Close socket fd + cfunc.write("\tclose(socket_fd);\n\n") + + # close log_client file + cfunc.write("\tfclose(log_client);") + + # Close cm_ function + cfunc.write("\n}") + cfunc.close() + + def createIfSpecFile(self): + + # ################### Creating ifspec.ifs file #################### # + + print("Starting with ifspec.ifs file") + ifspec = open('ifspec.ifs', 'w') + + print("Gathering Al the content for ifspec file") + + ifspec_comment = ''' + /* + SUMMARY: This file is auto generated and it contains the interface + specification for the code model. */\n + ''' + + name_table = 'NAME_TABLE:\n\ + C_Function_Name: cm_' + self.fname.split('.')[0] + '\n\ + Spice_Model_Name: ' + self.fname.split('.')[0] + '\n\ + Description: "Model generated from ghdl code ' + self.fname + '" \n' + + # Input and Output Port Table + in_port_table = [] + out_port_table = [] + + for item in self.input_port: + port_table = 'PORT_TABLE:\n' + port_name = 'Port_Name:\t' + item.split(':')[0] + '\n' + description = ( + 'Description:\t"input port ' + item.split(':')[0] + '"\n' + ) + direction = 'Direction:\tin\n' + default_type = 'Default_Type:\td\n' + allowed_type = 'Allowed_Types:\t[d]\n' + vector = 'Vector:\tyes\n' + vector_bounds = ( + 'Vector_Bounds:\t[' + item.split(':')[1] + + ' ' + item.split(":")[1] + ']\n' + ) + null_allowed = 'Null_Allowed:\tno\n' + + # Insert detail in the list + in_port_table.append( + port_table + port_name + description + + direction + default_type + allowed_type + + vector + vector_bounds + null_allowed + ) + + for item in self.output_port: + port_table = 'PORT_TABLE:\n' + port_name = 'Port_Name:\t' + item.split(':')[0] + '\n' + description = ( + 'Description:\t"output port ' + item.split(':')[0] + '"\n' + ) + direction = 'Direction:\tout\n' + default_type = 'Default_Type:\td\n' + allowed_type = 'Allowed_Types:\t[d]\n' + vector = 'Vector:\tyes\n' + vector_bounds = ( + 'Vector_Bounds:\t[' + item.split(':')[1] + + ' ' + item.split(":")[1] + ']\n' + ) + null_allowed = 'Null_Allowed:\tno\n' + + # Insert detail in the list + in_port_table.append( + port_table + port_name + description + + direction + default_type + allowed_type + + vector + vector_bounds + null_allowed + ) + + parameter_table = ''' + + PARAMETER_TABLE: + Parameter_Name: instance_id input_load + Description: "instance_id" "input load value (F)" + Data_Type: real real + Default_Value: 0 1.0e-12 + Limits: - - + Vector: no no + Vector_Bounds: - - + Null_Allowed: yes yes + + PARAMETER_TABLE: + Parameter_Name: rise_delay fall_delay + Description: "rise delay" "fall delay" + Data_Type: real real + Default_Value: 1.0e-9 1.0e-9 + Limits: [1e-12 -] [1e-12 -] + Vector: no no + Vector_Bounds: - - + Null_Allowed: yes yes + + ''' + + static_table = ''' + + STATIC_VAR_TABLE: -#testbench Clock -tb_clk= "clk_s <= not clk_s after 5 us;\n\n" -#Adding Process block for Vhpi -process_Vhpi=[] -process_Vhpi.append("\tprocess\n\t\tvariable sock_port : integer;\n\t\ttype string_ptr is access string;\n\t\tvariable sock_ip : string_ptr;\n\t\tbegin\n\t\tsock_port := sock_port_fun;\n\t\tsock_ip := new string'(sock_ip_fun);\n\t\tVhpi_Initialize(sock_port, Pack_String_To_Vhpi_String(sock_ip.all));\n\t\twait until clk_s = '1';\n\t\twhile true loop\n\t\t\twait until clk_s = '0';\n\t\t\tVhpi_Listen;\n\t\t\twait for 1 us;\n\t\t\tVhpi_Send;\n\t\tend loop;\n\t\twait;\n\tend process;\n\n") -#Adding process block -process=[] -process.append("\tprocess\n") -process.append("\t\tvariable count : integer:=0;\n") + Static_Var_Name: my_ip + Data_Type: pointer + Description: "connect to ghdlserver through this ip" -for item in input_port: - process.append("\t\tvariable "+item.split(':')[0]+"_v : VhpiString;\n") - -for item in output_port: - process.append("\t\tvariable "+item.split(':')[0]+"_v : VhpiString;\n") - -process.append("\t\tvariable obj_ref : VhpiString;\n") -process.append("\tbegin\n") -process.append("\t\twhile true loop\n") -process.append("\t\t\twait until clk_s = '0';\n\n") - -port_vector_count = 0 - -for item in input_port: - process.append('\t\t\tobj_ref := Pack_String_To_Vhpi_String("'+item.split(':')[0]+'");\n') - process.append('\t\t\tVhpi_Get_Port_Value(obj_ref,'+item.split(':')[0]+'_v,'+item.split(':')[1]+');\n') - if port_vector_info[port_vector_count]: - process.append('\t\t\t'+item.split(':')[0]+' <= Unpack_String('+item.split(':')[0]+'_v,'+item.split(':')[1]+');\n') - else: - process.append('\t\t\t'+item.split(':')[0]+' <= To_Std_Logic('+item.split(':')[0]+'_v'+');\n') - port_vector_count += 1 - process.append("\n") - -process.append('\t\t\twait for 1 us;\n') - -for item in output_port: - if port_vector_info[port_vector_count]: - process.append('\t\t\t'+item.split(':')[0]+'_v := Pack_String_To_Vhpi_String(Convert_SLV_To_String('+item.split(':')[0]+'));\n') - else: - process.append('\t\t\t'+item.split(':')[0]+'_v := Pack_String_To_Vhpi_String(To_String('+item.split(':')[0]+'));\n') - port_vector_count += 1 - - process.append('\t\t\tobj_ref := Pack_String_To_Vhpi_String("'+item.split(':')[0]+'");\n') - process.append('\t\t\tVhpi_Set_Port_Value(obj_ref,'+item.split(':')[0]+'_v,'+item.split(':')[1]+');\n') - process.append("\n") - -process.append('\t\t\treport "Iteration - "' + "& integer'image(count) severity note;\n") -process.append('\t\t\tcount := count + 1;\n') -process.append("\t\tend loop;\n") -process.append("\tend process;\n\n") -process.append("end architecture;") - - -#Writing all the components to testbench file -testbench.write(comment_vhdl) -testbench.write(tb_header) -testbench.write(tb_entity) -testbench.write(arch) - -for item in components: - testbench.write(item) - -for item in signals: - testbench.write(item) - -testbench.write("\n\n") - -testbench.write("begin\n\n") - -for item in map: - testbench.write(item) - -testbench.write("\n\t"+tb_clk) - -for item in process_Vhpi: - testbench.write(item) - -for item in process: - testbench.write(item) - - -testbench.close() - -##################################### Creating and writing components in start_server.sh ################################ - -start_server = open('start_server.sh','w') - -start_server.write("#!/bin/bash\n\n") -start_server.write("###This server run ghdl testebench for infinite time till ngspice send END signal to stop it\n\n") -start_server.write("cd "+home+"/ngspice-nghdl/src/xspice/icm/ghdl/"+fname.split('.')[0]+"/DUTghdl/\n") -start_server.write("chmod 775 sock_pkg_create.sh &&\n") -start_server.write("./sock_pkg_create.sh $1 $2 &&\n") -start_server.write("ghdl -a sock_pkg.vhdl &&\n") -start_server.write("ghdl -a "+fname+" &&\n") -start_server.write("ghdl -a "+fname.split('.')[0]+"_tb.vhdl &&\n") -start_server.write("ghdl -e -Wl,ghdlserver.o "+fname.split('.')[0]+"_tb &&\n") -start_server.write("./"+fname.split('.')[0]+"_tb") - -start_server.close() - -##################################### Creating and writing in sock_pkg_create.sh ######################################## - -sock_pkg_create = open('sock_pkg_create.sh','w') - -sock_pkg_create.write("#!/bin/bash\n\n") -sock_pkg_create.write("##This file creates sock_pkg.vhdl file and sets the port and ip from parameters passed to it\n\n") -sock_pkg_create.write("echo \"library ieee;\n") -sock_pkg_create.write("package sock_pkg is\n") -sock_pkg_create.write("\tfunction sock_port_fun return integer;\n") -sock_pkg_create.write("\tfunction sock_ip_fun return string;\n") -sock_pkg_create.write("end;\n\n") -sock_pkg_create.write("package body sock_pkg is\n") -sock_pkg_create.write("\tfunction sock_port_fun return integer is\n") -sock_pkg_create.write("\t\tvariable sock_port : integer;\n") -sock_pkg_create.write("\t\t\tbegin\n") -sock_pkg_create.write("\t\t\t\tsock_port := $1;\n") -sock_pkg_create.write("\t\t\t\treturn sock_port;\n") -sock_pkg_create.write("\t\t\tend function;\n\n") -sock_pkg_create.write("\tfunction sock_ip_fun return string is\n") -sock_pkg_create.write("\t\ttype string_ptr is access string;\n") -sock_pkg_create.write("\t\tvariable sock_ip : string_ptr;\n") -sock_pkg_create.write("\t\t\tbegin\n") -sock_pkg_create.write('\t\t\t\tsock_ip := new string\'(\\"$2\\");\n') -sock_pkg_create.write("\t\t\t\treturn sock_ip.all;\n") -sock_pkg_create.write("\t\t\tend function;\n\n") -sock_pkg_create.write("\t\tend package body;\" > sock_pkg.vhdl")
\ No newline at end of file + ''' + + # Writing all the content in ifspec file + ifspec.write(ifspec_comment) + ifspec.write(name_table + "\n\n") + + for item in in_port_table: + ifspec.write(item + "\n") + + ifspec.write("\n") + + for item in out_port_table: + ifspec.write(item + "\n") + + ifspec.write("\n") + ifspec.write(parameter_table) + ifspec.write("\n") + ifspec.write(static_table) + ifspec.close() + + def createTestbench(self): + + # #################### Creating testbench file ##################### # + + print("Starting with testbench file") + + testbench = open(self.fname.split('.')[0] + '_tb.vhdl', 'w') + print(self.fname.split('.')[0] + '_tb.vhdl') + + # comment + comment_vhdl = "------------------------------------------------------" + comment_vhdl += "--------------------------\n" + comment_vhdl += "--This testbench has been created by " + comment_vhdl += "Ambikeshwar Srivastava, Rahul Paknikar \n" + comment_vhdl += "--------------------------- FOSSEE, IIT Bombay ------" + comment_vhdl += "---------------------------\n" + comment_vhdl += "-----------------------------------------------------" + comment_vhdl += "---------------------------\n" + + # Adding header, entity and architecture statement + tb_header = ''' + library ieee; + use ieee.std_logic_1164.all; + use ieee.numeric_std.all; + library work; + use work.Vhpi_Foreign.all; + use work.Utility_Package.all; + use work.sock_pkg.all; + + ''' + + tb_entity = ("entity " + self.fname.split('.')[0] + + "_tb is\nend entity;\n\n") + + arch = ("architecture " + self.fname.split('.')[0] + "_tb_beh of " + + self.fname.split('.')[0] + "_tb is\n") + + # Adding components + components = [] + components.append("\tcomponent " + self.fname.split('.')[0] + + " is\n\t\tport(\n\t\t\t\t") + + port_vector_count = 0 + + for item in self.input_port: + if self.port_vector_info[port_vector_count]: + components.append( + item.split(':')[0] + ": in std_logic_vector(" + + str(int(item.split(':')[1]) - int(1)) + + " downto 0);\n\t\t\t\t" + ) + else: + components.append( + item.split(':')[0] + ": in std_logic;\n\t\t\t\t" + ) + + port_vector_count += 1 + # if item.split(":")[1] != '1': + # components.append( + # item.split(':')[0] + ": in std_logic_vector(" + + # str(int(item.split(':')[1])-int(1)) + " downto 0);" + + # "\n\t\t\t\t" + # ) + # else: + # components.append( + # item.split(':')[0] + ": in std_logic_vector(" + + # str(int(item.split(':')[1])-int(1)) + " downto 0);" + + # "\n\t\t\t\t" + # ) + for item in self.output_port[:-1]: + if self.port_vector_info[port_vector_count]: + components.append( + item.split(':')[0] + ": out std_logic_vector(" + + str(int(item.split(':')[1]) - int(1)) + + " downto 0);\n\t\t\t\t" + ) + else: + components.append( + item.split(':')[0] + ": out std_logic;\n\t\t\t\t" + ) + + port_vector_count += 1 + + if self.port_vector_info[port_vector_count]: + components.append( + self.output_port[-1].split(':')[0] + + ": out std_logic_vector(" + + str(int(self.output_port[-1].split(':')[1]) - int(1)) + + " downto 0)\n\t\t\t\t" + ) + else: + components.append(self.output_port[-1].split(':')[0] + + ": out std_logic\n\t\t\t\t") + # if item.split(":")[1] != '1': + # components.append(item.split(':')[0]+": + # out std_logic_vector(" + # +str(int(item.split(':')[1])-int(1))+" downto 0)\n\t\t\t\t") + # else: + # components.append(item.split(':')[0]+": + # out std_logic_vector(" + # +str(int(item.split(':')[1])-int(1))+" downto 0)\n\t\t\t\t") + + components.append(");\n") + components.append("\tend component;\n\n") + + # Adding signals + signals = [] + signals.append("\tsignal clk_s : std_logic := '0';\n") + + port_vector_count = 0 + + for item in self.input_port: + if self.port_vector_info[port_vector_count]: + signals.append( + "\tsignal " + item.split(':')[0] + ": std_logic_vector(" + + str(int(item.split(':')[1]) - int(1)) + " downto 0);\n" + ) + else: + signals.append( + "\tsignal " + item.split(':')[0] + ": std_logic;\n" + ) + port_vector_count += 1 + + # if item.split(":")[1] != '1': + # signals.append("\tsignal "+item.split(':')[0]+": + # std_logic_vector("+str(int(item.split(':')[1])- + # int(1))+" downto 0);\n") + # else: + # signals.append("\tsignal "+item.split(':')[0]+": + # std_logic_vector("+str(int(item.split(':')[1])- + # int(1))+" downto 0);\n") + + for item in self.output_port: + if self.port_vector_info[port_vector_count]: + signals.append( + "\tsignal " + item.split(':')[0] + ": std_logic_vector(" + + str(int(item.split(':')[1]) - int(1)) + " downto 0);\n" + ) + else: + signals.append( + "\tsignal " + item.split(':')[0] + ": std_logic;\n" + ) + + port_vector_count += 1 + # if item.split(":")[1] != '1': + # signals.append( + # "\tsignal " + item.split(':')[0] + ":std_logic_vector(" + + # str(int(item.split(':')[1]) - int(1)) + " downto 0);\n" + # ) + # else: + # signals.append( + # "\tsignal " + item.split(':')[0] + ":std_logic_vector(" + + # str(int(item.split(':')[1]) - int(1)) + " downto 0);\n" + # ) + + # Adding mapping part + map = [] + map.append("\tu1 : " + self.fname.split('.')[0] + " port map(\n") + + for item in self.input_port: + map.append("\t\t\t\t" + item.split(':')[0] + + " => " + item.split(':')[0] + ",\n") + + for item in self.output_port: + if self.output_port.index(item) == len(self.output_port) - 1: + map.append("\t\t\t\t" + item.split(':')[0] + + " => " + item.split(':')[0] + "\n") + else: + map.append("\t\t\t\t" + item.split(':')[0] + + " => " + item.split(':')[0] + ",\n") + map.append("\t\t\t);") + + # Testbench Clock + tb_clk = "clk_s <= not clk_s after 5 us;\n\n" + + # Adding Process block for Vhpi + process_Vhpi = [] + process_Vhpi.append( + "process\n\t\tvariable sock_port : integer;" + + "\n\t\ttype string_ptr is access string;" + + "\n\t\tvariable sock_ip : string_ptr;" + + "\n\t\tbegin\n\t\tsock_port := sock_port_fun;" + + "\n\t\tsock_ip := new string'(sock_ip_fun);" + + "\n\t\tVhpi_Initialize(sock_port," + + "Pack_String_To_Vhpi_String(sock_ip.all));" + + "\n\t\twait until clk_s = '1';" + + "\n\t\twhile true loop\n\t\t\twait until clk_s = '0';" + + "\n\t\t\tVhpi_Listen;\n\t\t\twait for 1 us;\n\t\t\t" + + "Vhpi_Send;" + + "\n\t\tend loop;\n\t\twait;\n\tend process;\n\n" + ) + + # Adding process block + process = [] + process.append("\tprocess\n") + process.append("\t\tvariable count : integer:=0;\n") + + for item in self.input_port: + process.append( + "\t\tvariable " + item.split(':')[0] + "_v : VhpiString;\n" + ) + + for item in self.output_port: + process.append( + "\t\tvariable " + item.split(':')[0] + "_v : VhpiString;\n" + ) + + process.append("\t\tvariable obj_ref : VhpiString;\n") + process.append("\tbegin\n") + process.append("\t\twhile true loop\n") + process.append("\t\t\twait until clk_s = '0';\n\n") + + port_vector_count = 0 + + for item in self.input_port: + process.append( + '\t\t\tobj_ref := Pack_String_To_Vhpi_String("' + + item.split(':')[0] + '");\n' + ) + process.append( + '\t\t\tVhpi_Get_Port_Value(obj_ref,' + + item.split(':')[0] + '_v,' + item.split(':')[1] + ');\n' + ) + + if self.port_vector_info[port_vector_count]: + process.append( + '\t\t\t' + item.split(':')[0] + + ' <= Unpack_String(' + item.split(':')[0] + '_v,' + + item.split(':')[1] + ');\n' + ) + else: + process.append( + '\t\t\t' + item.split(':')[0] + + ' <= To_Std_Logic('+item.split(':')[0]+'_v'+');\n' + ) + + port_vector_count += 1 + process.append("\n") + + process.append('\t\t\twait for 1 us;\n') + + for item in self.output_port: + if self.port_vector_info[port_vector_count]: + process.append( + '\t\t\t' + item.split(':')[0] + + '_v := Pack_String_To_Vhpi_String' + + '(Convert_SLV_To_String(' + + item.split(':')[0]+'));\n' + ) + else: + process.append( + '\t\t\t' + item.split(':')[0] + + '_v := Pack_String_To_Vhpi_String(To_String(' + + item.split(':')[0]+'));\n' + ) + + port_vector_count += 1 + + process.append( + '\t\t\tobj_ref := Pack_String_To_Vhpi_String("' + + item.split(':')[0]+'");\n' + ) + process.append( + '\t\t\tVhpi_Set_Port_Value(obj_ref,' + + item.split(':')[0] + '_v,' + item.split(':')[1] + ');\n' + ) + process.append("\n") + + process.append( + '\t\t\treport "Iteration - "' + + "& integer'image(count) severity note;\n" + ) + process.append('\t\t\tcount := count + 1;\n') + process.append("\t\tend loop;\n") + process.append("\tend process;\n\n") + process.append("end architecture;") + + # Writing all the components to testbench file + testbench.write(comment_vhdl) + testbench.write(tb_header) + testbench.write(tb_entity) + testbench.write(arch) + + for item in components: + testbench.write(item) + + for item in signals: + testbench.write(item) + + testbench.write("\n\n") + + testbench.write("begin\n\n") + + for item in map: + testbench.write(item) + + testbench.write("\n\t"+tb_clk) + + for item in process_Vhpi: + testbench.write(item) + + for item in process: + testbench.write(item) + + testbench.close() + + def createServerScript(self): + + # ####### Creating and writing components in start_server.sh ####### # + + start_server = open('start_server.sh', 'w') + + start_server.write("#!/bin/bash\n\n") + start_server.write( + "###This server run ghdl testebench for infinite time till " + + "ngspice send END signal to stop it\n\n" + ) + start_server.write( + "cd "+self.home+"/ngspice-nghdl/src/xspice/icm/ghdl/" + + self.fname.split('.')[0]+"/DUTghdl/\n" + ) + start_server.write("chmod 775 sock_pkg_create.sh &&\n") + start_server.write("./sock_pkg_create.sh $1 $2 &&\n") + start_server.write("ghdl -i *.vhdl &&\n") + start_server.write("ghdl -a *.vhdl &&\n") + start_server.write("ghdl -a "+self.fname+" &&\n") + start_server.write( + "ghdl -a "+self.fname.split('.')[0]+"_tb.vhdl &&\n" + ) + start_server.write( + "ghdl -e -Wl,ghdlserver.o " + self.fname.split('.')[0] + "_tb &&\n" + ) + start_server.write("./"+self.fname.split('.')[0]+"_tb") + + start_server.close() + + def createSockScript(self): + + # ########### Creating and writing in sock_pkg_create.sh ########### # + + sock_pkg_create = open('sock_pkg_create.sh', 'w') + + sock_pkg_create.write("#!/bin/bash\n\n") + sock_pkg_create.write( + "##This file creates sock_pkg.vhdl file and sets the port " + + "and ip from parameters passed to it\n\n" + ) + sock_pkg_create.write("echo \"library ieee;\n") + sock_pkg_create.write("package sock_pkg is\n") + sock_pkg_create.write("\tfunction sock_port_fun return integer;\n") + sock_pkg_create.write("\tfunction sock_ip_fun return string;\n") + sock_pkg_create.write("end;\n\n") + sock_pkg_create.write("package body sock_pkg is\n") + sock_pkg_create.write("\tfunction sock_port_fun return integer is\n") + sock_pkg_create.write("\t\tvariable sock_port : integer;\n") + sock_pkg_create.write("\t\t\tbegin\n") + sock_pkg_create.write("\t\t\t\tsock_port := $1;\n") + sock_pkg_create.write("\t\t\t\treturn sock_port;\n") + sock_pkg_create.write("\t\t\tend function;\n\n") + sock_pkg_create.write("\tfunction sock_ip_fun return string is\n") + sock_pkg_create.write("\t\ttype string_ptr is access string;\n") + sock_pkg_create.write("\t\tvariable sock_ip : string_ptr;\n") + sock_pkg_create.write("\t\t\tbegin\n") + sock_pkg_create.write('\t\t\t\tsock_ip := new string\'(\\"$2\\");\n') + sock_pkg_create.write("\t\t\t\treturn sock_ip.all;\n") + sock_pkg_create.write("\t\t\tend function;\n\n") + sock_pkg_create.write("\t\tend package body;\" > sock_pkg.vhdl") diff --git a/src/ngspice_ghdl.py b/src/ngspice_ghdl.py index 4afeef3..9991793 100755 --- a/src/ngspice_ghdl.py +++ b/src/ngspice_ghdl.py @@ -1,9 +1,7 @@ -#!/usr/bin/env python +#!/usr/bin/python3 -"""#!/usr/bin/python""" - -#This file create the gui to install code model in the ngspice. +# This file create the gui to install code model in the ngspice. import os import sys @@ -11,34 +9,40 @@ import shutil import subprocess from PyQt4 import QtGui from PyQt4 import QtCore -from ConfigParser import SafeConfigParser +from configparser import SafeConfigParser from Appconfig import Appconfig from createKicadLibrary import AutoSchematic +from model_generation import ModelGeneration + class Mainwindow(QtGui.QWidget): + def __init__(self): - #super(Mainwindow, self).__init__() + # super(Mainwindow, self).__init__() QtGui.QMainWindow.__init__(self) - print "Initializing.........." + print("Initializing..........") + self.home = os.path.expanduser("~") - #Reading all varibale from config.ini + # Reading all variables from config.ini self.parser = SafeConfigParser() - self.parser.read(os.path.join(self.home, os.path.join('.nghdl','config.ini'))) - self.ngspice_home = self.parser.get('NGSPICE','NGSPICE_HOME') - self.release_dir = self.parser.get('NGSPICE','RELEASE') - self.src_home = self.parser.get('SRC','SRC_HOME') - self.licensefile = self.parser.get('SRC','LICENSE') - #Printing LICENCE file on terminal + self.parser.read( + os.path.join(self.home, os.path.join('.nghdl', 'config.ini')) + ) + self.ngspice_home = self.parser.get('NGSPICE', 'NGSPICE_HOME') + self.release_dir = self.parser.get('NGSPICE', 'RELEASE') + self.src_home = self.parser.get('SRC', 'SRC_HOME') + self.licensefile = self.parser.get('SRC', 'LICENSE') + # Printing LICENCE file on terminal fileopen = open(self.licensefile, 'r') - print fileopen.read() + print(fileopen.read()) fileopen.close() - self.file_list = [] #to keep the supporting files - self.errorFlag = False #to keep the check of "make install" errors + self.file_list = [] # to keep the supporting files + self.errorFlag = False # to keep the check of "make install" errors self.initUI() def initUI(self): self.uploadbtn = QtGui.QPushButton('Upload') - self.uploadbtn.clicked.connect(self.uploadModle) + self.uploadbtn.clicked.connect(self.uploadModel) self.exitbtn = QtGui.QPushButton('Exit') self.exitbtn.clicked.connect(self.closeWindow) self.browsebtn = QtGui.QPushButton('Browse') @@ -58,7 +62,7 @@ class Mainwindow(QtGui.QWidget): self.termedit.setPalette(pal) self.termedit.setStyleSheet("QTextEdit {color:white}") - #Creating gridlayout + # Creating gridlayout grid = QtGui.QGridLayout() grid.setSpacing(5) grid.addWidget(self.ledit, 1, 0) @@ -68,45 +72,41 @@ class Mainwindow(QtGui.QWidget): grid.addWidget(self.removebtn, 3, 1) grid.addWidget(self.termedit, 6, 0, 10, 1) grid.addWidget(self.uploadbtn, 17, 0) - grid.addWidget(self.exitbtn,17, 1) + grid.addWidget(self.exitbtn, 17, 1) self.setLayout(grid) - self.setGeometry(300, 300, 600,600) + self.setGeometry(300, 300, 600, 600) self.setWindowTitle("Ngspice Digital Model Creator") - #self.setWindowIcon(QtGui.QIcon('logo.png')) + # self.setWindowIcon(QtGui.QIcon('logo.png')) self.show() - def closeWindow(self): try: self.process.close() - except: - pass - print "Close button clicked" - quit() - + except BaseException: + pass + print("Close button clicked") + sys.exit() def browseFile(self): - print "Browse button clicked" - self.filename = QtGui.QFileDialog.getOpenFileName(self, 'Open File', '.') + print("Browse button clicked") + self.filename = QtGui.QFileDialog.getOpenFileName( + self, 'Open File', '.') self.ledit.setText(self.filename) - print "Vhdl file uploaded to process :", self.filename - + print("Vhdl file uploaded to process :", self.filename) def addFiles(self): - print "Starts adding supporting files" + print("Starts adding supporting files") title = self.addbtn.text() for file in QtGui.QFileDialog.getOpenFileNames(self, title): - self.sedit.append(str(file)) - self.file_list.append(file) - print "Supporting Files are :",self.file_list - + self.sedit.append(str(file)) + self.file_list.append(file) + print("Supporting Files are :", self.file_list) def removeFiles(self): - self.fileRemover = FileRemover(self) + self.fileRemover = FileRemover(self) - - #check extensions of all supporting files + # Check extensions of all supporting files def checkSupportFiles(self): nonvhdl_count = 0 for file in self.file_list: @@ -116,171 +116,198 @@ class Mainwindow(QtGui.QWidget): self.file_list.remove(file) if nonvhdl_count > 0: - QtGui.QMessageBox.critical(self,'Critical','''<b>Important Message.</b><br/><br/>Supporting files should be <b>.vhdl</b> file ''') - + QtGui.QMessageBox.critical( + self, 'Critical', '''<b>Important Message.</b> + <br/><br/>Supporting files should be <b>.vhdl</b> file ''' + ) def createModelDirectory(self): - print "Create Model Directory Called" - self.digital_home=self.parser.get('NGSPICE','DIGITAL_MODEL') + print("Create Model Directory Called") + self.digital_home = self.parser.get('NGSPICE', 'DIGITAL_MODEL') os.chdir(self.digital_home) - print "Current Working Directory Changed to",os.getcwd() + print("Current Working Directory Changed to", os.getcwd()) self.modelname = os.path.basename(str(self.filename)).split('.')[0] - print "Model to be created :",self.modelname + print("Model to be created :", self.modelname) # Looking if model directory is present or not if os.path.isdir(self.modelname): - print "Model Already present" - ret = QtGui.QMessageBox.warning(self, "Warning",'''<b>This model already exist. Do you want to overwrite it?</b><br/> - If yes press ok, else cancel it and change the name of your vhdl file.''', QtGui.QMessageBox.Ok, QtGui.QMessageBox.Cancel) + print("Model Already present") + ret = QtGui.QMessageBox.warning( + self, "Warning", + "<b>This model already exist. Do you want to " + + "overwrite it?</b><br/> If yes press ok, else cancel it and " + + "change the name of your vhdl file.", + QtGui.QMessageBox.Ok, QtGui.QMessageBox.Cancel + ) if ret == QtGui.QMessageBox.Ok: - print "Overwriting existing model "+self.modelname - cmd="rm -rf "+self.modelname - #process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) + print("Overwriting existing model " + self.modelname) + cmd = "rm -rf " + self.modelname + # process = subprocess.Popen( + # cmd, stdout=subprocess.PIPE, + # stderr=subprocess.PIPE, shell=True + # ) subprocess.call(cmd, shell=True) os.mkdir(self.modelname) else: - print "Exiting application" - quit() + print("Exiting application") + sys.exit() else: - print "Creating model "+self.modelname+" directory" + print("Creating model " + self.modelname + " directory") os.mkdir(self.modelname) - def addingModelInModpath(self): - print "Adding Model "+self.modelname+" in Modpath file "+self.digital_home - #Adding name of model in the modpath file - #Check if the string is already in the file - with open(self.digital_home+"/modpath.lst",'a+') as f: + print("Adding Model " + self.modelname + + " in Modpath file " + self.digital_home) + # Adding name of model in the modpath file + # Check if the string is already in the file + with open(self.digital_home + "/modpath.lst", 'r+') as f: flag = 0 for line in f: if line.strip() == self.modelname: - print "Found model "+self.modelname+" in the modpath.lst" + print("Found model "+self.modelname+" in the modpath.lst") flag = 1 break - else: - pass if flag == 0: - print "Adding model name "+self.modelname+" into modpath.lst" - f.write(self.modelname+"\n") + print("Adding model name "+self.modelname+" into modpath.lst") + f.write(self.modelname + "\n") else: - print "Model name is already into modpath.lst" - + print("Model name is already into modpath.lst") def createModelFiles(self): - print "Create Model Files Called" + print("Create Model Files Called") os.chdir(self.cur_dir) - print "Current Working directory changed to "+self.cur_dir - cmd = "python "+self.src_home+"/src/model_generation.py "+str(self.ledit.text()) - stdouterr = os.popen4(cmd)[1].read() - print stdouterr - #Moving file to model directory - path=os.path.join(self.digital_home,self.modelname) - shutil.move("cfunc.mod",path) - shutil.move("ifspec.ifs",path) - - #Creating directory inside model directoy - print "Creating DUT directory at "+os.path.join(path,"DUTghdl") - os.mkdir(path+"/DUTghdl/") - print "Copying required file to DUTghdl directory" - shutil.move("connection_info.txt",path+"/DUTghdl/") - shutil.move("start_server.sh",path+"/DUTghdl/") - shutil.move("sock_pkg_create.sh",path+"/DUTghdl/") - shutil.move(self.modelname+"_tb.vhdl",path+"/DUTghdl/") - - shutil.copy(str(self.filename),path+"/DUTghdl/") - shutil.copy(os.path.join(self.home, self.src_home)+"/src/ghdlserver/compile.sh",path+"/DUTghdl/") - shutil.copy(os.path.join(self.home, self.src_home)+"/src/ghdlserver/uthash.h",path+"/DUTghdl/") - shutil.copy(os.path.join(self.home, self.src_home)+"/src/ghdlserver/ghdlserver.c",path+"/DUTghdl/") - shutil.copy(os.path.join(self.home, self.src_home)+"/src/ghdlserver/ghdlserver.h",path+"/DUTghdl/") - shutil.copy(os.path.join(self.home, self.src_home)+"/src/ghdlserver/Utility_Package.vhdl",path+"/DUTghdl/") - shutil.copy(os.path.join(self.home, self.src_home)+"/src/ghdlserver/Vhpi_Package.vhdl",path+"/DUTghdl/") + print("Current Working directory changed to " + self.cur_dir) + + # Generate model corresponding to the uploaded VHDL file + model = ModelGeneration(str(self.ledit.text())) + model.readPortInfo() + model.createCfuncModFile() + model.createIfSpecFile() + model.createTestbench() + model.createServerScript() + model.createSockScript() + + # Moving file to model directory + path = os.path.join(self.digital_home, self.modelname) + shutil.move("cfunc.mod", path) + shutil.move("ifspec.ifs", path) + + # Creating directory inside model directoy + print("Creating DUT directory at " + os.path.join(path, "DUTghdl")) + os.mkdir(path + "/DUTghdl/") + print("Copying required file to DUTghdl directory") + shutil.move("connection_info.txt", path + "/DUTghdl/") + shutil.move("start_server.sh", path + "/DUTghdl/") + shutil.move("sock_pkg_create.sh", path + "/DUTghdl/") + shutil.move(self.modelname + "_tb.vhdl", path + "/DUTghdl/") + + shutil.copy(str(self.filename), path + "/DUTghdl/") + shutil.copy(os.path.join(self.home, self.src_home) + + "/src/ghdlserver/compile.sh", path + "/DUTghdl/") + shutil.copy(os.path.join(self.home, self.src_home) + + "/src/ghdlserver/uthash.h", path + "/DUTghdl/") + shutil.copy(os.path.join(self.home, self.src_home) + + "/src/ghdlserver/ghdlserver.c", path + "/DUTghdl/") + shutil.copy(os.path.join(self.home, self.src_home) + + "/src/ghdlserver/ghdlserver.h", path + "/DUTghdl/") + shutil.copy(os.path.join(self.home, self.src_home) + + "/src/ghdlserver/Utility_Package.vhdl", path + "/DUTghdl/") + shutil.copy(os.path.join(self.home, self.src_home) + + "/src/ghdlserver/Vhpi_Package.vhdl", path + "/DUTghdl/") for file in self.file_list: - shutil.copy(str(file), path+"/DUTghdl/") - - os.chdir(path+"/DUTghdl") - subprocess.call("bash "+path+"/DUTghdl/compile.sh", shell=True) - subprocess.call("chmod a+x start_server.sh",shell=True) - subprocess.call("chmod a+x sock_pkg_create.sh",shell=True) + shutil.copy(str(file), path + "/DUTghdl/") + + os.chdir(path + "/DUTghdl") + subprocess.call("bash " + path + "/DUTghdl/compile.sh", shell=True) + subprocess.call("chmod a+x start_server.sh", shell=True) + subprocess.call("chmod a+x sock_pkg_create.sh", shell=True) os.remove("compile.sh") os.remove("ghdlserver.c") - #os.remove("ghdlserver.h") - #os.remove("Utility_Package.vhdl") - #os.remove("Vhpi_Package.vhdl") - - - #slot to redirect stdout and stderr to window console + # os.remove("ghdlserver.h") + # os.remove("Utility_Package.vhdl") + # os.remove("Vhpi_Package.vhdl") + + # Slot to redirect stdout and stderr to window console @QtCore.pyqtSlot() def readAllStandard(self): - self.termedit.append(QtCore.QString(self.process.readAllStandardOutput())) - stderror = QtCore.QString(self.process.readAllStandardError()) - if stderror.contains("ERROR", QtCore.Qt.CaseInsensitive): - self.errorFlag = True - self.termedit.append(stderror) - + self.termedit.append( + str(self.process.readAllStandardOutput().data(), encoding='utf-8') + ) + stderror = self.process.readAllStandardError() + if stderror.toUpper().contains("ERROR"): + self.errorFlag = True + self.termedit.append(str(stderror.data(), encoding='utf-8')) def runMake(self): - print "run Make Called" - self.release_home=self.parser.get('NGSPICE','RELEASE') + print("run Make Called") + self.release_home = self.parser.get('NGSPICE', 'RELEASE') os.chdir(self.release_home) try: cmd = " make" - print "Running Make command in "+self.release_home - path = os.getcwd() + print("Running Make command in " + self.release_home) + path = os.getcwd() # noqa self.process = QtCore.QProcess(self) self.process.start(cmd) - print "make command process pid ---------- >",self.process.pid() - - except: - print "There is error in 'make' " - quit() - + print("make command process pid ---------- >", self.process.pid()) + except BaseException: + print("There is error in 'make' ") + sys.exit() def runMakeInstall(self): - print "run Make Install Called" + print("run Make Install Called") try: cmd = " make install" - print "Running Make Install" - path = os.getcwd() + print("Running Make Install") + path = os.getcwd() # noqa try: self.process.close() - except: + except BaseException: pass - + self.process = QtCore.QProcess(self) self.process.start(cmd) self.process.finished.connect(self.createSchematicLib) - QtCore.QObject.connect(self.process, QtCore.SIGNAL("readyReadStandardOutput()"), self, QtCore.SLOT("readAllStandard()")) + QtCore.QObject.connect( + self.process, QtCore.SIGNAL("readyReadStandardOutput()"), + self, QtCore.SLOT("readAllStandard()") + ) os.chdir(self.cur_dir) - except: - print "There is error during in 'make install' " - quit() - + except BaseException: + print("There is error in 'make install' ") + sys.exit() def createSchematicLib(self): if Appconfig.esimFlag == 1: if not self.errorFlag: - print 'Creating library files.................................' + print('Creating library files................................') schematicLib = AutoSchematic(self.modelname) schematicLib.createKicadLibrary() else: - QtGui.QMessageBox.critical(self,'Error','''Cannot create Schematic Library of your model. Resolve the <b>errors</b> shown on console of NGHDL window. ''') + QtGui.QMessageBox.critical( + self, 'Error', '''Cannot create Schematic Library of ''' + + '''your model. Resolve the <b>errors</b> shown on ''' + + '''console of NGHDL window. ''' + ) else: - QtGui.QMessageBox.information(self,'Message','''<b>Important Message</b><br/><br/>To create Schematic Library of your model, use NGHDL through <b>eSim</b> ''') - - - def uploadModle(self): - print "Upload button clicked" + QtGui.QMessageBox.information( + self, 'Message', '''<b>Important Message</b><br/><br/>''' + + '''To create Schematic Library of your model, ''' + + '''use NGHDL through <b>eSim</b> ''' + ) + + def uploadModel(self): + print("Upload button clicked") try: self.process.close() - except: - pass + except BaseException: + pass try: self.file_extension = os.path.splitext(str(self.filename))[1] - print "Uploaded File extension :"+self.file_extension + print("Uploaded File extension :" + self.file_extension) self.cur_dir = os.getcwd() - print "Current Working Directory :"+self.cur_dir + print("Current Working Directory :" + self.cur_dir) self.checkSupportFiles() if self.file_extension == ".vhdl": self.errorFlag = False @@ -290,82 +317,79 @@ class Mainwindow(QtGui.QWidget): self.runMake() self.runMakeInstall() else: - QtGui.QMessageBox.information(self,'Message','''<b>Important Message.</b><br/><br/>This accepts only <b>.vhdl</b> file ''') + QtGui.QMessageBox.information( + self, 'Message', '''<b>Important Message.</b><br/>''' + + '''<br/>This accepts only <b>.vhdl</b> file ''' + ) except Exception as e: QtGui.QMessageBox.critical(self, 'Error', str(e)) -class FileRemover(QtGui.QWidget): - - def __init__(self, main_obj): - super(FileRemover, self).__init__() - self.row = 0 - self.col = 0 - self.cb_dict = {} - self.marked_list = [] - self.files = main_obj.file_list - self.sedit = main_obj.sedit - - print self.files - - self.grid = QtGui.QGridLayout() - removebtn = QtGui.QPushButton('Remove', self) - removebtn.clicked.connect(self.removeFiles) - - self.grid.addWidget(self.createCheckBox(), 0, 0) - self.grid.addWidget(removebtn, 1, 1) - self.setLayout(self.grid) - self.show() - - def createCheckBox(self): - - self.checkbox = QtGui.QGroupBox() - self.checkbox.setTitle('Remove Files') - self.checkgrid = QtGui.QGridLayout() +class FileRemover(QtGui.QWidget): - self.checkgroupbtn = QtGui.QButtonGroup() + def __init__(self, main_obj): + super(FileRemover, self).__init__() + self.row = 0 + self.col = 0 + self.cb_dict = {} + self.marked_list = [] + self.files = main_obj.file_list + self.sedit = main_obj.sedit - for path in self.files: + print(self.files) - print path + self.grid = QtGui.QGridLayout() + removebtn = QtGui.QPushButton('Remove', self) + removebtn.clicked.connect(self.removeFiles) - self.cb_dict[path] = QtGui.QCheckBox(path) - self.checkgroupbtn.addButton(self.cb_dict[path]) - self.checkgrid.addWidget(self.cb_dict[path], self.row, self.col) - self.row += 1 + self.grid.addWidget(self.createCheckBox(), 0, 0) + self.grid.addWidget(removebtn, 1, 1) - self.checkgroupbtn.setExclusive(False) - self.checkgroupbtn.buttonClicked.connect(self.mark_file) - self.checkbox.setLayout(self.checkgrid) + self.setLayout(self.grid) + self.show() - return self.checkbox + def createCheckBox(self): + self.checkbox = QtGui.QGroupBox() + self.checkbox.setTitle('Remove Files') + self.checkgrid = QtGui.QGridLayout() - def mark_file(self): + self.checkgroupbtn = QtGui.QButtonGroup() - for path in self.cb_dict: - if self.cb_dict[path].isChecked(): - if path not in self.marked_list: - self.marked_list.append(path) + for path in self.files: + print(path) + self.cb_dict[path] = QtGui.QCheckBox(path) + self.checkgroupbtn.addButton(self.cb_dict[path]) + self.checkgrid.addWidget(self.cb_dict[path], self.row, self.col) + self.row += 1 - else: - if path in self.marked_list: - self.marked_list.remove(path) + self.checkgroupbtn.setExclusive(False) + self.checkgroupbtn.buttonClicked.connect(self.mark_file) + self.checkbox.setLayout(self.checkgrid) - def removeFiles(self): + return self.checkbox - for path in self.marked_list: - print path +" is removed" - self.sedit.append(path + " removed") - self.files.remove(path) + def mark_file(self): + for path in self.cb_dict: + if self.cb_dict[path].isChecked(): + if path not in self.marked_list: + self.marked_list.append(path) + else: + if path in self.marked_list: + self.marked_list.remove(path) - self.sedit.clear() - for path in self.files: - self.sedit.append(path) + def removeFiles(self): + for path in self.marked_list: + print(path + " is removed") + self.sedit.append(path + " removed") + self.files.remove(path) - self.marked_list[:] = [] - self.files[:] = [] - self.close() + self.sedit.clear() + for path in self.files: + self.sedit.append(path) + self.marked_list[:] = [] + self.files[:] = [] + self.close() def main(): @@ -373,8 +397,12 @@ def main(): if len(sys.argv) > 1: if sys.argv[1] == '-e': Appconfig.esimFlag = 1 - w = Mainwindow() + + # Mainwindow() object must be assigned to a variable. + # Otherwise, it is destroyed as soon as it gets created. + w = Mainwindow() # noqa sys.exit(app.exec_()) -if __name__=='__main__': + +if __name__ == '__main__': main() |