etherlab/EthercatCIA402Slave.py
branchethercat_from_kosmos
changeset 2641 c9deff128c37
parent 2165 02a2b5dee5e3
child 2643 b98d9e08231f
equal deleted inserted replaced
2192:09d5d1456616 2641:c9deff128c37
    11 
    11 
    12 import os
    12 import os
    13 
    13 
    14 import wx
    14 import wx
    15 
    15 
    16 from PLCControler import LOCATION_CONFNODE, LOCATION_MODULE, LOCATION_GROUP, LOCATION_VAR_INPUT, LOCATION_VAR_OUTPUT, LOCATION_VAR_MEMORY
    16 from PLCControler import LOCATION_CONFNODE, LOCATION_MODULE, LOCATION_GROUP, \
       
    17     LOCATION_VAR_INPUT, LOCATION_VAR_OUTPUT, LOCATION_VAR_MEMORY
    17 
    18 
    18 from MotionLibrary import Headers, AxisXSD
    19 from MotionLibrary import Headers, AxisXSD
    19 from EthercatSlave import _EthercatSlaveCTN, _CommonSlave
    20 from EthercatSlave import _EthercatSlaveCTN, _CommonSlave
    20 from ConfigEditor import CIA402NodeEditor
    21 from ConfigEditor import CIA402NodeEditor
    21 
    22 
    22 # Definition of node variables that have to be mapped in PDO
    23 #HSAHN 2015.07.26
    23 # [(name, index, subindex, type, 
    24 #remove NODE_VARIABLES's optional items.
    24 #   direction for master ('I': input, 'Q': output)),...]
    25 #As for now, optional items will be added dynamicaly.
    25 NODE_VARIABLES = [
    26 NODE_VARIABLES = [
    26     ("ControlWord",             0x6040, 0x00, "UINT", "Q"),
    27     ("ControlWord", 0x6040, 0x00, "UINT", "Q"),
    27     ("TargetPosition",          0x607a, 0x00, "DINT", "Q"),
    28     ("ModesOfOperation", 0x6060, 0x00, "SINT", "Q"),
    28     ("TargetVelocity",          0x60ff, 0x00, "DINT", "Q"),
    29     ("StatusWord", 0x6041, 0x00, "UINT", "I"),
    29     ("TargetTorque",            0x6071, 0x00, "INT",  "Q"),
       
    30     ("ModesOfOperation",        0x6060, 0x00, "SINT", "Q"),
       
    31     ("StatusWord",              0x6041, 0x00, "UINT", "I"),
       
    32     ("ModesOfOperationDisplay", 0x6061, 0x00, "SINT", "I"),
    30     ("ModesOfOperationDisplay", 0x6061, 0x00, "SINT", "I"),
    33     ("ActualPosition",          0x6064, 0x00, "DINT", "I"),
       
    34     ("ActualVelocity",          0x606c, 0x00, "DINT", "I"),
       
    35     ("ActualTorque",            0x6077, 0x00, "INT",  "I"),
       
    36 ]
    31 ]
       
    32 
       
    33 #HSAHN 2015.07.26
       
    34 #reference variable
       
    35 ADD_NODE_VARIABLES = ({'name':"TargetPosition"   , 'index':0x607a, 'sub-index':0x00, 'type':"DINT", 'direction':"Q"},
       
    36                       {'name':"TargetVelocity"   , 'index':0x60ff, 'sub-index':0x00, 'type':"DINT", 'direction':"Q"},
       
    37                       {'name':"TargetTorque"     , 'index':0x6071, 'sub-index':0x00, 'type':"INT",  'direction':"Q"},
       
    38                       {'name':"ActualPosition"   , 'index':0x6064, 'sub-index':0x00, 'type':"DINT", 'direction':"I"},
       
    39                       {'name':"ActualVelocity"   , 'index':0x606c, 'sub-index':0x00, 'type':"DINT", 'direction':"I"},
       
    40                       {'name':"ActualTorque"     , 'index':0x6077, 'sub-index':0x00, 'type':"INT",  'direction':"I"})
       
    41 
       
    42 DEFAULT_RETRIEVE = "    __CIA402Node_%(location)s.axis->%(name)s = *(__CIA402Node_%(location)s.%(name)s);"
       
    43 DEFAULT_PUBLISH = "    *(__CIA402Node_%(location)s.%(name)s) = __CIA402Node_%(location)s.axis->%(name)s;"
    37 
    44 
    38 # Definition of optional node variables that can be added to PDO mapping.
    45 # Definition of optional node variables that can be added to PDO mapping.
    39 # A checkbox will be displayed for each section in node configuration panel to
    46 # A checkbox will be displayed for each section in node configuration panel to
    40 # enable them
    47 # enable them
    41 # [(section_name, 
    48 # [(section_name, 
    44 #     'retrieve', string_template_for_retrieve_variable (None: not retrieved, 
    51 #     'retrieve', string_template_for_retrieve_variable (None: not retrieved, 
    45 #                                 default string template if not defined),
    52 #                                 default string template if not defined),
    46 #     'publish', string_template_for_publish_variable (None: not published, 
    53 #     'publish', string_template_for_publish_variable (None: not published, 
    47 #                                 default string template if not defined),
    54 #                                 default string template if not defined),
    48 #    },...]
    55 #    },...]
       
    56 
    49 EXTRA_NODE_VARIABLES = [
    57 EXTRA_NODE_VARIABLES = [
    50     ("ErrorCode", [
    58     ("ErrorCode", [
    51         {"description": ("ErrorCode", 0x603F, 0x00, "UINT", "I"),
    59         {"description": ("ErrorCode", 0x603F, 0x00, "UINT", "I"),
    52          "publish": None}
    60          "publish": None}
    53         ]),
    61         ]),
    54     ("DigitalInputs", [
    62     ("DigitalInputs", [
    55         {"description": ("DigitalInputs", 0x60FD, 0x00, "UDINT", "I"),
    63         {"description": ("DigitalInputs", 0x60FD, 0x00, "UDINT", "I"),
    56          "publish": None}
    64          "publish": None}
    57         ]),
    65         ]),
    58     ("DigitalOutputs", [
    66     ("DigitalOutputs", [
    59         {"description": ("DigitalOutputs", 0x60FE, 0x00, "UDINT", "Q"),
    67         {"description": ("DigitalOutputs", 0x60FE, 0x01, "UDINT", "I"),
    60          "retrieve": None}
    68          "publish": None}
    61         ]),
    69         ]),
    62     ("TouchProbe", [
    70     ("TouchProbe", [
    63         {"description": ("TouchProbeFunction", 0x60B8, 0x00, "UINT", "Q"),
    71         {"description": ("TouchProbeFunction", 0x60B8, 0x00, "UINT", "Q"),
    64          "retrieve": None},
    72          "retrieve": None},
    65         {"description": ("TouchProbeStatus", 0x60B9, 0x00, "UINT", "I"),
    73         {"description": ("TouchProbeStatus", 0x60B9, 0x00, "UINT", "I"),
    75 # sections
    83 # sections
    76 EXTRA_NODE_VARIABLES_DICT = {
    84 EXTRA_NODE_VARIABLES_DICT = {
    77     "Enable" + name: params 
    85     "Enable" + name: params 
    78     for name, params in EXTRA_NODE_VARIABLES}
    86     for name, params in EXTRA_NODE_VARIABLES}
    79 
    87 
    80 # List of block to define to interface MCL to fieldbus for specific functions
    88 BLOCK_INPUT_TEMPLATE = "    __SET_VAR(%(blockname)s->,%(input_name)s, %(input_value)s);"
       
    89 BLOCK_OUTPUT_TEMPLATE = "    __SET_VAR(data__->,%(output_name)s, __GET_VAR(%(blockname)s->%(output_name)s));"
       
    90 
       
    91 BLOCK_FUNCTION_TEMPLATE = """
       
    92 extern void ETHERLAB%(ucase_blocktype)s_body__(ETHERLAB%(ucase_blocktype)s* data__);
       
    93 void __%(blocktype)s_%(location)s(MC_%(ucase_blocktype)s *data__) {
       
    94 __DECLARE_GLOBAL_PROTOTYPE(ETHERLAB%(ucase_blocktype)s, %(blockname)s);
       
    95 ETHERLAB%(ucase_blocktype)s* %(blockname)s = __GET_GLOBAL_%(blockname)s();
       
    96 __SET_VAR(%(blockname)s->, POS, AxsPub.axis->NetworkPosition);
       
    97 %(extract_inputs)s
       
    98 ETHERLAB%(ucase_blocktype)s_body__(%(blockname)s);
       
    99 %(return_outputs)s
       
   100 }
       
   101 """
       
   102 
       
   103 BLOCK_FUNTION_DEFINITION_TEMPLATE = "        __CIA402Node_%(location)s.axis->__mcl_func_MC_%(blocktype)s = __%(blocktype)s_%(location)s;"
       
   104 
    81 FIELDBUS_INTERFACE_GLOBAL_INSTANCES = [
   105 FIELDBUS_INTERFACE_GLOBAL_INSTANCES = [
    82     {"blocktype": "GetTorqueLimit", 
   106     {"blocktype": "GetTorqueLimit", 
    83      "inputs": [],
   107      "inputs": [],
    84      "outputs": [{"name": "TorqueLimitPos", "type": "UINT"},
   108      "outputs": [{"name": "TorqueLimitPos", "type": "UINT"},
    85                  {"name": "TorqueLimitNeg", "type": "UINT"}]},
   109                  {"name": "TorqueLimitNeg", "type": "UINT"}]},
    86     {"blocktype": "SetTorqueLimit", 
   110     {"blocktype": "SetTorqueLimit", 
    87      "inputs": [{"name": "TorqueLimitPos", "type": "UINT"},
   111      "inputs": [{"name": "TorqueLimitPos", "type": "UINT"},
    88                 {"name": "TorqueLimitNeg", "type": "UINT"}],
   112                 {"name": "TorqueLimitNeg", "type": "UINT"}],
    89      "outputs": []},
   113      "outputs": []},
    90 ]
   114 ]
       
   115 
       
   116 # add jblee
       
   117 MODEOFOP_HOMING_METHOD_TEMPLATE = """
       
   118 	if(*(AxsPub.ModesOfOperation) == 0x06){
       
   119 		IEC_BOOL homing = AxsPub.axis->HomingOperationStart;
       
   120 		if(power){
       
   121 			if (homing)
       
   122 				CW |= Homing_OperationStart_Origin;
       
   123 			else
       
   124 				CW &= ~(Homing_OperationStart_Origin);
       
   125 		}
       
   126 		else{
       
   127 			if (homing)
       
   128 				CW |= Homing_OperationStart_Edit;
       
   129 			else
       
   130 				CW &= ~(EnableOperation);
       
   131 		}
       
   132 
       
   133 	}
       
   134 """
       
   135 
       
   136 MODEOFOP_COMPUTATION_MODE_TEMPLATE = """
       
   137 	switch (AxsPub.axis->AxisMotionMode) {
       
   138 		//ssh_add
       
   139 		case mc_mode_hm:
       
   140 			*(AxsPub.ModesOfOperation) = 0x06;
       
   141 			break;
       
   142 		case mc_mode_cst:
       
   143 			*(AxsPub.ModesOfOperation) = 0x0a;
       
   144 			break;
       
   145 		case mc_mode_csv:
       
   146 			*(AxsPub.ModesOfOperation) = 0x09;
       
   147 			break;
       
   148 		default:
       
   149 			*(AxsPub.ModesOfOperation) = 0x08;
       
   150 			break;
       
   151 	}
       
   152 """
    91 
   153 
    92 #--------------------------------------------------
   154 #--------------------------------------------------
    93 #                 Ethercat CIA402 Node
   155 #                 Ethercat CIA402 Node
    94 #--------------------------------------------------
   156 #--------------------------------------------------
    95 
   157 
   129     
   191     
   130     def __init__(self):
   192     def __init__(self):
   131         # ----------- call ethercat mng. function --------------
   193         # ----------- call ethercat mng. function --------------
   132         self.CommonMethod = _CommonSlave(self)
   194         self.CommonMethod = _CommonSlave(self)
   133     
   195     
       
   196         #HSAHN
       
   197         # Select PDO Mapping
       
   198         self.SelectedPDOIndex = []
       
   199         self.SelectedRxPDOIndex = []
       
   200         self.SelectedTxPDOIndex = []
       
   201         #HSAHN END
       
   202 
   134     def GetIconName(self):
   203     def GetIconName(self):
   135         return "CIA402Slave"
   204         return "CIA402Slave"
   136     
   205     
   137     def SetParamsAttribute(self, path, value):
   206     def SetParamsAttribute(self, path, value):
   138         if path == "CIA402SlaveParams.Type":
   207         if path == "CIA402SlaveParams.Type":
   184         
   253         
   185     def _getCIA402AxisRef(self):
   254     def _getCIA402AxisRef(self):
   186         self.StartDragNDrop(
   255         self.StartDragNDrop(
   187             ("%%IW%s.402" % ".".join(map(str, self.GetCurrentLocation())), 
   256             ("%%IW%s.402" % ".".join(map(str, self.GetCurrentLocation())), 
   188              "location", "AXIS_REF", self.CTNName(), ""))
   257              "location", "AXIS_REF", self.CTNName(), ""))
       
   258 
       
   259     # add jblee
       
   260     """
       
   261     def LoadPDOSelectData(self):
       
   262         ReadData = []
       
   263         files = os.listdir(self.CTNPath())
       
   264         filepath = os.path.join(self.CTNPath(), "DataForPDO.txt")
       
   265         if os.path.isfile(filepath):
       
   266             PDODataRead = open(filepath, 'r')
       
   267             ReadData = PDODataRead.readlines()
       
   268             PDODataRead.close()
       
   269 
       
   270         if len(ReadData) > 1:
       
   271             for data in ReadData[0].split() :
       
   272                 if data == "RxPDO":
       
   273                     continue
       
   274                 self.SelectedRxPDOIndex.append(int(data, 0))
       
   275 
       
   276             for data in ReadData[1].split() :
       
   277                 if data == "TxPDO":
       
   278                     continue
       
   279                 self.SelectedTxPDOIndex.append(int(data, 0))
       
   280     """
       
   281 
       
   282     def LoadPDOSelectData(self):
       
   283         RxPDOData = self.BaseParams.getRxPDO()
       
   284         RxPDOs = []
       
   285         if RxPDOData != "None":
       
   286             RxPDOs = RxPDOData.split()
       
   287         if RxPDOs :
       
   288             for RxPDO in RxPDOs :
       
   289                 self.SelectedRxPDOIndex.append(int(RxPDO, 0))
       
   290 
       
   291         TxPDOData = self.BaseParams.getTxPDO()
       
   292         TxPDOs = []
       
   293         if TxPDOData != "None":
       
   294             TxPDOs = TxPDOData.split()
       
   295         if TxPDOs :
       
   296             for TxPDO in TxPDOs :
       
   297                 self.SelectedTxPDOIndex.append(int(TxPDO, 0))
       
   298 
       
   299     def LoadDefaultPDOSet(self):
       
   300         ReturnData = []
       
   301         rx_pdo_entries = self.CommonMethod.GetRxPDOCategory()
       
   302         if len(rx_pdo_entries):
       
   303             for i in range(len(rx_pdo_entries)):
       
   304                 if rx_pdo_entries[i]['sm'] is not None:
       
   305                     ReturnData.append(rx_pdo_entries[i]['pdo_index'])
       
   306 
       
   307         tx_pdo_entries = self.CommonMethod.GetTxPDOCategory()
       
   308         if len(tx_pdo_entries):
       
   309             for i in range(len(tx_pdo_entries)):
       
   310                 if tx_pdo_entries[i]['sm'] is not None:
       
   311                     ReturnData.append(tx_pdo_entries[i]['pdo_index'])
       
   312 
       
   313         if ReturnData :
       
   314             return ReturnData
       
   315         else :
       
   316             return [5632, 6656]
   189         
   317         
   190     def CTNGenerate_C(self, buildpath, locations):
   318     def CTNGenerate_C(self, buildpath, locations):
   191         current_location = self.GetCurrentLocation()
   319         current_location = self.GetCurrentLocation()
   192         
   320         
   193         location_str = "_".join(map(lambda x:str(x), current_location))
   321         location_str = "_".join(map(lambda x:str(x), current_location))
   194         slave_pos = self.GetSlavePos()
   322         
   195         MCL_headers = Headers
   323         plc_cia402node_filepath = os.path.join(os.path.split(__file__)[0], "plc_cia402node.c")
   196         
       
   197         # Open CIA402 node code template file 
       
   198         plc_cia402node_filepath = os.path.join(os.path.split(__file__)[0], 
       
   199                                                "plc_cia402node.c")
       
   200         plc_cia402node_file = open(plc_cia402node_filepath, 'r')
   324         plc_cia402node_file = open(plc_cia402node_filepath, 'r')
   201         plc_cia402node_code = plc_cia402node_file.read()
   325         plc_cia402node_code = plc_cia402node_file.read()
   202         plc_cia402node_file.close()
   326         plc_cia402node_file.close()
   203         
   327         # HSAHN 150726
   204         # Init list of generated strings for each code template file section
   328         # add "default_variables_retrieve": [], "default_variables_publish": [],
   205         fieldbus_interface_declaration = []
   329 		# As PDO mapping object, it will add auto-complete code.
   206         fieldbus_interface_definition = []
   330         # add "modeofop_homing_method", "modeofop_computation_mode" by jblee
   207         init_axis_params = []
   331         str_completion = {
   208         extra_variables_retrieve = []
   332             "slave_pos": self.GetSlavePos(),
   209         extra_variables_publish = []
   333             "location": location_str,
   210         extern_located_variables_declaration = []
   334             "MCL_headers": Headers,
   211         entry_variables = []
   335             "extern_located_variables_declaration": [],
   212         init_entry_variables = []
   336             "fieldbus_interface_declaration": [],
   213         
   337             "fieldbus_interface_definition": [],
   214         # Fieldbus interface code sections
   338             "entry_variables": [],
       
   339             "init_axis_params": [],
       
   340             "init_entry_variables": [],
       
   341             "default_variables_retrieve": [],
       
   342             "default_variables_publish": [],
       
   343             "extra_variables_retrieve": [],
       
   344             "extra_variables_publish": [],
       
   345             "modeofop_homing_method": [],
       
   346             "modeofop_computation_mode": []
       
   347         }
       
   348         
   215         for blocktype_infos in FIELDBUS_INTERFACE_GLOBAL_INSTANCES:
   349         for blocktype_infos in FIELDBUS_INTERFACE_GLOBAL_INSTANCES:
   216             blocktype = blocktype_infos["blocktype"]
   350             texts = {
   217             ucase_blocktype = blocktype.upper()
   351                 "blocktype": blocktype_infos["blocktype"],
   218             blockname = "_".join([ucase_blocktype, location_str])
   352                 "ucase_blocktype": blocktype_infos["blocktype"].upper(),
       
   353                 "location": "_".join(map(str, current_location))
       
   354             }
       
   355             texts["blockname"] = "%(ucase_blocktype)s_%(location)s" % texts
   219             
   356             
   220             extract_inputs = "\n".join(["""\
   357             inputs = [{"input_name": "POS", "input_value": str(self.GetSlavePos())},
   221     __SET_VAR(%s->, %s,, %s);""" % (blockname, input_name, input_value)
   358                       {"input_name": "EXECUTE", "input_value": "__GET_VAR(data__->EXECUTE)"}] +\
   222                 for (input_name, input_value) in [
   359                      [{"input_name": input["name"].upper(), 
   223                     ("EXECUTE", "__GET_VAR(data__->EXECUTE)")] + [
   360                        "input_value": "__GET_VAR(data__->%s)" % input["name"].upper()}
   224                     (input["name"].upper(), 
   361                       for input in blocktype_infos["inputs"]]
   225                      "__GET_VAR(data__->%s)" % input["name"].upper())
   362             input_texts = []
   226                     for input in blocktype_infos["inputs"]]
   363             for input_infos in inputs:
   227                 ])
   364                 input_infos.update(texts)
       
   365                 input_texts.append(BLOCK_INPUT_TEMPLATE % input_infos)
       
   366             texts["extract_inputs"] = "\n".join(input_texts)
   228             
   367             
       
   368             outputs = [{"output_name": output} for output in ["DONE", "BUSY", "ERROR"]] + \
       
   369                       [{"output_name": output["name"].upper()} for output in blocktype_infos["outputs"]]
       
   370             output_texts = []
       
   371             for output_infos in outputs:
       
   372                 output_infos.update(texts)
       
   373                 output_texts.append(BLOCK_OUTPUT_TEMPLATE % output_infos)
       
   374             texts["return_outputs"] = "\n".join(output_texts)
   229             
   375             
   230             return_outputs = "\n".join(["""\
   376             str_completion["fieldbus_interface_declaration"].append(
   231     __SET_VAR(data__->,%(output_name)s,, 
   377                     BLOCK_FUNCTION_TEMPLATE % texts)
   232               __GET_VAR(%(blockname)s->%(output_name)s));""" % locals()
   378             
   233                     for output_name in ["DONE", "BUSY", "ERROR"] + [
   379             str_completion["fieldbus_interface_definition"].append(
   234                         output["name"].upper()
   380                     BLOCK_FUNTION_DEFINITION_TEMPLATE % texts)
   235                         for output in blocktype_infos["outputs"]]
   381 
   236                 ])
   382         variables = NODE_VARIABLES[:]
       
   383 
       
   384 #HSAHN
       
   385 #2015. 7. 24 PDO Variable
       
   386         #if PDO is not selected, use 1st PDO set
       
   387         self.LoadPDOSelectData()
       
   388         if not self.SelectedRxPDOIndex and not self.SelectedTxPDOIndex :
       
   389             self.SelectedPDOIndex = self.LoadDefaultPDOSet()
       
   390         else :
       
   391             self.SelectedPDOIndex = self.SelectedRxPDOIndex + self.SelectedTxPDOIndex
       
   392 
       
   393         add_idx = []
       
   394         for i in range(len(ADD_NODE_VARIABLES)):
       
   395             add_idx.append(ADD_NODE_VARIABLES[i]['index'])
       
   396 
       
   397         self.CommonMethod.RequestPDOInfo()
       
   398         pdo_info = self.CommonMethod.GetRxPDOCategory() + self.CommonMethod.GetTxPDOCategory()
       
   399         pdo_entry = self.CommonMethod.GetRxPDOInfo() + self.CommonMethod.GetTxPDOInfo()
       
   400         list_index = 0
       
   401         ModeOfOpFlag = False
       
   402         ModeOfOpDisplayFlag = False
       
   403         for i in range(len(pdo_info)):
       
   404             #if pdo_index is in the SelectedPDOIndex: put the PDO mapping information intto the "used" object
       
   405             if pdo_info[i]['pdo_index'] in self.SelectedPDOIndex:
       
   406                 used = pdo_entry[list_index:list_index + pdo_info[i]['number_of_entry']]
       
   407                 for used_data in used:
       
   408                     # 24672 -> 0x6060, Mode of Operation
       
   409                     if used_data['entry_index'] == 24672:
       
   410                         ModeOfOpFlag = True
       
   411                     # 24673 -> 0x6061, Mode of Operation Display
       
   412                     elif used_data["entry_index"] == 24673:
       
   413                         ModeOfOpDisplayFlag = True
       
   414 
       
   415                     if used_data['entry_index'] in add_idx:
       
   416                         idx = add_idx.index(used_data['entry_index'])
       
   417                         adder = list([ADD_NODE_VARIABLES[idx]['name'], ADD_NODE_VARIABLES[idx]['index'], \
       
   418                                      ADD_NODE_VARIABLES[idx]['sub-index'], ADD_NODE_VARIABLES[idx]['type'], \
       
   419                                      ADD_NODE_VARIABLES[idx]['direction']])
       
   420                         variables.append(adder)
       
   421                         if ADD_NODE_VARIABLES[idx]['direction'] == "Q":                           
       
   422                             parsed_string = ADD_NODE_VARIABLES[idx]['name'].replace("Target", "")
       
   423                             # add jblee
       
   424                             check_q_data = "    *(AxsPub.Target%s) = AxsPub.axis->Raw%sSetPoint;" %(parsed_string, parsed_string)
       
   425                             if check_q_data not in str_completion["default_variables_publish"]:
       
   426                                 str_completion["default_variables_publish"].append(check_q_data)
       
   427                         elif ADD_NODE_VARIABLES[idx]['direction'] == "I":
       
   428                             parsed_string = ADD_NODE_VARIABLES[idx]['name'].replace("Actual", "")
       
   429                             # add jblee
       
   430                             check_i_data = "    AxsPub.axis->ActualRaw%s = *(AxsPub.Actual%s);" %(parsed_string, parsed_string)
       
   431                             if check_i_data not in str_completion["default_variables_retrieve"]:
       
   432                                 str_completion["default_variables_retrieve"].append(check_i_data)
       
   433             list_index += pdo_info[i]['number_of_entry']
       
   434 #HSAHN END
       
   435 
       
   436         params = self.CTNParams[1].getElementInfos(self.CTNParams[0])
       
   437         for param in params["children"]:
       
   438             if param["name"] in EXTRA_NODE_VARIABLES_DICT:
       
   439                 if param["value"]:
       
   440                     extra_variables = EXTRA_NODE_VARIABLES_DICT.get(param["name"])
       
   441                     for variable_infos in extra_variables:
       
   442                         var_infos = {
       
   443                             "location": location_str,
       
   444                             "name": variable_infos["description"][0]
       
   445                         }
       
   446                         variables.append(variable_infos["description"])
       
   447                         retrieve_template = variable_infos.get("retrieve", DEFAULT_RETRIEVE)
       
   448                         publish_template = variable_infos.get("publish", DEFAULT_PUBLISH)
   237                         
   449                         
   238             fieldbus_interface_declaration.append("""
   450                         if retrieve_template is not None:
   239 extern void ETHERLAB%(ucase_blocktype)s_body__(ETHERLAB%(ucase_blocktype)s* data__);
   451                             str_completion["extra_variables_retrieve"].append(
   240 void __%(blocktype)s_%(location_str)s(MC_%(ucase_blocktype)s *data__) {
   452                                 retrieve_template % var_infos)
   241 __DECLARE_GLOBAL_PROTOTYPE(ETHERLAB%(ucase_blocktype)s, %(blockname)s);
   453                         if publish_template is not None:
   242 ETHERLAB%(ucase_blocktype)s* %(blockname)s = __GET_GLOBAL_%(blockname)s();
   454                             str_completion["extra_variables_publish"].append(
   243 __SET_VAR(%(blockname)s->, POS,, AxsPub.axis->NetworkPosition);
   455                                 publish_template % var_infos)
   244 %(extract_inputs)s
   456 
   245 ETHERLAB%(ucase_blocktype)s_body__(%(blockname)s);
   457             #elif param["value"] is not None:
   246 %(return_outputs)s
       
   247 }""" % locals())
       
   248             
       
   249             fieldbus_interface_definition.append("""\
       
   250         AxsPub.axis->__mcl_func_MC_%(blocktype)s = __%(blocktype)s_%(location_str)s;\
       
   251 """ % locals())
       
   252         
       
   253         # Get a copy list of default variables to map
       
   254         variables = NODE_VARIABLES[:]
       
   255         
       
   256         # Set AxisRef public struct members value
       
   257         node_params = self.CTNParams[1].getElementInfos(self.CTNParams[0])
       
   258         for param in node_params["children"]:
       
   259             param_name = param["name"]
       
   260             
       
   261             # Param is optional variables section enable flag
       
   262             extra_node_variable_infos = EXTRA_NODE_VARIABLES_DICT.get(param_name)
       
   263             if extra_node_variable_infos is not None:
       
   264                 param_name = param_name.replace("Enable", "") + "Enabled"
       
   265                 
       
   266                 if not param["value"]:
       
   267                     continue
       
   268                 
       
   269                 # Optional variables section is enabled
       
   270                 for variable_infos in extra_node_variable_infos:
       
   271                     var_name = variable_infos["description"][0]
       
   272                     
       
   273                     # Add each variables defined in section description to the
       
   274                     # list of variables to map
       
   275                     variables.append(variable_infos["description"])
       
   276                     
       
   277                     # Add code to publish or retrive variable
       
   278                     for var_exchange_dir, str_list, default_template in [
       
   279                          ("retrieve", extra_variables_retrieve,
       
   280                           "    AxsPub.axis->%(var_name)s = *(AxsPub.%(var_name)s);"),
       
   281                          ("publish", extra_variables_publish,
       
   282                           "    *(AxsPub.%(var_name)s) = AxsPub.axis->%(var_name)s;")]:
       
   283                         
       
   284                         template = variable_infos.get(var_exchange_dir, 
       
   285                                                       default_template)
       
   286                         if template is not None:
       
   287                             extra_variables_publish.append(template % locals())
       
   288             
       
   289             # Set AxisRef public struct member value if defined
       
   290             if param["value"] is not None:
   458             if param["value"] is not None:
   291                 param_value = ({True: "1", False: "0"}[param["value"]]
   459                 param_infos = {
   292                                if param["type"] == "boolean"
   460                     "location": location_str,
   293                                else str(param["value"]))
   461                     "param_name": param["name"],
   294                 
   462                 }
   295                 init_axis_params.append("""\
   463                 if param["type"] == "boolean":
   296         AxsPub.axis->%(param_name)s = %(param_value)s;""" % locals())
   464                     param_infos["param_value"] = {True: "1", False: "0"}[param["value"]]
   297         
   465                     param_infos["param_name"] = param["name"].replace("Enable", "") + "Enabled"
   298         # Add each variable in list of variables to map to master list of
   466                     if param["value"] == False:
   299         # variables to add to network configuration
   467                         continue
   300         for name, index, subindex, var_type, dir in variables:
   468                 else:
   301             var_size = self.GetSizeOfType(var_type)
   469                     param_infos["param_value"] = str(param["value"])
   302             var_name = """\
   470                 # param_name = param_name.replace("Enable", "") + "Enabled"
   303 __%(dir)s%(var_size)s%(location_str)s_%(index)d_%(subindex)d""" % locals()
   471                 str_completion["init_axis_params"].append(
   304             
   472                     "        __CIA402Node_%(location)s.axis->%(param_name)s = %(param_value)s;" % param_infos)
   305             extern_located_variables_declaration.append(
   473         
   306                     "IEC_%(var_type)s *%(var_name)s;" % locals())
   474         check_variable = []
   307             entry_variables.append(
   475         for variable in variables:
   308                     "    IEC_%(var_type)s *%(name)s;" % locals())
   476             # add jblee
   309             init_entry_variables.append(
   477             if variable in check_variable:
   310                     "    AxsPub.%(name)s = %(var_name)s;" % locals())
   478                 continue
       
   479 
       
   480             var_infos = dict(zip(["name", "index", "subindex", "var_type", "dir"], variable))
       
   481             var_infos["location"] = location_str
       
   482             var_infos["var_size"] = self.GetSizeOfType(var_infos["var_type"])
       
   483             var_infos["var_name"] = "__%(dir)s%(var_size)s%(location)s_%(index)d_%(subindex)d" % var_infos
       
   484 
       
   485             # add jblee
       
   486             if var_infos["index"] in [24672] and ModeOfOpFlag:
       
   487                 str_completion["modeofop_homing_method"].append(MODEOFOP_HOMING_METHOD_TEMPLATE)
       
   488                 str_completion["modeofop_computation_mode"].append(MODEOFOP_COMPUTATION_MODE_TEMPLATE)
       
   489 
       
   490             # add jblee
       
   491             if var_infos["index"] in [24672, 24673] and (not ModeOfOpFlag or not ModeOfOpDisplayFlag):
       
   492                 continue
       
   493 
       
   494             str_completion["extern_located_variables_declaration"].append(
       
   495                     "IEC_%(var_type)s *%(var_name)s;" % var_infos)
       
   496             str_completion["entry_variables"].append(
       
   497                     "    IEC_%(var_type)s *%(name)s;" % var_infos)
       
   498             str_completion["init_entry_variables"].append(
       
   499                     "    __CIA402Node_%(location)s.%(name)s = %(var_name)s;" % var_infos)
   311             
   500             
   312             self.CTNParent.FileGenerator.DeclareVariable(
   501             self.CTNParent.FileGenerator.DeclareVariable(
   313                     slave_pos, index, subindex, var_type, dir, var_name)
   502                     self.GetSlavePos(), var_infos["index"], var_infos["subindex"], 
   314         
   503                     var_infos["var_type"], var_infos["dir"], var_infos["var_name"])
   315         # Add newline between string in list of generated strings for sections
   504 
   316         [fieldbus_interface_declaration, fieldbus_interface_definition,
   505             # add jblee
   317          init_axis_params, extra_variables_retrieve, extra_variables_publish,
   506             check_variable.append(variable)
   318          extern_located_variables_declaration, entry_variables, 
   507         
   319          init_entry_variables] = map(lambda l: "\n".join(l), [
   508         for element in ["extern_located_variables_declaration", 
   320             fieldbus_interface_declaration, fieldbus_interface_definition,
   509                         "fieldbus_interface_declaration",
   321             init_axis_params, extra_variables_retrieve, extra_variables_publish,
   510                         "fieldbus_interface_definition",
   322             extern_located_variables_declaration, entry_variables, 
   511                         "entry_variables", 
   323             init_entry_variables])
   512                         "init_axis_params", 
   324         
   513                         "init_entry_variables",
   325         # Write generated content to CIA402 node file
   514                         "default_variables_retrieve",
   326         Gen_CIA402Nodefile_path = os.path.join(buildpath, 
   515                         "default_variables_publish",
   327                                 "cia402node_%s.c"%location_str)
   516                         "extra_variables_retrieve",
       
   517                         "extra_variables_publish",
       
   518                         "modeofop_homing_method",
       
   519                         "modeofop_computation_mode"]:
       
   520             str_completion[element] = "\n".join(str_completion[element])
       
   521         
       
   522         Gen_CIA402Nodefile_path = os.path.join(buildpath, "cia402node_%s.c"%location_str)
   328         cia402nodefile = open(Gen_CIA402Nodefile_path, 'w')
   523         cia402nodefile = open(Gen_CIA402Nodefile_path, 'w')
   329         cia402nodefile.write(plc_cia402node_code % locals())
   524         cia402nodefile.write(plc_cia402node_code % str_completion)
   330         cia402nodefile.close()
   525         cia402nodefile.close()
   331         
   526         
   332         return [(Gen_CIA402Nodefile_path, '"-I%s"'%os.path.abspath(self.GetCTRoot().GetIECLibPath()))],"",True
   527         return [(Gen_CIA402Nodefile_path, '"-I%s"'%os.path.abspath(self.GetCTRoot().GetIECLibPath()))],"",True
       
   528