laurent@2022: import os, shutil
laurent@2022: import cPickle
laurent@2022: from xml.dom import minidom
laurent@2022:
laurent@2022: import wx
Laurent@2097: import csv
laurent@2022:
laurent@2022: from xmlclass import *
Laurent@2086: from POULibrary import POULibrary
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@2098: from ConfigEditor import NodeEditor, CIA402NodeEditor, MasterEditor, LibraryEditor, ETHERCAT_VENDOR, ETHERCAT_GROUP, ETHERCAT_DEVICE
Laurent@2102: from dialogs import BrowseValuesLibraryDialog
Laurent@2102: from IDEFrame import TITLE, FILEMENU, PROJECTTREE
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:
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@2086: # Etherlab Specific Blocks Library
Laurent@2086: #--------------------------------------------------
Laurent@2086:
Laurent@2086: def GetLocalPath(filename):
Laurent@2086: return os.path.join(os.path.split(__file__)[0], filename)
Laurent@2086:
Laurent@2086: class EtherlabLibrary(POULibrary):
Laurent@2086: def GetLibraryPath(self):
Laurent@2086: return GetLocalPath("pous.xml")
Laurent@2086:
Laurent@2086: def Generate_C(self, buildpath, varlist, IECCFLAGS):
Laurent@2086: etherlab_ext_file = open(GetLocalPath("etherlab_ext.c"), 'r')
Laurent@2086: etherlab_ext_code = etherlab_ext_file.read()
Laurent@2086: etherlab_ext_file.close()
Laurent@2086:
Laurent@2086: Gen_etherlabfile_path = os.path.join(buildpath, "etherlab_ext.c")
Laurent@2086: ethelabfile = open(Gen_etherlabfile_path,'w')
Laurent@2086: ethelabfile.write(etherlab_ext_code)
Laurent@2086: ethelabfile.close()
Laurent@2086:
Laurent@2086: runtimefile_path = os.path.join(os.path.split(__file__)[0], "runtime_etherlab.py")
Laurent@2086: return ((["etherlab_ext"], [(Gen_etherlabfile_path, IECCFLAGS)], True), "",
Laurent@2086: ("runtime_etherlab.py", file(GetLocalPath("runtime_etherlab.py"))))
Laurent@2086:
Laurent@2086: #--------------------------------------------------
laurent@2041: # Ethercat Node
laurent@2041: #--------------------------------------------------
laurent@2041:
Edouard@2048: class _EthercatSlaveCTN:
Laurent@2063:
laurent@2041: NODE_PROFILE = None
laurent@2041: EditorType = NodeEditor
laurent@2034:
Laurent@2068: def GetIconName(self):
Laurent@2068: return "Slave"
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@2063: if self.CTNParams:
Laurent@2063: params.append(self.CTNParams[1].getElementInfos(self.CTNParams[0]))
Laurent@2063: else:
Laurent@2063: params.append({
Laurent@2063: 'use': 'required',
Laurent@2063: 'type': 'element',
Laurent@2063: 'name': 'SlaveParams',
Laurent@2063: 'value': None,
Laurent@2063: 'children': []
Laurent@2063: })
Laurent@2063:
Edouard@2048: slave_type = self.CTNParent.GetSlaveType(self.GetSlavePos())
Laurent@2063: params[0]['children'].insert(0,
Laurent@2063: {'use': 'optional',
Edouard@2048: 'type': self.CTNParent.GetSlaveTypesLibrary(self.NODE_PROFILE),
laurent@2041: 'name': 'Type',
Laurent@2063: 'value': (slave_type["device_type"], slave_type)})
Laurent@2063: params[0]['children'].insert(1,
laurent@2041: {'use': 'optional',
laurent@2041: 'type': 'unsignedLong',
laurent@2041: 'name': 'Alias',
Laurent@2063: 'value': self.CTNParent.GetSlaveAlias(self.GetSlavePos())})
laurent@2041: return params
laurent@2041:
laurent@2041: def SetParamsAttribute(self, path, value):
Laurent@2066: position = self.BaseParams.getIEC_Channel()
Laurent@2066:
Laurent@2063: if path == "SlaveParams.Type":
Laurent@2063: self.CTNParent.SetSlaveType(position, value)
Laurent@2063: slave_type = self.CTNParent.GetSlaveType(self.GetSlavePos())
Laurent@2063: value = (slave_type["device_type"], slave_type)
Laurent@2067: if self._View is not None:
Laurent@2067: wx.CallAfter(self._View.RefreshSlaveInfos)
Laurent@2063: return value, True
Laurent@2063: elif path == "SlaveParams.Alias":
Laurent@2063: self.CTNParent.SetSlaveAlias(position, value)
Laurent@2063: return value, True
Laurent@2063:
Laurent@2080: value, refresh = ConfigTreeNode.SetParamsAttribute(self, path, value)
Laurent@2080:
laurent@2041: # Filter IEC_Channel, Slave_Type and Alias that have specific behavior
Laurent@2080: if path == "BaseParams.IEC_Channel" and value != position:
Edouard@2048: self.CTNParent.SetSlavePosition(position, value)
Laurent@2063:
Laurent@2080: return value, refresh
Laurent@2080:
laurent@2034: def GetSlaveInfos(self):
Edouard@2048: return self.CTNParent.GetSlaveInfos(self.GetSlavePos())
laurent@2041:
Laurent@2098: def GetSlaveVariables(self, limits):
Laurent@2098: return self.CTNParent.GetSlaveVariables(self.GetSlavePos(), limits)
Laurent@2098:
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@2062: ("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@2091: ("ActualVelocity", 0x606C, 0x00, "DINT", "I"),
laurent@2041: ]
laurent@2041:
Laurent@2085: DEFAULT_RETRIEVE = " __CIA402Node_%(location)s.axis->%(name)s = *(__CIA402Node_%(location)s.%(name)s);"
Laurent@2085: DEFAULT_PUBLISH = " *(__CIA402Node_%(location)s.%(name)s) = __CIA402Node_%(location)s.axis->%(name)s;"
Laurent@2084:
Laurent@2084: EXTRA_NODE_VARIABLES = [
Laurent@2096: ("ErrorCode", [
Laurent@2096: {"description": ("ErrorCode", 0x603F, 0x00, "UINT", "I"),
Laurent@2096: "publish": None}
Laurent@2096: ]),
Laurent@2084: ("DigitalInputs", [
Laurent@2084: {"description": ("DigitalInputs", 0x60FD, 0x00, "UDINT", "I"),
Laurent@2084: "publish": None}
Laurent@2096: ]),
Laurent@2096: ("DigitalOutputs", [
Laurent@2096: {"description": ("DigitalOutputs", 0x60FE, 0x00, "UDINT", "Q"),
Laurent@2096: "retrieve": None}
Laurent@2084: ])
Laurent@2084: ]
Laurent@2084: EXTRA_NODE_VARIABLES_DICT = dict([("Enable" + name, value) for name, value in EXTRA_NODE_VARIABLES])
Laurent@2092:
Laurent@2094: BLOCK_INPUT_TEMPLATE = " __SET_VAR(%(blockname)s->,%(input_name)s, %(input_value)s);"
Laurent@2094: BLOCK_OUTPUT_TEMPLATE = " __SET_VAR(data__->,%(output_name)s, __GET_VAR(%(blockname)s->%(output_name)s));"
Laurent@2092:
Laurent@2092: BLOCK_FUNCTION_TEMPLATE = """
Laurent@2093: extern void ETHERLAB%(ucase_blocktype)s_body__(ETHERLAB%(ucase_blocktype)s* data__);
Laurent@2093: void __%(blocktype)s_%(location)s(MC_%(ucase_blocktype)s *data__) {
Laurent@2094: __DECLARE_GLOBAL_PROTOTYPE(ETHERLAB%(ucase_blocktype)s, %(blockname)s);
Laurent@2094: ETHERLAB%(ucase_blocktype)s* %(blockname)s = __GET_GLOBAL_%(blockname)s();
Laurent@2092: %(extract_inputs)s
Laurent@2094: ETHERLAB%(ucase_blocktype)s_body__(%(blockname)s);
Laurent@2092: %(return_outputs)s
Laurent@2092: }
Laurent@2092: """
Laurent@2092:
Laurent@2094: BLOCK_FUNTION_DEFINITION_TEMPLATE = """ if (!__CIA402Node_%(location)s.axis->__mcl_func_MC_%(blocktype)s)
Laurent@2094: __CIA402Node_%(location)s.axis->__mcl_func_MC_%(blocktype)s = __%(blocktype)s_%(location)s;"""
Laurent@2092:
Laurent@2092: GLOBAL_INSTANCES = [
Laurent@2092: {"blocktype": "GetTorqueLimit",
Laurent@2092: "inputs": [],
Laurent@2092: "outputs": [{"name": "TorqueLimitPos", "type": "UINT"},
Laurent@2092: {"name": "TorqueLimitNeg", "type": "UINT"}]},
Laurent@2092: {"blocktype": "SetTorqueLimit",
Laurent@2092: "inputs": [{"name": "TorqueLimitPos", "type": "UINT"},
Laurent@2092: {"name": "TorqueLimitNeg", "type": "UINT"}],
Laurent@2092: "outputs": []},
Laurent@2092: ]
Laurent@2084:
Edouard@2048: class _EthercatCIA402SlaveCTN(_EthercatSlaveCTN):
laurent@2041: XSD = """
laurent@2041:
laurent@2043:
laurent@2041:
laurent@2041: %s
laurent@2041:
laurent@2041:
laurent@2041:
Laurent@2084: """ % ("\n".join(['' % category
Laurent@2084: for category, variables in EXTRA_NODE_VARIABLES]) + AxisXSD)
laurent@2041:
laurent@2041: NODE_PROFILE = 402
laurent@2043: EditorType = CIA402NodeEditor
laurent@2043:
Laurent@2062: ConfNodeMethods = [
Laurent@2068: {"bitmap" : "CIA402AxisRef",
Laurent@2062: "name" : _("Axis Ref"),
Laurent@2062: "tooltip" : _("Initiate Drag'n drop of Axis ref located variable"),
Laurent@2063: "method" : "_getCIA402AxisRef",
Laurent@2063: "push": True},
Laurent@2062: ]
Laurent@2062:
Laurent@2068: def GetIconName(self):
Laurent@2068: return "CIA402Slave"
laurent@2041:
Laurent@2063: def SetParamsAttribute(self, path, value):
Laurent@2063: if path == "CIA402SlaveParams.Type":
Laurent@2063: path = "SlaveParams.Type"
Laurent@2063: elif path == "CIA402SlaveParams.Alias":
Laurent@2063: path = "SlaveParams.Alias"
Laurent@2063: return _EthercatSlaveCTN.SetParamsAttribute(self, path, value)
Laurent@2063:
Laurent@2063: def GetVariableLocationTree(self):
Laurent@2062: axis_name = self.CTNName()
Laurent@2063: current_location = self.GetCurrentLocation()
Laurent@2063: children = [{"name": "%s Axis Ref" % (axis_name),
Laurent@2063: "type": LOCATION_VAR_INPUT,
Laurent@2063: "size": "W",
Laurent@2083: "IEC_type": "AXIS_REF",
Laurent@2063: "var_name": axis_name,
Laurent@2063: "location": "%%IW%s.0" % (".".join(map(str, current_location))),
Laurent@2063: "description": "",
Laurent@2063: "children": []}]
Laurent@2063: children.extend(self.CTNParent.GetDeviceLocationTree(self.GetSlavePos(), current_location, axis_name))
Laurent@2063: return {"name": axis_name,
Laurent@2063: "type": LOCATION_CONFNODE,
Laurent@2063: "location": self.GetFullIEC_Channel(),
Laurent@2063: "children": children,
Laurent@2063: }
Laurent@2062:
Laurent@2092: def CTNGlobalInstances(self):
Laurent@2092: current_location = self.GetCurrentLocation()
Laurent@2092: return [("%s_%s" % (block_infos["blocktype"], "_".join(map(str, current_location))),
Laurent@2092: "EtherLab%s" % block_infos["blocktype"]) for block_infos in GLOBAL_INSTANCES]
Laurent@2092:
Laurent@2062: def _getCIA402AxisRef(self):
Laurent@2074: data = wx.TextDataObject(str(("%%IW%s.0" % ".".join(map(str, self.GetCurrentLocation())),
Laurent@2062: "location", "AXIS_REF", self.CTNName(), "")))
Laurent@2062: dragSource = wx.DropSource(self.GetCTRoot().AppFrame)
Laurent@2062: dragSource.SetData(data)
Laurent@2062: dragSource.DoDragDrop()
Laurent@2062:
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@2088: "slave_pos": self.GetSlavePos(),
laurent@2041: "location": location_str,
laurent@2041: "MCL_headers": Headers,
laurent@2041: "extern_located_variables_declaration": [],
Laurent@2092: "fieldbus_interface_declaration": [],
Laurent@2092: "fieldbus_interface_definition": [],
laurent@2041: "entry_variables": [],
laurent@2041: "init_axis_params": [],
laurent@2041: "init_entry_variables": [],
Laurent@2084: "extra_variables_retrieve": [],
Laurent@2084: "extra_variables_publish": []
laurent@2041: }
laurent@2041:
Laurent@2092: for blocktype_infos in GLOBAL_INSTANCES:
Laurent@2092: texts = {
Laurent@2092: "blocktype": blocktype_infos["blocktype"],
Laurent@2092: "ucase_blocktype": blocktype_infos["blocktype"].upper(),
Laurent@2092: "location": "_".join(map(str, current_location))
Laurent@2092: }
Laurent@2092: texts["blockname"] = "%(ucase_blocktype)s_%(location)s" % texts
Laurent@2092:
Laurent@2092: inputs = [{"input_name": "POS", "input_value": str(self.GetSlavePos())},
Laurent@2092: {"input_name": "EXECUTE", "input_value": "__GET_VAR(data__->EXECUTE)"}] +\
Laurent@2092: [{"input_name": input["name"].upper(),
Laurent@2092: "input_value": "__GET_VAR(data__->%s)" % input["name"].upper()}
Laurent@2092: for input in blocktype_infos["inputs"]]
Laurent@2092: input_texts = []
Laurent@2092: for input_infos in inputs:
Laurent@2092: input_infos.update(texts)
Laurent@2092: input_texts.append(BLOCK_INPUT_TEMPLATE % input_infos)
Laurent@2092: texts["extract_inputs"] = "\n".join(input_texts)
Laurent@2092:
Laurent@2092: outputs = [{"output_name": output} for output in ["DONE", "BUSY", "ERROR"]] + \
Laurent@2092: [{"output_name": output["name"].upper()} for output in blocktype_infos["outputs"]]
Laurent@2092: output_texts = []
Laurent@2092: for output_infos in outputs:
Laurent@2092: output_infos.update(texts)
Laurent@2092: output_texts.append(BLOCK_OUTPUT_TEMPLATE % output_infos)
Laurent@2092: texts["return_outputs"] = "\n".join(output_texts)
Laurent@2092:
Laurent@2092: str_completion["fieldbus_interface_declaration"].append(
Laurent@2092: BLOCK_FUNCTION_TEMPLATE % texts)
Laurent@2092:
Laurent@2092: str_completion["fieldbus_interface_definition"].append(
Laurent@2092: BLOCK_FUNTION_DEFINITION_TEMPLATE % texts)
Laurent@2092:
Laurent@2084: variables = NODE_VARIABLES[:]
Laurent@2084:
Laurent@2084: params = self.CTNParams[1].getElementInfos(self.CTNParams[0])
Laurent@2084: for param in params["children"]:
Laurent@2084: if param["name"] in EXTRA_NODE_VARIABLES_DICT:
Laurent@2084: if param["value"]:
Laurent@2084: extra_variables = EXTRA_NODE_VARIABLES_DICT.get(param["name"])
Laurent@2084: for variable_infos in extra_variables:
Laurent@2084: var_infos = {
Laurent@2084: "location": location_str,
Laurent@2084: "name": variable_infos["description"][0]
Laurent@2084: }
Laurent@2084: variables.append(variable_infos["description"])
Laurent@2084: retrieve_template = variable_infos.get("retrieve", DEFAULT_RETRIEVE)
Laurent@2084: publish_template = variable_infos.get("publish", DEFAULT_PUBLISH)
Laurent@2084:
Laurent@2084: if retrieve_template is not None:
Laurent@2084: str_completion["extra_variables_retrieve"].append(
Laurent@2084: retrieve_template % var_infos)
Laurent@2084: if publish_template is not None:
Laurent@2084: str_completion["extra_variables_publish"].append(
Laurent@2084: publish_template % var_infos)
Laurent@2084: elif param["value"] is not None:
Laurent@2084: param_infos = {
Laurent@2084: "location": location_str,
Laurent@2084: "param_name": param["name"],
Laurent@2084: }
Laurent@2084: if param["type"] == "boolean":
Laurent@2084: param_infos["param_value"] = {True: "true", False: "false"}[param["value"]]
Laurent@2084: else:
Laurent@2084: param_infos["param_value"] = str(param["value"])
Laurent@2084: str_completion["init_axis_params"].append(
Laurent@2084: " __CIA402Node_%(location)s.axis->%(param_name)s = %(param_value)s;" % param_infos)
Laurent@2084:
Laurent@2084: for variable in 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:
laurent@2041: for element in ["extern_located_variables_declaration",
Laurent@2092: "fieldbus_interface_declaration",
Laurent@2092: "fieldbus_interface_definition",
laurent@2041: "entry_variables",
laurent@2041: "init_axis_params",
Laurent@2084: "init_entry_variables",
Laurent@2084: "extra_variables_retrieve",
Laurent@2084: "extra_variables_publish"]:
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@2098: def sort_commands(x, y):
Laurent@2098: if x["Index"] == y["Index"]:
Laurent@2098: return cmp(x["Subindex"], y["Subindex"])
Laurent@2098: return cmp(x["Index"], y["Index"])
Laurent@2098:
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@2098:
Laurent@2098: def getInitCmds(self, create_default=False):
Laurent@2098: Mailbox = self.getMailbox()
Laurent@2098: if Mailbox is None:
Laurent@2098: if create_default:
Laurent@2098: self.addMailbox()
Laurent@2098: Mailbox = self.getMailbox()
Laurent@2098: else:
Laurent@2098: return None
Laurent@2098: CoE = Mailbox.getCoE()
Laurent@2098: if CoE is None:
Laurent@2098: if create_default:
Laurent@2098: Mailbox.addCoE()
Laurent@2098: CoE = Mailbox.getCoE()
Laurent@2098: else:
Laurent@2098: return None
Laurent@2098: InitCmds = CoE.getInitCmds()
Laurent@2098: if InitCmds is None and create_default:
Laurent@2098: CoE.addInitCmds()
Laurent@2098: InitCmds = CoE.getInitCmds()
Laurent@2098: return InitCmds
Laurent@2098: setattr(cls, "getInitCmds", getInitCmds)
Laurent@2098:
Laurent@2098: def getStartupCommands(self):
Laurent@2098: pos = self.getInfo().getPhysAddr()
Laurent@2098: InitCmds = self.getInitCmds()
Laurent@2098: if InitCmds is None:
Laurent@2098: return []
Laurent@2098: commands = []
Laurent@2098: for idx, InitCmd in enumerate(InitCmds.getInitCmd()):
Laurent@2098: comment = InitCmd.getComment()
Laurent@2098: if comment is None:
Laurent@2098: comment = ""
Laurent@2098: commands.append({
Laurent@2098: "command_idx": idx,
Laurent@2098: "Position": pos,
Laurent@2098: "Index": InitCmd.getIndex(),
Laurent@2098: "Subindex": InitCmd.getSubIndex(),
Laurent@2098: "Value": InitCmd.getData(),
Laurent@2098: "Description": comment})
Laurent@2098: commands.sort(sort_commands)
Laurent@2098: return commands
Laurent@2098: setattr(cls, "getStartupCommands", getStartupCommands)
Laurent@2098:
Laurent@2098: def appendStartupCommand(self, command_infos):
Laurent@2098: InitCmds = self.getInitCmds(True)
Laurent@2098: command = EtherCATConfigClasses["InitCmds_InitCmd"]()
Laurent@2098: command.setIndex(command_infos["Index"])
Laurent@2098: command.setSubIndex(command_infos["Subindex"])
Laurent@2098: command.setData(command_infos["Value"])
Laurent@2098: command.setComment(command_infos["Description"])
Laurent@2098: InitCmds.appendInitCmd(command)
Laurent@2098: return len(InitCmds.getInitCmd()) - 1
Laurent@2098: setattr(cls, "appendStartupCommand", appendStartupCommand)
Laurent@2098:
Laurent@2098: def setStartupCommand(self, command_infos):
Laurent@2098: InitCmds = self.getInitCmds()
Laurent@2098: if InitCmds is not None:
Laurent@2098: commands = InitCmds.getInitCmd()
Laurent@2098: if command_infos["command_idx"] < len(commands):
Laurent@2098: command = commands[command_infos["command_idx"]]
Laurent@2098: command.setIndex(command_infos["Index"])
Laurent@2098: command.setSubIndex(command_infos["Subindex"])
Laurent@2098: command.setData(command_infos["Value"])
Laurent@2098: command.setComment(command_infos["Description"])
Laurent@2098: setattr(cls, "setStartupCommand", setStartupCommand)
Laurent@2098:
Laurent@2098: def removeStartupCommand(self, command_idx):
Laurent@2098: InitCmds = self.getInitCmds()
Laurent@2098: if InitCmds is not None:
Laurent@2098: if command_idx < len(InitCmds.getInitCmd()):
Laurent@2098: InitCmds.removeInitCmd(command_idx)
Laurent@2098: setattr(cls, "removeStartupCommand", removeStartupCommand)
Laurent@2098:
Laurent@2098: ProcessVariablesXSD = """
laurent@2022:
Laurent@2098:
laurent@2022:
Laurent@2098:
Laurent@2098:
Laurent@2098:
Laurent@2098:
Laurent@2098:
Laurent@2098:
Laurent@2098:
Laurent@2098:
Laurent@2098:
Laurent@2098:
Laurent@2098:
Laurent@2098:
laurent@2022:
laurent@2022:
Laurent@2098:
Laurent@2098:
Laurent@2098:
Laurent@2098:
Laurent@2098:
laurent@2022:
Laurent@2098: """
Laurent@2098:
Laurent@2098: ProcessVariablesClasses = GenerateClassesFromXSDstring(ProcessVariablesXSD)
Laurent@2098:
Laurent@2098: class _EthercatCTN:
laurent@2041:
Edouard@2048: CTNChildrenTypes = [("EthercatSlave", _EthercatSlaveCTN, "Ethercat Slave")]
laurent@2041: if HAS_MCL:
Edouard@2048: CTNChildrenTypes.append(("EthercatCIA402Slave", _EthercatCIA402SlaveCTN, "Ethercat CIA402 Slave"))
Laurent@2098: EditorType = MasterEditor
laurent@2032:
laurent@2022: def __init__(self):
Laurent@2098: config_filepath = self.ConfigFileName()
Laurent@2098: config_is_saved = False
laurent@2022: self.Config = EtherCATConfigClasses["EtherCATConfig"]()
Laurent@2098: if os.path.isfile(config_filepath):
Laurent@2098: config_xmlfile = open(config_filepath, 'r')
Laurent@2098: config_tree = minidom.parse(config_xmlfile)
Laurent@2098: config_xmlfile.close()
laurent@2022:
Laurent@2098: for child in config_tree.childNodes:
Laurent@2098: if child.nodeType == config_tree.ELEMENT_NODE and child.nodeName == "EtherCATConfig":
laurent@2051: self.Config.loadXMLTree(child)
Laurent@2098: config_is_saved = True
Laurent@2098:
Laurent@2098: process_filepath = self.ProcessVariablesFileName()
Laurent@2098: process_is_saved = False
Laurent@2098: self.ProcessVariables = ProcessVariablesClasses["ProcessVariables"]()
Laurent@2098: if os.path.isfile(process_filepath):
Laurent@2098: process_xmlfile = open(process_filepath, 'r')
Laurent@2098: process_tree = minidom.parse(process_xmlfile)
Laurent@2098: process_xmlfile.close()
Laurent@2098:
Laurent@2098: for child in process_tree.childNodes:
Laurent@2098: if child.nodeType == process_tree.ELEMENT_NODE and child.nodeName == "ProcessVariables":
Laurent@2098: self.ProcessVariables.loadXMLTree(child)
Laurent@2098: process_is_saved = True
Laurent@2098:
Laurent@2098: if config_is_saved and process_is_saved:
Laurent@2098: self.CreateBuffer(True)
laurent@2022: else:
Laurent@2098: self.CreateBuffer(False)
Edouard@2048: self.OnCTNSave()
Laurent@2102:
Laurent@2102: def GetContextualMenuItems(self):
Laurent@2102: return [("Add Ethercat Slave", "Add Ethercat Slave to Master", self.OnAddEthercatSlave)]
Laurent@2102:
Laurent@2102: def OnAddEthercatSlave(self, event):
Laurent@2102: app_frame = self.GetCTRoot().AppFrame
Laurent@2102: dialog = BrowseValuesLibraryDialog(app_frame,
Laurent@2102: "Ethercat Slave Type", self.GetSlaveTypesLibrary())
Laurent@2102: if dialog.ShowModal() == wx.ID_OK:
Laurent@2102: type_infos = dialog.GetValueInfos()
Laurent@2102: device, alignment = self.GetModuleInfos(type_infos)
Laurent@2102: if device is not None:
Laurent@2102: if HAS_MCL and _EthercatCIA402SlaveCTN.NODE_PROFILE in device.GetProfileNumbers():
Laurent@2102: ConfNodeType = "EthercatCIA402Slave"
Laurent@2102: else:
Laurent@2102: ConfNodeType = "EthercatSlave"
Laurent@2102: new_child = self.CTNAddChild("%s_0" % ConfNodeType, ConfNodeType)
Laurent@2102: new_child.SetParamsAttribute("SlaveParams.Type", type_infos)
Laurent@2102: self.CTNRequestSave()
Laurent@2105: new_child._OpenView()
Laurent@2102: app_frame._Refresh(TITLE, FILEMENU, PROJECTTREE)
Laurent@2102: dialog.Destroy()
Laurent@2102:
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@2098:
Laurent@2098: def ProcessVariablesFileName(self):
Laurent@2098: return os.path.join(self.CTNPath(), "process_variables.xml")
Laurent@2098:
Laurent@2098: def FilterSlave(self, slave, vendor=None, slave_pos=None, slave_profile=None):
Laurent@2098: if slave_pos is not None and slave.getInfo().getPhysAddr() != slave_pos:
Laurent@2098: return False
Laurent@2098: type_infos = slave.getType()
Laurent@2098: if vendor is not None and ExtractHexDecValue(type_infos["vendor"]) != vendor:
Laurent@2098: return False
Laurent@2098: device, alignment = self.GetModuleInfos(type_infos)
Laurent@2098: if slave_profile is not None and slave_profile not in device.GetProfileNumbers():
Laurent@2098: return False
Laurent@2098: return True
Laurent@2098:
Laurent@2099: def GetSlaves(self, vendor=None, slave_pos=None, slave_profile=None):
Laurent@2099: slaves = []
Laurent@2099: for slave in self.Config.getConfig().getSlave():
Laurent@2099: if self.FilterSlave(slave, vendor, slave_pos, slave_profile):
Laurent@2099: slaves.append(slave.getInfo().getPhysAddr())
Laurent@2099: slaves.sort()
Laurent@2099: return slaves
Laurent@2099:
Laurent@2099: def GetSlave(self, slave_pos):
Laurent@2099: for slave in self.Config.getConfig().getSlave():
Laurent@2099: slave_info = slave.getInfo()
Laurent@2099: if slave_info.getPhysAddr() == slave_pos:
Laurent@2099: return slave
Laurent@2099: return None
Laurent@2099:
Laurent@2098: def GetStartupCommands(self, vendor=None, slave_pos=None, slave_profile=None):
Laurent@2098: commands = []
Laurent@2098: for slave in self.Config.getConfig().getSlave():
Laurent@2098: if self.FilterSlave(slave, vendor, slave_pos, slave_profile):
Laurent@2098: commands.append((slave.getInfo().getPhysAddr(), slave.getStartupCommands()))
Laurent@2098: commands.sort()
Laurent@2098: return reduce(lambda x, y: x + y[1], commands, [])
Laurent@2098:
Laurent@2098: def AppendStartupCommand(self, command_infos):
Laurent@2098: slave = self.GetSlave(command_infos["Position"])
Laurent@2098: if slave is not None:
Laurent@2098: command_idx = slave.appendStartupCommand(command_infos)
Laurent@2098: self.BufferModel()
Laurent@2098: return command_idx
Laurent@2098: return None
Laurent@2098:
Laurent@2098: def SetStartupCommandInfos(self, command_infos):
Laurent@2098: slave = self.GetSlave(command_infos["Position"])
Laurent@2098: if slave is not None:
Laurent@2098: slave.setStartupCommand(command_infos)
Laurent@2098: self.BufferModel()
Laurent@2098:
Laurent@2101: def RemoveStartupCommand(self, slave_pos, command_idx, buffer=True):
Laurent@2098: slave = self.GetSlave(slave_pos)
Laurent@2098: if slave is not None:
Laurent@2098: slave.removeStartupCommand(command_idx)
Laurent@2101: if buffer:
Laurent@2101: self.BufferModel()
Laurent@2098:
Laurent@2098: def SetProcessVariables(self, variables):
Laurent@2098: vars = []
Laurent@2098: for var in variables:
Laurent@2098: variable = ProcessVariablesClasses["ProcessVariables_variable"]()
Laurent@2098: variable.setName(var["Name"])
Laurent@2098: variable.setComment(var["Description"])
Laurent@2098: if var["ReadFrom"] != "":
Laurent@2098: position, index, subindex = var["ReadFrom"]
Laurent@2098: if variable.getReadFrom() is None:
Laurent@2098: variable.addReadFrom()
Laurent@2098: read_from = variable.getReadFrom()
Laurent@2098: read_from.setPosition(position)
Laurent@2098: read_from.setIndex(index)
Laurent@2098: read_from.setSubIndex(subindex)
Laurent@2098: elif variable.getReadFrom() is not None:
Laurent@2098: variable.deleteReadFrom()
Laurent@2098: if var["WriteTo"] != "":
Laurent@2098: position, index, subindex = var["WriteTo"]
Laurent@2098: if variable.getWriteTo() is None:
Laurent@2098: variable.addWriteTo()
Laurent@2098: write_to = variable.getWriteTo()
Laurent@2098: write_to.setPosition(position)
Laurent@2098: write_to.setIndex(index)
Laurent@2098: write_to.setSubIndex(subindex)
Laurent@2098: elif variable.getWriteTo() is not None:
Laurent@2098: variable.deleteWriteTo()
Laurent@2098: vars.append(variable)
Laurent@2098: self.ProcessVariables.setvariable(vars)
Laurent@2098: self.BufferModel()
Laurent@2098:
Laurent@2098: def GetProcessVariables(self):
Laurent@2098: variables = []
Laurent@2099: idx = 0
Laurent@2098: for variable in self.ProcessVariables.getvariable():
Laurent@2098: var = {"Name": variable.getName(),
Laurent@2099: "Number": idx,
Laurent@2098: "Description": variable.getComment()}
Laurent@2098: read_from = variable.getReadFrom()
Laurent@2098: if read_from is not None:
Laurent@2098: var["ReadFrom"] = (read_from.getPosition(),
Laurent@2098: read_from.getIndex(),
Laurent@2098: read_from.getSubIndex())
Laurent@2098: else:
Laurent@2098: var["ReadFrom"] = ""
Laurent@2098: write_to = variable.getWriteTo()
Laurent@2098: if write_to is not None:
Laurent@2098: var["WriteTo"] = (write_to.getPosition(),
Laurent@2098: write_to.getIndex(),
Laurent@2098: write_to.getSubIndex())
Laurent@2098: else:
Laurent@2098: var["WriteTo"] = ""
Laurent@2098: variables.append(var)
Laurent@2099: idx += 1
Laurent@2098: return variables
Laurent@2098:
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@2097: device, alignment = 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@2098: self.BufferModel()
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@2098: self.BufferModel()
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@2099: for variable in self.ProcessVariables.getvariable():
Laurent@2099: read_from = variable.getReadFrom()
Laurent@2099: if read_from is not None and read_from.getPosition() == slave_pos:
Laurent@2099: read_from.setPosition(new_pos)
Laurent@2099: write_to = variable.getWriteTo()
Laurent@2099: if write_to is not None and write_to.getPosition() == slave_pos:
Laurent@2099: write_to.setPosition(new_pos)
Laurent@2099: self.CreateBuffer(True)
Laurent@2099: self.OnCTNSave()
Laurent@2099: if self._View is not None:
Laurent@2099: self._View.RefreshView()
Laurent@2099: self._View.RefreshBuffer()
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@2098: self.BufferModel()
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@2098: self.BufferModel()
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@2098: device, alignment = self.GetModuleInfos(type_infos)
laurent@2022: if device is not None:
laurent@2022: infos = type_infos.copy()
laurent@2022: infos.update({"physics": device.getPhysics(),
laurent@2029: "sync_managers": device.GetSyncManagers(),
Laurent@2098: "entries": self.GetSlaveVariables(device)})
laurent@2022: return infos
laurent@2022: return None
laurent@2022:
Laurent@2098: def GetSlaveVariables(self, slave_pos=None, limits=None, device=None):
Laurent@2098: if device is None and slave_pos is not None:
Laurent@2098: slave = self.GetSlave(slave_pos)
Laurent@2098: if slave is not None:
Laurent@2098: type_infos = slave.getType()
Laurent@2098: device, alignment = self.GetModuleInfos(type_infos)
Laurent@2098: if device is not None:
Laurent@2098: entries = device.GetEntriesList(limits)
Laurent@2098: entries_list = entries.items()
Laurent@2098: entries_list.sort()
Laurent@2098: entries = []
Laurent@2098: current_index = None
Laurent@2098: current_entry = None
Laurent@2098: for (index, subindex), entry in entries_list:
Laurent@2098: entry["children"] = []
Laurent@2098: if slave_pos is not None:
Laurent@2098: entry["Position"] = str(slave_pos)
Laurent@2098: entry
Laurent@2098: if index != current_index:
Laurent@2098: current_index = index
Laurent@2098: current_entry = entry
Laurent@2098: entries.append(entry)
Laurent@2098: elif current_entry is not None:
Laurent@2098: current_entry["children"].append(entry)
Laurent@2098: else:
Laurent@2098: entries.append(entry)
Laurent@2098: return entries
Laurent@2098: return []
Laurent@2098:
Laurent@2099: def GetSlaveVariableDataType(self, slave_pos, index, subindex):
Laurent@2099: slave = self.GetSlave(slave_pos)
Laurent@2099: if slave is not None:
Laurent@2099: device, alignment = self.GetModuleInfos(slave.getType())
Laurent@2099: if device is not None:
Laurent@2099: entries = device.GetEntriesList()
Laurent@2099: entry_infos = entries.get((index, subindex))
Laurent@2099: if entry_infos is not None:
Laurent@2099: return entry_infos["Type"]
Laurent@2099: return None
Laurent@2099:
Laurent@2098: def GetNodesVariables(self, vendor=None, slave_pos=None, slave_profile=None, limits=None):
Laurent@2098: entries = []
Laurent@2098: for slave_position in self.GetSlaves():
Laurent@2098: if slave_pos is not None and slave_position != slave_pos:
Laurent@2098: continue
Laurent@2098: slave = self.GetSlave(slave_position)
Laurent@2098: type_infos = slave.getType()
Laurent@2098: if vendor is not None and ExtractHexDecValue(type_infos["vendor"]) != vendor:
Laurent@2098: continue
Laurent@2098: device, alignment = self.GetModuleInfos(type_infos)
Laurent@2098: if slave_profile is not None and slave_profile not in device.GetProfileNumbers():
Laurent@2098: continue
Laurent@2098: entries.extend(self.GetSlaveVariables(slave_position, limits, device))
Laurent@2098: return entries
Laurent@2098:
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@2098: def GetLibraryVendors(self):
Laurent@2098: return self.CTNParent.GetVendors()
Laurent@2098:
laurent@2041: def GetDeviceLocationTree(self, slave_pos, current_location, device_name):
laurent@2041: slave = self.GetSlave(slave_pos)
Laurent@2062: vars = []
laurent@2041: if slave is not None:
laurent@2041: type_infos = slave.getType()
laurent@2041:
Laurent@2098: device, alignment = 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@2098: return self.ChangesToSave or not self.ModelIsSaved()
laurent@2022:
Edouard@2048: def OnCTNSave(self):
Laurent@2098: config_filepath = self.ConfigFileName()
Laurent@2098:
Laurent@2098: config_text = "\n"
Laurent@2098: config_extras = {"xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance",
laurent@2022: "xsi:noNamespaceSchemaLocation" : "EtherCATInfo.xsd"}
Laurent@2098: config_text += self.Config.generateXMLText("EtherCATConfig", 0, config_extras)
Laurent@2098:
Laurent@2098: config_xmlfile = open(config_filepath,"w")
Laurent@2098: config_xmlfile.write(config_text.encode("utf-8"))
Laurent@2098: config_xmlfile.close()
Laurent@2098:
Laurent@2098: process_filepath = self.ProcessVariablesFileName()
Laurent@2098:
Laurent@2098: process_text = "\n"
Laurent@2098: process_extras = {"xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance"}
Laurent@2098: process_text += self.ProcessVariables.generateXMLText("ProcessVariables", 0, process_extras)
Laurent@2098:
Laurent@2098: process_xmlfile = open(process_filepath,"w")
Laurent@2098: process_xmlfile.write(process_text.encode("utf-8"))
Laurent@2098: process_xmlfile.close()
Laurent@2098:
Laurent@2098: self.Buffer.CurrentSaved()
laurent@2022: return True
laurent@2022:
Laurent@2101: def GetProcessVariableName(self, location, var_type):
Laurent@2101: return "__M%s_%s" % (self.GetSizeOfType(var_type), "_".join(map(str, location)))
Laurent@2101:
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@2103: for idx, variable in enumerate(self.ProcessVariables.getvariable()):
Laurent@2101: name = None
Laurent@2101: var_type = None
Laurent@2101: read_from = variable.getReadFrom()
Laurent@2101: write_to = variable.getWriteTo()
Laurent@2101: if read_from is not None:
Laurent@2101: pos = read_from.getPosition()
Laurent@2101: index = read_from.getIndex()
Laurent@2101: subindex = read_from.getSubIndex()
Laurent@2103: location = current_location + (idx, )
Laurent@2101: var_type = self.GetSlaveVariableDataType(pos, index, subindex)
Laurent@2101: name = self.FileGenerator.DeclareVariable(
Laurent@2101: pos, index, subindex, var_type, "I",
Laurent@2101: self.GetProcessVariableName(location, var_type))
Laurent@2101: if write_to is not None:
Laurent@2101: pos = write_to.getPosition()
Laurent@2101: index = write_to.getIndex()
Laurent@2101: subindex = write_to.getSubIndex()
Laurent@2101: if name is None:
Laurent@2103: location = current_location + (idx, )
Laurent@2101: var_type = self.GetSlaveVariableDataType(pos, index, subindex)
Laurent@2101: name = self.GetProcessVariableName(location, var_type)
Laurent@2101: self.FileGenerator.DeclareVariable(
Laurent@2103: pos, index, subindex, var_type, "Q", name, True)
Laurent@2101:
Laurent@2099: self.FileGenerator.GenerateCFile(Gen_Ethercatfile_path, location_str, self.BaseParams.getIEC_Channel())
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 = [
Laurent@2068: {"bitmap" : "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@2099: self.FileGenerator.DeclareSlave(slave_pos, slave)
laurent@2022:
laurent@2022: for location in locations:
laurent@2022: loc = location["LOC"][len(current_location):]
laurent@2041: slave_pos = loc[0]
Laurent@2101: if slave_pos in slaves and len(loc) == 3 and location["DIR"] != "M":
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@2098: def CreateBuffer(self, saved):
Laurent@2098: self.Buffer = UndoBuffer(cPickle.dumps((self.Config, self.ProcessVariables)), saved)
Laurent@2098:
Laurent@2098: def BufferModel(self):
Laurent@2098: self.Buffer.Buffering(cPickle.dumps((self.Config, self.ProcessVariables)))
Laurent@2098:
Laurent@2098: def ModelIsSaved(self):
Laurent@2098: if self.Buffer is not None:
Laurent@2098: return self.Buffer.IsCurrentSaved()
laurent@2022: else:
laurent@2022: return True
laurent@2022:
laurent@2022: def LoadPrevious(self):
Laurent@2098: self.Config, self.ProcessVariables = cPickle.loads(self.Buffer.Previous())
laurent@2022:
laurent@2022: def LoadNext(self):
Laurent@2098: self.Config, self.ProcessVariables = cPickle.loads(self.Buffer.Next())
laurent@2022:
laurent@2022: def GetBufferState(self):
Laurent@2098: first = self.Buffer.IsFirst()
Laurent@2098: last = self.Buffer.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@2081: uint8_t value[%(data_size)d];
Laurent@2081: EC_WRITE_%(data_type)s((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@2081: %(real_var)s = EC_READ_%(data_type)s((uint8_t *)value);
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@2103: if not entry_infos.get("no_decl", False):
Laurent@2103: if entry_infos.has_key("real_var"):
Laurent@2103: str_completion["located_variables_declaration"].append(
Laurent@2103: "IEC_%(var_type)s %(real_var)s;" % entry_infos)
Laurent@2103: else:
Laurent@2103: entry_infos["real_var"] = "beremiz" + entry_infos["var_name"]
Laurent@2103: str_completion["located_variables_declaration"].extend(
Laurent@2103: ["IEC_%(var_type)s %(real_var)s;" % entry_infos,
Laurent@2103: "IEC_%(var_type)s *%(var_name)s = &%(real_var)s;" % entry_infos])
Laurent@2103: for declaration in entry_infos.get("extra_declarations", []):
Laurent@2103: entry_infos["extra_decl"] = declaration
Laurent@2103: str_completion["located_variables_declaration"].append(
Laurent@2103: "IEC_%(var_type)s *%(extra_decl)s = &%(real_var)s;" % entry_infos)
Laurent@2103: elif not entry_infos.has_key("real_var"):
laurent@2039: entry_infos["real_var"] = "beremiz" + entry_infos["var_name"]
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@2082: def ExclusionSortFunction(x, y):
Laurent@2082: if x["matching"] == y["matching"]:
Laurent@2082: if x["assigned"] and not y["assigned"]:
Laurent@2082: return -1
Laurent@2082: elif not x["assigned"] and y["assigned"]:
Laurent@2082: return 1
Laurent@2082: return cmp(x["count"], y["count"])
Laurent@2082: return -cmp(x["matching"], y["matching"])
Laurent@2082:
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@2079:
Laurent@2099: def DeclareSlave(self, slave_index, slave):
Laurent@2099: self.Slaves.append((slave_index, slave.getInfo().getAutoIncAddr(), slave))
laurent@2041:
Laurent@2103: def DeclareVariable(self, slave_index, index, subindex, iec_type, dir, name, no_decl=False):
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@2103: "infos": (iec_type, dir, name, no_decl, []),
laurent@2029: "mapped": False}
Laurent@2101: return name
Laurent@2101: elif entry_infos["infos"][:2] == (iec_type, dir):
Laurent@2101: if name != entry_infos["infos"][2]:
Laurent@2101: if dir == "I":
Laurent@2101: entry_infos["infos"][3].append(name)
Laurent@2101: return entry_infos["infos"][2]
Laurent@2101: else:
Laurent@2101: raise ValueError, _("Output variables can't be defined with different locations (%s and %s)") % (entry_infos["infos"][2], name)
Laurent@2101: else:
laurent@2022: raise ValueError, _("Definition conflict for location \"%s\"") % name
laurent@2029:
Laurent@2099: def GenerateCFile(self, filepath, location_str, master_number):
laurent@2022:
Laurent@2079: # Extract etherlab master code template
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@2079: # Initialize strings for formatting master code template
laurent@2022: str_completion = {
laurent@2022: "location": location_str,
Laurent@2099: "master_number": master_number,
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@2079: # Initialize variable storing variable mapping state
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@2079: # Sort slaves by position (IEC_Channel)
laurent@2041: self.Slaves.sort()
Laurent@2079: # Initialize dictionary storing alias auto-increment position values
laurent@2041: alias = {}
Laurent@2079:
Laurent@2079: # Generating code for each slave
Laurent@2099: for (slave_idx, slave_alias, slave) in self.Slaves:
Laurent@2099: type_infos = slave.getType()
Laurent@2079:
Laurent@2079: # Defining slave alias and auto-increment position
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@2079: # Extract slave device informations
Laurent@2098: device, alignment = self.Controler.GetModuleInfos(type_infos)
laurent@2032: if device is not None:
Laurent@2079:
Laurent@2079: # Extract slaves variables to be mapped
laurent@2041: slave_variables = self.UsedVariables.get(slave_idx, {})
Laurent@2079:
Laurent@2079: # Extract slave device object dictionary entries
laurent@2032: device_entries = device.GetEntriesList()
laurent@2022:
Laurent@2079: # Adding code for declaring slave in master code template strings
Laurent@2079: for element in ["vendor", "product_code", "revision_number"]:
Laurent@2079: type_infos[element] = ExtractHexDecValue(type_infos[element])
Laurent@2079: type_infos.update(dict(zip(["slave", "alias", "position"], (slave_idx,) + slave_pos)))
Laurent@2079:
Laurent@2079: # Extract slave device CoE informations
Laurent@2079: device_coe = device.getCoE()
Laurent@2079: if device_coe is not None:
laurent@2022:
Laurent@2079: # If device support CanOpen over Ethernet, adding code for calling
Laurent@2079: # init commands when initializing slave in master code template strings
Laurent@2099: initCmds = []
Laurent@2079: for initCmd in device_coe.getInitCmd():
Laurent@2099: initCmds.append({
Laurent@2099: "Index": ExtractHexDecValue(initCmd.getIndex()),
Laurent@2099: "Subindex": ExtractHexDecValue(initCmd.getSubIndex()),
Laurent@2099: "Value": initCmd.getData().getcontent()})
Laurent@2099: initCmds.extend(slave.getStartupCommands())
Laurent@2099: for initCmd in initCmds:
Laurent@2099: index = initCmd["Index"]
Laurent@2099: subindex = initCmd["Subindex"]
laurent@2032: entry = device_entries.get((index, subindex), None)
laurent@2032: if entry is not None:
laurent@2032: data_size = entry["BitSize"] / 8
Laurent@2099: data_str = ("0x%%.%dx" % (data_size * 2)) % initCmd["Value"]
laurent@2032: init_cmd_infos = {
laurent@2032: "index": index,
laurent@2032: "subindex": subindex,
laurent@2032: "data": data_str,
Laurent@2081: "data_type": DATATYPECONVERSION.get(entry["Type"]),
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@2079:
Laurent@2079: # Extract slave device PDO configuration capabilities
Laurent@2079: PdoAssign = device_coe.getPdoAssign()
Laurent@2079: PdoConfig = device_coe.getPdoConfig()
Laurent@2079: else:
Laurent@2079: PdoAssign = PdoConfig = False
Laurent@2079:
Laurent@2079: # Test if slave has a configuration or need one
Laurent@2079: if len(device.getTxPdo() + device.getRxPdo()) > 0 or len(slave_variables) > 0 and PdoConfig and PdoAssign:
Laurent@2079:
Laurent@2079: str_completion["slaves_declaration"] += "static ec_slave_config_t *slave%(slave)d = NULL;\n" % type_infos
Laurent@2079: str_completion["slaves_configuration"] += SLAVE_CONFIGURATION_TEMPLATE % type_infos
Laurent@2079:
Laurent@2079: # Initializing
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@2082: exclusive_pdos = {}
Laurent@2082: selected_pdos = []
Laurent@2082: for pdo, pdo_type in ([(pdo, "Inputs") for pdo in device.getTxPdo()] +
Laurent@2082: [(pdo, "Outputs") for pdo in device.getRxPdo()]):
Laurent@2082:
Laurent@2082: pdo_index = ExtractHexDecValue(pdo.getIndex().getcontent())
Laurent@2082: pdos_index.append(pdo_index)
Laurent@2082:
Laurent@2082: excluded_list = pdo.getExclude()
Laurent@2082: if len(excluded_list) > 0:
Laurent@2082: exclusion_list = [pdo_index]
Laurent@2082: for excluded in excluded_list:
Laurent@2082: exclusion_list.append(ExtractHexDecValue(excluded.getcontent()))
Laurent@2082: exclusion_list.sort()
Laurent@2082:
Laurent@2082: exclusion_scope = exclusive_pdos.setdefault(tuple(exclusion_list), [])
Laurent@2082:
laurent@2032: entries = pdo.getEntry()
Laurent@2082: pdo_mapping_match = {
Laurent@2082: "index": pdo_index,
Laurent@2082: "matching": 0,
Laurent@2082: "count": len(entries),
Laurent@2082: "assigned": pdo.getSm() is not None
Laurent@2082: }
Laurent@2082: exclusion_scope.append(pdo_mapping_match)
laurent@2032:
laurent@2032: for entry in entries:
laurent@2032: index = ExtractHexDecValue(entry.getIndex().getcontent())
laurent@2032: subindex = ExtractHexDecValue(entry.getSubIndex())
Laurent@2082: if slave_variables.get((index, subindex), None) is not None:
Laurent@2082: pdo_mapping_match["matching"] += 1
Laurent@2082:
Laurent@2082: elif pdo.getMandatory():
Laurent@2082: selected_pdos.append(pdo_index)
laurent@2032:
Laurent@2082: excluded_pdos = []
Laurent@2082: for exclusion_scope in exclusive_pdos.itervalues():
Laurent@2082: exclusion_scope.sort(ExclusionSortFunction)
Laurent@2082: start_excluding_index = 0
Laurent@2082: if exclusion_scope[0]["matching"] > 0:
Laurent@2082: selected_pdos.append(exclusion_scope[0]["index"])
Laurent@2082: start_excluding_index = 1
Laurent@2082: excluded_pdos.extend([pdo["index"] for pdo in exclusion_scope[start_excluding_index:] if PdoAssign or not pdo["assigned"]])
Laurent@2082:
Laurent@2082: for pdo, pdo_type in ([(pdo, "Inputs") for pdo in device.getTxPdo()] +
Laurent@2082: [(pdo, "Outputs") for pdo in device.getRxPdo()]):
Laurent@2082: entries = pdo.getEntry()
Laurent@2082:
Laurent@2082: pdo_index = ExtractHexDecValue(pdo.getIndex().getcontent())
Laurent@2082: if pdo_index in excluded_pdos:
Laurent@2082: continue
Laurent@2082:
Laurent@2082: pdo_needed = pdo_index in selected_pdos
Laurent@2082:
Laurent@2082: entries_infos = []
Laurent@2082:
Laurent@2082: for entry in entries:
Laurent@2082: index = ExtractHexDecValue(entry.getIndex().getcontent())
Laurent@2082: subindex = ExtractHexDecValue(entry.getSubIndex())
Laurent@2082: entry_infos = {
Laurent@2082: "index": index,
Laurent@2082: "subindex": subindex,
Laurent@2082: "name": ExtractName(entry.getName()),
Laurent@2082: "bitlen": entry.getBitLen(),
Laurent@2082: }
Laurent@2082: entry_infos.update(type_infos)
Laurent@2082: entries_infos.append(" {0x%(index).4x, 0x%(subindex).2x, %(bitlen)d}, /* %(name)s */" % entry_infos)
Laurent@2082:
Laurent@2082: entry_declaration = slave_variables.get((index, subindex), None)
Laurent@2082: if entry_declaration is not None and not entry_declaration["mapped"]:
Laurent@2082: pdo_needed = True
Laurent@2082:
Laurent@2103: entry_infos.update(dict(zip(["var_type", "dir", "var_name", "no_decl", "extra_declarations"],
Laurent@2103: entry_declaration["infos"])))
Laurent@2082: entry_declaration["mapped"] = True
Laurent@2082:
Laurent@2082: entry_type = entry.getDataType().getcontent()
Laurent@2082: if entry_infos["var_type"] != entry_type:
Laurent@2082: message = _("Wrong type for location \"%s\"!") % entry_infos["var_name"]
Laurent@2082: if (self.Controler.GetSizeOfType(entry_infos["var_type"]) !=
Laurent@2082: self.Controler.GetSizeOfType(entry_type)):
Laurent@2082: raise ValueError, message
Laurent@2082: else:
Laurent@2082: self.Controler.GetCTRoot().logger.write_warning(_("Warning: ") + message + "\n")
Laurent@2082:
Laurent@2082: if (entry_infos["dir"] == "I" and pdo_type != "Inputs" or
Laurent@2082: entry_infos["dir"] == "Q" and pdo_type != "Outputs"):
Laurent@2082: raise ValueError, _("Wrong direction for location \"%s\"!") % entry_infos["var_name"]
Laurent@2082:
Laurent@2082: ConfigureVariable(entry_infos, str_completion)
Laurent@2082:
Laurent@2082: elif pdo_type == "Outputs" and entry.getDataType() is not None and device_coe is not None:
Laurent@2082: data_type = entry.getDataType().getcontent()
Laurent@2082: entry_infos["dir"] = "Q"
Laurent@2082: entry_infos["data_size"] = max(1, entry_infos["bitlen"] / 8)
Laurent@2082: entry_infos["data_type"] = DATATYPECONVERSION.get(data_type)
Laurent@2082: entry_infos["var_type"] = data_type
Laurent@2082: entry_infos["real_var"] = "slave%(slave)d_%(index).4x_%(subindex).2x_default" % entry_infos
Laurent@2082:
Laurent@2082: ConfigureVariable(entry_infos, str_completion)
Laurent@2082:
Laurent@2082: str_completion["slaves_output_pdos_default_values_extraction"] += \
Laurent@2082: SLAVE_OUTPUT_PDO_DEFAULT_VALUE % entry_infos
Laurent@2082:
Laurent@2082: if pdo_needed:
Laurent@2082: for excluded in pdo.getExclude():
Laurent@2082: excluded_index = ExtractHexDecValue(excluded.getcontent())
Laurent@2082: if excluded_index not in excluded_pdos:
Laurent@2082: excluded_pdos.append(excluded_index)
Laurent@2082:
Laurent@2082: sm = pdo.getSm()
Laurent@2082: if sm is None:
Laurent@2082: for sm_idx, sync_manager in enumerate(sync_managers):
Laurent@2082: if sync_manager["name"] == pdo_type:
Laurent@2082: sm = sm_idx
Laurent@2082: if sm is None:
Laurent@2082: raise ValueError, _("No sync manager available for %s pdo!") % pdo_type
Laurent@2082:
Laurent@2082: sync_managers[sm]["pdos_number"] += 1
Laurent@2082: sync_managers[sm]["pdos"].append(
Laurent@2082: {"slave": slave_idx,
Laurent@2082: "index": pdo_index,
Laurent@2082: "name": ExtractName(pdo.getName()),
Laurent@2082: "type": pdo_type,
Laurent@2082: "entries": entries_infos,
Laurent@2082: "entries_number": len(entries_infos),
Laurent@2082: "fixed": pdo.getFixed() == True})
Laurent@2082:
Laurent@2079: if PdoConfig and PdoAssign:
Laurent@2062: dynamic_pdos = {}
Laurent@2062: dynamic_pdos_number = 0
Laurent@2062: for category, min_index, max_index in [("Inputs", 0x1600, 0x1800),
Laurent@2062: ("Outputs", 0x1a00, 0x1C00)]:
Laurent@2062: for sync_manager in sync_managers:
Laurent@2062: if sync_manager["name"] == category:
Laurent@2062: category_infos = dynamic_pdos.setdefault(category, {})
Laurent@2062: category_infos["sync_manager"] = sync_manager
Laurent@2062: category_infos["pdos"] = [pdo for pdo in category_infos["sync_manager"]["pdos"]
Laurent@2062: if not pdo["fixed"] and pdo["type"] == category]
Laurent@2062: category_infos["current_index"] = min_index
Laurent@2062: category_infos["max_index"] = max_index
Laurent@2062: break
laurent@2032:
Laurent@2062: for (index, subindex), entry_declaration in slave_variables.iteritems():
laurent@2032:
Laurent@2062: if not entry_declaration["mapped"]:
Laurent@2062: entry = device_entries.get((index, subindex), None)
Laurent@2062: if entry is None:
Laurent@2062: raise ValueError, _("Unknown entry index 0x%4.4x, subindex 0x%2.2x for device %s") % \
Laurent@2062: (index, subindex, type_infos["device_type"])
Laurent@2062:
Laurent@2062: entry_infos = {
Laurent@2062: "index": index,
Laurent@2062: "subindex": subindex,
Laurent@2062: "name": entry["Name"],
Laurent@2062: "bitlen": entry["BitSize"],
Laurent@2062: }
Laurent@2062: entry_infos.update(type_infos)
Laurent@2062:
Laurent@2103: entry_infos.update(dict(zip(["var_type", "dir", "var_name", "no_decl", "extra_declarations"],
Laurent@2103: entry_declaration["infos"])))
Laurent@2062: entry_declaration["mapped"] = True
Laurent@2062:
Laurent@2062: if entry_infos["var_type"] != entry["Type"]:
Laurent@2062: message = _("Wrong type for location \"%s\"!") % entry_infos["var_name"]
Laurent@2062: if (self.Controler.GetSizeOfType(entry_infos["var_type"]) !=
Laurent@2062: self.Controler.GetSizeOfType(entry["Type"])):
Laurent@2062: raise ValueError, message
Laurent@2062: else:
Laurent@2062: self.Controler.GetCTRoot().logger.write_warning(message + "\n")
Laurent@2062:
Laurent@2062: if entry_infos["dir"] == "I" and entry["PDOMapping"] in ["T", "RT"]:
Laurent@2062: pdo_type = "Inputs"
Laurent@2062: elif entry_infos["dir"] == "Q" and entry["PDOMapping"] in ["R", "RT"]:
Laurent@2062: pdo_type = "Outputs"
laurent@2045: else:
Laurent@2062: raise ValueError, _("Wrong direction for location \"%s\"!") % entry_infos["var_name"]
laurent@2029:
Laurent@2062: if not dynamic_pdos.has_key(pdo_type):
Laurent@2062: raise ValueError, _("No Sync manager defined for %s!") % pdo_type
Laurent@2062:
Laurent@2062: ConfigureVariable(entry_infos, str_completion)
Laurent@2062:
Laurent@2062: if len(dynamic_pdos[pdo_type]["pdos"]) > 0:
Laurent@2062: pdo = dynamic_pdos[pdo_type]["pdos"][0]
Laurent@2062: else:
Laurent@2062: while dynamic_pdos[pdo_type]["current_index"] in pdos_index:
Laurent@2062: dynamic_pdos[pdo_type]["current_index"] += 1
Laurent@2062: if dynamic_pdos[pdo_type]["current_index"] >= dynamic_pdos[pdo_type]["max_index"]:
Laurent@2062: raise ValueError, _("No more free PDO index available for %s!") % pdo_type
Laurent@2062: pdos_index.append(dynamic_pdos[pdo_type]["current_index"])
Laurent@2062:
Laurent@2062: dynamic_pdos_number += 1
Laurent@2062: pdo = {"slave": slave_idx,
Laurent@2062: "index": dynamic_pdos[pdo_type]["current_index"],
Laurent@2062: "name": "Dynamic PDO %d" % dynamic_pdos_number,
Laurent@2062: "type": pdo_type,
Laurent@2062: "entries": [],
Laurent@2062: "entries_number": 0,
Laurent@2062: "fixed": False}
Laurent@2062: dynamic_pdos[pdo_type]["sync_manager"]["pdos_number"] += 1
Laurent@2062: dynamic_pdos[pdo_type]["sync_manager"]["pdos"].append(pdo)
Laurent@2062: dynamic_pdos[pdo_type]["pdos"].append(pdo)
Laurent@2062:
Laurent@2062: pdo["entries"].append(" {0x%(index).4x, 0x%(subindex).2x, %(bitlen)d}, /* %(name)s */" % entry_infos)
Laurent@2099: if entry_infos["bitlen"] < alignment:
Laurent@2101: print (alignment, entry_infos["bitlen"])
Laurent@2099: pdo["entries"].append(" {0x0000, 0x00, %d}, /* None */" % (alignment - entry_infos["bitlen"]))
Laurent@2062: pdo["entries_number"] += 1
Laurent@2062:
Laurent@2062: if pdo["entries_number"] == 255:
Laurent@2062: dynamic_pdos[pdo_type]["pdos"].pop(0)
Laurent@2079:
laurent@2032: pdo_offset = 0
laurent@2032: entry_offset = 0
laurent@2032: for sync_manager_infos in sync_managers:
Laurent@2079:
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@2079:
Laurent@2079: for (index, subindex), entry_declaration in slave_variables.iteritems():
Laurent@2079: if not entry_declaration["mapped"]:
Laurent@2079: message = _("Entry index 0x%4.4x, subindex 0x%2.2x not mapped for device %s") % \
Laurent@2079: (index, subindex, type_infos["device_type"])
Laurent@2079: self.Controler.GetCTRoot().logger.write_warning(_("Warning: ") + message + "\n")
Laurent@2079:
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@2074: cls = EtherCATInfoClasses["EtherCATBase.xsd"].get("DictionaryType", None)
Laurent@2074: if cls:
Laurent@2074: cls.loadXMLTreeArgs = None
Laurent@2074:
Laurent@2074: setattr(cls, "_loadXMLTree", getattr(cls, "loadXMLTree"))
Laurent@2074:
Laurent@2074: def loadXMLTree(self, *args):
Laurent@2074: self.loadXMLTreeArgs = args
Laurent@2074: setattr(cls, "loadXMLTree", loadXMLTree)
Laurent@2074:
Laurent@2074: def load(self):
Laurent@2074: if self.loadXMLTreeArgs is not None:
Laurent@2074: self._loadXMLTree(*self.loadXMLTreeArgs)
Laurent@2074: self.loadXMLTreeArgs = None
Laurent@2074: setattr(cls, "load", load)
Laurent@2074:
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@2098: dictionary.load()
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@2079: def getCoE(self):
laurent@2032: mailbox = self.getMailbox()
Laurent@2079: if mailbox is not None:
Laurent@2079: return mailbox.getCoE()
Laurent@2079: return None
Laurent@2079: setattr(cls, "getCoE", getCoE)
laurent@2032:
Laurent@2098: def GetEntriesList(self, limits=None):
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@2074: dictionary.load()
laurent@2029:
laurent@2029: for object in dictionary.getObjects().getObject():
laurent@2029: entry_index = object.getIndex().getcontent()
laurent@2029: index = ExtractHexDecValue(entry_index)
Laurent@2098: if limits is None or limits[0] <= index <= limits[1]:
Laurent@2098: entry_type = object.getType()
Laurent@2098: entry_name = ExtractName(object.getName())
Laurent@2098:
Laurent@2098: entry_type_infos = self.DataTypes.get(entry_type, None)
Laurent@2098: if entry_type_infos is not None:
Laurent@2098: content = entry_type_infos.getcontent()
Laurent@2098: for subitem in content["value"]:
Laurent@2098: entry_subidx = subitem.getSubIdx()
Laurent@2098: if entry_subidx is None:
Laurent@2098: entry_subidx = "0"
Laurent@2098: subidx = ExtractHexDecValue(entry_subidx)
Laurent@2098: subitem_access = ""
Laurent@2098: subitem_pdomapping = ""
Laurent@2098: subitem_flags = subitem.getFlags()
Laurent@2098: if subitem_flags is not None:
Laurent@2098: access = subitem_flags.getAccess()
Laurent@2098: if access is not None:
Laurent@2098: subitem_access = access.getcontent()
Laurent@2098: pdomapping = subitem_flags.getPdoMapping()
Laurent@2098: if pdomapping is not None:
Laurent@2098: subitem_pdomapping = pdomapping.upper()
Laurent@2098: entries[(index, subidx)] = {
Laurent@2098: "Index": entry_index,
Laurent@2098: "SubIndex": entry_subidx,
Laurent@2098: "Name": "%s - %s" %
Laurent@2098: (entry_name.decode("utf-8"),
Laurent@2098: ExtractName(subitem.getDisplayName(),
Laurent@2098: subitem.getName()).decode("utf-8")),
Laurent@2098: "Type": subitem.getType(),
Laurent@2098: "BitSize": subitem.getBitSize(),
Laurent@2098: "Access": subitem_access,
Laurent@2098: "PDOMapping": subitem_pdomapping}
Laurent@2098: else:
Laurent@2098: entry_access = ""
Laurent@2098: entry_pdomapping = ""
Laurent@2098: entry_flags = object.getFlags()
Laurent@2098: if entry_flags is not None:
Laurent@2098: access = entry_flags.getAccess()
laurent@2029: if access is not None:
Laurent@2098: entry_access = access.getcontent()
Laurent@2098: pdomapping = entry_flags.getPdoMapping()
laurent@2032: if pdomapping is not None:
Laurent@2098: entry_pdomapping = pdomapping.upper()
Laurent@2098: entries[(index, 0)] = {
Laurent@2098: "Index": entry_index,
Laurent@2098: "SubIndex": "0",
Laurent@2098: "Name": entry_name,
Laurent@2098: "Type": entry_type,
Laurent@2098: "BitSize": object.getBitSize(),
Laurent@2098: "Access": entry_access,
Laurent@2098: "PDOMapping": entry_pdomapping}
laurent@2029:
laurent@2029: for TxPdo in self.getTxPdo():
Laurent@2098: ExtractPdoInfos(TxPdo, "Transmit", entries, limits)
laurent@2029: for RxPdo in self.getRxPdo():
Laurent@2098: ExtractPdoInfos(RxPdo, "Receive", entries, limits)
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@2098: def ExtractPdoInfos(pdo, pdo_type, entries, limits=None):
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@2098: if limits is None or limits[0] <= index <= limits[1]:
Laurent@2098: entry = entries.get((index, subindex), None)
Laurent@2098: if entry is not None:
Laurent@2098: entry["PDO index"] = pdo_index
Laurent@2098: entry["PDO name"] = pdo_name
Laurent@2098: entry["PDO type"] = pdo_type
Laurent@2098: else:
Laurent@2098: entry_type = pdo_entry.getDataType()
Laurent@2098: if entry_type is not None:
Laurent@2098: if pdo_type == "Transmit":
Laurent@2098: access = "ro"
Laurent@2098: pdomapping = "T"
Laurent@2098: else:
Laurent@2098: access = "wo"
Laurent@2098: pdomapping = "R"
Laurent@2098: entries[(index, subindex)] = {
Laurent@2098: "Index": entry_index,
Laurent@2098: "SubIndex": entry_subindex,
Laurent@2098: "Name": ExtractName(pdo_entry.getName()),
Laurent@2098: "Type": entry_type.getcontent(),
Laurent@2098: "Access": access,
Laurent@2098: "PDOMapping": pdomapping}
Laurent@2097:
Laurent@2097: DEFAULT_ALIGNMENT = 8
Laurent@2097:
Laurent@2097: class ModulesLibrary:
Laurent@2097:
Laurent@2097: def __init__(self, path, parent_library=None):
Laurent@2097: self.Path = path
Laurent@2097: if not os.path.exists(self.Path):
Laurent@2097: os.makedirs(self.Path)
Laurent@2097: self.ParentLibrary = parent_library
Laurent@2097:
Laurent@2098: if parent_library is not None:
Laurent@2098: self.LoadModules()
Laurent@2098: else:
Laurent@2098: self.Library = None
Laurent@2097: self.LoadAlignments()
Laurent@2097:
Laurent@2097: def GetPath(self):
Laurent@2097: return self.Path
Laurent@2097:
Laurent@2097: def GetAlignmentFilePath(self):
Laurent@2097: return os.path.join(self.Path, "alignments.cfg")
Laurent@2097:
Laurent@2097: def LoadModules(self):
Laurent@2097: self.Library = {}
Laurent@2097:
Laurent@2097: files = os.listdir(self.Path)
laurent@2022: for file in files:
Laurent@2097: filepath = os.path.join(self.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@2097: vendor_category = self.Library.setdefault(ExtractHexDecValue(vendor.getId()),
Laurent@2097: {"name": ExtractName(vendor.getName(), _("Miscellaneous")),
Laurent@2097: "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@2097:
laurent@2041: def GetModulesLibrary(self, profile_filter=None):
Laurent@2098: if self.Library is None:
Laurent@2098: self.LoadModules()
laurent@2022: library = []
Laurent@2097: for vendor_id, vendor in self.Library.iteritems():
laurent@2022: groups = []
Laurent@2073: children_dict = {}
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@2097: product_code = device.getType().getProductCode()
Laurent@2097: revision_number = device.getType().getRevisionNo()
Laurent@2097: alignment = self.GetAlignment(vendor_id, product_code, revision_number)
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@2097: "product_code": product_code,
Laurent@2097: "revision_number": revision_number,
Laurent@2097: "alignment": alignment},
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@2097:
Laurent@2098: def GetVendors(self):
Laurent@2098: return [(vendor_id, vendor["name"]) for vendor_id, vendor in self.Library.items()]
Laurent@2098:
Laurent@2097: def GetModuleInfos(self, module_infos):
Laurent@2097: vendor = ExtractHexDecValue(module_infos["vendor"])
Laurent@2097: vendor_infos = self.Library.get(vendor)
Laurent@2097: if vendor_infos is not None:
Laurent@2097: for group_name, group_infos in vendor_infos["groups"].iteritems():
Laurent@2097: for device_type, device_infos in group_infos["devices"]:
Laurent@2097: product_code = ExtractHexDecValue(device_infos.getType().getProductCode())
Laurent@2097: revision_number = ExtractHexDecValue(device_infos.getType().getRevisionNo())
Laurent@2097: if (product_code == ExtractHexDecValue(module_infos["product_code"]) and
Laurent@2097: revision_number == ExtractHexDecValue(module_infos["revision_number"])):
Laurent@2097: return device_infos, self.GetAlignment(vendor, product_code, revision_number)
Laurent@2097: return None, None
Laurent@2097:
Laurent@2097: def ImportModuleLibrary(self, filepath):
Laurent@2097: if os.path.isfile(filepath):
Laurent@2097: shutil.copy(filepath, self.Path)
Laurent@2097: self.LoadModules()
Laurent@2097: return True
Laurent@2097: return False
Laurent@2097:
Laurent@2097: def LoadAlignments(self):
Laurent@2097: self.Alignments = {}
Laurent@2097:
Laurent@2097: csvfile_path = self.GetAlignmentFilePath()
Laurent@2097: if os.path.exists(csvfile_path):
Laurent@2097: csvfile = open(csvfile_path, "rb")
Laurent@2097: sample = csvfile.read(1024)
Laurent@2097: csvfile.seek(0)
Laurent@2097: dialect = csv.Sniffer().sniff(sample)
Laurent@2097: has_header = csv.Sniffer().has_header(sample)
Laurent@2097: reader = csv.reader(csvfile, dialect)
Laurent@2097: for row in reader:
Laurent@2097: if has_header:
Laurent@2097: has_header = False
Laurent@2097: else:
Laurent@2097: try:
Laurent@2101: self.Alignments[tuple(map(int, row[:3]))] = int(row[3])
Laurent@2097: except:
Laurent@2097: pass
Laurent@2097: csvfile.close()
Laurent@2097:
Laurent@2097: def SaveAlignments(self):
Laurent@2097: csvfile = open(self.GetAlignmentFilePath(), "wb")
Laurent@2097: writer = csv.writer(csvfile, delimiter=';')
Laurent@2097: writer.writerow(['Vendor', 'product_code', 'revision_number', 'alignment'])
Laurent@2097: for (vendor, product_code, revision_number), alignment in self.Alignments.iteritems():
Laurent@2097: writer.writerow([vendor, product_code, revision_number, alignment])
Laurent@2097: csvfile.close()
Laurent@2097:
Laurent@2097: def SetAlignment(self, vendor, product_code, revision_number, alignment):
Laurent@2097: vendor = ExtractHexDecValue(vendor)
Laurent@2097: product_code = ExtractHexDecValue(product_code)
Laurent@2097: revision_number = ExtractHexDecValue(revision_number)
Laurent@2097:
Laurent@2097: self.Alignments[tuple([vendor, product_code, revision_number])] = alignment
Laurent@2097: self.SaveAlignments()
Laurent@2097:
Laurent@2097: def GetAlignment(self, vendor, product_code, revision_number):
Laurent@2097: vendor = ExtractHexDecValue(vendor)
Laurent@2097: product_code = ExtractHexDecValue(product_code)
Laurent@2097: revision_number = ExtractHexDecValue(revision_number)
Laurent@2097:
Laurent@2097: alignment = self.Alignments.get(tuple([vendor, product_code, revision_number]))
Laurent@2097: if alignment is not None:
Laurent@2097: return alignment
Laurent@2097:
Laurent@2097: if self.ParentLibrary is not None:
Laurent@2097: return self.ParentLibrary.GetAlignment(vendor, product_code, revision_number)
Laurent@2097: return DEFAULT_ALIGNMENT
Laurent@2097:
Laurent@2097: USERDATA_DIR = wx.StandardPaths.Get().GetUserDataDir()
Laurent@2097: if wx.Platform != '__WXMSW__':
Laurent@2097: USERDATA_DIR += '_files'
Laurent@2097:
Laurent@2097: ModulesDatabase = ModulesLibrary(
Laurent@2097: os.path.join(USERDATA_DIR, "ethercat_modules"))
Laurent@2097:
Laurent@2097: class RootClass:
Laurent@2097:
Laurent@2097: CTNChildrenTypes = [("EthercatNode",_EthercatCTN,"Ethercat Master")]
Laurent@2097: EditorType = LibraryEditor
Laurent@2097:
Laurent@2097: def __init__(self):
Laurent@2097: self.ModulesLibrary = None
Laurent@2097: self.LoadModulesLibrary()
Laurent@2097:
Laurent@2097: def GetModulesLibraryPath(self):
Laurent@2097: return os.path.join(self.CTNPath(), "modules")
Laurent@2097:
Laurent@2097: def CTNGenerate_C(self, buildpath, locations):
Laurent@2097: return [],"",False
Laurent@2097:
Laurent@2097: def LoadModulesLibrary(self):
Laurent@2097: if self.ModulesLibrary is None:
Laurent@2097: self.ModulesLibrary = ModulesLibrary(self.GetModulesLibraryPath(), ModulesDatabase)
Laurent@2097: else:
Laurent@2097: self.ModulesLibrary.LoadModulesLibrary()
Laurent@2097:
Laurent@2097: def GetModulesDatabaseInstance(self):
Laurent@2097: return ModulesDatabase
Laurent@2097:
Laurent@2097: def GetModulesLibraryInstance(self):
Laurent@2097: return self.ModulesLibrary
Laurent@2097:
Laurent@2097: def GetModulesLibrary(self, profile_filter=None):
Laurent@2097: return self.ModulesLibrary.GetModulesLibrary(profile_filter)
Laurent@2097:
Laurent@2098: def GetVendors(self):
Laurent@2098: return self.ModulesLibrary.GetVendors()
Laurent@2098:
Laurent@2097: def GetModuleInfos(self, module_infos):
Laurent@2097: return self.ModulesLibrary.GetModuleInfos(module_infos)
laurent@2041:
laurent@2041: