plugins/canfestival/config_utils.py
changeset 58 c0741cc16c99
child 59 b6ff896ff58b
equal deleted inserted replaced
57:3b53f9a509d9 58:c0741cc16c99
       
     1 #!/usr/bin/env python
       
     2 # -*- coding: utf-8 -*-
       
     3 
       
     4 #This file is part of Beremiz, a Integrated Development Environment for
       
     5 #programming IEC 61131-3 automates supporting plcopen standard and CanFestival. 
       
     6 #
       
     7 #Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD
       
     8 #
       
     9 #See COPYING file for copyrights details.
       
    10 #
       
    11 #This library is free software; you can redistribute it and/or
       
    12 #modify it under the terms of the GNU General Public
       
    13 #License as published by the Free Software Foundation; either
       
    14 #version 2.1 of the License, or (at your option) any later version.
       
    15 #
       
    16 #This library is distributed in the hope that it will be useful,
       
    17 #but WITHOUT ANY WARRANTY; without even the implied warranty of
       
    18 #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
       
    19 #General Public License for more details.
       
    20 #
       
    21 #You should have received a copy of the GNU General Public
       
    22 #License along with this library; if not, write to the Free Software
       
    23 #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
       
    24 
       
    25 from types import *
       
    26 
       
    27 # Translation between IEC types and Can Open types
       
    28 IECToCOType = {"BOOL":0x01, "SINT":0x02, "INT":0x03,"DINT":0x04,"LINT":0x10,
       
    29                "USINT":0x05,"UINT":0x06,"UDINT":0x07,"ULINT":0x1B,"REAL":0x08,
       
    30                "LREAL":0x11,"STRING":0x09,"BYTE":0x05,"WORD":0x06,"DWORD":0x07,
       
    31                "LWORD":0x1B,"WSTRING":0x0B}
       
    32 
       
    33 # Constants for PDO types 
       
    34 RPDO = 1
       
    35 TPDO = 2
       
    36 
       
    37 SlavePDOType = {"I" : TPDO, "Q" : RPDO}
       
    38 InvertPDOType = {RPDO : TPDO, TPDO : RPDO}
       
    39 
       
    40 VariableIncrement = 0x100
       
    41 VariableStartIndex = {TPDO : 0x2000, RPDO : 0x4000}
       
    42 VariableDirText = {TPDO : "__I", RPDO : "__Q"}
       
    43 VariableTypeOffset = dict(zip(["","X","B","W","D","L"], range(6)))
       
    44 
       
    45 TrashVariables = [(1, 0x01), (8, 0x05), (16, 0x06), (32, 0x07), (64, 0x1B)]
       
    46 
       
    47 def LE_to_BE(value, size):
       
    48     """
       
    49     Convert Little Endian to Big Endian
       
    50     @param value: value expressed in integer
       
    51     @param size: number of bytes generated
       
    52     @return: a string containing the value converted
       
    53     """
       
    54     
       
    55     data = ("%" + str(size * 2) + "." + str(size * 2) + "X") % value
       
    56     list_car = [data[i:i+2] for i in xrange(0, len(data), 2)]
       
    57     list_car.reverse()
       
    58     return "".join([chr(int(car, 16)) for car in list_car])
       
    59 
       
    60 
       
    61 def GetNodePDOIndexes(node, type, parameters = False):
       
    62     """
       
    63     Find the PDO indexes of a node
       
    64     @param node: node 
       
    65     @param type: type of PDO searched (RPDO or TPDO or both)
       
    66     @param parameters: indicate which indexes are expected (PDO paramaters : True or PDO mappings : False)
       
    67     @return: a list of indexes found
       
    68     """
       
    69     
       
    70     indexes = []
       
    71     if type & RPDO:
       
    72         indexes.extend([idx for idx in node.GetIndexes() if 0x1400 <= idx <= 0x15FF])
       
    73     if type & TPDO:
       
    74         indexes.extend([idx for idx in node.GetIndexes() if 0x1800 <= idx <= 0x19FF])
       
    75     if not parameters:
       
    76         return [idx + 0x200 for idx in indexes]
       
    77     else:
       
    78         return indexes
       
    79 
       
    80 
       
    81 def SearchNodePDOMapping(loc_infos, node):
       
    82     """
       
    83     Find the PDO indexes of a node
       
    84     @param node: node 
       
    85     @param type: type of PDO searched (RPDO or TPDO or both)
       
    86     @param parameters: indicate which indexes are expected (PDO paramaters : True or PDO mappings : False)
       
    87     @return: a list of indexes found
       
    88     """
       
    89     
       
    90     typeinfos = node.GetEntryInfos(loc_infos["type"])
       
    91     model = (loc_infos["index"] << 16) + (loc_infos["subindex"] << 8) + typeinfos["size"]
       
    92     
       
    93     for PDOidx in GetNodePDOIndexes(node, loc_infos["pdotype"]):
       
    94         values = node.GetEntry(PDOidx)
       
    95         if values != None:
       
    96             for subindex, mapping in enumerate(values):
       
    97                 if subindex != 0 and mapping == model:
       
    98                     return PDOidx, subindex
       
    99     return None
       
   100 
       
   101 
       
   102 def GeneratePDOMappingDCF(idx, cobid, transmittype, pdomapping):
       
   103     """
       
   104     Build concise DCF value for configuring a PDO
       
   105     @param idx: index of PDO parameters
       
   106     @param cobid: PDO generated COB ID
       
   107     @param transmittype : PDO transmit type
       
   108     @param pdomapping: list of PDO mappings
       
   109     @return: a tuple of value and number of parameters to add to DCF 
       
   110     """
       
   111     
       
   112     # Create entry for RPDO or TPDO parameters and Disable PDO
       
   113     dcfdata = LE_to_BE(idx, 2) + LE_to_BE(0x01, 1) + LE_to_BE(0x04, 4) + LE_to_BE((0x80000000 + cobid), 4)
       
   114     # Set Transmit type synchrone
       
   115     dcfdata += LE_to_BE(idx, 2) + LE_to_BE(0x02, 1) + LE_to_BE(0x01, 4) + LE_to_BE(transmittype, 1)
       
   116     # Re-Enable PDO
       
   117     #         ---- INDEX -----   --- SUBINDEX ----   ----- SIZE ------   ------ DATA ------
       
   118     dcfdata += LE_to_BE(idx, 2) + LE_to_BE(0x01, 1) + LE_to_BE(0x04, 4) + LE_to_BE(0x00000000 + cobid, 4)
       
   119     nbparams = 3
       
   120     # Map Variables
       
   121     for subindex, (name, loc_infos) in enumerate(pdomapping):
       
   122         value = (loc_infos["index"] << 16) + (loc_infos["subindex"] << 8) + loc_infos["size"]
       
   123         dcfdata += LE_to_BE(idx + 0x200, 2) + LE_to_BE(subindex + 1, 1) + LE_to_BE(0x04, 4) + LE_to_BE(value, 4)
       
   124         nbparams += 1
       
   125     return dcfdata, nbparams
       
   126 
       
   127 class ConciseDCFGenerator:
       
   128 
       
   129     def __init__(self, nodelist, nodename):
       
   130         # Dictionary of location informations classed by name
       
   131         self.IECLocations = {}
       
   132         # Dictionary of location that have not been mapped yet
       
   133         self.LocationsNotMapped = {}
       
   134         # Dictionary of location informations classed by name
       
   135         self.MasterMapping = {}
       
   136         # List of COB IDs available
       
   137         self.ListCobIDAvailable = range(0x180, 0x580)
       
   138         self.SlavesPdoNumber = {}
       
   139         # Dictionary of mapping value where unexpected variables are stored
       
   140         self.TrashVariables = {}
       
   141         
       
   142         self.NodeList = nodelist
       
   143         self.Manager = self.NodeList.Manager
       
   144         self.MasterNode = self.Manager.GetCurrentNodeCopy()
       
   145         self.MasterNode.SetNodeName(nodename)
       
   146         self.PrepareMasterNode()
       
   147 
       
   148     
       
   149     def RemoveUsedNodeCobId(self, node):
       
   150         """
       
   151         Remove all PDO COB ID used by the given node from the list of available COB ID
       
   152         @param node: node
       
   153         @return: a tuple of number of RPDO and TPDO for the node
       
   154         """
       
   155         
       
   156         # Get list of all node TPDO and RPDO indexes
       
   157         nodeRpdoIndexes = GetNodePDOIndexes(node, RPDO, True)
       
   158         nodeTpdoIndexes = GetNodePDOIndexes(node, TPDO, True)
       
   159         
       
   160         # Mark all the COB ID of the node already mapped PDO as not available
       
   161         for PdoIdx in nodeRpdoIndexes + nodeTpdoIndexes:
       
   162             pdo_cobid = node.GetEntry(PdoIdx, 0x01)
       
   163             # Extract COB ID, if PDO isn't active
       
   164             if pdo_cobid > 0x600 :
       
   165                 pdo_cobid -= 0x80000000
       
   166             # Remove COB ID from the list of available COB ID
       
   167             if pdo_cobid in self.ListCobIDAvailable:
       
   168                 self.ListCobIDAvailable.remove(pdo_cobid)
       
   169         
       
   170         return len(nodeRpdoIndexes), len(nodeTpdoIndexes)
       
   171 
       
   172     
       
   173     def PrepareMasterNode(self):
       
   174         """
       
   175         Add mandatory entries for DCF generation into MasterNode.
       
   176         """
       
   177         
       
   178         # Adding DCF entry into Master node
       
   179         if not self.MasterNode.IsEntry(0x1F22):
       
   180             self.MasterNode.AddEntry(0x1F22, 1, "")
       
   181         self.Manager.AddSubentriesToCurrent(0x1F22, 127, self.MasterNode)
       
   182         
       
   183         # Adding trash mappable variables for unused mapped datas
       
   184         idxTrashVariables = 0x2000 + self.MasterNode.GetNodeID()
       
   185         # Add an entry for storing unexpected all variable
       
   186         self.Manager.AddMapVariableToCurrent(idxTrashVariables, self.MasterNode.GetNodeName()+"_trashvariables", 3, len(TrashVariables), self.MasterNode)
       
   187         for subidx, (size, typeidx) in enumerate(TrashVariables):
       
   188             # Add a subentry for storing unexpected variable of this size
       
   189             self.Manager.SetCurrentEntry(idxTrashVariables, subidx + 1, "TRASH%d" % size, "name", None, self.MasterNode)
       
   190             self.Manager.SetCurrentEntry(idxTrashVariables, subidx + 1, typeidx, "type", None, self.MasterNode)
       
   191             # Store the mapping value for this entry
       
   192             self.TrashVariables[size] = (idxTrashVariables << 16) + ((subidx + 1) << 8) + size
       
   193         
       
   194         RPDOnumber, TPDOnumber = self.RemoveUsedNodeCobId(self.MasterNode)
       
   195         
       
   196         # Store the indexes of the first RPDO and TPDO available for MasterNode
       
   197         self.CurrentPDOParamsIdx = {RPDO : 0x1400 + RPDOnumber, TPDO : 0x1800 + TPDOnumber}
       
   198 
       
   199         # Prepare MasterNode with all nodelist slaves
       
   200         for idx, (nodeid, nodeinfos) in enumerate(self.NodeList.SlaveNodes.items()):
       
   201             node = nodeinfos["Node"]
       
   202             node.SetNodeID(nodeid)
       
   203             
       
   204             RPDOnumber, TPDOnumber = self.RemoveUsedNodeCobId(node)
       
   205             
       
   206             # Store the number of TPDO and RPDO for this node
       
   207             self.SlavesPdoNumber[nodeid] = {RPDO : RPDOnumber, TPDO : TPDOnumber}
       
   208             
       
   209             # Get Slave's default SDO server parameters
       
   210             RSDO_cobid = node.GetEntry(0x1200,0x01)
       
   211             if not RSDO_cobid:
       
   212                 RSDO_cobid = 0x600 + nodeid
       
   213             TSDO_cobid = node.GetEntry(0x1200,0x02)
       
   214             if not TSDO_cobid:
       
   215                 TSDO_cobid = 0x580 + nodeid
       
   216             
       
   217             # Configure Master's SDO parameters entries
       
   218             self.Manager.ManageEntriesOfCurrent([0x1280 + idx], [], self.MasterNode)
       
   219             self.MasterNode.SetEntry(0x1280 + idx, 0x01, RSDO_cobid)
       
   220             self.MasterNode.SetEntry(0x1280 + idx, 0x02, TSDO_cobid)
       
   221             self.MasterNode.SetEntry(0x1280 + idx, 0x03, nodeid)        
       
   222         
       
   223     
       
   224     def GetMasterNode(self):
       
   225         """
       
   226         Return MasterNode.
       
   227         """
       
   228         return self.MasterNode
       
   229 
       
   230     
       
   231     def GetNewCobID(self, nodeid, type):
       
   232         """
       
   233         Select a COB ID from the list of those available
       
   234         @param nodeid: id of the slave (int)
       
   235         @param type: type of PDO (RPDO or TPDO)
       
   236         @return: a tuple of the COD ID and PDO index or None
       
   237         """
       
   238         # Verify that there is still some cobid available
       
   239         if len(self.ListCobIDAvailable) == 0:
       
   240             return None
       
   241         
       
   242         # Get the number of PDO of the type given for the node
       
   243         nbSlavePDO = self.SlavesPdoNumber[nodeid][type]
       
   244         if type == RPDO:
       
   245             if nbSlavePDO < 4:
       
   246                 # For the four first RPDO -> cobid = 0x200 + ( numPdo parameters * 0x100) + nodeid
       
   247                 newcobid = (0x200 + nbSlavePDO * 0x100 + nodeid)
       
   248                 # Return calculated cobid if it's still available
       
   249                 if newcobid in self.ListCobIDAvailable:
       
   250                     self.ListCobIDAvailable.remove(newcobid)
       
   251                     return newcobid, 0x1400 + nbSlavePDO
       
   252             # Return the first cobid available if no cobid found
       
   253             return self.ListCobIDAvailable.pop(0), 0x1400 + nbSlavePDO
       
   254     
       
   255         elif type == TPDO:
       
   256             if nbSlavePDO < 4:
       
   257                 # For the four first TPDO -> cobid = 0x180 + ( numPdo parameters * 0x100) + nodeid
       
   258                 newcobid = (0x180 + nbSlavePDO * 0x100 + nodeid)
       
   259                 # Return calculated cobid if it's still available
       
   260                 if newcobid in self.ListCobIDAvailable:
       
   261                     self.ListCobIDAvailable.remove(newcobid)
       
   262                     return newcobid, 0x1800 + nbSlavePDO
       
   263             # Return the first cobid available if no cobid found
       
   264             return self.ListCobIDAvailable.pop(0), 0x1800 + nbSlavePDO
       
   265         
       
   266         return None
       
   267     
       
   268     
       
   269     def AddParamsToDCF(self, nodeid, data, nbparams):
       
   270         """
       
   271         Select a COB ID from the list of those available
       
   272         @param nodeid: id of the slave (int)
       
   273         @param data: data to add to slave DCF (string)
       
   274         @param nbparams: number of params added to slave DCF (int)
       
   275         """
       
   276         # Get current DCF for slave
       
   277         nodeDCF = self.MasterNode.GetEntry(0x1F22, nodeid)
       
   278         
       
   279         # Extract data and number of params in current DCF
       
   280         if nodeDCF != None and nodeDCF != '':
       
   281             tmpnbparams = [i for i in nodeDCF[:4]]
       
   282             tmpnbparams.reverse()
       
   283             nbparams += int(''.join(["%2.2x"%ord(i) for i in tmpnbparams]), 16)
       
   284             data = nodeDCF[4:] + data
       
   285         
       
   286         # Build new DCF
       
   287         dcf = LE_to_BE(nbparams, 0x04) + data
       
   288         # Set new DCF for slave
       
   289         self.MasterNode.SetEntry(0x1F22, nodeid, dcf)
       
   290     
       
   291     def AddPDOMapping(self, nodeid, pdotype, pdomapping, sync_TPDOs):
       
   292         """
       
   293         Select a COB ID from the list of those available
       
   294         @param nodeid: id of the slave (int)
       
   295         @param pdotype: type of PDO to generated (RPDO or TPDO)
       
   296         @param pdomapping: list od variables to map with PDO
       
   297         """
       
   298         # Get a new cob id
       
   299         result = self.GetNewCobID(nodeid, pdotype)
       
   300         if result:
       
   301             new_cobid, new_idx = result
       
   302             
       
   303             # Increment the number of PDO of this type for node
       
   304             self.SlavesPdoNumber[nodeid][pdotype] += 1
       
   305             
       
   306             # Add an entry to MasterMapping
       
   307             self.MasterMapping[new_cobid] = {"type" : InvertPDOType[pdotype], 
       
   308                 "mapping" : [None] + [(loc_infos["type"], name) for name, loc_infos in pdomapping]}
       
   309             
       
   310             # Return the data to add to DCF
       
   311             if sync_TPDOs:
       
   312                 return GeneratePDOMappingDCF(new_idx, new_cobid, 0x01, pdomapping)
       
   313             else:
       
   314                 return GeneratePDOMappingDCF(new_idx, new_cobid, 0xFF, pdomapping)
       
   315         return 0, ""
       
   316     
       
   317     def GenerateDCF(self, locations, current_location, sync_TPDOs):
       
   318         """
       
   319         Generate Concise DCF of MasterNode for the locations list given
       
   320         @param locations: list of locations to be mapped
       
   321         @param current_location: tuple of the located prefixes not to be considered
       
   322         @param sync_TPDOs: indicate if TPDO must be synchronous
       
   323         """
       
   324         
       
   325         #-------------------------------------------------------------------------------
       
   326         #               Verify that locations correspond to real slave variables
       
   327         #-------------------------------------------------------------------------------
       
   328         
       
   329         # Get list of locations check if exists and mappables -> put them in IECLocations
       
   330         for location in locations:
       
   331             COlocationtype = IECToCOType[location["IEC_TYPE"]]
       
   332             name = location["NAME"]
       
   333             if name in self.IECLocations:
       
   334                 if self.IECLocations[name]["type"] != COlocationtype:
       
   335                     raise ValueError, "Conflict type for location \"%s\"" % name 
       
   336             else:
       
   337                 # Get only the part of the location that concern this node
       
   338                 loc = location["LOC"][len(current_location):]
       
   339                 # loc correspond to (ID, INDEX, SUBINDEX [,BIT])
       
   340                 if len(loc) not in (3, 4):
       
   341                     raise ValueError, "Bad location size : %s"%str(loc)
       
   342                 
       
   343                 direction = location["DIR"]
       
   344                 
       
   345                 sizelocation = location["SIZE"]
       
   346                 
       
   347                 # Extract and check nodeid
       
   348                 nodeid, index, subindex = loc[:3]
       
   349                 
       
   350                 # Check Id is in slave node list
       
   351                 if nodeid not in self.NodeList.SlaveNodes.keys():
       
   352                     raise ValueError, "Non existing node ID : %d (variable %s)" % (nodeid,name)
       
   353                 
       
   354                 # Get the model for this node (made from EDS)
       
   355                 node = self.NodeList.SlaveNodes[nodeid]["Node"]
       
   356                 
       
   357                 # Extract and check index and subindex
       
   358                 if not node.IsEntry(index, subindex):
       
   359                     raise ValueError, "No such index/subindex (%x,%x) in ID : %d (variable %s)" % (index,subindex,nodeid,name)
       
   360                 
       
   361                 # Get the entry info
       
   362                 subentry_infos = node.GetSubentryInfos(index, subindex)
       
   363                 
       
   364                 # If a PDO mappable
       
   365                 if subentry_infos and subentry_infos["pdo"]:
       
   366                     if sizelocation == "X" and len(loc) > 3:
       
   367                         numbit = loc[4]
       
   368                     elif sizelocation != "X" and len(loc) > 3:
       
   369                         raise ValueError, "Cannot set bit offset for non bool '%s' variable (ID:%d,Idx:%x,sIdx:%x))" % (name,nodeid,index,subindex)
       
   370                     else:
       
   371                         numbit = None
       
   372                     
       
   373                     entryinfos = node.GetSubentryInfos(index, subindex)
       
   374                     if entryinfos["type"] != COlocationtype:
       
   375                         raise ValueError, "Invalid type \"%s\"-> %d != %d  for location\"%s\"" % (location["IEC_TYPE"], COlocationtype, entryinfos["type"] , name)
       
   376                     
       
   377                     typeinfos = node.GetEntryInfos(COlocationtype)
       
   378                     self.IECLocations[name] = {"type":COlocationtype, "pdotype":SlavePDOType[direction],
       
   379                                                 "nodeid": nodeid, "index": index,"subindex": subindex,
       
   380                                                 "bit": numbit, "size": typeinfos["size"], "sizelocation": sizelocation}
       
   381                 else:
       
   382                     raise ValueError, "Not PDO mappable variable : '%s' (ID:%d,Idx:%x,sIdx:%x))" % (name,nodeid,index,subindex)
       
   383         
       
   384         #-------------------------------------------------------------------------------
       
   385         #                         Search for locations already mapped
       
   386         #-------------------------------------------------------------------------------
       
   387         
       
   388         for name, locationinfos in self.IECLocations.items():
       
   389             node = self.NodeList.SlaveNodes[locationinfos["nodeid"]]["Node"]
       
   390             
       
   391             # Search if slave has a PDO mapping this locations
       
   392             result = SearchNodePDOMapping(locationinfos, node)
       
   393             if result != None:
       
   394                 index, subindex = result
       
   395                 # Get COB ID of the PDO
       
   396                 cobid = self.NodeList.GetSlaveNodeEntry(locationinfos["nodeid"], index - 0x200, 1)
       
   397                 
       
   398                 # Verify that PDO transmit type is conform to sync_TPDOs
       
   399                 transmittype = self.NodeList.GetSlaveNodeEntry(locationinfos["nodeid"], index - 0x200, 2)
       
   400                 if sync_TPDOs and transmittype != 0x01 or transmittype != 0xFF:
       
   401                     if sync_TPDOs:
       
   402                         # Change TransmitType to SYNCHRONE
       
   403                         data, nbparams = GeneratePDOMappingDCF(index - 0x200, cobid, 0x01, [])
       
   404                     else:
       
   405                         # Change TransmitType to ASYCHRONE
       
   406                         data, nbparams = GeneratePDOMappingDCF(index - 0x200, cobid, 0xFF, [])
       
   407                     
       
   408                     # Add entry to slave dcf to change transmit type of 
       
   409                     self.AddParamsToDCF(locationinfos["nodeid"], data, nbparams)
       
   410                 
       
   411                 # Add PDO to MasterMapping
       
   412                 if cobid not in self.MasterMapping.keys():
       
   413                     mapping = [None]
       
   414                     values = node.GetEntry(index)
       
   415                     # Store the size of each entry mapped in PDO
       
   416                     for value in values[1:]:
       
   417                         mapping.append(value % 0x100)
       
   418                     self.MasterMapping[cobid] = {"type" : InvertPDOType[locationinfos["pdotype"]], "mapping" : mapping}
       
   419             
       
   420                 # Indicate that this PDO entry must be saved
       
   421                 self.MasterMapping[cobid]["mapping"][subindex] = (locationinfos["type"], name)
       
   422                 
       
   423             else:
       
   424                 # Add location to those that haven't been mapped yet
       
   425                 if locationinfos["nodeid"] not in self.LocationsNotMapped.keys():
       
   426                     self.LocationsNotMapped[locationinfos["nodeid"]] = {TPDO : [], RPDO : []}
       
   427                 self.LocationsNotMapped[locationinfos["nodeid"]][locationinfos["pdotype"]].append((name, locationinfos))
       
   428     
       
   429         #-------------------------------------------------------------------------------
       
   430         #                         Build concise DCF for the others locations
       
   431         #-------------------------------------------------------------------------------
       
   432         
       
   433         for nodeid, locations in self.LocationsNotMapped.items():
       
   434             node = nodelist.SlaveNodes[nodeid]["Node"]
       
   435             
       
   436             # Initialize number of params and data to add to node DCF
       
   437             nbparams = 0
       
   438             dataparams = ""
       
   439             
       
   440             # Generate the best PDO mapping for each type of PDO
       
   441             for pdotype in (TPDO, RPDO):
       
   442                 pdosize = 0
       
   443                 pdomapping = []
       
   444                 for name, loc_infos in locations[pdotype]:
       
   445                     pdosize += loc_infos["size"]
       
   446                     # If pdo's size > 64 bits
       
   447                     if pdosize > 64:
       
   448                         # Generate a new PDO Mapping
       
   449                         data, nbaddedparams = self.AddPDOMapping(nodeid, pdotype, pdomapping, sync_TPDOs)
       
   450                         dataparams += data
       
   451                         nbparams += nbaddedparams
       
   452                         pdosize = loc_infos["size"]
       
   453                         pdomapping = [(name, loc_infos)]
       
   454                     else:
       
   455                         pdomapping.append((name, loc_infos))
       
   456                 # If there isn't locations yet but there is still a PDO to generate
       
   457                 if len(pdomapping) > 0:
       
   458                     # Generate a new PDO Mapping
       
   459                     data, nbaddedparams = self.AddPDOMapping(nodeid, pdotype, pdomapping, sync_TPDOs)
       
   460                     dataparams += data
       
   461                     nbparams += nbaddedparams
       
   462             
       
   463             # Add number of params and data to node DCF
       
   464             self.AddParamsToDCF(nodeid, dataparams, nbparams)
       
   465         
       
   466         #-------------------------------------------------------------------------------
       
   467         #                         Master Node Configuration
       
   468         #-------------------------------------------------------------------------------
       
   469         
       
   470         # Generate Master's Configuration from informations stored in MasterMapping
       
   471         for cobid, pdo_infos in self.MasterMapping.items():
       
   472             # Get next PDO index in MasterNode for this PDO type
       
   473             current_idx = self.CurrentPDOParamsIdx[pdo_infos["type"]]
       
   474             
       
   475             # Search if there is already a PDO in MasterNode with this cob id
       
   476             for idx in GetNodePDOIndexes(self.MasterNode, pdo_infos["type"], True):
       
   477                 if self.MasterNode.GetEntry(idx, 1) == cobid:
       
   478                     current_idx = idx
       
   479             
       
   480             # Add a PDO to MasterNode if not PDO have been found
       
   481             if current_idx == self.CurrentPDOParamsIdx[pdo_infos["type"]]:
       
   482                 addinglist = [current_idx, current_idx + 0x200]
       
   483                 self.Manager.ManageEntriesOfCurrent(addinglist, [], self.MasterNode)
       
   484                 self.MasterNode.SetEntry(current_idx, 0x01, cobid)
       
   485                 
       
   486                 # Increment the number of PDO for this PDO type
       
   487                 self.CurrentPDOParamsIdx[pdo_infos["type"]] += 1
       
   488             
       
   489             # Change the transmit type of the PDO
       
   490             if sync_TPDOs:
       
   491                 self.MasterNode.SetEntry(current_idx, 0x02, 0x01)
       
   492             else:
       
   493                 self.MasterNode.SetEntry(current_idx, 0x02, 0xFF)
       
   494             
       
   495             # Add some subentries to PDO mapping if there is not enough
       
   496             if len(pdo_infos["mapping"]) > 2:
       
   497                 self.Manager.AddSubentriesToCurrent(current_idx + 0x200, len(pdo_infos["mapping"]) - 2, self.MasterNode)
       
   498             
       
   499             # Generate MasterNode's PDO mapping
       
   500             for subindex, variable in enumerate(pdo_infos["mapping"]):
       
   501                 if subindex == 0:
       
   502                     continue
       
   503                 new_index = False
       
   504                 
       
   505                 if type(variable) == IntType:
       
   506                     # If variable is an integer then variable is unexpected
       
   507                     self.MasterNode.SetEntry(current_idx + 0x200, subindex, self.TrashVariables[variable])
       
   508                 else:
       
   509                     typeidx, varname = variable
       
   510                     variable_infos = self.IECLocations[varname]
       
   511                     
       
   512                     # Calculate base index for storing variable
       
   513                     mapvariableidx = VariableStartIndex[variable_infos["pdotype"]] + \
       
   514                                      VariableTypeOffset[variable_infos["sizelocation"]] * VariableIncrement + \
       
   515                                      variable_infos["nodeid"]
       
   516                     
       
   517                     # Search for an entry that has an empty subindex 
       
   518                     while mapvariableidx < VariableStartIndex[variable_infos["pdotype"]] + 0x2000:
       
   519                         # Entry doesn't exist
       
   520                         if not self.MasterNode.IsEntry(mapvariableidx):    
       
   521                             # Generate entry name
       
   522                             indexname = "%s%s%s_%d"%(VariableDirText[variable_infos["pdotype"]],
       
   523                                                      variable_infos["sizelocation"],
       
   524                                                      '_'.join(map(str,current_location)),
       
   525                                                      variable_infos["nodeid"])
       
   526                             # Add entry to MasterNode
       
   527                             self.Manager.AddMapVariableToCurrent(mapvariableidx, indexname, 3, 1, self.MasterNode)
       
   528                             new_index = True
       
   529                             nbsubentries = self.MasterNode.GetEntry(mapvariableidx, 0x00)
       
   530                         else:
       
   531                             # Get Number of subentries already defined
       
   532                             nbsubentries = self.MasterNode.GetEntry(mapvariableidx, 0x00)
       
   533                             # if entry is full, go to next entry possible or stop now
       
   534                             if nbsubentries == 0xFF:
       
   535                                 mapvariableidx += 8 * VariableIncrement
       
   536                             else:
       
   537                                 break
       
   538                                 
       
   539                     # Verify that a not full entry has been found
       
   540                     if mapvariableidx < VariableStartIndex[variable_infos["pdotype"]] + 0x2000:
       
   541                         # Generate subentry name
       
   542                         if variable_infos["bit"] != None:
       
   543                             subindexname = "%(index)d_%(subindex)d_%(bit)d"%variable_infos
       
   544                         else:
       
   545                             subindexname = "%(index)d_%(subindex)d"%variable_infos
       
   546                         # If entry have just been created, no subentry have to be added
       
   547                         if not new_index:
       
   548                             self.Manager.AddSubentriesToCurrent(mapvariableidx, 1, self.MasterNode)
       
   549                             nbsubentries += 1
       
   550                         # Add informations to the new subentry created
       
   551                         self.MasterNode.SetMappingEntry(mapvariableidx, nbsubentries, values = {"name" : subindexname})
       
   552                         self.MasterNode.SetMappingEntry(mapvariableidx, nbsubentries, values = {"type" : typeidx})
       
   553                         
       
   554                         # Set value of the PDO mapping
       
   555                         typeinfos = self.Manager.GetEntryInfos(typeidx)
       
   556                         if typeinfos != None:
       
   557                             value = (mapvariableidx << 16) + ((nbsubentries) << 8) + typeinfos["size"]
       
   558                             self.MasterNode.SetEntry(current_idx + 0x200, subindex, value)
       
   559 
       
   560 def GenerateConciseDCF(locations, current_location, nodelist, sync_TPDOs, nodename):
       
   561     """
       
   562     Fills a CanFestival network editor model, with DCF with requested PDO mappings.
       
   563     @param locations: List of complete variables locations \
       
   564         [{"IEC_TYPE" : the IEC type (i.e. "INT", "STRING", ...)
       
   565         "NAME" : name of the variable (generally "__IW0_1_2" style)
       
   566         "DIR" : direction "Q","I" or "M"
       
   567         "SIZE" : size "X", "B", "W", "D", "L"
       
   568         "LOC" : tuple of interger for IEC location (0,1,2,...)
       
   569         }, ...]
       
   570     @param nodelist: CanFestival network editor model
       
   571     @return: a modified copy of the given CanFestival network editor model
       
   572     """
       
   573     
       
   574     dcfgenerator = ConciseDCFGenerator(nodelist, nodename)
       
   575     dcfgenerator.GenerateDCF(locations, current_location, sync_TPDOs)
       
   576     return dcfgenerator.GetMasterNode()
       
   577 
       
   578 if __name__ == "__main__":
       
   579     import os, sys, getopt
       
   580 
       
   581     def usage():
       
   582         print """
       
   583 Usage of config_utils.py test :
       
   584 
       
   585     %s [options]
       
   586 
       
   587 Options:
       
   588     --help  (-h)
       
   589             Displays help informations for config_utils
       
   590 
       
   591     --reset (-r)
       
   592             Reset the reference result of config_utils test.
       
   593             Use with caution. Be sure that config_utils
       
   594             is currently working properly.
       
   595 """%sys.argv[0]
       
   596     
       
   597     # Boolean that indicate if reference result must be redefined
       
   598     reset = False
       
   599 
       
   600     # Extract command options
       
   601     try:
       
   602         opts, args = getopt.getopt(sys.argv[1:], "hr", ["help","reset"])
       
   603     except getopt.GetoptError:
       
   604         # print help information and exit:
       
   605         usage()
       
   606         sys.exit(2)
       
   607 
       
   608     # Test each option
       
   609     for o, a in opts:
       
   610         if o in ("-h", "--help"):
       
   611             usage()
       
   612             sys.exit()
       
   613         elif o in ("-r", "--reset"):
       
   614             reset = True
       
   615 
       
   616     # Extract workspace base folder
       
   617     base_folder = sys.path[0]
       
   618     for i in xrange(3):
       
   619         base_folder = os.path.split(base_folder)[0]
       
   620     # Add CanFestival folder to search pathes
       
   621     sys.path.append(os.path.join(base_folder, "CanFestival-3", "objdictgen"))
       
   622     
       
   623     from nodemanager import *
       
   624     from nodelist import *
       
   625     
       
   626     # Open the test nodelist contained into test_config folder
       
   627     manager = NodeManager()
       
   628     nodelist = NodeList(manager)
       
   629     result = nodelist.LoadProject("test_config")
       
   630     
       
   631     # List of locations, we try to map for test
       
   632     locations = [{"IEC_TYPE":"BYTE","NAME":"__IB0_1_64_24576_1","DIR":"I","SIZE":"B","LOC":(0,1,64,24576,1)},
       
   633                  {"IEC_TYPE":"INT","NAME":"__IW0_1_64_25601_2","DIR":"I","SIZE":"W","LOC":(0,1,64,25601,2)},
       
   634                  {"IEC_TYPE":"INT","NAME":"__IW0_1_64_25601_3","DIR":"I","SIZE":"W","LOC":(0,1,64,25601,3)},
       
   635                  {"IEC_TYPE":"INT","NAME":"__QW0_1_64_25617_2","DIR":"Q","SIZE":"W","LOC":(0,1,64,25617,1)},
       
   636                  {"IEC_TYPE":"BYTE","NAME":"__IB0_1_64_24578_1","DIR":"I","SIZE":"B","LOC":(0,1,64,24578,1)},
       
   637                  {"IEC_TYPE":"UDINT","NAME":"__ID0_1_64_25638_1","DIR":"I","SIZE":"D","LOC":(0,1,64,25638,1)},
       
   638                  {"IEC_TYPE":"UDINT","NAME":"__ID0_1_64_25638_2","DIR":"I","SIZE":"D","LOC":(0,1,64,25638,2)},
       
   639                  {"IEC_TYPE":"UDINT","NAME":"__ID0_1_64_25638_3","DIR":"I","SIZE":"D","LOC":(0,1,64,25638,3)},
       
   640                  {"IEC_TYPE":"UDINT","NAME":"__ID0_1_64_25638_4","DIR":"I","SIZE":"D","LOC":(0,1,64,25638,4)}]
       
   641     
       
   642     # Generate MasterNode configuration
       
   643     try:
       
   644         masternode = GenerateConciseDCF(locations, (0, 1), nodelist, True)
       
   645     except ValueError, message:
       
   646         print "%s\nTest Failed!"%message
       
   647         sys.exit()
       
   648     
       
   649     # Get Text corresponding to MasterNode 
       
   650     result = masternode.PrintString()
       
   651     
       
   652     # If reset has been choosen
       
   653     if reset:
       
   654         # Write Text into reference result file
       
   655         file = open("test_config/result.txt", "w")
       
   656         file.write(result)
       
   657         file.close()
       
   658         
       
   659         print "Reset Successful!"
       
   660     else:
       
   661         # Test each line of the result with the reference result
       
   662         test = [line.rstrip() for line in result.splitlines()]
       
   663         
       
   664         file = open("test_config/result.txt", "r")
       
   665         model = [line.rstrip() for line in file.readlines() if line.rstrip()]
       
   666         file.close()
       
   667         
       
   668         errors = 0
       
   669         for i, line in enumerate(model):
       
   670             if i >= len(test):
       
   671                 errors += 1
       
   672                 print "Line %d disappear :\n%s\n"%(i + 1, line)
       
   673             elif line != test[i]:
       
   674                 errors += 1
       
   675                 print "Error on line %d :\n%s\nInstead of :\n%s\n"%(i + 1, test[i], line)
       
   676         for i in xrange(len(model), len(test)):
       
   677             errors += 1
       
   678             print "Line %d appear :\n%s\n"%(i + 1, test[i])
       
   679         
       
   680         if errors > 0:
       
   681             print "%d errors found.\nTest Failed!"%errors
       
   682         else:
       
   683             print "Test Successful!"