laurent@2022: import os, shutil
laurent@2022: import cPickle
laurent@2022: from xml.dom import minidom
laurent@2022:
laurent@2022: import wx
laurent@2022:
laurent@2022: from xmlclass import *
Edouard@2048: from ConfigTreeNode import ConfigTreeNode
Edouard@2048: from PLCControler import UndoBuffer, LOCATION_CONFNODE, LOCATION_MODULE, LOCATION_GROUP, LOCATION_VAR_INPUT, LOCATION_VAR_OUTPUT, LOCATION_VAR_MEMORY
laurent@2043: from ConfigEditor import NodeEditor, CIA402NodeEditor, ETHERCAT_VENDOR, ETHERCAT_GROUP, ETHERCAT_DEVICE
laurent@2041:
laurent@2041: try:
Edouard@2049: from MotionLibrary import Headers, AxisXSD
laurent@2041: HAS_MCL = True
laurent@2041: except:
laurent@2041: HAS_MCL = False
laurent@2041:
Edouard@2048: CONFNODEFOLDER = os.path.split(os.path.realpath(__file__))[0]
laurent@2041:
laurent@2041: TYPECONVERSION = {"BOOL" : "X", "SINT" : "B", "INT" : "W", "DINT" : "D", "LINT" : "L",
laurent@2041: "USINT" : "B", "UINT" : "W", "UDINT" : "D", "ULINT" : "L",
laurent@2041: "BYTE" : "B", "WORD" : "W", "DWORD" : "D", "LWORD" : "L"}
laurent@2041:
laurent@2041: DATATYPECONVERSION = {"BOOL" : "BIT", "SINT" : "S8", "INT" : "S16", "DINT" : "S32", "LINT" : "S64",
laurent@2041: "USINT" : "U8", "UINT" : "U16", "UDINT" : "U32", "ULINT" : "U64",
laurent@2041: "BYTE" : "U8", "WORD" : "U16", "DWORD" : "U32", "LWORD" : "U64"}
laurent@2041:
laurent@2041: VARCLASSCONVERSION = {"T": LOCATION_VAR_INPUT, "R": LOCATION_VAR_OUTPUT, "RT": LOCATION_VAR_MEMORY}
laurent@2022:
laurent@2032: #--------------------------------------------------
laurent@2041: # Remote Exec Etherlab Commands
laurent@2032: #--------------------------------------------------
laurent@2032:
laurent@2041: SCAN_COMMAND = """
laurent@2041: import commands
laurent@2041: result = commands.getoutput("ethercat slaves")
laurent@2041: slaves = []
laurent@2041: for slave_line in result.splitlines():
laurent@2041: chunks = slave_line.split()
laurent@2041: idx, pos, state, flag = chunks[:4]
laurent@2041: name = " ".join(chunks[4:])
laurent@2041: alias, position = pos.split(":")
laurent@2041: slave = {"idx": int(idx),
laurent@2041: "alias": int(alias),
laurent@2041: "position": int(position),
laurent@2041: "name": name}
laurent@2041: details = commands.getoutput("ethercat slaves -p %d -v" % slave["idx"])
laurent@2041: for details_line in details.splitlines():
laurent@2041: details_line = details_line.strip()
laurent@2041: for header, param in [("Vendor Id:", "vendor_id"),
laurent@2041: ("Product code:", "product_code"),
laurent@2041: ("Revision number:", "revision_number")]:
laurent@2041: if details_line.startswith(header):
laurent@2042: slave[param] = details_line.split()[-1]
laurent@2041: break
laurent@2041: slaves.append(slave)
laurent@2041: returnVal = slaves
laurent@2041: """
laurent@2041:
laurent@2041: #--------------------------------------------------
laurent@2041: # Ethercat Node
laurent@2041: #--------------------------------------------------
laurent@2041:
Edouard@2048: class _EthercatSlaveCTN:
laurent@2041:
laurent@2041: NODE_PROFILE = None
laurent@2041: EditorType = NodeEditor
laurent@2034:
laurent@2053: def GetIconPath(self):
laurent@2053: return os.path.join(CONFNODEFOLDER, "images", "Slave.png")
laurent@2043:
laurent@2034: def ExtractHexDecValue(self, value):
laurent@2034: return ExtractHexDecValue(value)
laurent@2041:
laurent@2034: def GetSizeOfType(self, type):
Edouard@2048: return TYPECONVERSION.get(self.GetCTRoot().GetBaseType(type), None)
laurent@2032:
laurent@2041: def GetSlavePos(self):
laurent@2041: return self.BaseParams.getIEC_Channel()
laurent@2032:
laurent@2032: def GetParamsAttributes(self, path = None):
laurent@2041: if path:
laurent@2041: parts = path.split(".", 1)
laurent@2041: if self.MandatoryParams and parts[0] == self.MandatoryParams[0]:
laurent@2041: return self.MandatoryParams[1].getElementInfos(parts[0], parts[1])
Edouard@2048: elif self.CTNParams and parts[0] == self.CTNParams[0]:
Edouard@2048: return self.CTNParams[1].getElementInfos(parts[0], parts[1])
laurent@2041: else:
laurent@2041: params = []
laurent@2041: if wx.VERSION < (2, 8, 0) and self.MandatoryParams:
laurent@2041: params.append(self.MandatoryParams[1].getElementInfos(self.MandatoryParams[0]))
Edouard@2048: slave_type = self.CTNParent.GetSlaveType(self.GetSlavePos())
laurent@2041: params.append({
laurent@2041: 'use': 'required',
laurent@2041: 'type': 'element',
laurent@2041: 'name': 'SlaveParams',
laurent@2041: 'value': None,
laurent@2041: 'children': [{
laurent@2041: 'use': 'optional',
Edouard@2048: 'type': self.CTNParent.GetSlaveTypesLibrary(self.NODE_PROFILE),
laurent@2041: 'name': 'Type',
laurent@2041: 'value': (slave_type["device_type"], slave_type)},
laurent@2041: {'use': 'optional',
laurent@2041: 'type': 'unsignedLong',
laurent@2041: 'name': 'Alias',
Edouard@2048: 'value': self.CTNParent.GetSlaveAlias(self.GetSlavePos())}]
laurent@2041: })
Edouard@2048: if self.CTNParams:
Edouard@2048: params.append(self.CTNParams[1].getElementInfos(self.CTNParams[0]))
laurent@2041: return params
laurent@2041:
laurent@2041: def SetParamsAttribute(self, path, value):
laurent@2041: position = self.BaseParams.getIEC_Channel()
Edouard@2048: value, changed = ConfigTreeNode.SetParamsAttribute(self, path, value)
laurent@2041: # Filter IEC_Channel, Slave_Type and Alias that have specific behavior
laurent@2041: if path == "BaseParams.IEC_Channel":
Edouard@2048: self.CTNParent.SetSlavePosition(position, value)
laurent@2041: elif path == "SlaveParams.Type":
Edouard@2048: self.CTNParent.SetSlaveType(position, value)
Edouard@2048: slave_type = self.CTNParent.GetSlaveType(self.GetSlavePos())
laurent@2041: value = (slave_type["device_type"], slave_type)
laurent@2041: changed = True
laurent@2041: elif path == "SlaveParams.Alias":
Edouard@2048: self.CTNParent.SetSlaveAlias(position, value)
laurent@2041: changed = True
laurent@2041: return value, changed
laurent@2032:
laurent@2034: def GetSlaveInfos(self):
Edouard@2048: return self.CTNParent.GetSlaveInfos(self.GetSlavePos())
laurent@2041:
laurent@2032: def GetVariableLocationTree(self):
laurent@2032: return {"name": self.BaseParams.getName(),
Edouard@2048: "type": LOCATION_CONFNODE,
laurent@2032: "location": self.GetFullIEC_Channel(),
Edouard@2048: "children": self.CTNParent.GetDeviceLocationTree(self.GetSlavePos(), self.GetCurrentLocation(), self.BaseParams.getName())
laurent@2041: }
laurent@2032:
Edouard@2048: def CTNGenerate_C(self, buildpath, locations):
laurent@2032: """
laurent@2032: Generate C code
Edouard@2048: @param current_location: Tupple containing confnode IEC location : %I0.0.4.5 => (0,0,4,5)
laurent@2032: @param locations: List of complete variables locations \
laurent@2032: [{"IEC_TYPE" : the IEC type (i.e. "INT", "STRING", ...)
laurent@2032: "NAME" : name of the variable (generally "__IW0_1_2" style)
laurent@2032: "DIR" : direction "Q","I" or "M"
laurent@2032: "SIZE" : size "X", "B", "W", "D", "L"
laurent@2032: "LOC" : tuple of interger for IEC location (0,1,2,...)
laurent@2032: }, ...]
laurent@2032: @return: [(C_file_name, CFLAGS),...] , LDFLAGS_TO_APPEND
laurent@2032: """
laurent@2041: return [],"",False
laurent@2041:
laurent@2041: #--------------------------------------------------
laurent@2043: # Ethercat CIA402 Node
laurent@2041: #--------------------------------------------------
laurent@2041:
laurent@2041: if HAS_MCL:
laurent@2041:
laurent@2041: NODE_VARIABLES = [
laurent@2041: ("ControlWord", 0x6040, 0x00, "UINT", "Q"),
laurent@2041: ("TargetPosition", 0x607a, 0x00, "DINT", "Q"),
Laurent@2057: # ("ModesOfOperation", 0x06060, 0x00, "SINT", "Q"),
laurent@2041: ("StatusWord", 0x6041, 0x00, "UINT", "I"),
laurent@2041: ("ModesOfOperationDisplay", 0x06061, 0x00, "SINT", "I"),
laurent@2041: ("ActualPosition", 0x6064, 0x00, "DINT", "I"),
laurent@2041: ]
laurent@2041:
Edouard@2048: class _EthercatCIA402SlaveCTN(_EthercatSlaveCTN):
laurent@2041: XSD = """
laurent@2041:
laurent@2043:
laurent@2041:
laurent@2041: %s
laurent@2041:
laurent@2041:
laurent@2041:
laurent@2041: """ % AxisXSD
laurent@2041:
laurent@2041: NODE_PROFILE = 402
laurent@2043: EditorType = CIA402NodeEditor
laurent@2043:
laurent@2053: def GetIconPath(self):
laurent@2053: return os.path.join(CONFNODEFOLDER, "images", "CIA402Slave.png")
laurent@2041:
Edouard@2048: def CTNGenerate_C(self, buildpath, locations):
laurent@2041: """
laurent@2041: Generate C code
Edouard@2048: @param current_location: Tupple containing confnode IEC location : %I0.0.4.5 => (0,0,4,5)
laurent@2041: @param locations: List of complete variables locations \
laurent@2041: [{"IEC_TYPE" : the IEC type (i.e. "INT", "STRING", ...)
laurent@2041: "NAME" : name of the variable (generally "__IW0_1_2" style)
laurent@2041: "DIR" : direction "Q","I" or "M"
laurent@2041: "SIZE" : size "X", "B", "W", "D", "L"
laurent@2041: "LOC" : tuple of interger for IEC location (0,1,2,...)
laurent@2041: }, ...]
laurent@2041: @return: [(C_file_name, CFLAGS),...] , LDFLAGS_TO_APPEND
laurent@2041: """
laurent@2041: current_location = self.GetCurrentLocation()
laurent@2041:
laurent@2041: location_str = "_".join(map(lambda x:str(x), current_location))
laurent@2041:
laurent@2045: plc_cia402node_filepath = os.path.join(os.path.split(__file__)[0], "plc_cia402node.c")
laurent@2045: plc_cia402node_file = open(plc_cia402node_filepath, 'r')
laurent@2045: plc_cia402node_code = plc_cia402node_file.read()
laurent@2045: plc_cia402node_file.close()
laurent@2041:
laurent@2041: str_completion = {
laurent@2041: "location": location_str,
laurent@2041: "MCL_headers": Headers,
laurent@2041: "extern_located_variables_declaration": [],
laurent@2041: "entry_variables": [],
laurent@2041: "init_axis_params": [],
laurent@2041: "init_entry_variables": [],
laurent@2041: }
laurent@2041:
laurent@2041: for variable in NODE_VARIABLES:
laurent@2041: var_infos = dict(zip(["name", "index", "subindex", "var_type", "dir"], variable))
laurent@2041: var_infos["location"] = location_str
laurent@2041: var_infos["var_size"] = self.GetSizeOfType(var_infos["var_type"])
laurent@2041: var_infos["var_name"] = "__%(dir)s%(var_size)s%(location)s_%(index)d_%(subindex)d" % var_infos
laurent@2041:
laurent@2041: str_completion["extern_located_variables_declaration"].append(
laurent@2041: "IEC_%(var_type)s *%(var_name)s;" % var_infos)
laurent@2041: str_completion["entry_variables"].append(
laurent@2041: " IEC_%(var_type)s *%(name)s;" % var_infos)
laurent@2041: str_completion["init_entry_variables"].append(
laurent@2043: " __CIA402Node_%(location)s.%(name)s = %(var_name)s;" % var_infos)
laurent@2041:
Edouard@2048: self.CTNParent.FileGenerator.DeclareVariable(
laurent@2041: self.GetSlavePos(), var_infos["index"], var_infos["subindex"],
laurent@2041: var_infos["var_type"], var_infos["dir"], var_infos["var_name"])
laurent@2041:
Edouard@2048: params = self.CTNParams[1].getElementInfos(self.CTNParams[0])
laurent@2041: for param in params["children"]:
laurent@2041: if param["value"] is not None:
laurent@2041: param_infos = {
laurent@2041: "location": location_str,
laurent@2041: "param_name": param["name"],
laurent@2041: }
laurent@2041: if param["type"] == "boolean":
laurent@2041: param_infos["param_value"] = {True: "true", False: "false"}[param["value"]]
laurent@2041: else:
laurent@2041: param_infos["param_value"] = str(param["value"])
laurent@2041: str_completion["init_axis_params"].append(
laurent@2043: " __CIA402Node_%(location)s.axis->%(param_name)s = %(param_value)s;" % param_infos)
laurent@2041:
laurent@2041: for element in ["extern_located_variables_declaration",
laurent@2041: "entry_variables",
laurent@2041: "init_axis_params",
laurent@2041: "init_entry_variables"]:
laurent@2041: str_completion[element] = "\n".join(str_completion[element])
laurent@2041:
laurent@2045: Gen_CIA402Nodefile_path = os.path.join(buildpath, "cia402node_%s.c"%location_str)
laurent@2045: cia402nodefile = open(Gen_CIA402Nodefile_path, 'w')
laurent@2045: cia402nodefile.write(plc_cia402node_code % str_completion)
laurent@2045: cia402nodefile.close()
laurent@2041:
Edouard@2048: return [(Gen_CIA402Nodefile_path, '"-I%s"'%os.path.abspath(self.GetCTRoot().GetIECLibPath()))],"",True
laurent@2029:
laurent@2022: #--------------------------------------------------
laurent@2022: # Ethercat MASTER
laurent@2022: #--------------------------------------------------
laurent@2022:
laurent@2022: EtherCATConfigClasses = GenerateClassesFromXSD(os.path.join(os.path.dirname(__file__), "EtherCATConfig.xsd"))
laurent@2022:
laurent@2022: def ExtractHexDecValue(value):
laurent@2022: try:
laurent@2022: return int(value)
laurent@2022: except:
laurent@2022: pass
laurent@2022: try:
laurent@2022: return int(value.replace("#", "0"), 16)
laurent@2022: except:
laurent@2029: raise ValueError, "Invalid value for HexDecValue \"%s\"" % value
laurent@2022:
laurent@2022: def GenerateHexDecValue(value, base=10):
laurent@2022: if base == 10:
laurent@2022: return str(value)
laurent@2022: elif base == 16:
laurent@2022: return "#x%.8x" % value
laurent@2022: else:
laurent@2029: raise ValueError, "Not supported base"
laurent@2022:
laurent@2022: cls = EtherCATConfigClasses.get("Config_Slave", None)
laurent@2022: if cls:
laurent@2022:
laurent@2022: def getType(self):
laurent@2022: slave_info = self.getInfo()
laurent@2022: return {"device_type": slave_info.getName(),
laurent@2022: "vendor": GenerateHexDecValue(slave_info.getVendorId()),
laurent@2022: "product_code": GenerateHexDecValue(slave_info.getProductCode(), 16),
laurent@2022: "revision_number": GenerateHexDecValue(slave_info.getRevisionNo(), 16)}
laurent@2022: setattr(cls, "getType", getType)
laurent@2022:
laurent@2022: def setType(self, type_infos):
laurent@2022: slave_info = self.getInfo()
laurent@2022: slave_info.setName(type_infos["device_type"])
laurent@2022: slave_info.setVendorId(ExtractHexDecValue(type_infos["vendor"]))
laurent@2022: slave_info.setProductCode(ExtractHexDecValue(type_infos["product_code"]))
laurent@2022: slave_info.setRevisionNo(ExtractHexDecValue(type_infos["revision_number"]))
laurent@2022: setattr(cls, "setType", setType)
laurent@2022:
Edouard@2048: class _EthercatCTN:
laurent@2022: XSD = """
laurent@2022:
laurent@2022:
laurent@2022:
laurent@2022:
laurent@2022:
laurent@2022:
laurent@2022:
laurent@2022:
laurent@2022: """
laurent@2041:
Edouard@2048: CTNChildrenTypes = [("EthercatSlave", _EthercatSlaveCTN, "Ethercat Slave")]
laurent@2041: if HAS_MCL:
Edouard@2048: CTNChildrenTypes.append(("EthercatCIA402Slave", _EthercatCIA402SlaveCTN, "Ethercat CIA402 Slave"))
laurent@2032:
laurent@2022: def __init__(self):
laurent@2022: filepath = self.ConfigFileName()
laurent@2022:
laurent@2022: self.Config = EtherCATConfigClasses["EtherCATConfig"]()
laurent@2022: if os.path.isfile(filepath):
laurent@2022: xmlfile = open(filepath, 'r')
laurent@2022: tree = minidom.parse(xmlfile)
laurent@2022: xmlfile.close()
laurent@2022:
laurent@2022: for child in tree.childNodes:
laurent@2022: if child.nodeType == tree.ELEMENT_NODE and child.nodeName == "EtherCATConfig":
laurent@2051: self.Config.loadXMLTree(child)
laurent@2022: self.CreateConfigBuffer(True)
laurent@2022: else:
laurent@2022: self.CreateConfigBuffer(False)
Edouard@2048: self.OnCTNSave()
laurent@2022:
laurent@2022: def ExtractHexDecValue(self, value):
laurent@2022: return ExtractHexDecValue(value)
laurent@2022:
laurent@2022: def GetSizeOfType(self, type):
Edouard@2048: return TYPECONVERSION.get(self.GetCTRoot().GetBaseType(type), None)
laurent@2022:
laurent@2022: def ConfigFileName(self):
Edouard@2048: return os.path.join(self.CTNPath(), "config.xml")
laurent@2022:
laurent@2022: def GetSlaves(self):
laurent@2022: slaves = []
laurent@2022: for slave in self.Config.getConfig().getSlave():
laurent@2041: slaves.append(slave.getInfo().getPhysAddr())
laurent@2022: slaves.sort()
laurent@2022: return slaves
laurent@2022:
laurent@2022: def GetSlave(self, slave_pos):
laurent@2022: for slave in self.Config.getConfig().getSlave():
laurent@2022: slave_info = slave.getInfo()
laurent@2041: if slave_info.getPhysAddr() == slave_pos:
laurent@2022: return slave
laurent@2022: return None
laurent@2022:
laurent@2042: def _ScanNetwork(self):
Edouard@2048: app_frame = self.GetCTRoot().AppFrame
laurent@2042:
laurent@2042: execute = True
Edouard@2048: if len(self.Children) > 0:
laurent@2042: dialog = wx.MessageDialog(app_frame,
laurent@2042: _("The current network configuration will be deleted.\nDo you want to continue?"),
laurent@2042: _("Scan Network"),
laurent@2042: wx.YES_NO|wx.ICON_QUESTION)
laurent@2042: execute = dialog.ShowModal() == wx.ID_YES
laurent@2042: dialog.Destroy()
laurent@2042:
laurent@2042: if execute:
laurent@2042: error, returnVal = self.RemoteExec(SCAN_COMMAND, returnVal = None)
laurent@2042: if error != 0:
laurent@2042: dialog = wx.MessageDialog(app_frame, returnVal, "Error", wx.OK|wx.ICON_ERROR)
laurent@2042: dialog.ShowModal()
laurent@2042: dialog.Destroy()
laurent@2042: elif returnVal is not None:
Edouard@2048: for child in self.IECSortedChildren():
laurent@2042: self._doRemoveChild(child)
laurent@2042:
laurent@2042: for slave in returnVal:
laurent@2042: type_infos = {
laurent@2042: "vendor": slave["vendor_id"],
laurent@2042: "product_code": slave["product_code"],
laurent@2042: "revision_number":slave["revision_number"],
laurent@2042: }
laurent@2042: device = self.GetModuleInfos(type_infos)
laurent@2042: if device is not None:
Edouard@2048: if HAS_MCL and _EthercatCIA402SlaveCTN.NODE_PROFILE in device.GetProfileNumbers():
Edouard@2048: CTNType = "EthercatCIA402Slave"
laurent@2042: else:
Edouard@2048: CTNType = "EthercatSlave"
Edouard@2048: self.CTNAddChild("slave%s" % slave["idx"], CTNType, slave["idx"])
laurent@2042: self.SetSlaveAlias(slave["idx"], slave["alias"])
laurent@2042: type_infos["device_type"] = device.getType().getcontent()
laurent@2042: self.SetSlaveType(slave["idx"], type_infos)
laurent@2042:
Edouard@2048: def CTNAddChild(self, CTNName, CTNType, IEC_Channel=0):
laurent@2041: """
Edouard@2048: Create the confnodes that may be added as child to this node self
Edouard@2048: @param CTNType: string desining the confnode class name (get name from CTNChildrenTypes)
Edouard@2048: @param CTNName: string for the name of the confnode instance
laurent@2041: """
Edouard@2048: newConfNodeOpj = ConfigTreeNode.CTNAddChild(self, CTNName, CTNType, IEC_Channel)
Edouard@2048:
Edouard@2048: slave = self.GetSlave(newConfNodeOpj.BaseParams.getIEC_Channel())
laurent@2041: if slave is None:
laurent@2041: slave = EtherCATConfigClasses["Config_Slave"]()
laurent@2041: slave_infos = slave.getInfo()
laurent@2041: slave_infos.setName("undefined")
Edouard@2048: slave_infos.setPhysAddr(newConfNodeOpj.BaseParams.getIEC_Channel())
laurent@2041: slave_infos.setAutoIncAddr(0)
laurent@2041: self.Config.getConfig().appendSlave(slave)
laurent@2041: self.BufferConfig()
Edouard@2048: self.OnCTNSave()
Edouard@2048:
Edouard@2048: return newConfNodeOpj
Edouard@2048:
Edouard@2048: def _doRemoveChild(self, CTNInstance):
Edouard@2048: slave_pos = CTNInstance.GetSlavePos()
laurent@2022: config = self.Config.getConfig()
laurent@2022: for idx, slave in enumerate(config.getSlave()):
laurent@2022: slave_infos = slave.getInfo()
laurent@2041: if slave_infos.getPhysAddr() == slave_pos:
laurent@2022: config.removeSlave(idx)
laurent@2022: self.BufferConfig()
Edouard@2048: self.OnCTNSave()
Edouard@2048: ConfigTreeNode._doRemoveChild(self, CTNInstance)
laurent@2041:
laurent@2041: def SetSlavePosition(self, slave_pos, new_pos):
laurent@2022: slave = self.GetSlave(slave_pos)
laurent@2022: if slave is not None:
laurent@2022: slave_info = slave.getInfo()
laurent@2041: slave_info.setPhysAddr(new_pos)
laurent@2022: self.BufferConfig()
laurent@2041:
laurent@2041: def GetSlaveAlias(self, slave_pos):
laurent@2041: slave = self.GetSlave(slave_pos)
laurent@2041: if slave is not None:
laurent@2041: slave_info = slave.getInfo()
laurent@2041: return slave_info.getAutoIncAddr()
laurent@2022: return None
laurent@2022:
laurent@2041: def SetSlaveAlias(self, slave_pos, alias):
laurent@2041: slave = self.GetSlave(slave_pos)
laurent@2041: if slave is not None:
laurent@2041: slave_info = slave.getInfo()
laurent@2041: slave_info.setAutoIncAddr(alias)
laurent@2041: self.BufferConfig()
laurent@2041:
laurent@2022: def GetSlaveType(self, slave_pos):
laurent@2022: slave = self.GetSlave(slave_pos)
laurent@2022: if slave is not None:
laurent@2022: return slave.getType()
laurent@2022: return None
laurent@2022:
laurent@2022: def SetSlaveType(self, slave_pos, type_infos):
laurent@2022: slave = self.GetSlave(slave_pos)
laurent@2022: if slave is not None:
laurent@2022: slave.setType(type_infos)
laurent@2022: self.BufferConfig()
laurent@2022:
laurent@2022: def GetSlaveInfos(self, slave_pos):
laurent@2022: slave = self.GetSlave(slave_pos)
laurent@2022: if slave is not None:
laurent@2022: type_infos = slave.getType()
laurent@2022: device = self.GetModuleInfos(type_infos)
laurent@2022: if device is not None:
laurent@2022: infos = type_infos.copy()
laurent@2029: entries = device.GetEntriesList()
laurent@2029: entries_list = entries.items()
laurent@2029: entries_list.sort()
laurent@2038: entries = []
laurent@2038: current_index = None
laurent@2038: current_entry = None
laurent@2038: for (index, subindex), entry in entries_list:
laurent@2038: entry["children"] = []
laurent@2038: if index != current_index:
laurent@2038: current_index = index
laurent@2038: current_entry = entry
laurent@2038: entries.append(entry)
laurent@2038: elif current_entry is not None:
laurent@2038: current_entry["children"].append(entry)
laurent@2038: else:
laurent@2038: entries.append(entry)
laurent@2022: infos.update({"physics": device.getPhysics(),
laurent@2029: "sync_managers": device.GetSyncManagers(),
laurent@2038: "entries": entries})
laurent@2022: return infos
laurent@2022: return None
laurent@2022:
laurent@2022: def GetModuleInfos(self, type_infos):
Edouard@2048: return self.CTNParent.GetModuleInfos(type_infos)
laurent@2022:
laurent@2041: def GetSlaveTypesLibrary(self, profile_filter=None):
Edouard@2048: return self.CTNParent.GetModulesLibrary(profile_filter)
laurent@2041:
laurent@2041: def GetDeviceLocationTree(self, slave_pos, current_location, device_name):
laurent@2041: slave = self.GetSlave(slave_pos)
laurent@2041: if slave is not None:
laurent@2041: type_infos = slave.getType()
laurent@2041:
laurent@2041: vars = []
laurent@2041:
laurent@2041: device = self.GetModuleInfos(type_infos)
laurent@2041: if device is not None:
laurent@2041: sync_managers = []
laurent@2041: for sync_manager in device.getSm():
laurent@2041: sync_manager_control_byte = ExtractHexDecValue(sync_manager.getControlByte())
laurent@2041: sync_manager_direction = sync_manager_control_byte & 0x0c
laurent@2041: if sync_manager_direction:
laurent@2041: sync_managers.append(LOCATION_VAR_OUTPUT)
laurent@2041: else:
laurent@2041: sync_managers.append(LOCATION_VAR_INPUT)
laurent@2041:
laurent@2041: entries = device.GetEntriesList().items()
laurent@2041: entries.sort()
laurent@2041: for (index, subindex), entry in entries:
laurent@2041: var_size = self.GetSizeOfType(entry["Type"])
laurent@2041: if var_size is not None:
laurent@2041: var_class = VARCLASSCONVERSION.get(entry["PDOMapping"], None)
laurent@2041: if var_class is not None:
laurent@2041: if var_class == LOCATION_VAR_INPUT:
laurent@2041: var_dir = "%I"
laurent@2041: else:
laurent@2041: var_dir = "%Q"
laurent@2041:
laurent@2041: vars.append({"name": "0x%4.4x-0x%2.2x: %s" % (index, subindex, entry["Name"]),
laurent@2041: "type": var_class,
laurent@2041: "size": var_size,
laurent@2041: "IEC_type": entry["Type"],
laurent@2041: "var_name": "%s_%4.4x_%2.2x" % ("_".join(device_name.split()), index, subindex),
laurent@2041: "location": "%s%s%s"%(var_dir, var_size, ".".join(map(str, current_location +
laurent@2041: (index, subindex)))),
laurent@2041: "description": "",
laurent@2041: "children": []})
laurent@2032:
laurent@2032: return vars
laurent@2032:
Edouard@2048: def CTNTestModified(self):
laurent@2022: return self.ChangesToSave or not self.ConfigIsSaved()
laurent@2022:
Edouard@2048: def OnCTNSave(self):
laurent@2022: filepath = self.ConfigFileName()
laurent@2022:
laurent@2022: text = "\n"
laurent@2022: extras = {"xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance",
laurent@2022: "xsi:noNamespaceSchemaLocation" : "EtherCATInfo.xsd"}
laurent@2022: text += self.Config.generateXMLText("EtherCATConfig", 0, extras)
laurent@2022:
laurent@2022: xmlfile = open(filepath,"w")
laurent@2022: xmlfile.write(text.encode("utf-8"))
laurent@2022: xmlfile.close()
laurent@2022:
laurent@2022: self.ConfigBuffer.CurrentSaved()
laurent@2022: return True
laurent@2022:
laurent@2032: def _Generate_C(self, buildpath, locations):
laurent@2032: current_location = self.GetCurrentLocation()
laurent@2032: # define a unique name for the generated C file
laurent@2032: location_str = "_".join(map(lambda x:str(x), current_location))
laurent@2032:
laurent@2032: Gen_Ethercatfile_path = os.path.join(buildpath, "ethercat_%s.c"%location_str)
laurent@2032:
laurent@2032: self.FileGenerator = _EthercatCFileGenerator(self)
laurent@2032:
Edouard@2048: LocationCFilesAndCFLAGS, LDFLAGS, extra_files = ConfigTreeNode._Generate_C(self, buildpath, locations)
laurent@2032:
laurent@2032: self.FileGenerator.GenerateCFile(Gen_Ethercatfile_path, location_str, self.EtherlabNode)
laurent@2032:
laurent@2032: LocationCFilesAndCFLAGS.append(
laurent@2032: (current_location,
Edouard@2048: [(Gen_Ethercatfile_path, '"-I%s"'%os.path.abspath(self.GetCTRoot().GetIECLibPath()))],
laurent@2032: True))
laurent@2032: LDFLAGS.append("-lethercat -lrtdm")
laurent@2032:
laurent@2032: return LocationCFilesAndCFLAGS, LDFLAGS, extra_files
laurent@2032:
Edouard@2048: ConfNodeMethods = [
Edouard@2048: {"bitmap" : os.path.join(CONFNODEFOLDER, "images", "ScanNetwork"),
laurent@2042: "name" : _("Scan Network"),
laurent@2042: "tooltip" : _("Scan Network"),
laurent@2042: "method" : "_ScanNetwork"},
laurent@2042: ]
laurent@2042:
Edouard@2048: def CTNGenerate_C(self, buildpath, locations):
laurent@2022: """
laurent@2022: Generate C code
Edouard@2048: @param current_location: Tupple containing confnode IEC location : %I0.0.4.5 => (0,0,4,5)
laurent@2022: @param locations: List of complete variables locations \
laurent@2022: [{"IEC_TYPE" : the IEC type (i.e. "INT", "STRING", ...)
laurent@2022: "NAME" : name of the variable (generally "__IW0_1_2" style)
laurent@2022: "DIR" : direction "Q","I" or "M"
laurent@2022: "SIZE" : size "X", "B", "W", "D", "L"
laurent@2022: "LOC" : tuple of interger for IEC location (0,1,2,...)
laurent@2022: }, ...]
laurent@2022: @return: [(C_file_name, CFLAGS),...] , LDFLAGS_TO_APPEND
laurent@2022: """
laurent@2022: current_location = self.GetCurrentLocation()
laurent@2032:
laurent@2032: slaves = self.GetSlaves()
laurent@2032: for slave_pos in slaves:
laurent@2032: slave = self.GetSlave(slave_pos)
laurent@2032: if slave is not None:
laurent@2041: self.FileGenerator.DeclareSlave(slave_pos, slave.getInfo().getAutoIncAddr(), slave.getType())
laurent@2022:
laurent@2022: for location in locations:
laurent@2022: loc = location["LOC"][len(current_location):]
laurent@2041: slave_pos = loc[0]
laurent@2041: if slave_pos in slaves and len(loc) == 3:
laurent@2032: self.FileGenerator.DeclareVariable(
laurent@2041: slave_pos, loc[1], loc[2], location["IEC_TYPE"], location["DIR"], location["NAME"])
laurent@2032:
laurent@2032: return [],"",False
laurent@2032:
laurent@2022: #-------------------------------------------------------------------------------
laurent@2022: # Current Buffering Management Functions
laurent@2022: #-------------------------------------------------------------------------------
laurent@2022:
laurent@2022: """
laurent@2022: Return a copy of the config
laurent@2022: """
laurent@2022: def Copy(self, model):
laurent@2022: return cPickle.loads(cPickle.dumps(model))
laurent@2022:
laurent@2022: def CreateConfigBuffer(self, saved):
laurent@2022: self.ConfigBuffer = UndoBuffer(cPickle.dumps(self.Config), saved)
laurent@2022:
laurent@2022: def BufferConfig(self):
laurent@2022: self.ConfigBuffer.Buffering(cPickle.dumps(self.Config))
laurent@2022:
laurent@2022: def ConfigIsSaved(self):
laurent@2022: if self.ConfigBuffer is not None:
laurent@2022: return self.ConfigBuffer.IsCurrentSaved()
laurent@2022: else:
laurent@2022: return True
laurent@2022:
laurent@2022: def LoadPrevious(self):
laurent@2022: self.Config = cPickle.loads(self.ConfigBuffer.Previous())
laurent@2022:
laurent@2022: def LoadNext(self):
laurent@2022: self.Config = cPickle.loads(self.ConfigBuffer.Next())
laurent@2022:
laurent@2022: def GetBufferState(self):
laurent@2022: first = self.ConfigBuffer.IsFirst()
laurent@2022: last = self.ConfigBuffer.IsLast()
laurent@2022: return not first, not last
laurent@2022:
laurent@2022:
laurent@2022: SLAVE_PDOS_CONFIGURATION_DECLARATION = """
laurent@2022: /* Slave %(slave)d, "%(device_type)s"
laurent@2022: * Vendor ID: 0x%(vendor).8x
laurent@2022: * Product code: 0x%(product_code).8x
laurent@2022: * Revision number: 0x%(revision_number).8x
laurent@2022: */
laurent@2022:
laurent@2022: ec_pdo_entry_info_t slave_%(slave)d_pdo_entries[] = {
laurent@2022: %(pdos_entries_infos)s
laurent@2022: };
laurent@2022:
laurent@2022: ec_pdo_info_t slave_%(slave)d_pdos[] = {
laurent@2022: %(pdos_infos)s
laurent@2022: };
laurent@2022:
laurent@2022: ec_sync_info_t slave_%(slave)d_syncs[] = {
laurent@2022: %(pdos_sync_infos)s
laurent@2022: {0xff}
laurent@2022: };
laurent@2022: """
laurent@2022:
laurent@2022: SLAVE_CONFIGURATION_TEMPLATE = """
laurent@2022: if (!(slave%(slave)d = ecrt_master_slave_config(master, %(alias)d, %(position)d, 0x%(vendor).8x, 0x%(product_code).8x))) {
laurent@2022: fprintf(stderr, "Failed to get slave %(device_type)s configuration at alias %(alias)d and position %(position)d.\\n");
laurent@2022: return -1;
laurent@2022: }
laurent@2022:
laurent@2022: if (ecrt_slave_config_pdos(slave%(slave)d, EC_END, slave_%(slave)d_syncs)) {
laurent@2022: fprintf(stderr, "Failed to configure PDOs for slave %(device_type)s at alias %(alias)d and position %(position)d.\\n");
laurent@2022: return -1;
laurent@2022: }
laurent@2022: """
laurent@2022:
laurent@2032: SLAVE_INITIALIZATION_TEMPLATE = """
laurent@2032: {
laurent@2032: uint8_t value[] = {%(data)s};
laurent@2032: if (ecrt_master_sdo_download(master, %(slave)d, 0x%(index).4x, 0x%(subindex).2x, (uint8_t *)value, %(data_size)d, &abort_code)) {
laurent@2032: fprintf(stderr, "Failed to initialize slave %(device_type)s at alias %(alias)d and position %(position)d.\\nError: %%d\\n", abort_code);
laurent@2032: return -1;
laurent@2032: }
laurent@2032: }
laurent@2032: """
laurent@2032:
laurent@2039: SLAVE_OUTPUT_PDO_DEFAULT_VALUE = """
laurent@2039: {
laurent@2039: uint8_t value[%(data_size)d];
laurent@2039: if (ecrt_master_sdo_upload(master, %(slave)d, 0x%(index).4x, 0x%(subindex).2x, (uint8_t *)value, %(data_size)d, &result_size, &abort_code)) {
laurent@2039: fprintf(stderr, "Failed to get default value for output PDO in slave %(device_type)s at alias %(alias)d and position %(position)d.\\nError: %%d\\n", abort_code);
laurent@2039: return -1;
laurent@2039: }
laurent@2039: for (i = 0; i < result_size; i++) {
laurent@2039: %(real_var)s = (%(real_var)s << 8) + value[i];
laurent@2039: }
laurent@2039: }
laurent@2039: """
laurent@2039:
laurent@2029: def ConfigureVariable(entry_infos, str_completion):
laurent@2032: entry_infos["data_type"] = DATATYPECONVERSION.get(entry_infos["var_type"], None)
laurent@2032: if entry_infos["data_type"] is None:
laurent@2029: raise ValueError, _("Type of location \"%s\" not yet supported!") % entry_infos["var_name"]
laurent@2039:
laurent@2039: if entry_infos.has_key("real_var"):
laurent@2039: str_completion["located_variables_declaration"].append(
laurent@2039: "IEC_%(var_type)s %(real_var)s;" % entry_infos)
laurent@2039: else:
laurent@2039: entry_infos["real_var"] = "beremiz" + entry_infos["var_name"]
laurent@2039: str_completion["located_variables_declaration"].extend(
laurent@2039: ["IEC_%(var_type)s %(real_var)s;" % entry_infos,
laurent@2039: "IEC_%(var_type)s *%(var_name)s = &%(real_var)s;" % entry_infos])
laurent@2034:
laurent@2034: str_completion["used_pdo_entry_offset_variables_declaration"].append(
laurent@2034: "unsigned int slave%(slave)d_%(index).4x_%(subindex).2x;" % entry_infos)
laurent@2032:
laurent@2032: if entry_infos["data_type"] == "BIT":
laurent@2034: str_completion["used_pdo_entry_offset_variables_declaration"].append(
laurent@2034: "unsigned int slave%(slave)d_%(index).4x_%(subindex).2x_bit;" % entry_infos)
laurent@2034:
laurent@2034: str_completion["used_pdo_entry_configuration"].append(
laurent@2034: (" {%(alias)d, %(position)d, 0x%(vendor).8x, 0x%(product_code).8x, " +
laurent@2034: "0x%(index).4x, %(subindex)d, &slave%(slave)d_%(index).4x_%(subindex).2x, " +
laurent@2034: "&slave%(slave)d_%(index).4x_%(subindex).2x_bit},") % entry_infos)
laurent@2034:
laurent@2032: if entry_infos["dir"] == "I":
laurent@2032: str_completion["retrieve_variables"].append(
laurent@2032: (" %(real_var)s = EC_READ_BIT(domain1_pd + slave%(slave)d_%(index).4x_%(subindex).2x, " +
laurent@2032: "slave%(slave)d_%(index).4x_%(subindex).2x_bit);") % entry_infos)
laurent@2032: elif entry_infos["dir"] == "Q":
laurent@2032: str_completion["publish_variables"].append(
laurent@2032: (" EC_WRITE_BIT(domain1_pd + slave%(slave)d_%(index).4x_%(subindex).2x, " +
laurent@2032: "slave%(slave)d_%(index).4x_%(subindex).2x_bit, %(real_var)s);") % entry_infos)
laurent@2032:
laurent@2032: else:
laurent@2034: str_completion["used_pdo_entry_configuration"].append(
laurent@2034: (" {%(alias)d, %(position)d, 0x%(vendor).8x, 0x%(product_code).8x, 0x%(index).4x, " +
laurent@2034: "%(subindex)d, &slave%(slave)d_%(index).4x_%(subindex).2x},") % entry_infos)
laurent@2034:
laurent@2032: if entry_infos["dir"] == "I":
laurent@2032: str_completion["retrieve_variables"].append(
laurent@2032: (" %(real_var)s = EC_READ_%(data_type)s(domain1_pd + " +
laurent@2032: "slave%(slave)d_%(index).4x_%(subindex).2x);") % entry_infos)
laurent@2032: elif entry_infos["dir"] == "Q":
laurent@2032: str_completion["publish_variables"].append(
laurent@2032: (" EC_WRITE_%(data_type)s(domain1_pd + slave%(slave)d_%(index).4x_%(subindex).2x, " +
laurent@2032: "%(real_var)s);") % entry_infos)
laurent@2032:
laurent@2022: class _EthercatCFileGenerator:
laurent@2022:
laurent@2032: def __init__(self, controler):
laurent@2022: self.Controler = controler
laurent@2032:
laurent@2032: self.Slaves = []
laurent@2022: self.UsedVariables = {}
laurent@2032:
laurent@2022: def __del__(self):
laurent@2032: self.Controler = None
laurent@2032:
laurent@2041: def DeclareSlave(self, slave_index, slave_alias, slave):
laurent@2041: self.Slaves.append((slave_index, slave_alias, slave))
laurent@2041:
laurent@2041: def DeclareVariable(self, slave_index, index, subindex, iec_type, dir, name):
laurent@2041: slave_variables = self.UsedVariables.setdefault(slave_index, {})
laurent@2022:
laurent@2022: entry_infos = slave_variables.get((index, subindex), None)
laurent@2022: if entry_infos is None:
laurent@2029: slave_variables[(index, subindex)] = {
laurent@2029: "infos": (iec_type, dir, name),
laurent@2029: "mapped": False}
laurent@2029: elif entry_infos["infos"] != (iec_type, dir, name):
laurent@2022: raise ValueError, _("Definition conflict for location \"%s\"") % name
laurent@2029:
laurent@2032: def GenerateCFile(self, filepath, location_str, etherlab_node_infos):
laurent@2022:
laurent@2022: plc_etherlab_filepath = os.path.join(os.path.split(__file__)[0], "plc_etherlab.c")
laurent@2022: plc_etherlab_file = open(plc_etherlab_filepath, 'r')
laurent@2022: plc_etherlab_code = plc_etherlab_file.read()
laurent@2022: plc_etherlab_file.close()
laurent@2022:
laurent@2022: str_completion = {
laurent@2022: "location": location_str,
laurent@2032: "configure_pdos": int(etherlab_node_infos.getConfigurePDOs()),
laurent@2032: "master_number": etherlab_node_infos.getMasterNumber(),
laurent@2022: "located_variables_declaration": [],
laurent@2022: "used_pdo_entry_offset_variables_declaration": [],
laurent@2022: "used_pdo_entry_configuration": [],
laurent@2022: "pdos_configuration_declaration": "",
laurent@2022: "slaves_declaration": "",
laurent@2022: "slaves_configuration": "",
laurent@2039: "slaves_output_pdos_default_values_extraction": "",
laurent@2032: "slaves_initialization": "",
laurent@2022: "retrieve_variables": [],
laurent@2022: "publish_variables": [],
laurent@2022: }
laurent@2022:
laurent@2029: for slave_entries in self.UsedVariables.itervalues():
laurent@2029: for entry_infos in slave_entries.itervalues():
laurent@2029: entry_infos["mapped"] = False
laurent@2029:
laurent@2041: self.Slaves.sort()
laurent@2041: alias = {}
laurent@2041: for (slave_idx, slave_alias, type_infos) in self.Slaves:
laurent@2041: if alias.get(slave_alias) is not None:
laurent@2041: alias[slave_alias] += 1
laurent@2041: else:
laurent@2041: alias[slave_alias] = 0
laurent@2041: slave_pos = (slave_alias, alias[slave_alias])
laurent@2032:
laurent@2032: device = self.Controler.GetModuleInfos(type_infos)
laurent@2032: if device is not None:
laurent@2032:
laurent@2041: slave_variables = self.UsedVariables.get(slave_idx, {})
laurent@2032: device_entries = device.GetEntriesList()
laurent@2022:
laurent@2032: if len(device.getTxPdo() + device.getRxPdo()) > 0 or len(slave_variables) > 0:
laurent@2022:
laurent@2032: for element in ["vendor", "product_code", "revision_number"]:
laurent@2032: type_infos[element] = ExtractHexDecValue(type_infos[element])
laurent@2032: type_infos.update(dict(zip(["slave", "alias", "position"], (slave_idx,) + slave_pos)))
laurent@2032:
laurent@2032: str_completion["slaves_declaration"] += "static ec_slave_config_t *slave%(slave)d = NULL;\n" % type_infos
laurent@2032: str_completion["slaves_configuration"] += SLAVE_CONFIGURATION_TEMPLATE % type_infos
laurent@2032:
laurent@2032: for initCmd in device.getInitCmd():
laurent@2032: index = ExtractHexDecValue(initCmd.getIndex())
laurent@2032: subindex = ExtractHexDecValue(initCmd.getSubIndex())
laurent@2032: entry = device_entries.get((index, subindex), None)
laurent@2032: if entry is not None:
laurent@2032: data_size = entry["BitSize"] / 8
laurent@2032: data = ("%%.%dx" % (data_size * 2)) % initCmd.getData().getcontent()
laurent@2032: data_str = ",".join(["0x%s" % data[i:i+2] for i in xrange(0, data_size * 2, 2)])
laurent@2032: init_cmd_infos = {
laurent@2032: "index": index,
laurent@2032: "subindex": subindex,
laurent@2032: "data": data_str,
laurent@2032: "data_size": data_size
laurent@2032: }
laurent@2032: init_cmd_infos.update(type_infos)
laurent@2032: str_completion["slaves_initialization"] += SLAVE_INITIALIZATION_TEMPLATE % init_cmd_infos
laurent@2032:
laurent@2032: pdos_infos = {
laurent@2032: "pdos_entries_infos": [],
laurent@2032: "pdos_infos": [],
laurent@2032: "pdos_sync_infos": [],
laurent@2032: }
laurent@2032: pdos_infos.update(type_infos)
laurent@2032:
laurent@2032: sync_managers = []
laurent@2032: for sync_manager_idx, sync_manager in enumerate(device.getSm()):
laurent@2032: sync_manager_infos = {
laurent@2032: "index": sync_manager_idx,
laurent@2032: "name": sync_manager.getcontent(),
laurent@2032: "slave": slave_idx,
laurent@2032: "pdos": [],
laurent@2032: "pdos_number": 0,
laurent@2032: }
laurent@2022:
laurent@2032: sync_manager_control_byte = ExtractHexDecValue(sync_manager.getControlByte())
laurent@2032: sync_manager_direction = sync_manager_control_byte & 0x0c
laurent@2032: sync_manager_watchdog = sync_manager_control_byte & 0x40
laurent@2032: if sync_manager_direction:
laurent@2032: sync_manager_infos["sync_manager_type"] = "EC_DIR_OUTPUT"
laurent@2032: else:
laurent@2032: sync_manager_infos["sync_manager_type"] = "EC_DIR_INPUT"
laurent@2032: if sync_manager_watchdog:
laurent@2032: sync_manager_infos["watchdog"] = "EC_WD_ENABLE"
laurent@2032: else:
laurent@2032: sync_manager_infos["watchdog"] = "EC_WD_DISABLE"
laurent@2032:
laurent@2032: sync_managers.append(sync_manager_infos)
laurent@2022:
laurent@2032: pdos_index = []
laurent@2034: excluded_pdos = []
laurent@2032: for only_mandatory in [True, False]:
laurent@2032: for pdo, pdo_type in ([(pdo, "Inputs") for pdo in device.getTxPdo()] +
laurent@2032: [(pdo, "Outputs") for pdo in device.getRxPdo()]):
laurent@2032: entries = pdo.getEntry()
laurent@2032:
laurent@2032: pdo_needed = pdo.getMandatory()
laurent@2032: if pdo_needed is None:
laurent@2032: pdo_needed = False
laurent@2032: if only_mandatory != pdo_needed:
laurent@2032: continue
laurent@2032:
laurent@2032: pdo_index = ExtractHexDecValue(pdo.getIndex().getcontent())
laurent@2032: pdos_index.append(pdo_index)
laurent@2034: if pdo_index in excluded_pdos:
laurent@2034: continue
laurent@2034:
laurent@2032: entries_infos = []
laurent@2032:
laurent@2032: for entry in entries:
laurent@2032: index = ExtractHexDecValue(entry.getIndex().getcontent())
laurent@2032: subindex = ExtractHexDecValue(entry.getSubIndex())
laurent@2029: entry_infos = {
laurent@2029: "index": index,
laurent@2029: "subindex": subindex,
laurent@2032: "name": ExtractName(entry.getName()),
laurent@2032: "bitlen": entry.getBitLen(),
laurent@2023: }
laurent@2029: entry_infos.update(type_infos)
laurent@2032: entries_infos.append(" {0x%(index).4x, 0x%(subindex).2x, %(bitlen)d}, /* %(name)s */" % entry_infos)
laurent@2029:
laurent@2032: entry_declaration = slave_variables.get((index, subindex), None)
laurent@2032: if entry_declaration is not None and not entry_declaration["mapped"]:
laurent@2032: pdo_needed = True
laurent@2032:
laurent@2032: entry_infos.update(dict(zip(["var_type", "dir", "var_name"], entry_declaration["infos"])))
laurent@2032: entry_declaration["mapped"] = True
laurent@2032:
laurent@2045: entry_type = entry.getDataType().getcontent()
laurent@2045: if entry_infos["var_type"] != entry_type:
laurent@2045: message = _("Wrong type for location \"%s\"!") % entry_infos["var_name"]
laurent@2045: if (self.Controler.GetSizeOfType(entry_infos["var_type"]) !=
laurent@2045: self.Controler.GetSizeOfType(entry_type)):
laurent@2045: raise ValueError, message
laurent@2045: else:
Edouard@2048: self.Controler.GetCTRoot().logger.write_warning(message + "\n")
laurent@2032:
laurent@2032: if (entry_infos["dir"] == "I" and pdo_type != "Inputs" or
laurent@2032: entry_infos["dir"] == "Q" and pdo_type != "Outputs"):
laurent@2032: raise ValueError, _("Wrong direction for location \"%s\"!") % entry_infos["var_name"]
laurent@2032:
laurent@2034: ConfigureVariable(entry_infos, str_completion)
laurent@2039:
laurent@2039: elif pdo_type == "Outputs" and entry.getDataType() is not None:
laurent@2039: entry_infos["dir"] = "Q"
laurent@2039: entry_infos["data_size"] = max(1, entry_infos["bitlen"] / 8)
laurent@2039: entry_infos["var_type"] = entry.getDataType().getcontent()
laurent@2039: entry_infos["real_var"] = "slave%(slave)d_%(index).4x_%(subindex).2x_default" % entry_infos
laurent@2039:
laurent@2039: ConfigureVariable(entry_infos, str_completion)
laurent@2039:
laurent@2039: str_completion["slaves_output_pdos_default_values_extraction"] += \
laurent@2039: SLAVE_OUTPUT_PDO_DEFAULT_VALUE % entry_infos
laurent@2034:
laurent@2032: if pdo_needed:
laurent@2034: for excluded in pdo.getExclude():
laurent@2034: excluded_index = ExtractHexDecValue(excluded.getcontent())
laurent@2034: if excluded_index not in excluded_pdos:
laurent@2034: excluded_pdos.append(excluded_index)
laurent@2034:
laurent@2032: sm = pdo.getSm()
laurent@2032: if sm is None:
laurent@2032: for sm_idx, sync_manager in enumerate(sync_managers):
laurent@2032: if sync_manager["name"] == pdo_type:
laurent@2032: sm = sm_idx
laurent@2032: if sm is None:
laurent@2032: raise ValueError, _("No sync manager available for %s pdo!") % pdo_type
laurent@2032:
laurent@2032: sync_managers[sm]["pdos_number"] += 1
laurent@2032: sync_managers[sm]["pdos"].append(
laurent@2032: {"slave": slave_idx,
laurent@2032: "index": pdo_index,
laurent@2032: "name": ExtractName(pdo.getName()),
laurent@2032: "type": pdo_type,
laurent@2032: "entries": entries_infos,
laurent@2032: "entries_number": len(entries_infos),
laurent@2032: "fixed": pdo.getFixed() == True})
laurent@2032:
laurent@2032: dynamic_pdos = {}
laurent@2032: dynamic_pdos_number = 0
laurent@2032: for category, min_index, max_index in [("Inputs", 0x1600, 0x1800),
laurent@2032: ("Outputs", 0x1a00, 0x1C00)]:
laurent@2032: for sync_manager in sync_managers:
laurent@2032: if sync_manager["name"] == category:
laurent@2032: category_infos = dynamic_pdos.setdefault(category, {})
laurent@2032: category_infos["sync_manager"] = sync_manager
laurent@2032: category_infos["pdos"] = [pdo for pdo in category_infos["sync_manager"]["pdos"]
laurent@2032: if not pdo["fixed"] and pdo["type"] == category]
laurent@2032: category_infos["current_index"] = min_index
laurent@2032: category_infos["max_index"] = max_index
laurent@2032: break
laurent@2032:
laurent@2032: for (index, subindex), entry_declaration in slave_variables.iteritems():
laurent@2032:
laurent@2032: if not entry_declaration["mapped"]:
laurent@2032: entry = device_entries.get((index, subindex), None)
laurent@2032: if entry is None:
laurent@2032: raise ValueError, _("Unknown entry index 0x%4.4x, subindex 0x%2.2x for device %s") % \
laurent@2032: (index, subindex, type_infos["device_type"])
laurent@2032:
laurent@2032: entry_infos = {
laurent@2032: "index": index,
laurent@2032: "subindex": subindex,
laurent@2032: "name": entry["Name"],
laurent@2032: "bitlen": entry["BitSize"],
laurent@2032: }
laurent@2032: entry_infos.update(type_infos)
laurent@2032:
laurent@2032: entry_infos.update(dict(zip(["var_type", "dir", "var_name", "real_var"], entry_declaration["infos"])))
laurent@2032: entry_declaration["mapped"] = True
laurent@2032:
laurent@2032: if entry_infos["var_type"] != entry["Type"]:
laurent@2045: message = _("Wrong type for location \"%s\"!") % entry_infos["var_name"]
laurent@2045: if (self.Controler.GetSizeOfType(entry_infos["var_type"]) !=
laurent@2045: self.Controler.GetSizeOfType(entry["Type"])):
laurent@2045: raise ValueError, message
laurent@2045: else:
Edouard@2048: self.Controler.GetCTRoot().logger.write_warning(message + "\n")
laurent@2032:
laurent@2032: if entry_infos["dir"] == "I" and entry["PDOMapping"] in ["T", "RT"]:
laurent@2032: pdo_type = "Inputs"
laurent@2032: elif entry_infos["dir"] == "Q" and entry["PDOMapping"] in ["R", "RT"]:
laurent@2032: pdo_type = "Outputs"
laurent@2032: else:
laurent@2032: raise ValueError, _("Wrong direction for location \"%s\"!") % entry_infos["var_name"]
laurent@2032:
laurent@2032: if not dynamic_pdos.has_key(pdo_type):
laurent@2032: raise ValueError, _("No Sync manager defined for %s!") % pdo_type
laurent@2032:
laurent@2034: ConfigureVariable(entry_infos, str_completion)
laurent@2032:
laurent@2032: if len(dynamic_pdos[pdo_type]["pdos"]) > 0:
laurent@2032: pdo = dynamic_pdos[pdo_type]["pdos"][0]
laurent@2032: else:
laurent@2032: while dynamic_pdos[pdo_type]["current_index"] in pdos_index:
laurent@2032: dynamic_pdos[pdo_type]["current_index"] += 1
laurent@2032: if dynamic_pdos[pdo_type]["current_index"] >= dynamic_pdos[pdo_type]["max_index"]:
laurent@2032: raise ValueError, _("No more free PDO index available for %s!") % pdo_type
laurent@2032: pdos_index.append(dynamic_pdos[pdo_type]["current_index"])
laurent@2029:
laurent@2032: dynamic_pdos_number += 1
laurent@2032: pdo = {"slave": slave_idx,
laurent@2032: "index": dynamic_pdos[pdo_type]["current_index"],
laurent@2032: "name": "Dynamic PDO %d" % dynamic_pdos_number,
laurent@2032: "type": pdo_type,
laurent@2032: "entries": [],
laurent@2032: "entries_number": 0,
laurent@2032: "fixed": False}
laurent@2032: dynamic_pdos[pdo_type]["sync_manager"]["pdos_number"] += 1
laurent@2032: dynamic_pdos[pdo_type]["sync_manager"]["pdos"].append(pdo)
laurent@2032: dynamic_pdos[pdo_type]["pdos"].append(pdo)
laurent@2032:
laurent@2032: pdo["entries"].append(" {0x%(index).4x, 0x%(subindex).2x, %(bitlen)d}, /* %(name)s */" % entry_infos)
laurent@2032: pdo["entries_number"] += 1
laurent@2032:
laurent@2032: if pdo["entries_number"] == 255:
laurent@2032: dynamic_pdos[pdo_type]["pdos"].pop(0)
laurent@2032:
laurent@2032: pdo_offset = 0
laurent@2032: entry_offset = 0
laurent@2032: for sync_manager_infos in sync_managers:
laurent@2022:
laurent@2032: for pdo_infos in sync_manager_infos["pdos"]:
laurent@2032: pdo_infos["offset"] = entry_offset
laurent@2032: pdo_entries = pdo_infos["entries"]
laurent@2032: pdos_infos["pdos_infos"].append(
laurent@2032: (" {0x%(index).4x, %(entries_number)d, " +
laurent@2032: "slave_%(slave)d_pdo_entries + %(offset)d}, /* %(name)s */") % pdo_infos)
laurent@2032: entry_offset += len(pdo_entries)
laurent@2032: pdos_infos["pdos_entries_infos"].extend(pdo_entries)
laurent@2022:
laurent@2032: sync_manager_infos["offset"] = pdo_offset
edouard_and_laurent@2047: pdo_offset_shift = sync_manager_infos["pdos_number"]
laurent@2032: pdos_infos["pdos_sync_infos"].append(
laurent@2032: (" {%(index)d, %(sync_manager_type)s, %(pdos_number)d, " +
edouard_and_laurent@2047: ("slave_%(slave)d_pdos + %(offset)d" if pdo_offset_shift else "NULL") +
edouard_and_laurent@2047: ", %(watchdog)s},") % sync_manager_infos)
edouard_and_laurent@2047: pdo_offset += pdo_offset_shift
laurent@2032:
laurent@2032: for element in ["pdos_entries_infos", "pdos_infos", "pdos_sync_infos"]:
laurent@2032: pdos_infos[element] = "\n".join(pdos_infos[element])
laurent@2032:
laurent@2032: str_completion["pdos_configuration_declaration"] += SLAVE_PDOS_CONFIGURATION_DECLARATION % pdos_infos
laurent@2022:
laurent@2023: for element in ["used_pdo_entry_offset_variables_declaration",
laurent@2023: "used_pdo_entry_configuration",
laurent@2023: "located_variables_declaration",
laurent@2023: "retrieve_variables",
laurent@2023: "publish_variables"]:
laurent@2022: str_completion[element] = "\n".join(str_completion[element])
laurent@2022:
laurent@2032: etherlabfile = open(filepath, 'w')
laurent@2022: etherlabfile.write(plc_etherlab_code % str_completion)
laurent@2022: etherlabfile.close()
laurent@2022:
laurent@2022: #--------------------------------------------------
Edouard@2048: # Ethercat ConfNode
laurent@2022: #--------------------------------------------------
laurent@2022:
laurent@2022: EtherCATInfoClasses = GenerateClassesFromXSD(os.path.join(os.path.dirname(__file__), "EtherCATInfo.xsd"))
laurent@2022:
laurent@2029: cls = EtherCATInfoClasses["EtherCATInfo.xsd"].get("DeviceType", None)
laurent@2029: if cls:
laurent@2029: cls.DataTypes = None
laurent@2029:
laurent@2032: def GetProfileNumbers(self):
laurent@2032: profiles = []
laurent@2032:
laurent@2032: for profile in self.getProfile():
laurent@2032: profile_content = profile.getcontent()
laurent@2032: if profile_content is None:
laurent@2032: continue
laurent@2032:
laurent@2032: for content_element in profile_content["value"]:
laurent@2032: if content_element["name"] == "ProfileNo":
laurent@2032: profiles.append(content_element["value"])
laurent@2032:
laurent@2032: return profiles
laurent@2032: setattr(cls, "GetProfileNumbers", GetProfileNumbers)
laurent@2032:
laurent@2029: def GetProfileDictionaries(self):
laurent@2029: dictionaries = []
laurent@2029:
laurent@2029: for profile in self.getProfile():
laurent@2029:
laurent@2029: profile_content = profile.getcontent()
laurent@2029: if profile_content is None:
laurent@2031: continue
laurent@2029:
laurent@2029: for content_element in profile_content["value"]:
laurent@2029: if content_element["name"] == "Dictionary":
laurent@2029: dictionaries.append(content_element["value"])
laurent@2029: elif content_element["name"] == "DictionaryFile":
laurent@2029: raise ValueError, "DictionaryFile for defining Device Profile is not yet supported!"
laurent@2029:
laurent@2029: return dictionaries
laurent@2029: setattr(cls, "GetProfileDictionaries", GetProfileDictionaries)
laurent@2029:
laurent@2029: def ExtractDataTypes(self):
laurent@2029: self.DataTypes = {}
laurent@2029:
laurent@2029: for dictionary in self.GetProfileDictionaries():
laurent@2029:
laurent@2029: datatypes = dictionary.getDataTypes()
laurent@2029: if datatypes is not None:
laurent@2029:
laurent@2029: for datatype in datatypes.getDataType():
laurent@2029: content = datatype.getcontent()
laurent@2029: if content is not None and content["name"] == "SubItem":
laurent@2029: self.DataTypes[datatype.getName()] = datatype
laurent@2029:
laurent@2029: setattr(cls, "ExtractDataTypes", ExtractDataTypes)
laurent@2029:
laurent@2032: def getInitCmd(self):
laurent@2032: mailbox = self.getMailbox()
laurent@2032: if mailbox is None:
laurent@2032: return []
laurent@2032:
laurent@2032: coe = mailbox.getCoE()
laurent@2032: if coe is None:
laurent@2032: return []
laurent@2032:
laurent@2032: return coe.getInitCmd()
laurent@2032: setattr(cls, "getInitCmd", getInitCmd)
laurent@2032:
laurent@2029: def GetEntriesList(self):
laurent@2029: if self.DataTypes is None:
laurent@2029: self.ExtractDataTypes()
laurent@2029:
laurent@2029: entries = {}
laurent@2029:
laurent@2029: for dictionary in self.GetProfileDictionaries():
laurent@2029:
laurent@2029: for object in dictionary.getObjects().getObject():
laurent@2029: entry_index = object.getIndex().getcontent()
laurent@2029: index = ExtractHexDecValue(entry_index)
laurent@2029: entry_type = object.getType()
laurent@2029: entry_name = ExtractName(object.getName())
laurent@2029:
laurent@2029: entry_type_infos = self.DataTypes.get(entry_type, None)
laurent@2029: if entry_type_infos is not None:
laurent@2029: content = entry_type_infos.getcontent()
laurent@2029: for subitem in content["value"]:
laurent@2029: entry_subidx = subitem.getSubIdx()
laurent@2029: if entry_subidx is None:
laurent@2029: entry_subidx = "0"
laurent@2029: subidx = ExtractHexDecValue(entry_subidx)
laurent@2029: subitem_access = ""
laurent@2032: subitem_pdomapping = ""
laurent@2029: subitem_flags = subitem.getFlags()
laurent@2029: if subitem_flags is not None:
laurent@2029: access = subitem_flags.getAccess()
laurent@2029: if access is not None:
laurent@2029: subitem_access = access.getcontent()
laurent@2032: pdomapping = subitem_flags.getPdoMapping()
laurent@2032: if pdomapping is not None:
laurent@2032: subitem_pdomapping = pdomapping.upper()
laurent@2029: entries[(index, subidx)] = {
laurent@2029: "Index": entry_index,
laurent@2029: "SubIndex": entry_subidx,
laurent@2029: "Name": "%s - %s" %
laurent@2029: (entry_name.decode("utf-8"),
laurent@2029: ExtractName(subitem.getDisplayName(),
laurent@2029: subitem.getName()).decode("utf-8")),
laurent@2029: "Type": subitem.getType(),
laurent@2029: "BitSize": subitem.getBitSize(),
laurent@2029: "Access": subitem_access,
laurent@2032: "PDOMapping": subitem_pdomapping,
laurent@2029: "PDO index": "",
laurent@2029: "PDO name": "",
laurent@2029: "PDO type": ""}
laurent@2029: else:
laurent@2029: entry_access = ""
laurent@2032: entry_pdomapping = ""
laurent@2029: entry_flags = object.getFlags()
laurent@2029: if entry_flags is not None:
laurent@2029: access = entry_flags.getAccess()
laurent@2029: if access is not None:
laurent@2029: entry_access = access.getcontent()
laurent@2032: pdomapping = entry_flags.getPdoMapping()
laurent@2032: if pdomapping is not None:
laurent@2032: entry_pdomapping = pdomapping.upper()
laurent@2029: entries[(index, 0)] = {
laurent@2029: "Index": entry_index,
laurent@2029: "SubIndex": "0",
laurent@2029: "Name": entry_name,
laurent@2029: "Type": entry_type,
laurent@2029: "BitSize": object.getBitSize(),
laurent@2029: "Access": entry_access,
laurent@2032: "PDOMapping": entry_pdomapping,
laurent@2029: "PDO index": "",
laurent@2029: "PDO name": "",
laurent@2029: "PDO type": ""}
laurent@2029:
laurent@2029: for TxPdo in self.getTxPdo():
laurent@2029: ExtractPdoInfos(TxPdo, "Transmit", entries)
laurent@2029: for RxPdo in self.getRxPdo():
laurent@2029: ExtractPdoInfos(RxPdo, "Receive", entries)
laurent@2029:
laurent@2029: return entries
laurent@2029: setattr(cls, "GetEntriesList", GetEntriesList)
laurent@2029:
laurent@2029: def GetSyncManagers(self):
laurent@2029: sync_managers = []
laurent@2029: for sync_manager in self.getSm():
laurent@2029: sync_manager_infos = {}
laurent@2029: for name, value in [("Name", sync_manager.getcontent()),
laurent@2029: ("Start Address", sync_manager.getStartAddress()),
laurent@2029: ("Default Size", sync_manager.getDefaultSize()),
laurent@2029: ("Control Byte", sync_manager.getControlByte()),
laurent@2029: ("Enable", sync_manager.getEnable())]:
laurent@2029: if value is None:
laurent@2029: value =""
laurent@2029: sync_manager_infos[name] = value
laurent@2029: sync_managers.append(sync_manager_infos)
laurent@2029: return sync_managers
laurent@2029: setattr(cls, "GetSyncManagers", GetSyncManagers)
laurent@2029:
laurent@2022: def GroupItemCompare(x, y):
laurent@2022: if x["type"] == y["type"]:
laurent@2022: if x["type"] == ETHERCAT_GROUP:
laurent@2031: return cmp(x["order"], y["order"])
laurent@2022: else:
laurent@2031: return cmp(x["name"], y["name"])
laurent@2022: elif x["type"] == ETHERCAT_GROUP:
laurent@2022: return -1
laurent@2022: return 1
laurent@2022:
laurent@2022: def SortGroupItems(group):
laurent@2022: for item in group["children"]:
laurent@2022: if item["type"] == ETHERCAT_GROUP:
laurent@2022: SortGroupItems(item)
laurent@2022: group["children"].sort(GroupItemCompare)
laurent@2022:
laurent@2022: def ExtractName(names, default=None):
laurent@2022: if len(names) == 1:
laurent@2022: return names[0].getcontent()
laurent@2022: else:
laurent@2022: for name in names:
laurent@2022: if name.getLcId() == 1033:
laurent@2022: return name.getcontent()
laurent@2022: return default
laurent@2022:
laurent@2029: def ExtractPdoInfos(pdo, pdo_type, entries):
laurent@2022: pdo_index = pdo.getIndex().getcontent()
laurent@2029: pdo_name = ExtractName(pdo.getName())
laurent@2029: for pdo_entry in pdo.getEntry():
laurent@2029: entry_index = pdo_entry.getIndex().getcontent()
laurent@2029: entry_subindex = pdo_entry.getSubIndex()
laurent@2029: index = ExtractHexDecValue(entry_index)
laurent@2029: subindex = ExtractHexDecValue(entry_subindex)
laurent@2029:
laurent@2029: entry = entries.get((index, subindex), None)
laurent@2029: if entry is not None:
laurent@2029: entry["PDO index"] = pdo_index
laurent@2029: entry["PDO name"] = pdo_name
laurent@2029: entry["PDO type"] = pdo_type
laurent@2029: else:
laurent@2031: entry_type = pdo_entry.getDataType()
laurent@2031: if entry_type is not None:
laurent@2031: if pdo_type == "Transmit":
laurent@2031: access = "ro"
laurent@2032: pdomapping = "T"
laurent@2031: else:
laurent@2031: access = "wo"
laurent@2032: pdomapping = "R"
laurent@2031: entries[(index, subindex)] = {
laurent@2031: "Index": entry_index,
laurent@2031: "SubIndex": entry_subindex,
laurent@2031: "Name": ExtractName(pdo_entry.getName()),
laurent@2031: "Type": entry_type.getcontent(),
laurent@2031: "Access": access,
laurent@2032: "PDOMapping": pdomapping,
laurent@2031: "PDO index": pdo_index,
laurent@2031: "PDO name": pdo_name,
laurent@2031: "PDO type": pdo_type}
laurent@2022:
laurent@2022: class RootClass:
laurent@2022:
Edouard@2048: CTNChildrenTypes = [("EthercatNode",_EthercatCTN,"Ethercat Master")]
laurent@2022:
laurent@2022: def __init__(self):
laurent@2022: self.LoadModulesLibrary()
laurent@2022:
laurent@2022: def GetModulesLibraryPath(self):
Edouard@2048: library_path = os.path.join(self.CTNPath(), "modules")
laurent@2022: if not os.path.exists(library_path):
laurent@2022: os.mkdir(library_path)
laurent@2022: return library_path
laurent@2022:
laurent@2022: def _ImportModuleLibrary(self):
Edouard@2048: dialog = wx.FileDialog(self.GetCTRoot().AppFrame, _("Choose an XML file"), os.getcwd(), "", _("XML files (*.xml)|*.xml|All files|*.*"), wx.OPEN)
laurent@2022: if dialog.ShowModal() == wx.ID_OK:
laurent@2022: filepath = dialog.GetPath()
laurent@2022: if os.path.isfile(filepath):
laurent@2022: shutil.copy(filepath, self.GetModulesLibraryPath())
laurent@2022: self.LoadModulesLibrary()
laurent@2022: else:
Edouard@2048: self.GetCTRoot().logger.write_error(_("No such XML file: %s\n") % filepath)
laurent@2022: dialog.Destroy()
laurent@2022:
Edouard@2048: ConfNodeMethods = [
Edouard@2048: {"bitmap" : os.path.join(CONFNODEFOLDER, "images", "ImportESI"),
laurent@2022: "name" : _("Import module library"),
laurent@2022: "tooltip" : _("Import module library"),
laurent@2022: "method" : "_ImportModuleLibrary"},
laurent@2022: ]
laurent@2022:
Edouard@2048: def CTNGenerate_C(self, buildpath, locations):
laurent@2023: return [],"",False
laurent@2023:
laurent@2022: def LoadModulesLibrary(self):
laurent@2022: self.ModulesLibrary = {}
laurent@2022:
laurent@2022: library_path = self.GetModulesLibraryPath()
laurent@2022:
laurent@2022: files = os.listdir(library_path)
laurent@2022: for file in files:
laurent@2022: filepath = os.path.join(library_path, file)
laurent@2022: if os.path.isfile(filepath) and os.path.splitext(filepath)[-1] == ".xml":
laurent@2022: xmlfile = open(filepath, 'r')
laurent@2022: xml_tree = minidom.parse(xmlfile)
laurent@2022: xmlfile.close()
laurent@2022:
laurent@2022: modules_infos = None
laurent@2022: for child in xml_tree.childNodes:
laurent@2022: if child.nodeType == xml_tree.ELEMENT_NODE and child.nodeName == "EtherCATInfo":
laurent@2022: modules_infos = EtherCATInfoClasses["EtherCATInfo.xsd"]["EtherCATInfo"]()
laurent@2051: modules_infos.loadXMLTree(child)
laurent@2022:
laurent@2022: if modules_infos is not None:
laurent@2022: vendor = modules_infos.getVendor()
laurent@2022:
laurent@2031: vendor_category = self.ModulesLibrary.setdefault(ExtractHexDecValue(vendor.getId()),
laurent@2031: {"name": ExtractName(vendor.getName(), _("Miscellaneous")),
laurent@2031: "groups": {}})
laurent@2022:
laurent@2022: for group in modules_infos.getDescriptions().getGroups().getGroup():
laurent@2022: group_type = group.getType()
laurent@2022:
laurent@2022: vendor_category["groups"].setdefault(group_type, {"name": ExtractName(group.getName(), group_type),
laurent@2022: "parent": group.getParentGroup(),
laurent@2022: "order": group.getSortOrder(),
laurent@2022: "devices": []})
laurent@2022:
laurent@2022: for device in modules_infos.getDescriptions().getDevices().getDevice():
laurent@2022: device_group = device.getGroupType()
laurent@2022: if not vendor_category["groups"].has_key(device_group):
laurent@2022: raise ValueError, "Not such group \"%\"" % device_group
laurent@2022: vendor_category["groups"][device_group]["devices"].append((device.getType().getcontent(), device))
laurent@2022:
laurent@2041: def GetModulesLibrary(self, profile_filter=None):
laurent@2022: library = []
laurent@2022: children_dict = {}
laurent@2022: for vendor_id, vendor in self.ModulesLibrary.iteritems():
laurent@2022: groups = []
laurent@2022: for group_type, group in vendor["groups"].iteritems():
laurent@2022: group_infos = {"name": group["name"],
laurent@2022: "order": group["order"],
laurent@2022: "type": ETHERCAT_GROUP,
laurent@2041: "infos": None,
laurent@2022: "children": children_dict.setdefault(group_type, [])}
laurent@2022: device_dict = {}
laurent@2022: for device_type, device in group["devices"]:
laurent@2041: if profile_filter is None or profile_filter in device.GetProfileNumbers():
laurent@2041: device_infos = {"name": ExtractName(device.getName()),
laurent@2041: "type": ETHERCAT_DEVICE,
laurent@2041: "infos": {"device_type": device_type,
laurent@2041: "vendor": vendor_id,
laurent@2041: "product_code": device.getType().getProductCode(),
laurent@2041: "revision_number": device.getType().getRevisionNo()},
laurent@2041: "children": []}
laurent@2041: group_infos["children"].append(device_infos)
laurent@2041: device_type_occurrences = device_dict.setdefault(device_type, [])
laurent@2041: device_type_occurrences.append(device_infos)
laurent@2022: for device_type_occurrences in device_dict.itervalues():
laurent@2022: if len(device_type_occurrences) > 1:
laurent@2022: for occurrence in device_type_occurrences:
laurent@2022: occurrence["name"] += _(" (rev. %s)") % occurrence["infos"]["revision_number"]
laurent@2041: if len(group_infos["children"]) > 0:
laurent@2041: if group["parent"] is not None:
laurent@2041: parent_children = children_dict.setdefault(group["parent"], [])
laurent@2041: parent_children.append(group_infos)
laurent@2041: else:
laurent@2041: groups.append(group_infos)
laurent@2041: if len(groups) > 0:
laurent@2041: library.append({"name": vendor["name"],
laurent@2041: "type": ETHERCAT_VENDOR,
laurent@2041: "infos": None,
laurent@2041: "children": groups})
laurent@2031: library.sort(lambda x, y: cmp(x["name"], y["name"]))
laurent@2022: return library
laurent@2022:
laurent@2022: def GetModuleInfos(self, type_infos):
laurent@2031: vendor = self.ModulesLibrary.get(ExtractHexDecValue(type_infos["vendor"]), None)
laurent@2022: if vendor is not None:
laurent@2022: for group_name, group in vendor["groups"].iteritems():
laurent@2022: for device_type, device in group["devices"]:
laurent@2029: product_code = ExtractHexDecValue(device.getType().getProductCode())
laurent@2029: revision_number = ExtractHexDecValue(device.getType().getRevisionNo())
laurent@2042: if (product_code == ExtractHexDecValue(type_infos["product_code"]) and
laurent@2029: revision_number == ExtractHexDecValue(type_infos["revision_number"])):
laurent@2022: return device
laurent@2022: return None
laurent@2041:
laurent@2041: