etherlab/EthercatCIA402Slave.py
changeset 2643 b98d9e08231f
parent 2413 803daf19a1b5
parent 2641 c9deff128c37
equal deleted inserted replaced
2640:1b4b335e19ea 2643:b98d9e08231f
   199     def _getCIA402AxisRef(self):
   199     def _getCIA402AxisRef(self):
   200         self.StartDragNDrop(
   200         self.StartDragNDrop(
   201             ("%%IW%s.402" % ".".join(map(str, self.GetCurrentLocation())),
   201             ("%%IW%s.402" % ".".join(map(str, self.GetCurrentLocation())),
   202              "location", "AXIS_REF", self.CTNName(), ""))
   202              "location", "AXIS_REF", self.CTNName(), ""))
   203 
   203 
       
   204     # add jblee
       
   205     """
       
   206     def LoadPDOSelectData(self):
       
   207         ReadData = []
       
   208         files = os.listdir(self.CTNPath())
       
   209         filepath = os.path.join(self.CTNPath(), "DataForPDO.txt")
       
   210         if os.path.isfile(filepath):
       
   211             PDODataRead = open(filepath, 'r')
       
   212             ReadData = PDODataRead.readlines()
       
   213             PDODataRead.close()
       
   214 
       
   215         if len(ReadData) > 1:
       
   216             for data in ReadData[0].split() :
       
   217                 if data == "RxPDO":
       
   218                     continue
       
   219                 self.SelectedRxPDOIndex.append(int(data, 0))
       
   220 
       
   221             for data in ReadData[1].split() :
       
   222                 if data == "TxPDO":
       
   223                     continue
       
   224                 self.SelectedTxPDOIndex.append(int(data, 0))
       
   225     """
       
   226 
       
   227     def LoadPDOSelectData(self):
       
   228         RxPDOData = self.BaseParams.getRxPDO()
       
   229         RxPDOs = []
       
   230         if RxPDOData != "None":
       
   231             RxPDOs = RxPDOData.split()
       
   232         if RxPDOs :
       
   233             for RxPDO in RxPDOs :
       
   234                 self.SelectedRxPDOIndex.append(int(RxPDO, 0))
       
   235 
       
   236         TxPDOData = self.BaseParams.getTxPDO()
       
   237         TxPDOs = []
       
   238         if TxPDOData != "None":
       
   239             TxPDOs = TxPDOData.split()
       
   240         if TxPDOs :
       
   241             for TxPDO in TxPDOs :
       
   242                 self.SelectedTxPDOIndex.append(int(TxPDO, 0))
       
   243 
       
   244     def LoadDefaultPDOSet(self):
       
   245         ReturnData = []
       
   246         rx_pdo_entries = self.CommonMethod.GetRxPDOCategory()
       
   247         if len(rx_pdo_entries):
       
   248             for i in range(len(rx_pdo_entries)):
       
   249                 if rx_pdo_entries[i]['sm'] is not None:
       
   250                     ReturnData.append(rx_pdo_entries[i]['pdo_index'])
       
   251 
       
   252         tx_pdo_entries = self.CommonMethod.GetTxPDOCategory()
       
   253         if len(tx_pdo_entries):
       
   254             for i in range(len(tx_pdo_entries)):
       
   255                 if tx_pdo_entries[i]['sm'] is not None:
       
   256                     ReturnData.append(tx_pdo_entries[i]['pdo_index'])
       
   257 
       
   258         if ReturnData :
       
   259             return ReturnData
       
   260         else :
       
   261             return [5632, 6656]
       
   262         
   204     def CTNGenerate_C(self, buildpath, locations):
   263     def CTNGenerate_C(self, buildpath, locations):
   205         current_location = self.GetCurrentLocation()
   264         current_location = self.GetCurrentLocation()
   206 
   265 
   207         location_str = "_".join(map(str, current_location))
   266         location_str = "_".join(map(str, current_location))
   208         slave_pos = self.GetSlavePos()
       
   209 
   267 
   210         # Open CIA402 node code template file
   268         # Open CIA402 node code template file
   211         plc_cia402node_filepath = os.path.join(os.path.split(__file__)[0],
   269         plc_cia402node_filepath = os.path.join(os.path.split(__file__)[0],
   212                                                "plc_cia402node.c")
   270                                                "plc_cia402node.c")
   213         plc_cia402node_file = open(plc_cia402node_filepath, 'r')
   271         plc_cia402node_file = open(plc_cia402node_filepath, 'r')
   214         plc_cia402node_code = plc_cia402node_file.read()
   272         plc_cia402node_code = plc_cia402node_file.read()
   215         plc_cia402node_file.close()
   273         plc_cia402node_file.close()
   216 
   274         # HSAHN 150726
   217         # Init list of generated strings for each code template file section
   275         # add "default_variables_retrieve": [], "default_variables_publish": [],
   218         fieldbus_interface_declaration = []
   276 		# As PDO mapping object, it will add auto-complete code.
   219         fieldbus_interface_definition = []
   277         # add "modeofop_homing_method", "modeofop_computation_mode" by jblee
   220         init_axis_params = []
   278         str_completion = {
   221         extra_variables_retrieve = []
   279             "slave_pos": self.GetSlavePos(),
   222         extra_variables_publish = []
   280             "location": location_str,
   223         extern_located_variables_declaration = []
   281             "MCL_headers": Headers,
   224         entry_variables = []
   282             "extern_located_variables_declaration": [],
   225         init_entry_variables = []
   283             "fieldbus_interface_declaration": [],
   226 
   284             "fieldbus_interface_definition": [],
   227         # Fieldbus interface code sections
   285             "entry_variables": [],
       
   286             "init_axis_params": [],
       
   287             "init_entry_variables": [],
       
   288             "default_variables_retrieve": [],
       
   289             "default_variables_publish": [],
       
   290             "extra_variables_retrieve": [],
       
   291             "extra_variables_publish": [],
       
   292             "modeofop_homing_method": [],
       
   293             "modeofop_computation_mode": []
       
   294         }
       
   295         
   228         for blocktype_infos in FIELDBUS_INTERFACE_GLOBAL_INSTANCES:
   296         for blocktype_infos in FIELDBUS_INTERFACE_GLOBAL_INSTANCES:
   229             blocktype = blocktype_infos["blocktype"]
   297             texts = {
   230             ucase_blocktype = blocktype.upper()
   298                 "blocktype": blocktype_infos["blocktype"],
   231             blockname = "_".join([ucase_blocktype, location_str])
   299                 "ucase_blocktype": blocktype_infos["blocktype"].upper(),
   232 
   300                 "location": "_".join(map(str, current_location))
   233             extract_inputs = "\n".join([
   301             }
   234                 """\
   302             texts["blockname"] = "%(ucase_blocktype)s_%(location)s" % texts
   235                 __SET_VAR(%s->, %s,, %s);""" % (blockname, input_name, input_value)
   303             
   236                 for (input_name, input_value) in
   304             inputs = [{"input_name": "POS", "input_value": str(self.GetSlavePos())},
   237                 [("EXECUTE", "__GET_VAR(data__->EXECUTE)")] + [
   305                       {"input_name": "EXECUTE", "input_value": "__GET_VAR(data__->EXECUTE)"}] +\
   238                     (input["name"].upper(),
   306                      [{"input_name": input["name"].upper(), 
   239                      "__GET_VAR(data__->%s)" % input["name"].upper())
   307                        "input_value": "__GET_VAR(data__->%s)" % input["name"].upper()}
   240                     for input in blocktype_infos["inputs"]
   308                       for input in blocktype_infos["inputs"]]
   241                 ]])
   309             input_texts = []
   242 
   310             for input_infos in inputs:
   243             return_outputs = "\n".join([
   311                 input_infos.update(texts)
   244                 """\
   312                 input_texts.append(BLOCK_INPUT_TEMPLATE % input_infos)
   245                 __SET_VAR(data__->,%(output_name)s,,
   313             texts["extract_inputs"] = "\n".join(input_texts)
   246                 __GET_VAR(%(blockname)s->%(output_name)s));""" % {
   314             
   247                     "output_name": output_name,
   315             outputs = [{"output_name": output} for output in ["DONE", "BUSY", "ERROR"]] + \
   248                     "blockname": blockname
   316                       [{"output_name": output["name"].upper()} for output in blocktype_infos["outputs"]]
       
   317             output_texts = []
       
   318             for output_infos in outputs:
       
   319                 output_infos.update(texts)
       
   320                 output_texts.append(BLOCK_OUTPUT_TEMPLATE % output_infos)
       
   321             texts["return_outputs"] = "\n".join(output_texts)
       
   322             
       
   323             str_completion["fieldbus_interface_declaration"].append(
       
   324                     BLOCK_FUNCTION_TEMPLATE % texts)
       
   325             
       
   326             str_completion["fieldbus_interface_definition"].append(
       
   327                     BLOCK_FUNTION_DEFINITION_TEMPLATE % texts)
       
   328 
       
   329         variables = NODE_VARIABLES[:]
       
   330 
       
   331 #HSAHN
       
   332 #2015. 7. 24 PDO Variable
       
   333         #if PDO is not selected, use 1st PDO set
       
   334         self.LoadPDOSelectData()
       
   335         if not self.SelectedRxPDOIndex and not self.SelectedTxPDOIndex :
       
   336             self.SelectedPDOIndex = self.LoadDefaultPDOSet()
       
   337         else :
       
   338             self.SelectedPDOIndex = self.SelectedRxPDOIndex + self.SelectedTxPDOIndex
       
   339 
       
   340         add_idx = []
       
   341         for i in range(len(ADD_NODE_VARIABLES)):
       
   342             add_idx.append(ADD_NODE_VARIABLES[i]['index'])
       
   343 
       
   344         self.CommonMethod.RequestPDOInfo()
       
   345         pdo_info = self.CommonMethod.GetRxPDOCategory() + self.CommonMethod.GetTxPDOCategory()
       
   346         pdo_entry = self.CommonMethod.GetRxPDOInfo() + self.CommonMethod.GetTxPDOInfo()
       
   347         list_index = 0
       
   348         ModeOfOpFlag = False
       
   349         ModeOfOpDisplayFlag = False
       
   350         for i in range(len(pdo_info)):
       
   351             #if pdo_index is in the SelectedPDOIndex: put the PDO mapping information intto the "used" object
       
   352             if pdo_info[i]['pdo_index'] in self.SelectedPDOIndex:
       
   353                 used = pdo_entry[list_index:list_index + pdo_info[i]['number_of_entry']]
       
   354                 for used_data in used:
       
   355                     # 24672 -> 0x6060, Mode of Operation
       
   356                     if used_data['entry_index'] == 24672:
       
   357                         ModeOfOpFlag = True
       
   358                     # 24673 -> 0x6061, Mode of Operation Display
       
   359                     elif used_data["entry_index"] == 24673:
       
   360                         ModeOfOpDisplayFlag = True
       
   361 
       
   362                     if used_data['entry_index'] in add_idx:
       
   363                         idx = add_idx.index(used_data['entry_index'])
       
   364                         adder = list([ADD_NODE_VARIABLES[idx]['name'], ADD_NODE_VARIABLES[idx]['index'], \
       
   365                                      ADD_NODE_VARIABLES[idx]['sub-index'], ADD_NODE_VARIABLES[idx]['type'], \
       
   366                                      ADD_NODE_VARIABLES[idx]['direction']])
       
   367                         variables.append(adder)
       
   368                         if ADD_NODE_VARIABLES[idx]['direction'] == "Q":                           
       
   369                             parsed_string = ADD_NODE_VARIABLES[idx]['name'].replace("Target", "")
       
   370                             # add jblee
       
   371                             check_q_data = "    *(AxsPub.Target%s) = AxsPub.axis->Raw%sSetPoint;" %(parsed_string, parsed_string)
       
   372                             if check_q_data not in str_completion["default_variables_publish"]:
       
   373                                 str_completion["default_variables_publish"].append(check_q_data)
       
   374                         elif ADD_NODE_VARIABLES[idx]['direction'] == "I":
       
   375                             parsed_string = ADD_NODE_VARIABLES[idx]['name'].replace("Actual", "")
       
   376                             # add jblee
       
   377                             check_i_data = "    AxsPub.axis->ActualRaw%s = *(AxsPub.Actual%s);" %(parsed_string, parsed_string)
       
   378                             if check_i_data not in str_completion["default_variables_retrieve"]:
       
   379                                 str_completion["default_variables_retrieve"].append(check_i_data)
       
   380             list_index += pdo_info[i]['number_of_entry']
       
   381 #HSAHN END
       
   382 
       
   383         params = self.CTNParams[1].getElementInfos(self.CTNParams[0])
       
   384         for param in params["children"]:
       
   385             if param["name"] in EXTRA_NODE_VARIABLES_DICT:
       
   386                 if param["value"]:
       
   387                     extra_variables = EXTRA_NODE_VARIABLES_DICT.get(param["name"])
       
   388                     for variable_infos in extra_variables:
       
   389                         var_infos = {
       
   390                             "location": location_str,
       
   391                             "name": variable_infos["description"][0]
       
   392                         }
       
   393                         variables.append(variable_infos["description"])
       
   394                         retrieve_template = variable_infos.get("retrieve", DEFAULT_RETRIEVE)
       
   395                         publish_template = variable_infos.get("publish", DEFAULT_PUBLISH)
       
   396                         
       
   397                         if retrieve_template is not None:
       
   398                             str_completion["extra_variables_retrieve"].append(
       
   399                                 retrieve_template % var_infos)
       
   400                         if publish_template is not None:
       
   401                             str_completion["extra_variables_publish"].append(
       
   402                                 publish_template % var_infos)
       
   403 
       
   404             #elif param["value"] is not None:
       
   405             if param["value"] is not None:
       
   406                 param_infos = {
       
   407                     "location": location_str,
       
   408                     "param_name": param["name"],
   249                 }
   409                 }
   250                 for output_name in ["DONE", "BUSY", "ERROR"] + [
   410                 if param["type"] == "boolean":
   251                     output["name"].upper()
   411                     param_infos["param_value"] = {True: "1", False: "0"}[param["value"]]
   252                     for output in blocktype_infos["outputs"]]
   412                     param_infos["param_name"] = param["name"].replace("Enable", "") + "Enabled"
   253             ])
   413                     if param["value"] == False:
   254 
   414                         continue
   255             loc_dict = {
   415                 else:
   256                 "ucase_blocktype": ucase_blocktype,
   416                     param_infos["param_value"] = str(param["value"])
   257                 "blocktype": blocktype,
   417                 # param_name = param_name.replace("Enable", "") + "Enabled"
   258                 "blockname": blockname,
   418                 str_completion["init_axis_params"].append(
   259                 "location_str": location_str,
   419                     "        __CIA402Node_%(location)s.axis->%(param_name)s = %(param_value)s;" % param_infos)
   260                 "extract_inputs": extract_inputs,
   420         
   261                 "return_outputs": return_outputs,
   421         check_variable = []
   262             }
   422         for variable in variables:
   263 
   423             # add jblee
   264             fieldbus_interface_declaration.append("""
   424             if variable in check_variable:
   265 extern void ETHERLAB%(ucase_blocktype)s_body__(ETHERLAB%(ucase_blocktype)s* data__);
   425                 continue
   266 void __%(blocktype)s_%(location_str)s(MC_%(ucase_blocktype)s *data__) {
   426 
   267 __DECLARE_GLOBAL_PROTOTYPE(ETHERLAB%(ucase_blocktype)s, %(blockname)s);
   427             var_infos = dict(zip(["name", "index", "subindex", "var_type", "dir"], variable))
   268 ETHERLAB%(ucase_blocktype)s* %(blockname)s = __GET_GLOBAL_%(blockname)s();
   428             var_infos["location"] = location_str
   269 __SET_VAR(%(blockname)s->, POS,, AxsPub.axis->NetworkPosition);
   429             var_infos["var_size"] = self.GetSizeOfType(var_infos["var_type"])
   270 %(extract_inputs)s
   430             var_infos["var_name"] = "__%(dir)s%(var_size)s%(location)s_%(index)d_%(subindex)d" % var_infos
   271 ETHERLAB%(ucase_blocktype)s_body__(%(blockname)s);
   431 
   272 %(return_outputs)s
   432             # add jblee
   273 }""" % loc_dict)
   433             if var_infos["index"] in [24672] and ModeOfOpFlag:
   274 
   434                 str_completion["modeofop_homing_method"].append(MODEOFOP_HOMING_METHOD_TEMPLATE)
   275             fieldbus_interface_definition.append("""\
   435                 str_completion["modeofop_computation_mode"].append(MODEOFOP_COMPUTATION_MODE_TEMPLATE)
   276         AxsPub.axis->__mcl_func_MC_%(blocktype)s = __%(blocktype)s_%(location_str)s;\
   436 
   277 """ % loc_dict)
   437             # add jblee
   278 
   438             if var_infos["index"] in [24672, 24673] and (not ModeOfOpFlag or not ModeOfOpDisplayFlag):
   279         # Get a copy list of default variables to map
   439                 continue
   280         variables = NODE_VARIABLES[:]
   440 
   281 
   441             str_completion["extern_located_variables_declaration"].append(
   282         # Set AxisRef public struct members value
   442                     "IEC_%(var_type)s *%(var_name)s;" % var_infos)
   283         node_params = self.CTNParams[1].getElementInfos(self.CTNParams[0])
   443             str_completion["entry_variables"].append(
   284         for param in node_params["children"]:
   444                     "    IEC_%(var_type)s *%(name)s;" % var_infos)
   285             param_name = param["name"]
   445             str_completion["init_entry_variables"].append(
   286 
   446                     "    __CIA402Node_%(location)s.%(name)s = %(var_name)s;" % var_infos)
   287             # Param is optional variables section enable flag
   447             
   288             extra_node_variable_infos = EXTRA_NODE_VARIABLES_DICT.get(param_name)
       
   289             if extra_node_variable_infos is not None:
       
   290                 param_name = param_name.replace("Enable", "") + "Enabled"
       
   291 
       
   292                 if not param["value"]:
       
   293                     continue
       
   294 
       
   295                 # Optional variables section is enabled
       
   296                 for variable_infos in extra_node_variable_infos:
       
   297                     var_name = variable_infos["description"][0]
       
   298 
       
   299                     # Add each variables defined in section description to the
       
   300                     # list of variables to map
       
   301                     variables.append(variable_infos["description"])
       
   302 
       
   303                     # Add code to publish or retrive variable
       
   304                     coded = [
       
   305                         ("retrieve",
       
   306                          extra_variables_retrieve,
       
   307                          "    AxsPub.axis->%(var_name)s = *(AxsPub.%(var_name)s);"),
       
   308                         ("publish",
       
   309                          extra_variables_publish,
       
   310                          "    *(AxsPub.%(var_name)s) = AxsPub.axis->%(var_name)s;")
       
   311                     ]
       
   312                     for var_exchange_dir, _str_list, default_template in coded:
       
   313                         template = variable_infos.get(var_exchange_dir, default_template)
       
   314                         if template is not None:
       
   315                             extra_variables_publish.append(template % locals())
       
   316 
       
   317             # Set AxisRef public struct member value if defined
       
   318             if param["value"] is not None:
       
   319                 param_value = ({True: "1", False: "0"}[param["value"]]
       
   320                                if param["type"] == "boolean"
       
   321                                else str(param["value"]))
       
   322 
       
   323                 init_axis_params.append("""\
       
   324                 AxsPub.axis->%(param_name)s = %(param_value)s;""" % {
       
   325                     "param_value": param_value,
       
   326                     "param_name": param_name,
       
   327                 })
       
   328 
       
   329         # Add each variable in list of variables to map to master list of
       
   330         # variables to add to network configuration
       
   331         for name, index, subindex, var_type, dir in variables:
       
   332             var_size = self.GetSizeOfType(var_type)
       
   333             loc_dict = {
       
   334                 "var_size": var_size,
       
   335                 "var_type": var_type,
       
   336                 "name:": name,
       
   337                 "location_str": location_str,
       
   338                 "index": index,
       
   339                 "subindex": subindex,
       
   340             }
       
   341             var_name = """\
       
   342 __%(dir)s%(var_size)s%(location_str)s_%(index)d_%(subindex)d""" % loc_dict
       
   343             loc_dict["var_name"] = var_name
       
   344 
       
   345             extern_located_variables_declaration.append(
       
   346                 "IEC_%(var_type)s *%(var_name)s;" % loc_dict)
       
   347             entry_variables.append(
       
   348                 "    IEC_%(var_type)s *%(name)s;" % loc_dict)
       
   349             init_entry_variables.append(
       
   350                 "    AxsPub.%(name)s = %(var_name)s;" % loc_dict)
       
   351 
       
   352             self.CTNParent.FileGenerator.DeclareVariable(
   448             self.CTNParent.FileGenerator.DeclareVariable(
   353                 slave_pos, index, subindex, var_type, dir, var_name)
   449                     self.GetSlavePos(), var_infos["index"], var_infos["subindex"], 
   354 
   450                     var_infos["var_type"], var_infos["dir"], var_infos["var_name"])
   355         # Add newline between string in list of generated strings for sections
   451 
   356         [fieldbus_interface_declaration, fieldbus_interface_definition,
   452             # add jblee
   357          init_axis_params, extra_variables_retrieve, extra_variables_publish,
   453             check_variable.append(variable)
   358          extern_located_variables_declaration, entry_variables,
   454         
   359          init_entry_variables] = map("\n".join, [
   455         for element in ["extern_located_variables_declaration", 
   360              fieldbus_interface_declaration, fieldbus_interface_definition,
   456                         "fieldbus_interface_declaration",
   361              init_axis_params, extra_variables_retrieve, extra_variables_publish,
   457                         "fieldbus_interface_definition",
   362              extern_located_variables_declaration, entry_variables,
   458                         "entry_variables", 
   363              init_entry_variables])
   459                         "init_axis_params", 
   364 
   460                         "init_entry_variables",
   365         # Write generated content to CIA402 node file
   461                         "default_variables_retrieve",
   366         Gen_CIA402Nodefile_path = os.path.join(buildpath,
   462                         "default_variables_publish",
   367                                                "cia402node_%s.c" % location_str)
   463                         "extra_variables_retrieve",
       
   464                         "extra_variables_publish",
       
   465                         "modeofop_homing_method",
       
   466                         "modeofop_computation_mode"]:
       
   467             str_completion[element] = "\n".join(str_completion[element])
       
   468         
       
   469         Gen_CIA402Nodefile_path = os.path.join(buildpath, "cia402node_%s.c"%location_str)
   368         cia402nodefile = open(Gen_CIA402Nodefile_path, 'w')
   470         cia402nodefile = open(Gen_CIA402Nodefile_path, 'w')
   369         cia402nodefile.write(plc_cia402node_code % locals())
   471         cia402nodefile.write(plc_cia402node_code % str_completion)
   370         cia402nodefile.close()
   472         cia402nodefile.close()
   371 
   473 
   372         return [(Gen_CIA402Nodefile_path, '"-I%s"' % os.path.abspath(self.GetCTRoot().GetIECLibPath()))], "", True
   474         return [(Gen_CIA402Nodefile_path, '"-I%s"' % os.path.abspath(self.GetCTRoot().GetIECLibPath()))], "", True