etherlab/EthercatMaster.py
branchethercat_from_kosmos
changeset 2641 c9deff128c37
parent 2165 02a2b5dee5e3
child 2643 b98d9e08231f
--- a/etherlab/EthercatMaster.py	Sat Jun 23 09:17:20 2018 +0200
+++ b/etherlab/EthercatMaster.py	Wed Nov 20 16:57:15 2019 +0100
@@ -85,9 +85,12 @@
         ethelabfile.write(etherlab_ext_code)
         ethelabfile.close()
         
-        runtimefile_path = os.path.join(os.path.split(__file__)[0], "runtime_etherlab.py")
-        return ((["etherlab_ext"], [(Gen_etherlabfile_path, IECCFLAGS)], True), "", 
+        try:
+            return ((["etherlab_ext"], [(Gen_etherlabfile_path, IECCFLAGS)], True), "", 
                 ("runtime_etherlab.py", file(GetLocalPath("runtime_etherlab.py"))))
+        except:
+            return ((["etherlab_ext"], [(Gen_etherlabfile_path, IECCFLAGS)], True), "", 
+                ("runtime_etherlab.pyc", file(GetLocalPath("runtime_etherlab.pyc"))))
     
 #--------------------------------------------------
 #                 Ethercat MASTER
@@ -221,7 +224,7 @@
 ProcessVariablesParser = GenerateParserFromXSDstring(ProcessVariablesXSD) 
 
 class _EthercatCTN:
-
+    
     CTNChildrenTypes = [("EthercatSlave", _EthercatSlaveCTN, "Ethercat Slave")]
     if HAS_MCL:
         CTNChildrenTypes.append(("EthercatCIA402Slave", _EthercatCIA402SlaveCTN, "Ethercat CIA402 Slave"))
@@ -231,20 +234,21 @@
         config_filepath = self.ConfigFileName()
         config_is_saved = False
         self.Config = None
-        if os.path.isfile(config_filepath):
-            config_xmlfile = open(config_filepath, 'r')
-            try:
-                self.Config, error = \
-                    EtherCATConfigParser.LoadXMLString(config_xmlfile.read())
-                if error is None:
-                    config_is_saved = True
-            except Exception, e:
-                error = e.message
-            config_xmlfile.close()
+
+        #if os.path.isfile(config_filepath):
+        #    config_xmlfile = open(config_filepath, 'r')
+        #    try:
+        #        self.Config, error = \
+        #            EtherCATConfigParser.LoadXMLString(config_xmlfile.read())
+        #        if error is None:
+        #            config_is_saved = True
+        #    except Exception, e:
+        #        error = e.message
+        #    config_xmlfile.close()
             
-            if error is not None:
-                self.GetCTRoot().logger.write_error(
-                    _("Couldn't load %s network configuration file.") % CTNName)    
+        #    if error is not None:
+        #        self.GetCTRoot().logger.write_error(
+        #            _("Couldn't load %s network configuration file.") % CTNName)    
             
         if self.Config is None:
             self.Config = EtherCATConfigParser.CreateElement("EtherCATConfig")
@@ -270,14 +274,32 @@
         if self.ProcessVariables is None:
             self.ProcessVariables = ProcessVariablesParser.CreateElement("ProcessVariables")
         
-        if config_is_saved and process_is_saved:
+        #if config_is_saved and process_is_saved:
+        if process_is_saved:
             self.CreateBuffer(True)
         else:
             self.CreateBuffer(False)
             self.OnCTNSave()
-         
+
+        if os.path.isfile(config_filepath):
+            config_xmlfile = open(config_filepath, 'r')
+            try:
+                self.Config, error = \
+                    EtherCATConfigParser.LoadXMLString(config_xmlfile.read())
+                if error is None:
+                    config_is_saved = True
+            except Exception, e:
+                error = e.message
+            config_xmlfile.close()
+            
+            if error is not None:
+                self.GetCTRoot().logger.write_error(
+                    _("Couldn't load %s network configuration file.") % CTNName)
+
         # ----------- call ethercat mng. function --------------
         self.CommonMethod = _CommonSlave(self)
+        
+        ###################################### Test Section #########################################
     
     def GetIconName(self):
         return "Ethercat"
@@ -293,7 +315,10 @@
             type_infos = dialog.GetValueInfos()
             device, module_extra_params = self.GetModuleInfos(type_infos)
             if device is not None:
-                if HAS_MCL and _EthercatCIA402SlaveCTN.NODE_PROFILE in device.GetProfileNumbers():
+                # device.GetProfileNumbers() return type is string
+                # _EthercatCIA402SlaveCTN.NODE_PROFILE change to string
+                # 151224 jblee
+                if HAS_MCL and str(_EthercatCIA402SlaveCTN.NODE_PROFILE) in device.GetProfileNumbers():
                     ConfNodeType = "EthercatCIA402Slave"
                 else:
                     ConfNodeType = "EthercatSlave"
@@ -563,6 +588,7 @@
                 return infos
         return None
     
+    """
     def GetSlaveVariables(self, slave_pos=None, limits=None, device=None):
         if device is None and slave_pos is not None:
             slave = self.GetSlave(slave_pos)
@@ -571,7 +597,6 @@
                 device, module_extra_params = self.GetModuleInfos(type_infos)
         if device is not None:
             entries = device.GetEntriesList(limits)
-            #print entries
             entries_list = entries.items()
             entries_list.sort()
             entries = []
@@ -592,6 +617,128 @@
                     entries.append(entry)
             return entries
         return []
+    #"""
+
+    def GetSlaveVariables(self, slave_pos=None, limits=None, device=None, module=None):
+        # add jblee
+        files = os.listdir(self.CTNPath())
+        moduleNames = []
+        modulePos = 1
+        for file in files:
+            filepath = os.path.join(self.CTNPath(), file)
+            if os.path.isdir(filepath):
+                MDPFilePath = os.path.join(filepath, "DataForMDP.txt")
+                CheckConfNodePath = os.path.join(filepath, "baseconfnode.xml")
+
+                try :
+                    moduleDataFile = open(MDPFilePath, 'r')
+                    confNodeFile = open(CheckConfNodePath, 'r')
+
+                    lines = moduleDataFile.readlines()
+                    checklines = confNodeFile.readlines()
+
+                    moduleDataFile.close()
+                    confNodeFile.close()
+
+                    module_info = self.GetModuleEntryList()
+                    # checklines(ex) : <BaseParams xmlns:xsd="http://www.w3.org/2001/XMLSchema" IEC_Channel="0" Name="EthercatSlave_0"/>
+                    # checklines[1].split() : [<BaseParams, xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+                    #                           IEC_Channel="0", Name="EthercatSlave_0"/>]
+                    # checklines[1].split()[2] : IEC_Channel="0"
+                    # checklines[1].split()[2].split("\"") = [IEC_Channel=, 0, ]
+                    pos_check = int(checklines[1].split()[2].split("\"")[1])
+
+                    if slave_pos != pos_check:
+                        continue
+
+                    for line in lines:
+                        if line == "\n":
+                            continue
+                        # module_name : ST-1214, ST-2314, ...
+                        # if user add module => ST-1214 3EA, ST-2314 3EA
+                        # each result_module_name : 
+                        #    (ST-1214, Module 1), (ST-1214, Module 2), (ST-1214, Module 3)
+                        #    (ST-2314, Module 4), (ST-2314, Module 5), (ST-2314, Module 6)  
+                        module_name = line.split()[0]
+                        result_module_name = module_name + ", Module %d" % modulePos
+                        moduleNames.append(result_module_name)
+                        modulePos += 1
+                except :
+                    pass
+
+        if device is None and slave_pos is not None:
+            slave = self.GetSlave(slave_pos)
+            if slave is not None:
+                type_infos = slave.getType()
+                device, module_extra_params = self.GetModuleInfos(type_infos)
+                
+        if device is not None:
+            # Test OD
+            entries = device.GetEntriesList(limits)
+            #entries = self.CTNParent.GetEntriesList()
+            entries_list = entries.items()
+            entries_list.sort()
+            entries = []
+            current_index = None
+            current_entry = None
+            for (index, subindex), entry in entries_list:
+                entry["children"] = []
+                if slave_pos is not None:
+                    entry["Position"] = str(slave_pos)
+                entry
+                if index != current_index:
+                    current_index = index
+                    current_entry = entry
+                    entries.append(entry)
+                elif current_entry is not None:
+                    current_entry["children"].append(entry)
+                else:
+                    entries.append(entry)
+
+            increment = self.CTNParent.GetModuleIncrement()[0]
+            count = 1
+            #print module_info
+            # moduleNameAndPos : (ST-1214, Module 1), (ST-1214, Module 2), ... ,
+            # moduleNameAndPos.split(",") : ["ST-1214", " Module 1"]
+            # moduleNameAndPos.split(",")[0] : "ST-1214"
+            for moduleNameAndPos in moduleNames:
+                moduleName = moduleNameAndPos.split(",")[0]
+                modulePosName = moduleNameAndPos.split(",")[1]
+                idx_increment = int(increment) * count
+                
+                for MDP_entry in module_info.get(moduleName):
+                    LocalMDPEntry = []
+                    #print MDP_entry
+                    local_idx = MDP_entry["Index"]
+                    if ExtractHexDecValue(local_idx) == 0: #and local_idx[0] == "#":
+                        temp_index = ExtractHexDecValue(local_idx)
+                    else :
+                        temp_index = ExtractHexDecValue(MDP_entry["Index"]) + idx_increment
+                    #temp_index = ExtractHexDecValue(MDP_entry["Index"]) + idx_increment
+                    entry_index = hex(temp_index)
+                    entry_subidx = MDP_entry["SubIndex"]
+                    entry_name = MDP_entry["Name"] + ", " + " " + \
+                                 moduleName + " - " + modulePosName
+                    entry_type = MDP_entry["Type"]
+                    entry_bitsize = MDP_entry["BitSize"]
+                    entry_access = MDP_entry["Access"]
+                    mapping_type = MDP_entry["PDOMapping"]
+
+                    LocalMDPEntry.append({
+                        "Index": entry_index,
+                        "SubIndex": entry_subidx,
+                        "Name": entry_name,
+                        "Type": entry_type,
+                        "BitSize": entry_bitsize,
+                        "Access": entry_access, 
+                        "PDOMapping": mapping_type,
+                        "children": ""})
+                    entries.append(LocalMDPEntry[0])
+                count += 1
+            
+            #print entries
+            return entries
+        return []
     
     def GetSlaveVariableDataType(self, slave_pos, index, subindex):
         slave = self.GetSlave(slave_pos)
@@ -599,6 +746,7 @@
             device, module_extra_params = self.GetModuleInfos(slave.getType())
             if device is not None:
                 entries = device.GetEntriesList()
+                #entries = self.CTNParent.GetEntriesList()
                 entry_infos = entries.get((index, subindex))
                 if entry_infos is not None:
                     return entry_infos["Type"]
@@ -621,6 +769,10 @@
      
     def GetModuleInfos(self, type_infos):
         return self.CTNParent.GetModuleInfos(type_infos)
+
+    # add jblee
+    def GetModuleEntryList(self):
+        return self.CTNParent.GetModuleEntryList()
     
     def GetSlaveTypesLibrary(self, profile_filter=None):
         return self.CTNParent.GetModulesLibrary(profile_filter)
@@ -630,7 +782,54 @@
     
     def GetDeviceLocationTree(self, slave_pos, current_location, device_name):
         slave = self.GetSlave(slave_pos)
-        vars = []    
+        vars = []
+
+        # add jblee
+        files = os.listdir(self.CTNPath())
+        moduleNames = []
+        modulePos = 1
+        for file in files:
+            filepath = os.path.join(self.CTNPath(), file)
+            if os.path.isdir(filepath):
+                MDPFilePath = os.path.join(filepath, "DataForMDP.txt")
+                CheckConfNodePath = os.path.join(filepath, "baseconfnode.xml")
+
+                try :
+                    moduleDataFile = open(MDPFilePath, 'r')
+                    confNodeFile = open(CheckConfNodePath, 'r')
+
+                    lines = moduleDataFile.readlines()
+                    checklines = confNodeFile.readlines()
+
+                    moduleDataFile.close()
+                    confNodeFile.close()
+
+                    module_info = self.GetModuleEntryList()
+                    # checklines(ex) : <BaseParams xmlns:xsd="http://www.w3.org/2001/XMLSchema" IEC_Channel="0" Name="EthercatSlave_0"/>
+                    # checklines[1].split() : [<BaseParams, xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+                    #                           IEC_Channel="0", Name="EthercatSlave_0"/>]
+                    # checklines[1].split()[2] : IEC_Channel="0"
+                    # checklines[1].split()[2].split("\"") = [IEC_Channel=, 0, ]
+                    pos_check = int(checklines[1].split()[2].split("\"")[1])
+
+                    if slave_pos != pos_check:
+                        continue
+
+                    for line in lines:
+                        if line == "\n":
+                            continue
+                        # module_name : ST-1214, ST-2314, ...
+                        # if user add module => ST-1214 3EA, ST-2314 3EA
+                        # each result_module_name : 
+                        #    (ST-1214, Module 1), (ST-1214, Module 2), (ST-1214, Module 3)
+                        #    (ST-2314, Module 4), (ST-2314, Module 5), (ST-2314, Module 6)  
+                        module_name = line.split()[0]
+                        result_module_name = module_name + ", Module %d" % modulePos
+                        moduleNames.append(result_module_name)
+                        modulePos += 1
+                except :
+                    pass
+
         if slave is not None:
             type_infos = slave.getType()
         
@@ -645,8 +844,11 @@
                     else:
                         sync_managers.append(LOCATION_VAR_INPUT)
                 
+                # Test OD
                 entries = device.GetEntriesList().items()
+                #entries = self.CTNParent.GetEntriesList().items()
                 entries.sort()
+                
                 for (index, subindex), entry in entries:
                     var_size = self.GetSizeOfType(entry["Type"])
                     if var_size is not None:
@@ -666,7 +868,40 @@
                                                                                                     (index, subindex)))),
                                          "description": "",
                                          "children": []})
-        
+
+                # add jblee for MDP
+                if not entries :
+                    increment = self.CTNParent.GetModuleIncrement()[0]
+                    count = 1
+                    for moduleNameAndPos in moduleNames:
+                        moduleName = moduleNameAndPos.split(",")[0]
+                        idx_increment = int(increment) * count
+                        for MDP_entry in module_info.get(moduleName):
+                            local_idx = MDP_entry["Index"]
+                            if ExtractHexDecValue(local_idx) != 0 and local_idx[0] == "#":
+                                index = ExtractHexDecValue(local_idx) + idx_increment
+                            else :
+                                index = ExtractHexDecValue(MDP_entry["Index"])
+                            subindex = int(MDP_entry["SubIndex"])
+                            var_class = VARCLASSCONVERSION.get(MDP_entry["PDOMapping"], None)
+                            if var_class is not None:
+                                if var_class == LOCATION_VAR_INPUT:
+                                    var_dir = "%I"
+                                else:
+                                    var_dir = "%Q"
+                            var_size = self.GetSizeOfType(MDP_entry["Type"])
+                            result_name = MDP_entry["Name"] + ", " + moduleNameAndPos
+                            vars.append({"name": "0x%4.4x-0x%2.2x: %s" % (index, subindex, result_name),
+                                         "type": var_class,
+                                         "size": var_size,
+                                         "IEC_type": MDP_entry["Type"],
+                                         "var_name": "%s_%4.4x_%2.2x" % ("_".join(moduleName.split()), index, subindex),
+                                         "location": "%s%s%s"%(var_dir, var_size, ".".join(map(str, current_location + 
+                                                                                                    (index, subindex)))),
+                                         "description": "",
+                                         "children": []})
+                        count += 1
+
         return vars
     
     def CTNTestModified(self):
@@ -674,7 +909,6 @@
 
     def OnCTNSave(self, from_project_path=None):
         config_filepath = self.ConfigFileName()
-        
         config_xmlfile = open(config_filepath,"w")
         config_xmlfile.write(etree.tostring(
             self.Config,