edouard@2165: #!/usr/bin/env python
edouard@2165: # -*- coding: utf-8 -*-
edouard@2165:
edouard@2165: # This file is part of Beremiz
edouard@2165: #
edouard@2165: # Copyright (C) 2011-2014: Laurent BESSARD, Edouard TISSERANT
edouard@2165: # RTES Lab : CRKim, JBLee, youcu
edouard@2165: # Higen Motor : Donggu Kang
edouard@2165: #
edouard@2165: # See COPYING file for copyrights details.
edouard@2165:
andrej@2405: from __future__ import absolute_import
andrej@2437: from __future__ import division
Laurent@2111: import os
Laurent@2111:
andrej@2405: from etherlab.EthercatSlave import ExtractHexDecValue, DATATYPECONVERSION, ExtractName
Laurent@2111:
Laurent@2111: SLAVE_PDOS_CONFIGURATION_DECLARATION = """
Laurent@2111: /* Slave %(slave)d, "%(device_type)s"
Laurent@2111: * Vendor ID: 0x%(vendor).8x
Laurent@2111: * Product code: 0x%(product_code).8x
Laurent@2111: * Revision number: 0x%(revision_number).8x
Laurent@2111: */
Laurent@2111:
Laurent@2111: ec_pdo_entry_info_t slave_%(slave)d_pdo_entries[] = {
Laurent@2111: %(pdos_entries_infos)s
Laurent@2111: };
Laurent@2111:
Laurent@2111: ec_pdo_info_t slave_%(slave)d_pdos[] = {
Laurent@2111: %(pdos_infos)s
Laurent@2111: };
Laurent@2111:
Laurent@2111: ec_sync_info_t slave_%(slave)d_syncs[] = {
Laurent@2111: %(pdos_sync_infos)s
Laurent@2111: {0xff}
Laurent@2111: };
Laurent@2111: """
Laurent@2111:
Laurent@2111: SLAVE_CONFIGURATION_TEMPLATE = """
Laurent@2111: if (!(slave%(slave)d = ecrt_master_slave_config(master, %(alias)d, %(position)d, 0x%(vendor).8x, 0x%(product_code).8x))) {
Edouard@2116: SLOGF(LOG_CRITICAL, "EtherCAT failed to get slave %(device_type)s configuration at alias %(alias)d and position %(position)d.");
Edouard@2121: goto ecat_failed;
Laurent@2111: }
Laurent@2111:
Laurent@2111: if (ecrt_slave_config_pdos(slave%(slave)d, EC_END, slave_%(slave)d_syncs)) {
Edouard@2116: SLOGF(LOG_CRITICAL, "EtherCAT failed to configure PDOs for slave %(device_type)s at alias %(alias)d and position %(position)d.");
Edouard@2117: goto ecat_failed;
Laurent@2111: }
Laurent@2111: """
Laurent@2111:
Laurent@2111: SLAVE_INITIALIZATION_TEMPLATE = """
Laurent@2111: {
Laurent@2111: uint8_t value[%(data_size)d];
Laurent@2111: EC_WRITE_%(data_type)s((uint8_t *)value, %(data)s);
Laurent@2111: if (ecrt_master_sdo_download(master, %(slave)d, 0x%(index).4x, 0x%(subindex).2x, (uint8_t *)value, %(data_size)d, &abort_code)) {
Edouard@2116: SLOGF(LOG_CRITICAL, "EtherCAT Failed to initialize slave %(device_type)s at alias %(alias)d and position %(position)d. Error: %%d", abort_code);
Edouard@2117: goto ecat_failed;
Laurent@2111: }
Laurent@2111: }
Laurent@2111: """
Laurent@2111:
Laurent@2111: SLAVE_OUTPUT_PDO_DEFAULT_VALUE = """
Laurent@2111: {
Laurent@2111: uint8_t value[%(data_size)d];
Laurent@2111: if (ecrt_master_sdo_upload(master, %(slave)d, 0x%(index).4x, 0x%(subindex).2x, (uint8_t *)value, %(data_size)d, &result_size, &abort_code)) {
Edouard@2116: SLOGF(LOG_CRITICAL, "EtherCAT failed to get default value for output PDO in slave %(device_type)s at alias %(alias)d and position %(position)d. Error: %%ud", abort_code);
Edouard@2117: goto ecat_failed;
Laurent@2111: }
Laurent@2111: %(real_var)s = EC_READ_%(data_type)s((uint8_t *)value);
Laurent@2111: }
Laurent@2111: """
Laurent@2111:
edouard@2641: SLAVE_OUTPUT_PDO_DEFAULT_VALUE_BIT = """
edouard@2641: {
edouard@2641: uint8_t value[%(data_size)d];
edouard@2641: if (ecrt_master_sdo_upload(master, %(slave)d, 0x%(index).4x, 0x%(subindex).2x, (uint8_t *)value, %(data_size)d, &result_size, &abort_code)) {
edouard@2641: SLOGF(LOG_CRITICAL, "EtherCAT failed to get default value for output PDO in slave %(device_type)s at alias %(alias)d and position %(position)d. Error: %%ud", abort_code);
edouard@2641: goto ecat_failed;
edouard@2641: }
edouard@2641: %(real_var)s = EC_READ_%(data_type)s((uint8_t *)value, %(subindex)d);
edouard@2641: }
edouard@2641: """
edouard@2641:
edouard@2641:
edouard@2641: SLAVE_INPUT_PDO_DEFAULT_VALUE = """
edouard@2641: {
edouard@2641: uint8_t value[%(data_size)d];
edouard@2641: if (ecrt_master_sdo_upload(master, %(slave)d, 0x%(index).4x, 0x%(subindex).2x, (uint8_t *)value, %(data_size)d, &result_size, &abort_code)) {
edouard@2641: SLOGF(LOG_CRITICAL, "EtherCAT failed to get default value for input PDO in slave %(device_type)s at alias %(alias)d and position %(position)d. Error: %%ud", abort_code);
edouard@2641: goto ecat_failed;
edouard@2641: }
edouard@2641: %(real_var)s = EC_READ_%(data_type)s((uint8_t *)value);
edouard@2641: }
edouard@2641: """
edouard@2641:
edouard@2641: DC_VARIABLE ="""
edouard@2641: #define DC_ENABLE %(dc_flag)d
edouard@2641: """
edouard@2641:
edouard@2641: CONFIG_DC = """
edouard@2641: ecrt_slave_config_dc (slave%(slave)d, 0x0%(assign_activate)ld, %(sync0_cycle_time)d, %(sync0_shift_time)d, %(sync1_cycle_time)d, %(sync1_shift_time)d);
edouard@2641: """
edouard@2641:
edouard@2641:
Laurent@2111: def ConfigureVariable(entry_infos, str_completion):
Laurent@2111: entry_infos["data_type"] = DATATYPECONVERSION.get(entry_infos["var_type"], None)
Laurent@2111: if entry_infos["data_type"] is None:
andrej@2378: msg = _("Type of location \"%s\" not yet supported!") % entry_infos["var_name"]
andrej@2378: raise ValueError(msg)
andrej@2355:
Laurent@2111: if not entry_infos.get("no_decl", False):
andrej@2377: if "real_var" in entry_infos:
Laurent@2111: str_completion["located_variables_declaration"].append(
Laurent@2111: "IEC_%(var_type)s %(real_var)s;" % entry_infos)
Laurent@2111: else:
Laurent@2111: entry_infos["real_var"] = "beremiz" + entry_infos["var_name"]
Laurent@2111: str_completion["located_variables_declaration"].extend(
Laurent@2111: ["IEC_%(var_type)s %(real_var)s;" % entry_infos,
Laurent@2111: "IEC_%(var_type)s *%(var_name)s = &%(real_var)s;" % entry_infos])
Laurent@2111: for declaration in entry_infos.get("extra_declarations", []):
Laurent@2111: entry_infos["extra_decl"] = declaration
Laurent@2111: str_completion["located_variables_declaration"].append(
andrej@2407: "IEC_%(var_type)s *%(extra_decl)s = &%(real_var)s;" % entry_infos)
andrej@2377: elif "real_var" not in entry_infos:
Laurent@2111: entry_infos["real_var"] = "beremiz" + entry_infos["var_name"]
andrej@2355:
Laurent@2111: str_completion["used_pdo_entry_offset_variables_declaration"].append(
Laurent@2111: "unsigned int slave%(slave)d_%(index).4x_%(subindex).2x;" % entry_infos)
andrej@2355:
Laurent@2111: if entry_infos["data_type"] == "BIT":
Laurent@2111: str_completion["used_pdo_entry_offset_variables_declaration"].append(
Laurent@2111: "unsigned int slave%(slave)d_%(index).4x_%(subindex).2x_bit;" % entry_infos)
andrej@2355:
Laurent@2111: str_completion["used_pdo_entry_configuration"].append(
andrej@2407: (" {%(alias)d, %(position)d, 0x%(vendor).8x, 0x%(product_code).8x, " +
andrej@2407: "0x%(index).4x, %(subindex)d, &slave%(slave)d_%(index).4x_%(subindex).2x, " +
andrej@2407: "&slave%(slave)d_%(index).4x_%(subindex).2x_bit},") % entry_infos)
andrej@2355:
Laurent@2111: if entry_infos["dir"] == "I":
Laurent@2111: str_completion["retrieve_variables"].append(
andrej@2407: (" %(real_var)s = EC_READ_BIT(domain1_pd + slave%(slave)d_%(index).4x_%(subindex).2x, " +
andrej@2407: "slave%(slave)d_%(index).4x_%(subindex).2x_bit);") % entry_infos)
Laurent@2111: elif entry_infos["dir"] == "Q":
Laurent@2111: str_completion["publish_variables"].append(
andrej@2407: (" EC_WRITE_BIT(domain1_pd + slave%(slave)d_%(index).4x_%(subindex).2x, " +
andrej@2407: "slave%(slave)d_%(index).4x_%(subindex).2x_bit, %(real_var)s);") % entry_infos)
andrej@2355:
Laurent@2111: else:
Laurent@2111: str_completion["used_pdo_entry_configuration"].append(
andrej@2355: (" {%(alias)d, %(position)d, 0x%(vendor).8x, 0x%(product_code).8x, 0x%(index).4x, " +
Laurent@2111: "%(subindex)d, &slave%(slave)d_%(index).4x_%(subindex).2x},") % entry_infos)
andrej@2355:
Laurent@2111: if entry_infos["dir"] == "I":
Laurent@2111: str_completion["retrieve_variables"].append(
andrej@2355: (" %(real_var)s = EC_READ_%(data_type)s(domain1_pd + " +
Laurent@2111: "slave%(slave)d_%(index).4x_%(subindex).2x);") % entry_infos)
Laurent@2111: elif entry_infos["dir"] == "Q":
Laurent@2111: str_completion["publish_variables"].append(
andrej@2355: (" EC_WRITE_%(data_type)s(domain1_pd + slave%(slave)d_%(index).4x_%(subindex).2x, " +
Laurent@2111: "%(real_var)s);") % entry_infos)
Laurent@2111:
andrej@2360:
Laurent@2111: def ExclusionSortFunction(x, y):
Laurent@2111: if x["matching"] == y["matching"]:
Laurent@2111: if x["assigned"] and not y["assigned"]:
Laurent@2111: return -1
Laurent@2111: elif not x["assigned"] and y["assigned"]:
Laurent@2111: return 1
Laurent@2111: return cmp(x["count"], y["count"])
Laurent@2111: return -cmp(x["matching"], y["matching"])
Laurent@2111:
andrej@2360:
andrej@2397: class _EthercatCFileGenerator(object):
andrej@2355:
Laurent@2111: def __init__(self, controler):
Laurent@2111: self.Controler = controler
andrej@2355:
Laurent@2111: self.Slaves = []
Laurent@2111: self.UsedVariables = {}
Laurent@2111:
Laurent@2111: def __del__(self):
andrej@2355: self.Controler = None
andrej@2355:
Laurent@2111: def DeclareSlave(self, slave_index, slave):
Laurent@2111: self.Slaves.append((slave_index, slave.getInfo().getAutoIncAddr(), slave))
Laurent@2111:
Laurent@2111: def DeclareVariable(self, slave_index, index, subindex, iec_type, dir, name, no_decl=False):
Laurent@2111: slave_variables = self.UsedVariables.setdefault(slave_index, {})
andrej@2355:
Laurent@2111: entry_infos = slave_variables.get((index, subindex), None)
Laurent@2111: if entry_infos is None:
Laurent@2111: slave_variables[(index, subindex)] = {
Laurent@2111: "infos": (iec_type, dir, name, no_decl, []),
Laurent@2111: "mapped": False}
Laurent@2111: return name
Laurent@2111: elif entry_infos["infos"][:2] == (iec_type, dir):
Laurent@2111: if name != entry_infos["infos"][2]:
Laurent@2111: if dir == "I":
Laurent@2111: entry_infos["infos"][4].append(name)
Laurent@2111: return entry_infos["infos"][2]
Laurent@2111: else:
andrej@2425: msg = _("Output variables can't be defined with different locations ({a1} and {a2})").\
andrej@2425: format(a1=entry_infos["infos"][2], a2=name)
andrej@2378: raise ValueError(msg)
Laurent@2111: else:
andrej@2378: raise ValueError(_("Definition conflict for location \"%s\"") % name)
andrej@2355:
Laurent@2111: def GenerateCFile(self, filepath, location_str, master_number):
andrej@2355:
Laurent@2111: # Extract etherlab master code template
Laurent@2111: plc_etherlab_filepath = os.path.join(os.path.split(__file__)[0], "plc_etherlab.c")
Laurent@2111: plc_etherlab_file = open(plc_etherlab_filepath, 'r')
Laurent@2111: plc_etherlab_code = plc_etherlab_file.read()
Laurent@2111: plc_etherlab_file.close()
andrej@2355:
Laurent@2111: # Initialize strings for formatting master code template
Laurent@2111: str_completion = {
Laurent@2111: "location": location_str,
Laurent@2111: "master_number": master_number,
Laurent@2111: "located_variables_declaration": [],
Laurent@2111: "used_pdo_entry_offset_variables_declaration": [],
Laurent@2111: "used_pdo_entry_configuration": [],
Laurent@2111: "pdos_configuration_declaration": "",
Laurent@2111: "slaves_declaration": "",
Laurent@2111: "slaves_configuration": "",
edouard@2641: # add jblee
edouard@2641: "slaves_input_pdos_default_values_extraction": "",
Laurent@2111: "slaves_output_pdos_default_values_extraction": "",
Laurent@2111: "slaves_initialization": "",
Laurent@2111: "retrieve_variables": [],
Laurent@2111: "publish_variables": [],
edouard@2641: #-----------This Code templete for dc -------------------#
edouard@2641: "dc_variable" : "",
edouard@2641: "config_dc": ""
Laurent@2111: }
andrej@2355:
Laurent@2111: # Initialize variable storing variable mapping state
Laurent@2111: for slave_entries in self.UsedVariables.itervalues():
Laurent@2111: for entry_infos in slave_entries.itervalues():
Laurent@2111: entry_infos["mapped"] = False
andrej@2355:
Laurent@2111: # Sort slaves by position (IEC_Channel)
Laurent@2111: self.Slaves.sort()
Laurent@2111: # Initialize dictionary storing alias auto-increment position values
Laurent@2111: alias = {}
edouard@2641:
edouard@2641: # add jblee
edouard@2641: slotNumber = 1
Laurent@2111:
Laurent@2111: # Generating code for each slave
Laurent@2111: for (slave_idx, slave_alias, slave) in self.Slaves:
Laurent@2111: type_infos = slave.getType()
andrej@2355:
Laurent@2111: # Defining slave alias and auto-increment position
Laurent@2111: if alias.get(slave_alias) is not None:
Laurent@2111: alias[slave_alias] += 1
Laurent@2111: else:
Laurent@2111: alias[slave_alias] = 0
Laurent@2111: slave_pos = (slave_alias, alias[slave_alias])
andrej@2355:
Laurent@2111: # Extract slave device informations
Laurent@2137: device, module_extra_params = self.Controler.GetModuleInfos(type_infos)
Laurent@2144: if device is None:
andrej@2378: msg = _("No informations found for device %s!") \
andrej@2378: % (type_infos["device_type"])
andrej@2378: raise ValueError(msg)
andrej@2355:
Laurent@2144: # Extract slaves variables to be mapped
Laurent@2144: slave_variables = self.UsedVariables.get(slave_idx, {})
andrej@2355:
Laurent@2144: # Extract slave device object dictionary entries
Laurent@2144: device_entries = device.GetEntriesList()
andrej@2355:
Laurent@2144: # Adding code for declaring slave in master code template strings
Laurent@2144: for element in ["vendor", "product_code", "revision_number"]:
Laurent@2144: type_infos[element] = ExtractHexDecValue(type_infos[element])
Laurent@2144: type_infos.update(dict(zip(["slave", "alias", "position"], (slave_idx,) + slave_pos)))
andrej@2355:
Laurent@2144: # Extract slave device CoE informations
Laurent@2144: device_coe = device.getCoE()
Laurent@2144: if device_coe is not None:
andrej@2355:
andrej@2355: # If device support CanOpen over Ethernet, adding code for calling
Laurent@2144: # init commands when initializing slave in master code template strings
Laurent@2144: initCmds = []
edouard@2641:
Laurent@2144: for initCmd in device_coe.getInitCmd():
Laurent@2144: initCmds.append({
Laurent@2144: "Index": ExtractHexDecValue(initCmd.getIndex()),
Laurent@2144: "Subindex": ExtractHexDecValue(initCmd.getSubIndex()),
edouard@2641: #"Value": initCmd.getData().getcontent()})
edouard@2641: "Value": int(initCmd.getData().text, 16)})
edouard@2641:
Laurent@2144: initCmds.extend(slave.getStartupCommands())
Laurent@2144: for initCmd in initCmds:
Laurent@2144: index = initCmd["Index"]
Laurent@2144: subindex = initCmd["Subindex"]
Laurent@2144: entry = device_entries.get((index, subindex), None)
Laurent@2144: if entry is not None:
andrej@2437: data_size = entry["BitSize"] // 8
Laurent@2144: data_str = ("0x%%.%dx" % (data_size * 2)) % initCmd["Value"]
Laurent@2144: init_cmd_infos = {
Laurent@2144: "index": index,
Laurent@2144: "subindex": subindex,
Laurent@2144: "data": data_str,
Laurent@2144: "data_type": DATATYPECONVERSION.get(entry["Type"]),
Laurent@2144: "data_size": data_size
Laurent@2144: }
Laurent@2144: init_cmd_infos.update(type_infos)
Laurent@2144: str_completion["slaves_initialization"] += SLAVE_INITIALIZATION_TEMPLATE % init_cmd_infos
andrej@2355:
Laurent@2144: # Extract slave device PDO configuration capabilities
Laurent@2144: PdoAssign = device_coe.getPdoAssign()
Laurent@2144: PdoConfig = device_coe.getPdoConfig()
Laurent@2144: else:
Laurent@2144: PdoAssign = PdoConfig = False
andrej@2355:
Laurent@2144: # Test if slave has a configuration or need one
Laurent@2144: if len(device.getTxPdo() + device.getRxPdo()) > 0 or len(slave_variables) > 0 and PdoConfig and PdoAssign:
andrej@2355:
Laurent@2144: str_completion["slaves_declaration"] += "static ec_slave_config_t *slave%(slave)d = NULL;\n" % type_infos
Laurent@2144: str_completion["slaves_configuration"] += SLAVE_CONFIGURATION_TEMPLATE % type_infos
edouard@2641:
andrej@2355: # Initializing
Laurent@2144: pdos_infos = {
Laurent@2144: "pdos_entries_infos": [],
Laurent@2144: "pdos_infos": [],
andrej@2355: "pdos_sync_infos": [],
Laurent@2144: }
Laurent@2144: pdos_infos.update(type_infos)
andrej@2355:
Laurent@2144: sync_managers = []
Laurent@2144: for sync_manager_idx, sync_manager in enumerate(device.getSm()):
Laurent@2144: sync_manager_infos = {
andrej@2355: "index": sync_manager_idx,
Laurent@2144: "name": sync_manager.getcontent(),
Laurent@2144: "slave": slave_idx,
andrej@2355: "pdos": [],
Laurent@2144: "pdos_number": 0,
Laurent@2111: }
andrej@2355:
Laurent@2144: sync_manager_control_byte = ExtractHexDecValue(sync_manager.getControlByte())
Laurent@2144: sync_manager_direction = sync_manager_control_byte & 0x0c
Laurent@2144: sync_manager_watchdog = sync_manager_control_byte & 0x40
Laurent@2144: if sync_manager_direction:
Laurent@2144: sync_manager_infos["sync_manager_type"] = "EC_DIR_OUTPUT"
Laurent@2144: else:
Laurent@2144: sync_manager_infos["sync_manager_type"] = "EC_DIR_INPUT"
Laurent@2144: if sync_manager_watchdog:
Laurent@2144: sync_manager_infos["watchdog"] = "EC_WD_ENABLE"
Laurent@2144: else:
Laurent@2144: sync_manager_infos["watchdog"] = "EC_WD_DISABLE"
andrej@2355:
Laurent@2144: sync_managers.append(sync_manager_infos)
andrej@2355:
Laurent@2144: pdos_index = []
Laurent@2144: exclusive_pdos = {}
Laurent@2144: selected_pdos = []
edouard@2641:
edouard@2641: # add jblee
edouard@2641: TxPdoData = []
edouard@2641: RxPdoData = []
edouard@2641: PdoData = []
edouard@2641:
edouard@2641: # add jblee
edouard@2641: if len(device.getTxPdo() + device.getRxPdo()) > 0:
edouard@2641: for pdo in device.getTxPdo():
edouard@2641: PdoData.append((pdo, "Inputs"))
edouard@2641: for pdo in device.getRxPdo():
edouard@2641: PdoData.append((pdo, "Outputs"))
edouard@2641:
edouard@2641: # mod jblee
edouard@2641: #for pdo, pdo_type in ([(pdo, "Inputs") for pdo in device.getTxPdo()] +
edouard@2641: # [(pdo, "Outputs") for pdo in device.getRxPdo()]):
edouard@2641: #for pdo, pdo_type in (TxPdoData + RxPdoData):
edouard@2641: data_files = os.listdir(self.Controler.CTNPath())
edouard@2641: PDODataList = []
edouard@2641: MDPData = []
edouard@2641: RxPDOData = self.Controler.GetChildByIECLocation((slave_idx,)).BaseParams.getRxPDO()
edouard@2641: TxPDOData = self.Controler.GetChildByIECLocation((slave_idx,)).BaseParams.getTxPDO()
edouard@2641: PDOList = RxPDOData.split() + TxPDOData.split()
edouard@2641: for PDOIndex in PDOList:
edouard@2641: if PDOIndex in ["RxPDO", "TxPDO", "None"]:
edouard@2641: continue
edouard@2641: PDODataList.append(int(PDOIndex, 0))
edouard@2641:
edouard@2641: # add jblee for DC Configuration
edouard@2641: dc_enable = self.Controler.GetChildByIECLocation((slave_idx,)).BaseParams.getDC_Enable()
edouard@2641: sync0_cycle_time = 0
edouard@2641: sync0_shift_time = 0
edouard@2641: sync1_cycle_time = 0
edouard@2641: sync1_shift_time = 0
edouard@2641: if dc_enable :
edouard@2641: sync0_cycle_token = self.Controler.GetChildByIECLocation((slave_idx,)).BaseParams.getDC_Sync0_Cycle_Time()
edouard@2641: if sync0_cycle_token != "None":
edouard@2641: sync0_cycle_time = int(sync0_cycle_token.split("_")[1]) * 1000
edouard@2641: sync0_shift_token = self.Controler.GetChildByIECLocation((slave_idx,)).BaseParams.getDC_Sync0_Shift_Time()
edouard@2641: if sync0_shift_token != "None":
edouard@2641: sync0_shift_time = int(sync0_shift_token) * 1000
edouard@2641: sync1_cycle_token = self.Controler.GetChildByIECLocation((slave_idx,)).BaseParams.getDC_Sync1_Cycle_Time()
edouard@2641: if sync1_cycle_token != "None":
edouard@2641: sync1_cycle_time = int(sync1_cycle_token.split("_")[1]) * 1000
edouard@2641: sync1_shift_token = self.Controler.GetChildByIECLocation((slave_idx,)).BaseParams.getDC_Sync1_Shift_Time()
edouard@2641: if sync1_shift_token != "None":
edouard@2641: sync1_shift_time = int(sync1_shift_token) * 1000
edouard@2641:
edouard@2641: dc_config_data = {
edouard@2641: "slave" : slave_idx,
edouard@2641: "assign_activate" : int(self.Controler.GetChildByIECLocation((slave_idx,)).BaseParams.getDC_Assign_Activate()),
edouard@2641: "sync0_cycle_time" : sync0_cycle_time,
edouard@2641: "sync0_shift_time" : sync0_shift_time,
edouard@2641: "sync1_cycle_time" : sync1_cycle_time,
edouard@2641: "sync1_shift_time" : sync1_shift_time,
edouard@2641: }
edouard@2641:
edouard@2641: if dc_enable and not str_completion["dc_variable"] :
edouard@2641: str_completion["dc_variable"] += DC_VARIABLE % {"dc_flag" : dc_enable}
edouard@2641: str_completion["config_dc"] += CONFIG_DC % dc_config_data
edouard@2641:
edouard@2641: for data_file in data_files:
edouard@2641: slave_path = os.path.join(self.Controler.CTNPath(), data_file)
edouard@2641: if os.path.isdir(slave_path):
edouard@2641: CheckConfNodePath = os.path.join(slave_path, "baseconfnode.xml")
edouard@2641: confNodeFile = open(CheckConfNodePath, 'r')
edouard@2641: checklines = confNodeFile.readlines()
edouard@2641: confNodeFile.close()
edouard@2641: # checklines(ex) :
edouard@2641: # checklines[1].split() : []
edouard@2641: # checklines[1].split()[2] : IEC_Channel="0"
edouard@2641: # checklines[1].split()[2].split("\"") = [IEC_Channel=, 0, ]
edouard@2641: pos_check = int(checklines[1].split()[2].split("\"")[1])
edouard@2641: if slave_idx == pos_check:
edouard@2641: MDPDataFilePath = os.path.join(slave_path, "DataForMDP.txt")
edouard@2641: if os.path.isfile(MDPDataFilePath):
edouard@2641: MDPDataFile = open(MDPDataFilePath, 'r')
edouard@2641: MDPData = MDPDataFile.readlines()
edouard@2641: MDPDataFile.close()
edouard@2641:
edouard@2641: for MDPLine in MDPData:
edouard@2641: if MDPLine == "\n":
edouard@2641: continue
edouard@2641: module_pos = int(MDPLine.split()[-1])
edouard@2641: module = self.Controler.CTNParent.GetSelectModule(module_pos)
edouard@2641: for pdo in module.getTxPdo():
edouard@2641: PdoData.append((pdo, "Inputs"))
edouard@2641: PDODataList.append(ExtractHexDecValue(pdo.getIndex().getcontent()))
edouard@2641: for pdo in module.getRxPdo():
edouard@2641: PdoData.append((pdo, "Outputs"))
edouard@2641: PDODataList.append(ExtractHexDecValue(pdo.getIndex().getcontent()))
edouard@2641:
edouard@2641: for pdo, pdo_type in PdoData:
Laurent@2144: pdo_index = ExtractHexDecValue(pdo.getIndex().getcontent())
Laurent@2144: pdos_index.append(pdo_index)
edouard@2641:
edouard@2641: if PDODataList and (pdo_index in PDODataList):
edouard@2641: continue
edouard@2641:
Laurent@2144: excluded_list = pdo.getExclude()
Laurent@2144: if len(excluded_list) > 0:
Laurent@2144: exclusion_list = [pdo_index]
Laurent@2144: for excluded in excluded_list:
Laurent@2144: exclusion_list.append(ExtractHexDecValue(excluded.getcontent()))
Laurent@2144: exclusion_list.sort()
andrej@2355:
Laurent@2144: exclusion_scope = exclusive_pdos.setdefault(tuple(exclusion_list), [])
andrej@2355:
Laurent@2144: entries = pdo.getEntry()
edouard@2641:
Laurent@2144: pdo_mapping_match = {
andrej@2355: "index": pdo_index,
andrej@2355: "matching": 0,
andrej@2355: "count": len(entries),
Laurent@2144: "assigned": pdo.getSm() is not None
Laurent@2111: }
edouard@2641:
Laurent@2144: exclusion_scope.append(pdo_mapping_match)
andrej@2355:
Laurent@2111: for entry in entries:
Laurent@2111: index = ExtractHexDecValue(entry.getIndex().getcontent())
Laurent@2111: subindex = ExtractHexDecValue(entry.getSubIndex())
Laurent@2144: if slave_variables.get((index, subindex), None) is not None:
Laurent@2144: pdo_mapping_match["matching"] += 1
andrej@2355:
andrej@2374: if pdo.getFixed() is not True:
Laurent@2144: pdo_mapping_match["matching"] += \
Laurent@2144: module_extra_params["max_pdo_size"] - \
Laurent@2144: pdo_mapping_match["count"]
andrej@2355:
Laurent@2144: elif pdo.getMandatory():
Laurent@2144: selected_pdos.append(pdo_index)
andrej@2355:
Laurent@2144: excluded_pdos = []
Laurent@2144: for exclusion_scope in exclusive_pdos.itervalues():
Laurent@2144: exclusion_scope.sort(ExclusionSortFunction)
Laurent@2144: start_excluding_index = 0
Laurent@2144: if exclusion_scope[0]["matching"] > 0:
Laurent@2144: selected_pdos.append(exclusion_scope[0]["index"])
Laurent@2144: start_excluding_index = 1
andrej@2381: excluded_pdos.extend([
andrej@2381: pdo["index"]
andrej@2355: for pdo in exclusion_scope[start_excluding_index:]
Laurent@2144: if PdoAssign or not pdo["assigned"]])
edouard@2641:
edouard@2641: # mod jblee
edouard@2641: #for pdo, pdo_type in ([(pdo, "Inputs") for pdo in device.getTxPdo()] +
edouard@2641: # [(pdo, "Outputs") for pdo in device.getRxPdo()]):
edouard@2641: #for pdo, pdo_type in (TxPdoData + RxPdoData):
edouard@2641: entry_check_list = []
edouard@2641: index_padding = 1
edouard@2641: for pdo, pdo_type in PdoData:
edouard@2641: entries = pdo.getEntry()
Laurent@2144:
Laurent@2144: pdo_index = ExtractHexDecValue(pdo.getIndex().getcontent())
Laurent@2144: if pdo_index in excluded_pdos:
Laurent@2144: continue
edouard@2641: if PDODataList and (pdo_index not in PDODataList):
edouard@2641: continue
edouard@2641:
edouard@2641: #pdo_needed = pdo_index in selected_pdos
edouard@2641: pdo_needed = pdo_index in PDODataList
edouard@2641:
edouard@2641: if len(MDPData) > 0:
edouard@2641: pdo_index += index_padding
edouard@2641: index_padding += 1
edouard@2641:
edouard@2641: entries_infos = []
Laurent@2144: for entry in entries:
Laurent@2144: index = ExtractHexDecValue(entry.getIndex().getcontent())
Laurent@2144: subindex = ExtractHexDecValue(entry.getSubIndex())
edouard@2641:
edouard@2641: # add jblee
edouard@2641: if len(MDPData) > 0:
edouard@2641: increse = self.Controler.CTNParent.GetMDPInfos(type_infos)
edouard@2641: if increse and index != 0:
edouard@2641: index += int(increse[0][2]) * slotNumber
edouard@2641:
Laurent@2144: entry_infos = {
Laurent@2144: "index": index,
Laurent@2144: "subindex": subindex,
Laurent@2144: "name": ExtractName(entry.getName()),
Laurent@2144: "bitlen": entry.getBitLen(),
Laurent@2144: }
edouard@2641:
Laurent@2144: entry_infos.update(type_infos)
edouard@2641: #temp_data = " {0x%(index).4x, 0x%(subindex).2x, %(bitlen)d}, /* %(name)s */" % entry_infos
edouard@2641: check_data = "{0x%(index).4x, 0x%(subindex).2x, %(bitlen)d}" % entry_infos
edouard@2641: if entry_check_list and check_data in entry_check_list:
edouard@2641: if (entry_infos["index"] == 0) or (entry_infos["name"] == None):
edouard@2641: pass
edouard@2641: else:
Laurent@2144: entry_infos.update(type_infos)
Laurent@2144: entries_infos.append(" {0x%(index).4x, 0x%(subindex).2x, %(bitlen)d}, /* %(name)s */" % entry_infos)
edouard@2641: entry_check_list.append(check_data)
Laurent@2144:
Laurent@2144: entry_declaration = slave_variables.get((index, subindex), None)
Laurent@2144: if entry_declaration is not None and not entry_declaration["mapped"]:
Laurent@2144: pdo_needed = True
andrej@2355:
andrej@2355: entry_infos.update(dict(zip(["var_type", "dir", "var_name", "no_decl", "extra_declarations"],
Laurent@2144: entry_declaration["infos"])))
Laurent@2144: entry_declaration["mapped"] = True
andrej@2355:
Laurent@2144: entry_type = entry.getDataType().getcontent()
Laurent@2144: if entry_infos["var_type"] != entry_type:
Laurent@2144: message = _("Wrong type for location \"%s\"!") % entry_infos["var_name"]
andrej@2379: if self.Controler.GetSizeOfType(entry_infos["var_type"]) != \
andrej@2379: self.Controler.GetSizeOfType(entry_type):
andrej@2378: raise ValueError(message)
Laurent@2144: else:
Laurent@2144: self.Controler.GetCTRoot().logger.write_warning(_("Warning: ") + message + "\n")
andrej@2355:
andrej@2379: if (entry_infos["dir"] == "I" and pdo_type != "Inputs") or \
andrej@2379: (entry_infos["dir"] == "Q" and pdo_type != "Outputs"):
andrej@2378: raise ValueError(_("Wrong direction for location \"%s\"!") % entry_infos["var_name"])
andrej@2355:
Laurent@2144: ConfigureVariable(entry_infos, str_completion)
andrej@2355:
Laurent@2144: elif pdo_type == "Outputs" and entry.getDataType() is not None and device_coe is not None:
Laurent@2144: data_type = entry.getDataType().getcontent()
Laurent@2144: entry_infos["dir"] = "Q"
andrej@2437: entry_infos["data_size"] = max(1, entry_infos["bitlen"] // 8)
Laurent@2144: entry_infos["data_type"] = DATATYPECONVERSION.get(data_type)
Laurent@2144: entry_infos["var_type"] = data_type
Laurent@2144: entry_infos["real_var"] = "slave%(slave)d_%(index).4x_%(subindex).2x_default" % entry_infos
andrej@2355:
Laurent@2144: ConfigureVariable(entry_infos, str_completion)
edouard@2641:
edouard@2641: if entry_infos["data_type"] == "BIT" :
edouard@2641: str_completion["slaves_output_pdos_default_values_extraction"] += \
edouard@2641: SLAVE_OUTPUT_PDO_DEFAULT_VALUE_BIT % entry_infos
edouard@2641: else :
edouard@2641: str_completion["slaves_output_pdos_default_values_extraction"] += \
edouard@2641: SLAVE_OUTPUT_PDO_DEFAULT_VALUE % entry_infos
edouard@2641:
edouard@2641: elif pdo_type == "Inputs" and entry.getDataType() is not None and device_coe is not None:
edouard@2641: data_type = entry.getDataType().getcontent()
edouard@2641: entry_infos["dir"] = "I"
edouard@2641: entry_infos["data_size"] = max(1, entry_infos["bitlen"] / 8)
edouard@2641: entry_infos["data_type"] = DATATYPECONVERSION.get(data_type)
edouard@2641: entry_infos["var_type"] = data_type
edouard@2641: entry_infos["real_var"] = "slave%(slave)d_%(index).4x_%(subindex).2x_default" % entry_infos
edouard@2641:
edouard@2641: ConfigureVariable(entry_infos, str_completion)
edouard@2641:
edouard@2641: str_completion["slaves_input_pdos_default_values_extraction"] += \
edouard@2641: SLAVE_INPUT_PDO_DEFAULT_VALUE % entry_infos
edouard@2641:
Laurent@2144: if pdo_needed:
Laurent@2144: for excluded in pdo.getExclude():
Laurent@2144: excluded_index = ExtractHexDecValue(excluded.getcontent())
Laurent@2144: if excluded_index not in excluded_pdos:
Laurent@2144: excluded_pdos.append(excluded_index)
andrej@2355:
Laurent@2144: sm = pdo.getSm()
Laurent@2144: if sm is None:
Laurent@2144: for sm_idx, sync_manager in enumerate(sync_managers):
Laurent@2144: if sync_manager["name"] == pdo_type:
Laurent@2144: sm = sm_idx
Laurent@2144: if sm is None:
andrej@2378: raise ValueError(_("No sync manager available for %s pdo!") % pdo_type)
andrej@2355:
Laurent@2144: sync_managers[sm]["pdos_number"] += 1
Laurent@2144: sync_managers[sm]["pdos"].append(
Laurent@2144: {"slave": slave_idx,
Laurent@2144: "index": pdo_index,
Laurent@2144: "name": ExtractName(pdo.getName()),
andrej@2355: "type": pdo_type,
Laurent@2144: "entries": entries_infos,
Laurent@2144: "entries_number": len(entries_infos),
andrej@2374: "fixed": pdo.getFixed() is True})
edouard@2641:
edouard@2641: # for MDP
edouard@2641: slotNumber += 1
Laurent@2144:
Laurent@2144: if PdoConfig and PdoAssign:
Laurent@2144: dynamic_pdos = {}
Laurent@2144: dynamic_pdos_number = 0
andrej@2355: for category, min_index, max_index in [("Inputs", 0x1600, 0x1800),
Laurent@2144: ("Outputs", 0x1a00, 0x1C00)]:
Laurent@2144: for sync_manager in sync_managers:
Laurent@2144: if sync_manager["name"] == category:
Laurent@2144: category_infos = dynamic_pdos.setdefault(category, {})
Laurent@2144: category_infos["sync_manager"] = sync_manager
andrej@2355: category_infos["pdos"] = [pdo for pdo in category_infos["sync_manager"]["pdos"]
Laurent@2144: if not pdo["fixed"] and pdo["type"] == category]
Laurent@2144: category_infos["current_index"] = min_index
Laurent@2144: category_infos["max_index"] = max_index
Laurent@2144: break
andrej@2355:
Laurent@2144: for (index, subindex), entry_declaration in slave_variables.iteritems():
andrej@2355:
Laurent@2144: if not entry_declaration["mapped"]:
Laurent@2144: entry = device_entries.get((index, subindex), None)
Laurent@2144: if entry is None:
andrej@2425: msg = _("Unknown entry index 0x{a1:.4x}, subindex 0x{a2:.2x} for device {a3}").\
andrej@2425: format(a1=index, a2=subindex, a3=type_infos["device_type"])
andrej@2378: raise ValueError(msg)
edouard@2641:
Laurent@2111: entry_infos = {
Laurent@2111: "index": index,
Laurent@2111: "subindex": subindex,
Laurent@2144: "name": entry["Name"],
Laurent@2144: "bitlen": entry["BitSize"],
Laurent@2111: }
Laurent@2111: entry_infos.update(type_infos)
andrej@2355:
andrej@2355: entry_infos.update(dict(zip(["var_type", "dir", "var_name", "no_decl", "extra_declarations"],
Laurent@2144: entry_declaration["infos"])))
Laurent@2144: entry_declaration["mapped"] = True
andrej@2355:
Laurent@2144: if entry_infos["var_type"] != entry["Type"]:
Laurent@2144: message = _("Wrong type for location \"%s\"!") % entry_infos["var_name"]
andrej@2379: if self.Controler.GetSizeOfType(entry_infos["var_type"]) != \
andrej@2379: self.Controler.GetSizeOfType(entry["Type"]):
andrej@2378: raise ValueError(message)
Laurent@2144: else:
Laurent@2144: self.Controler.GetCTRoot().logger.write_warning(message + "\n")
andrej@2355:
Laurent@2144: if entry_infos["dir"] == "I" and entry["PDOMapping"] in ["T", "RT"]:
Laurent@2144: pdo_type = "Inputs"
Laurent@2144: elif entry_infos["dir"] == "Q" and entry["PDOMapping"] in ["R", "RT"]:
Laurent@2144: pdo_type = "Outputs"
Laurent@2144: else:
andrej@2378: msg = _("Wrong direction for location \"%s\"!") \
andrej@2378: % entry_infos["var_name"]
andrej@2378: raise ValueError(msg)
andrej@2355:
andrej@2377: if pdo_type not in dynamic_pdos:
andrej@2378: msg = _("No Sync manager defined for %s!") % pdo_type
andrej@2378: raise ValueError(msg)
andrej@2355:
Laurent@2144: ConfigureVariable(entry_infos, str_completion)
andrej@2355:
Laurent@2144: if len(dynamic_pdos[pdo_type]["pdos"]) > 0:
Laurent@2144: pdo = dynamic_pdos[pdo_type]["pdos"][0]
Laurent@2144: elif module_extra_params["add_pdo"]:
Laurent@2144: while dynamic_pdos[pdo_type]["current_index"] in pdos_index:
Laurent@2144: dynamic_pdos[pdo_type]["current_index"] += 1
Laurent@2144: if dynamic_pdos[pdo_type]["current_index"] >= dynamic_pdos[pdo_type]["max_index"]:
andrej@2378: raise ValueError(_("No more free PDO index available for %s!") % pdo_type)
Laurent@2144: pdos_index.append(dynamic_pdos[pdo_type]["current_index"])
andrej@2355:
Laurent@2144: dynamic_pdos_number += 1
Laurent@2144: pdo = {"slave": slave_idx,
Laurent@2144: "index": dynamic_pdos[pdo_type]["current_index"],
Laurent@2144: "name": "Dynamic PDO %d" % dynamic_pdos_number,
andrej@2355: "type": pdo_type,
Laurent@2144: "entries": [],
Laurent@2144: "entries_number": 0,
Laurent@2144: "fixed": False}
Laurent@2144: dynamic_pdos[pdo_type]["sync_manager"]["pdos_number"] += 1
Laurent@2144: dynamic_pdos[pdo_type]["sync_manager"]["pdos"].append(pdo)
Laurent@2144: dynamic_pdos[pdo_type]["pdos"].append(pdo)
Laurent@2144: else:
Laurent@2144: break
andrej@2355:
Laurent@2144: pdo["entries"].append(" {0x%(index).4x, 0x%(subindex).2x, %(bitlen)d}, /* %(name)s */" % entry_infos)
Laurent@2144: if entry_infos["bitlen"] < module_extra_params["pdo_alignment"]:
Laurent@2144: pdo["entries"].append(" {0x0000, 0x00, %d}, /* None */" % (
andrej@2407: module_extra_params["pdo_alignment"] - entry_infos["bitlen"]))
Laurent@2144: pdo["entries_number"] += 1
andrej@2355:
Laurent@2144: if pdo["entries_number"] == module_extra_params["max_pdo_size"]:
Laurent@2144: dynamic_pdos[pdo_type]["pdos"].pop(0)
andrej@2355:
Laurent@2144: pdo_offset = 0
Laurent@2144: entry_offset = 0
edouard@2641: slotNumber = 1
Laurent@2144: for sync_manager_infos in sync_managers:
Laurent@2144: for pdo_infos in sync_manager_infos["pdos"]:
Laurent@2144: pdo_infos["offset"] = entry_offset
Laurent@2144: pdo_entries = pdo_infos["entries"]
Laurent@2144: pdos_infos["pdos_infos"].append(
andrej@2355: (" {0x%(index).4x, %(entries_number)d, " +
Laurent@2144: "slave_%(slave)d_pdo_entries + %(offset)d}, /* %(name)s */") % pdo_infos)
Laurent@2144: entry_offset += len(pdo_entries)
Laurent@2144: pdos_infos["pdos_entries_infos"].extend(pdo_entries)
andrej@2355:
Laurent@2144: sync_manager_infos["offset"] = pdo_offset
Laurent@2144: pdo_offset_shift = sync_manager_infos["pdos_number"]
Laurent@2144: pdos_infos["pdos_sync_infos"].append(
andrej@2355: (" {%(index)d, %(sync_manager_type)s, %(pdos_number)d, " +
Laurent@2144: ("slave_%(slave)d_pdos + %(offset)d" if pdo_offset_shift else "NULL") +
Laurent@2144: ", %(watchdog)s},") % sync_manager_infos)
andrej@2355: pdo_offset += pdo_offset_shift
andrej@2355:
Laurent@2144: for element in ["pdos_entries_infos", "pdos_infos", "pdos_sync_infos"]:
Laurent@2144: pdos_infos[element] = "\n".join(pdos_infos[element])
andrej@2355:
Laurent@2144: str_completion["pdos_configuration_declaration"] += SLAVE_PDOS_CONFIGURATION_DECLARATION % pdos_infos
Laurent@2144:
edouard@2641: #for (index, subindex), entry_declaration in slave_variables.iteritems():
edouard@2641: # if not entry_declaration["mapped"]:
edouard@2641: # message = _("Entry index 0x%4.4x, subindex 0x%2.2x not mapped for device %s") % \
edouard@2641: # (index, subindex, type_infos["device_type"])
edouard@2641: # self.Controler.GetCTRoot().logger.write_warning(_("Warning: ") + message + "\n")
Laurent@2111:
Laurent@2111: for element in ["used_pdo_entry_offset_variables_declaration",
Laurent@2111: "used_pdo_entry_configuration",
Laurent@2111: "located_variables_declaration",
Laurent@2111: "retrieve_variables",
Laurent@2111: "publish_variables"]:
Laurent@2111: str_completion[element] = "\n".join(str_completion[element])
andrej@2355:
Laurent@2111: etherlabfile = open(filepath, 'w')
Laurent@2111: etherlabfile.write(plc_etherlab_code % str_completion)
Laurent@2111: etherlabfile.close()