Working CanOpen OD generation
authoretisserant
Mon, 10 Sep 2007 18:12:03 +0200
changeset 24 585d5b387b6a
parent 23 e007d9d466d7
child 25 fa7503684c28
Working CanOpen OD generation
Beremiz.py
plugger.py
plugins/canfestival/canfestival.py
plugins/canfestival/config_utils.py
--- a/Beremiz.py	Mon Sep 10 14:10:03 2007 +0200
+++ b/Beremiz.py	Mon Sep 10 18:12:03 2007 +0200
@@ -324,7 +324,7 @@
         self.PluginRoot = PluginsRoot(self)
         
         if projectOpen:
-            self.PluginRoot.LoadProject(projectOpen)
+            self.PluginRoot.LoadProject(projectOpen, self.Log)
             self.RefreshPluginTree()
         
         self.RefreshPluginParams()
@@ -664,7 +664,7 @@
         if dialog.ShowModal() == wx.ID_OK:
             projectpath = dialog.GetPath()
             if os.path.isdir(projectpath):
-                result = self.PluginRoot.LoadProject(projectpath)
+                result = self.PluginRoot.LoadProject(projectpath, self.Log)
                 if not result:
                     self.RefreshPluginTree()
                     self.RefreshButtons()
--- a/plugger.py	Mon Sep 10 14:10:03 2007 +0200
+++ b/plugger.py	Mon Sep 10 18:12:03 2007 +0200
@@ -132,10 +132,9 @@
         shutil.copytree(src_PlugPath, self.PlugPath)
         return True
 
-    def PlugGenerate_C(self, buildpath, current_location, locations, logger):
+    def PlugGenerate_C(self, buildpath, locations, logger):
         """
         Generate C code
-        @param current_location: Tupple containing plugin IEC location : %I0.0.4.5 => (0,0,4,5)
         @param locations: List of complete variables locations \
             [{"IEC_TYPE" : the IEC type (i.e. "INT", "STRING", ...)
             "NAME" : name of the variable (generally "__IW0_1_2" style)
@@ -145,29 +144,23 @@
             }, ...]
         @return: [(C_file_name, CFLAGS),...] , LDFLAGS_TO_APPEND
         """
-        logger.write_warning(".".join(map(lambda x:str(x), current_location)) + " -> Nothing yo do\n")
+        logger.write_warning(".".join(map(lambda x:str(x), self.GetCurrentLocation())) + " -> Nothing yo do\n")
         return [],""
     
-    def _Generate_C(self, buildpath, current_location, locations, logger):
+    def _Generate_C(self, buildpath, locations, logger):
         # Generate plugins [(Cfiles, CFLAGS)], LDFLAGS
-        PlugCFilesAndCFLAGS, PlugLDFLAGS = self.PlugGenerate_C(buildpath, current_location, locations, logger)
+        PlugCFilesAndCFLAGS, PlugLDFLAGS = self.PlugGenerate_C(buildpath, locations, logger)
         # recurse through all childs, and stack their results
         for PlugChild in self.IterChilds():
-            # Compute child's IEC location
-            if current_location:
-                new_location = current_location + (self.BaseParams.getIEC_Channel())
-            else:
-                # root 
-                new_location = ()
-            # Get childs [(Cfiles, CFLAGS)], LDFLAGS
+            new_location = PlugChild.GetCurrentLocation()
+            # How deep are we in the tree ?
+            depth=len(new_location)
             CFilesAndCFLAGS, LDFLAGS = \
                 PlugChild._Generate_C(
                     #keep the same path
                     buildpath,
-                    # but update location (add curent IEC channel at the end)
-                    new_location,
                     # filter locations that start with current IEC location
-                    [loc for loc in locations if loc["LOC"][0:len(new_location)] == new_location ],
+                    [loc for loc in locations if loc["LOC"][0:depth] == new_location ],
                     #propagete logger
                     logger)
             # stack the result
@@ -208,6 +201,9 @@
         return self._GetChildBySomething('_',"IEC_Channel", Name)
     
     def GetCurrentLocation(self):
+        """
+        @return:  Tupple containing plugin IEC location of current plugin : %I0.0.4.5 => (0,0,4,5)
+        """
         return self.PlugParent.GetCurrentLocation() + (self.BaseParams.getIEC_Channel(),)
 
     def GetPlugRoot(self):
@@ -268,7 +264,7 @@
         # Ask to his parent to remove it
         PlugInstance.PlugParent._doRemoveChild(PlugInstance)
 
-    def PlugAddChild(self, PlugName, PlugType):
+    def PlugAddChild(self, PlugName, PlugType, logger):
         """
         Create the plugins that may be added as child to this node self
         @param PlugType: string desining the plugin class name (get name from PlugChildsTypes)
@@ -321,7 +317,7 @@
                     if getattr(PlugClass, "__init__", None):
                         PlugClass.__init__(_self)
                     #Load and init all the childs
-                    _self.LoadChilds()
+                    _self.LoadChilds(logger)
                 else:
                     # If plugin do not have corresponding file/dirs - they will be created on Save
                     # Set plugin name
@@ -357,15 +353,16 @@
             self.PlugParams[1].loadXMLTree(tree.childNodes[0])
             xmlfile.close()
         
-    def LoadChilds(self):
+    def LoadChilds(self, logger):
         # Iterate over all PlugName@PlugType in plugin directory, and try to open them
         for PlugDir in os.listdir(self.PlugPath()):
             if os.path.isdir(os.path.join(self.PlugPath(), PlugDir)) and \
                PlugDir.count(NameTypeSeparator) == 1:
-                #try:
-                self.PlugAddChild(*PlugDir.split(NameTypeSeparator))
-                #except Exception, e:
-                #    print e
+                pname, ptype = PlugDir.split(NameTypeSeparator)
+                try:
+                    self.PlugAddChild(pname, ptype, logger)
+                except Exception, e:
+                    logger.write_error("Could not add child \"%s\", type %s :\n%s\n"%(pname, ptype, str(e)))
 
 def _GetClassFunction(name):
     def GetRootClass():
@@ -535,7 +532,7 @@
         self.ProjectPath = ProjectPath
         return None
         
-    def LoadProject(self, ProjectPath):
+    def LoadProject(self, ProjectPath, logger):
         """
         Load a project contained in a folder
         @param ProjectPath: path of the project folder
@@ -562,7 +559,7 @@
             if result:
                 return result
             #Load and init all the childs
-            self.LoadChilds()
+            self.LoadChilds(logger)
         return None
     
     def SaveProject(self):
@@ -576,10 +573,9 @@
     def PluginXmlFilePath(self, PlugName=None):
         return os.path.join(self.PlugPath(PlugName), "beremiz.xml")
 
-    def PlugGenerate_C(self, buildpath, current_location, locations, logger):
+    def PlugGenerate_C(self, buildpath, locations, logger):
         """
         Generate C code
-        @param current_location: Tupple containing plugin IEC location : %I0.0.4.5 => (0,0,4,5)
         @param locations: List of complete variables locations \
             [(IEC_loc, IEC_Direction, IEC_Type, Name)]\
             ex: [((0,0,4,5),'I','STRING','__IX_0_0_4_5'),...]
@@ -663,6 +659,7 @@
         if not os.path.exists(buildpath):
             os.mkdir(buildpath)
         
+        logger.flush()
         logger.write("Start build in %s\n" % buildpath)
         
         # Generate SoftPLC code
@@ -673,16 +670,15 @@
         logger.write("SoftPLC code generation successfull\n")
         
         # Generate C code and compilation params from plugin hierarchy
-        #try:
-        CFilesAndCFLAGS, LDFLAGS = self._Generate_C(
-            buildpath, 
-            None, #root has no location
-            self.PLCGeneratedLocatedVars,
-            logger)
-        #except Exception, msg:
-        #    logger.write_error("Plugins code generation Failed !\n")
-        #    logger.write_error(str(msg))
-        #    return False
+        try:
+            CFilesAndCFLAGS, LDFLAGS = self._Generate_C(
+                buildpath, 
+                self.PLCGeneratedLocatedVars,
+                logger)
+        except Exception, msg:
+            logger.write_error("Plugins code generation Failed !\n")
+            logger.write_error(str(msg))
+            return False
 
         logger.write("Plugins code generation successfull\n")
 
--- a/plugins/canfestival/canfestival.py	Mon Sep 10 14:10:03 2007 +0200
+++ b/plugins/canfestival/canfestival.py	Mon Sep 10 18:12:03 2007 +0200
@@ -55,7 +55,7 @@
         self.SaveProject()
         return True
 
-    def PlugGenerate_C(self, buildpath, current_location, locations, logger):
+    def PlugGenerate_C(self, buildpath, locations, logger):
         """
         Generate C code
         @param current_location: Tupple containing plugin IEC location : %I0.0.4.5 => (0,0,4,5)
@@ -68,6 +68,7 @@
             }, ...]
         @return: [(C_file_name, CFLAGS),...] , LDFLAGS_TO_APPEND
         """
+        current_location = self.GetCurrentLocation()
         # define a unique name for the generated C file
         prefix = "_".join(map(lambda x:str(x), current_location))
         Gen_OD_path = os.path.join(buildpath, prefix + "_OD.c" )
@@ -77,7 +78,7 @@
         if res :
             raise Exception, res
         
-        return [(Gen_OD_path,CanFestival_OD_CFLAGS)],""
+        return [(Gen_OD_path,"")],""
     
 class RootClass:
     XSD = """<?xml version="1.0" encoding="ISO-8859-1" ?>
@@ -92,7 +93,7 @@
 
     PlugChildsTypes = [("CanOpenNode",_NodeListPlug)]
     
-    def PlugGenerate_C(self, buildpath, current_location, locations, logger):
+    def PlugGenerate_C(self, buildpath, locations, logger):
         return [],""
 
 
--- a/plugins/canfestival/config_utils.py	Mon Sep 10 14:10:03 2007 +0200
+++ b/plugins/canfestival/config_utils.py	Mon Sep 10 18:12:03 2007 +0200
@@ -26,7 +26,7 @@
 
 DicoTypes = {"BOOL":0x01, "SINT":0x02, "INT":0x03,"DINT":0x04,"LINT":0x10,
              "USINT":0x05,"UINT":0x06,"UDINT":0x07,"ULINT":0x1B,"REAL":0x08,
-             "LREAL":0x11,"STRING":0x09,"BYTE":0x02,"WORD":0x03,"DWORD":0x04,
+             "LREAL":0x11,"STRING":0x09,"BYTE":0x05,"WORD":0x06,"DWORD":0x07,
              "LWORD":0x1B,"WSTRING":0x0B}
 
 DictLocations = {}
@@ -211,7 +211,7 @@
             loc = location["LOC"][len(current_location):]
             # loc correspond to (ID, INDEX, SUBINDEX [,BIT])
             if len(loc) not in (3, 4):
-                raise ValueError, "Bad location size"
+                raise ValueError, "Bad location size : %s"%str(loc)
             
             direction = location["DIR"]
             
@@ -243,15 +243,15 @@
                 else:
                     numbit = None
                 
-                locationtype = DicoTypes[locationtype]
+                COlocationtype = DicoTypes[locationtype]
                 entryinfos = node.GetSubentryInfos(index, subindex)
-                if entryinfos["type"] != locationtype:
-                    raise ValueError, "Invalid type for location \"%s\"" % name
-                
-                typeinfos = node.GetEntryInfos(locationtype)
-                DictLocations[name] = {"type":locationtype, "pdotype":SlavePDOType[direction],
-                                       "nodeid": nodeid, "index": index,"subindex": subindex, 
-                                       "bit": numbit, "size": typeinfos["size"], "busname": busname, "sizelocation": sizelocation}
+                if entryinfos["type"] != COlocationtype:
+                    raise ValueError, "Invalid type \"%s\"-> %d != %d  for location\"%s\"" % (locationtype,COlocationtype, entryinfos["type"] , name)
+                
+                typeinfos = node.GetEntryInfos(COlocationtype)
+                DictLocations[name] = {"type":COlocationtype, "pdotype":SlavePDOType[direction],
+                                       "nodeid": nodeid, "index": index,"subindex": subindex,
+                                       "bit": numbit, "size": typeinfos["size"], "sizelocation": sizelocation}
             else:
                 raise ValueError, "Not PDO mappable variable : '%s' (ID:%d,Idx:%x,sIdx:%x))" % (name,nodeid,index,subindex)
                 
@@ -375,8 +375,16 @@
             if type(variable) != IntType:
                 
                 typeidx, varname = variable
-                indexname = DictNameVariable[DictLocations[variable[1]]["pdotype"]][0] + DictLocations[variable[1]]["sizelocation"] + str(DictLocations[variable[1]]["busname"]) + "_" + str(DictLocations[variable[1]]["nodeid"])
+                indexname = \
+                    DictNameVariable[DictLocations[variable[1]]["pdotype"]][0] + \
+                    DictLocations[variable[1]]["sizelocation"] + \
+                    '_'.join(map(str,current_location)) + \
+                    "_" + \
+                    str(DictLocations[variable[1]]["nodeid"])
                 mapvariableidx = DictNameVariable[DictLocations[variable[1]]["pdotype"]][1] +  DictNameVariable[DictLocations[variable[1]]["sizelocation"]] * DictNameVariable["increment"]
+
+                #indexname = DictNameVariable[DictLocations[variable[1]]["pdotype"]][0] + DictLocations[variable[1]]["sizelocation"] + str(DictLocations[variable[1]]["prefix"]) + "_" + str(DictLocations[variable[1]]["nodeid"])
+                #mapvariableidx = DictNameVariable[DictLocations[variable[1]]["pdotype"]][1] +  DictNameVariable[DictLocations[variable[1]]["sizelocation"]] * DictNameVariable["increment"]
                 
                 if not masternode.IsEntry(mapvariableidx):
                     manager.AddMapVariableToCurrent(mapvariableidx, indexname, 3, 1, masternode)