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): |
|
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.PrepareMasterNode() |
|
146 |
|
147 |
|
148 def RemoveUsedNodeCobId(self, node): |
|
149 """ |
|
150 Remove all PDO COB ID used by the given node from the list of available COB ID |
|
151 @param node: node |
|
152 @return: a tuple of number of RPDO and TPDO for the node |
|
153 """ |
|
154 |
|
155 # Get list of all node TPDO and RPDO indexes |
|
156 nodeRpdoIndexes = GetNodePDOIndexes(node, RPDO, True) |
|
157 nodeTpdoIndexes = GetNodePDOIndexes(node, TPDO, True) |
|
158 |
|
159 # Mark all the COB ID of the node already mapped PDO as not available |
|
160 for PdoIdx in nodeRpdoIndexes + nodeTpdoIndexes: |
|
161 pdo_cobid = node.GetEntry(PdoIdx, 0x01) |
|
162 # Extract COB ID, if PDO isn't active |
|
163 if pdo_cobid > 0x600 : |
|
164 pdo_cobid -= 0x80000000 |
|
165 # Remove COB ID from the list of available COB ID |
|
166 if pdo_cobid in self.ListCobIDAvailable: |
|
167 self.ListCobIDAvailable.remove(pdo_cobid) |
|
168 |
|
169 return len(nodeRpdoIndexes), len(nodeTpdoIndexes) |
|
170 |
|
171 |
|
172 def PrepareMasterNode(self): |
|
173 """ |
|
174 Add mandatory entries for DCF generation into MasterNode. |
|
175 """ |
|
176 |
|
177 # Adding DCF entry into Master node |
|
178 if not self.MasterNode.IsEntry(0x1F22): |
|
179 self.MasterNode.AddEntry(0x1F22, 1, "") |
|
180 self.Manager.AddSubentriesToCurrent(0x1F22, 127, self.MasterNode) |
|
181 |
|
182 # Adding trash mappable variables for unused mapped datas |
|
183 idxTrashVariables = 0x2000 + self.MasterNode.GetNodeID() |
|
184 # Add an entry for storing unexpected all variable |
|
185 self.Manager.AddMapVariableToCurrent(idxTrashVariables, "trashvariables", 3, len(TrashVariables), self.MasterNode) |
|
186 for subidx, (size, typeidx) in enumerate(TrashVariables): |
|
187 # Add a subentry for storing unexpected variable of this size |
|
188 self.Manager.SetCurrentEntry(idxTrashVariables, subidx + 1, "TRASH%d" % size, "name", None, self.MasterNode) |
|
189 self.Manager.SetCurrentEntry(idxTrashVariables, subidx + 1, typeidx, "type", None, self.MasterNode) |
|
190 # Store the mapping value for this entry |
|
191 self.TrashVariables[size] = (idxTrashVariables << 16) + ((subidx + 1) << 8) + size |
|
192 |
|
193 RPDOnumber, TPDOnumber = self.RemoveUsedNodeCobId(self.MasterNode) |
|
194 |
|
195 # Store the indexes of the first RPDO and TPDO available for MasterNode |
|
196 self.CurrentPDOParamsIdx = {RPDO : 0x1400 + RPDOnumber, TPDO : 0x1800 + TPDOnumber} |
|
197 |
|
198 # Prepare MasterNode with all nodelist slaves |
|
199 for idx, (nodeid, nodeinfos) in enumerate(self.NodeList.SlaveNodes.items()): |
|
200 node = nodeinfos["Node"] |
|
201 node.SetNodeID(nodeid) |
|
202 |
|
203 RPDOnumber, TPDOnumber = self.RemoveUsedNodeCobId(node) |
|
204 |
|
205 # Store the number of TPDO and RPDO for this node |
|
206 self.SlavesPdoNumber[nodeid] = {RPDO : RPDOnumber, TPDO : TPDOnumber} |
|
207 |
|
208 # Get Slave's default SDO server parameters |
|
209 RSDO_cobid = node.GetEntry(0x1200,0x01) |
|
210 if not RSDO_cobid: |
|
211 RSDO_cobid = 0x600 + nodeid |
|
212 TSDO_cobid = node.GetEntry(0x1200,0x02) |
|
213 if not TSDO_cobid: |
|
214 TSDO_cobid = 0x580 + nodeid |
|
215 |
|
216 # Configure Master's SDO parameters entries |
|
217 self.Manager.ManageEntriesOfCurrent([0x1280 + idx], [], self.MasterNode) |
|
218 self.MasterNode.SetEntry(0x1280 + idx, 0x01, RSDO_cobid) |
|
219 self.MasterNode.SetEntry(0x1280 + idx, 0x02, TSDO_cobid) |
|
220 self.MasterNode.SetEntry(0x1280 + idx, 0x03, nodeid) |
|
221 |
|
222 |
|
223 def GetMasterNode(self): |
|
224 """ |
|
225 Return MasterNode. |
|
226 """ |
|
227 return self.MasterNode |
|
228 |
|
229 |
|
230 def GetNewCobID(self, nodeid, type): |
|
231 """ |
|
232 Select a COB ID from the list of those available |
|
233 @param nodeid: id of the slave (int) |
|
234 @param type: type of PDO (RPDO or TPDO) |
|
235 @return: a tuple of the COD ID and PDO index or None |
|
236 """ |
|
237 # Verify that there is still some cobid available |
|
238 if len(self.ListCobIDAvailable) == 0: |
|
239 return None |
|
240 |
|
241 # Get the number of PDO of the type given for the node |
|
242 nbSlavePDO = self.SlavesPdoNumber[nodeid][type] |
|
243 if type == RPDO: |
|
244 if nbSlavePDO < 4: |
|
245 # For the four first RPDO -> cobid = 0x200 + ( numPdo parameters * 0x100) + nodeid |
|
246 newcobid = (0x200 + nbSlavePDO * 0x100 + nodeid) |
|
247 # Return calculated cobid if it's still available |
|
248 if newcobid in self.ListCobIDAvailable: |
|
249 self.ListCobIDAvailable.remove(newcobid) |
|
250 return newcobid, 0x1400 + nbSlavePDO |
|
251 # Return the first cobid available if no cobid found |
|
252 return self.ListCobIDAvailable.pop(0), 0x1400 + nbSlavePDO |
|
253 |
|
254 elif type == TPDO: |
|
255 if nbSlavePDO < 4: |
|
256 # For the four first TPDO -> cobid = 0x180 + ( numPdo parameters * 0x100) + nodeid |
|
257 newcobid = (0x180 + nbSlavePDO * 0x100 + nodeid) |
|
258 # Return calculated cobid if it's still available |
|
259 if newcobid in self.ListCobIDAvailable: |
|
260 self.ListCobIDAvailable.remove(newcobid) |
|
261 return newcobid, 0x1800 + nbSlavePDO |
|
262 # Return the first cobid available if no cobid found |
|
263 return self.ListCobIDAvailable.pop(0), 0x1800 + nbSlavePDO |
|
264 |
|
265 return None |
|
266 |
|
267 |
|
268 def AddParamsToDCF(self, nodeid, data, nbparams): |
|
269 """ |
|
270 Select a COB ID from the list of those available |
|
271 @param nodeid: id of the slave (int) |
|
272 @param data: data to add to slave DCF (string) |
|
273 @param nbparams: number of params added to slave DCF (int) |
|
274 """ |
|
275 # Get current DCF for slave |
|
276 nodeDCF = self.MasterNode.GetEntry(0x1F22, nodeid) |
|
277 |
|
278 # Extract data and number of params in current DCF |
|
279 if nodeDCF != None and nodeDCF != '': |
|
280 tmpnbparams = [i for i in nodeDCF[:4]] |
|
281 tmpnbparams.reverse() |
|
282 nbparams += int(''.join(["%2.2x"%ord(i) for i in tmpnbparams]), 16) |
|
283 data = nodeDCF[4:] + data |
|
284 |
|
285 # Build new DCF |
|
286 dcf = LE_to_BE(nbparams, 0x04) + data |
|
287 # Set new DCF for slave |
|
288 self.MasterNode.SetEntry(0x1F22, nodeid, dcf) |
|
289 |
|
290 def AddPDOMapping(self, nodeid, pdotype, pdomapping, sync_TPDOs): |
|
291 """ |
|
292 Select a COB ID from the list of those available |
|
293 @param nodeid: id of the slave (int) |
|
294 @param pdotype: type of PDO to generated (RPDO or TPDO) |
|
295 @param pdomapping: list od variables to map with PDO |
|
296 """ |
|
297 # Get a new cob id |
|
298 result = self.GetNewCobID(nodeid, pdotype) |
|
299 if result: |
|
300 new_cobid, new_idx = result |
|
301 |
|
302 # Increment the number of PDO of this type for node |
|
303 self.SlavesPdoNumber[nodeid][pdotype] += 1 |
|
304 |
|
305 # Add an entry to MasterMapping |
|
306 self.MasterMapping[new_cobid] = {"type" : InvertPDOType[pdotype], |
|
307 "mapping" : [None] + [(loc_infos["type"], name) for name, loc_infos in pdomapping]} |
|
308 |
|
309 # Return the data to add to DCF |
|
310 if sync_TPDOs: |
|
311 return GeneratePDOMappingDCF(new_idx, new_cobid, 0x01, pdomapping) |
|
312 else: |
|
313 return GeneratePDOMappingDCF(new_idx, new_cobid, 0xFF, pdomapping) |
|
314 return 0, "" |
|
315 |
|
316 def GenerateDCF(self, locations, current_location, sync_TPDOs): |
|
317 """ |
|
318 Generate Concise DCF of MasterNode for the locations list given |
|
319 @param locations: list of locations to be mapped |
|
320 @param current_location: tuple of the located prefixes not to be considered |
|
321 @param sync_TPDOs: indicate if TPDO must be synchronous |
|
322 """ |
|
323 |
|
324 #------------------------------------------------------------------------------- |
|
325 # Verify that locations correspond to real slave variables |
|
326 #------------------------------------------------------------------------------- |
|
327 |
|
328 # Get list of locations check if exists and mappables -> put them in IECLocations |
|
329 for location in locations: |
|
330 COlocationtype = IECToCOType[location["IEC_TYPE"]] |
|
331 name = location["NAME"] |
|
332 if name in self.IECLocations: |
|
333 if self.IECLocations[name]["type"] != COlocationtype: |
|
334 raise ValueError, "Conflict type for location \"%s\"" % name |
|
335 else: |
|
336 # Get only the part of the location that concern this node |
|
337 loc = location["LOC"][len(current_location):] |
|
338 # loc correspond to (ID, INDEX, SUBINDEX [,BIT]) |
|
339 if len(loc) not in (3, 4): |
|
340 raise ValueError, "Bad location size : %s"%str(loc) |
|
341 |
|
342 direction = location["DIR"] |
|
343 |
|
344 sizelocation = location["SIZE"] |
|
345 |
|
346 # Extract and check nodeid |
|
347 nodeid, index, subindex = loc[:3] |
|
348 |
|
349 # Check Id is in slave node list |
|
350 if nodeid not in self.NodeList.SlaveNodes.keys(): |
|
351 raise ValueError, "Non existing node ID : %d (variable %s)" % (nodeid,name) |
|
352 |
|
353 # Get the model for this node (made from EDS) |
|
354 node = self.NodeList.SlaveNodes[nodeid]["Node"] |
|
355 |
|
356 # Extract and check index and subindex |
|
357 if not node.IsEntry(index, subindex): |
|
358 raise ValueError, "No such index/subindex (%x,%x) in ID : %d (variable %s)" % (index,subindex,nodeid,name) |
|
359 |
|
360 # Get the entry info |
|
361 subentry_infos = node.GetSubentryInfos(index, subindex) |
|
362 |
|
363 # If a PDO mappable |
|
364 if subentry_infos and subentry_infos["pdo"]: |
|
365 if sizelocation == "X" and len(loc) > 3: |
|
366 numbit = loc[4] |
|
367 elif sizelocation != "X" and len(loc) > 3: |
|
368 raise ValueError, "Cannot set bit offset for non bool '%s' variable (ID:%d,Idx:%x,sIdx:%x))" % (name,nodeid,index,subindex) |
|
369 else: |
|
370 numbit = None |
|
371 |
|
372 entryinfos = node.GetSubentryInfos(index, subindex) |
|
373 if entryinfos["type"] != COlocationtype: |
|
374 raise ValueError, "Invalid type \"%s\"-> %d != %d for location\"%s\"" % (location["IEC_TYPE"], COlocationtype, entryinfos["type"] , name) |
|
375 |
|
376 typeinfos = node.GetEntryInfos(COlocationtype) |
|
377 self.IECLocations[name] = {"type":COlocationtype, "pdotype":SlavePDOType[direction], |
|
378 "nodeid": nodeid, "index": index,"subindex": subindex, |
|
379 "bit": numbit, "size": typeinfos["size"], "sizelocation": sizelocation} |
|
380 else: |
|
381 raise ValueError, "Not PDO mappable variable : '%s' (ID:%d,Idx:%x,sIdx:%x))" % (name,nodeid,index,subindex) |
|
382 |
|
383 #------------------------------------------------------------------------------- |
|
384 # Search for locations already mapped |
|
385 #------------------------------------------------------------------------------- |
|
386 |
|
387 for name, locationinfos in self.IECLocations.items(): |
|
388 node = self.NodeList.SlaveNodes[locationinfos["nodeid"]]["Node"] |
|
389 |
|
390 # Search if slave has a PDO mapping this locations |
|
391 result = SearchNodePDOMapping(locationinfos, node) |
|
392 if result != None: |
|
393 index, subindex = result |
|
394 # Get COB ID of the PDO |
|
395 cobid = self.NodeList.GetSlaveNodeEntry(locationinfos["nodeid"], index - 0x200, 1) |
|
396 |
|
397 # Verify that PDO transmit type is conform to sync_TPDOs |
|
398 transmittype = self.NodeList.GetSlaveNodeEntry(locationinfos["nodeid"], index - 0x200, 2) |
|
399 if sync_TPDOs and transmittype != 0x01 or transmittype != 0xFF: |
|
400 if sync_TPDOs: |
|
401 # Change TransmitType to SYNCHRONE |
|
402 data, nbparams = GeneratePDOMappingDCF(index - 0x200, cobid, 0x01, []) |
|
403 else: |
|
404 # Change TransmitType to ASYCHRONE |
|
405 data, nbparams = GeneratePDOMappingDCF(index - 0x200, cobid, 0xFF, []) |
|
406 |
|
407 # Add entry to slave dcf to change transmit type of |
|
408 self.AddParamsToDCF(locationinfos["nodeid"], data, nbparams) |
|
409 |
|
410 # Add PDO to MasterMapping |
|
411 if cobid not in self.MasterMapping.keys(): |
|
412 mapping = [None] |
|
413 values = node.GetEntry(index) |
|
414 # Store the size of each entry mapped in PDO |
|
415 for value in values[1:]: |
|
416 mapping.append(value % 0x100) |
|
417 self.MasterMapping[cobid] = {"type" : InvertPDOType[locationinfos["pdotype"]], "mapping" : mapping} |
|
418 |
|
419 # Indicate that this PDO entry must be saved |
|
420 self.MasterMapping[cobid]["mapping"][subindex] = (locationinfos["type"], name) |
|
421 |
|
422 else: |
|
423 # Add location to those that haven't been mapped yet |
|
424 if locationinfos["nodeid"] not in self.LocationsNotMapped.keys(): |
|
425 self.LocationsNotMapped[locationinfos["nodeid"]] = {TPDO : [], RPDO : []} |
|
426 self.LocationsNotMapped[locationinfos["nodeid"]][locationinfos["pdotype"]].append((name, locationinfos)) |
|
427 |
|
428 #------------------------------------------------------------------------------- |
|
429 # Build concise DCF for the others locations |
|
430 #------------------------------------------------------------------------------- |
|
431 |
|
432 for nodeid, locations in self.LocationsNotMapped.items(): |
|
433 node = nodelist.SlaveNodes[nodeid]["Node"] |
|
434 |
|
435 # Initialize number of params and data to add to node DCF |
|
436 nbparams = 0 |
|
437 dataparams = "" |
|
438 |
|
439 # Generate the best PDO mapping for each type of PDO |
|
440 for pdotype in (TPDO, RPDO): |
|
441 pdosize = 0 |
|
442 pdomapping = [] |
|
443 for name, loc_infos in locations[pdotype]: |
|
444 pdosize += loc_infos["size"] |
|
445 # If pdo's size > 64 bits |
|
446 if pdosize > 64: |
|
447 # Generate a new PDO Mapping |
|
448 data, nbaddedparams = self.AddPDOMapping(nodeid, pdotype, pdomapping, sync_TPDOs) |
|
449 dataparams += data |
|
450 nbparams += nbaddedparams |
|
451 pdosize = loc_infos["size"] |
|
452 pdomapping = [(name, loc_infos)] |
|
453 else: |
|
454 pdomapping.append((name, loc_infos)) |
|
455 # If there isn't locations yet but there is still a PDO to generate |
|
456 if len(pdomapping) > 0: |
|
457 # Generate a new PDO Mapping |
|
458 data, nbaddedparams = self.AddPDOMapping(nodeid, pdotype, pdomapping, sync_TPDOs) |
|
459 dataparams += data |
|
460 nbparams += nbaddedparams |
|
461 |
|
462 # Add number of params and data to node DCF |
|
463 self.AddParamsToDCF(nodeid, dataparams, nbparams) |
|
464 |
|
465 #------------------------------------------------------------------------------- |
|
466 # Master Node Configuration |
|
467 #------------------------------------------------------------------------------- |
|
468 |
|
469 # Generate Master's Configuration from informations stored in MasterMapping |
|
470 for cobid, pdo_infos in self.MasterMapping.items(): |
|
471 # Get next PDO index in MasterNode for this PDO type |
|
472 current_idx = self.CurrentPDOParamsIdx[pdo_infos["type"]] |
|
473 |
|
474 # Search if there is already a PDO in MasterNode with this cob id |
|
475 for idx in GetNodePDOIndexes(self.MasterNode, pdo_infos["type"], True): |
|
476 if self.MasterNode.GetEntry(idx, 1) == cobid: |
|
477 current_idx = idx |
|
478 |
|
479 # Add a PDO to MasterNode if not PDO have been found |
|
480 if current_idx == self.CurrentPDOParamsIdx[pdo_infos["type"]]: |
|
481 addinglist = [current_idx, current_idx + 0x200] |
|
482 self.Manager.ManageEntriesOfCurrent(addinglist, [], self.MasterNode) |
|
483 self.MasterNode.SetEntry(current_idx, 0x01, cobid) |
|
484 |
|
485 # Increment the number of PDO for this PDO type |
|
486 self.CurrentPDOParamsIdx[pdo_infos["type"]] += 1 |
|
487 |
|
488 # Change the transmit type of the PDO |
|
489 if sync_TPDOs: |
|
490 self.MasterNode.SetEntry(current_idx, 0x02, 0x01) |
|
491 else: |
|
492 self.MasterNode.SetEntry(current_idx, 0x02, 0xFF) |
|
493 |
|
494 # Add some subentries to PDO mapping if there is not enough |
|
495 if len(pdo_infos["mapping"]) > 2: |
|
496 self.Manager.AddSubentriesToCurrent(current_idx + 0x200, len(pdo_infos["mapping"]) - 2, self.MasterNode) |
|
497 |
|
498 # Generate MasterNode's PDO mapping |
|
499 for subindex, variable in enumerate(pdo_infos["mapping"]): |
|
500 if subindex == 0: |
|
501 continue |
|
502 new_index = False |
|
503 |
|
504 if type(variable) == IntType: |
|
505 # If variable is an integer then variable is unexpected |
|
506 self.MasterNode.SetEntry(current_idx + 0x200, subindex, self.TrashVariables[variable]) |
|
507 else: |
|
508 typeidx, varname = variable |
|
509 variable_infos = self.IECLocations[varname] |
|
510 |
|
511 # Calculate base index for storing variable |
|
512 mapvariableidx = VariableStartIndex[variable_infos["pdotype"]] + \ |
|
513 VariableTypeOffset[variable_infos["sizelocation"]] * VariableIncrement + \ |
|
514 variable_infos["nodeid"] |
|
515 |
|
516 # Search for an entry that has an empty subindex |
|
517 while mapvariableidx < VariableStartIndex[variable_infos["pdotype"]] + 0x2000: |
|
518 # Entry doesn't exist |
|
519 if not self.MasterNode.IsEntry(mapvariableidx): |
|
520 # Generate entry name |
|
521 indexname = "%s%s%s_%d"%(VariableDirText[variable_infos["pdotype"]], |
|
522 variable_infos["sizelocation"], |
|
523 '_'.join(map(str,current_location)), |
|
524 variable_infos["nodeid"]) |
|
525 # Add entry to MasterNode |
|
526 self.Manager.AddMapVariableToCurrent(mapvariableidx, indexname, 3, 1, self.MasterNode) |
|
527 new_index = True |
|
528 nbsubentries = self.MasterNode.GetEntry(mapvariableidx, 0x00) |
|
529 else: |
|
530 # Get Number of subentries already defined |
|
531 nbsubentries = self.MasterNode.GetEntry(mapvariableidx, 0x00) |
|
532 # if entry is full, go to next entry possible or stop now |
|
533 if nbsubentries == 0xFF: |
|
534 mapvariableidx += 8 * VariableIncrement |
|
535 else: |
|
536 break |
|
537 |
|
538 # Verify that a not full entry has been found |
|
539 if mapvariableidx < VariableStartIndex[variable_infos["pdotype"]] + 0x2000: |
|
540 # Generate subentry name |
|
541 if variable_infos["bit"] != None: |
|
542 subindexname = "%(index)d_%(subindex)d_%(bit)d"%variable_infos |
|
543 else: |
|
544 subindexname = "%(index)d_%(subindex)d"%variable_infos |
|
545 # If entry have just been created, no subentry have to be added |
|
546 if not new_index: |
|
547 self.Manager.AddSubentriesToCurrent(mapvariableidx, 1, self.MasterNode) |
|
548 nbsubentries += 1 |
|
549 # Add informations to the new subentry created |
|
550 self.MasterNode.SetMappingEntry(mapvariableidx, nbsubentries, values = {"name" : subindexname}) |
|
551 self.MasterNode.SetMappingEntry(mapvariableidx, nbsubentries, values = {"type" : typeidx}) |
|
552 |
|
553 # Set value of the PDO mapping |
|
554 typeinfos = self.Manager.GetEntryInfos(typeidx) |
|
555 if typeinfos != None: |
|
556 value = (mapvariableidx << 16) + ((nbsubentries) << 8) + typeinfos["size"] |
|
557 self.MasterNode.SetEntry(current_idx + 0x200, subindex, value) |
|
558 |
|
559 def GenerateConciseDCF(locations, current_location, nodelist, sync_TPDOs): |
|
560 """ |
|
561 Fills a CanFestival network editor model, with DCF with requested PDO mappings. |
|
562 @param locations: List of complete variables locations \ |
|
563 [{"IEC_TYPE" : the IEC type (i.e. "INT", "STRING", ...) |
|
564 "NAME" : name of the variable (generally "__IW0_1_2" style) |
|
565 "DIR" : direction "Q","I" or "M" |
|
566 "SIZE" : size "X", "B", "W", "D", "L" |
|
567 "LOC" : tuple of interger for IEC location (0,1,2,...) |
|
568 }, ...] |
|
569 @param nodelist: CanFestival network editor model |
|
570 @return: a modified copy of the given CanFestival network editor model |
|
571 """ |
|
572 |
|
573 dcfgenerator = ConciseDCFGenerator(nodelist) |
|
574 dcfgenerator.GenerateDCF(locations, current_location, sync_TPDOs) |
|
575 return dcfgenerator.GetMasterNode() |
|
576 |
|
577 if __name__ == "__main__": |
|
578 import os, sys, getopt |
|
579 |
|
580 def usage(): |
|
581 print """ |
|
582 Usage of config_utils.py test : |
|
583 |
|
584 %s [options] |
|
585 |
|
586 Options: |
|
587 --help (-h) |
|
588 Displays help informations for config_utils |
|
589 |
|
590 --reset (-r) |
|
591 Reset the reference result of config_utils test. |
|
592 Use with caution. Be sure that config_utils |
|
593 is currently working properly. |
|
594 """%sys.argv[0] |
|
595 |
|
596 # Boolean that indicate if reference result must be redefined |
|
597 reset = False |
|
598 |
|
599 # Extract command options |
|
600 try: |
|
601 opts, args = getopt.getopt(sys.argv[1:], "hr", ["help","reset"]) |
|
602 except getopt.GetoptError: |
|
603 # print help information and exit: |
|
604 usage() |
|
605 sys.exit(2) |
|
606 |
|
607 # Test each option |
|
608 for o, a in opts: |
|
609 if o in ("-h", "--help"): |
|
610 usage() |
|
611 sys.exit() |
|
612 elif o in ("-r", "--reset"): |
|
613 reset = True |
|
614 |
|
615 # Extract workspace base folder |
|
616 base_folder = sys.path[0] |
|
617 for i in xrange(3): |
|
618 base_folder = os.path.split(base_folder)[0] |
|
619 # Add CanFestival folder to search pathes |
|
620 sys.path.append(os.path.join(base_folder, "CanFestival-3", "objdictgen")) |
|
621 |
|
622 from nodemanager import * |
|
623 from nodelist import * |
|
624 |
|
625 # Open the test nodelist contained into test_config folder |
|
626 manager = NodeManager() |
|
627 nodelist = NodeList(manager) |
|
628 result = nodelist.LoadProject("test_config") |
|
629 |
|
630 # List of locations, we try to map for test |
|
631 locations = [{"IEC_TYPE":"BYTE","NAME":"__IB0_1_64_24576_1","DIR":"I","SIZE":"B","LOC":(0,1,64,24576,1)}, |
|
632 {"IEC_TYPE":"INT","NAME":"__IW0_1_64_25601_2","DIR":"I","SIZE":"W","LOC":(0,1,64,25601,2)}, |
|
633 {"IEC_TYPE":"INT","NAME":"__IW0_1_64_25601_3","DIR":"I","SIZE":"W","LOC":(0,1,64,25601,3)}, |
|
634 {"IEC_TYPE":"INT","NAME":"__QW0_1_64_25617_2","DIR":"Q","SIZE":"W","LOC":(0,1,64,25617,1)}, |
|
635 {"IEC_TYPE":"BYTE","NAME":"__IB0_1_64_24578_1","DIR":"I","SIZE":"B","LOC":(0,1,64,24578,1)}, |
|
636 {"IEC_TYPE":"UDINT","NAME":"__ID0_1_64_25638_1","DIR":"I","SIZE":"D","LOC":(0,1,64,25638,1)}, |
|
637 {"IEC_TYPE":"UDINT","NAME":"__ID0_1_64_25638_2","DIR":"I","SIZE":"D","LOC":(0,1,64,25638,2)}, |
|
638 {"IEC_TYPE":"UDINT","NAME":"__ID0_1_64_25638_3","DIR":"I","SIZE":"D","LOC":(0,1,64,25638,3)}, |
|
639 {"IEC_TYPE":"UDINT","NAME":"__ID0_1_64_25638_4","DIR":"I","SIZE":"D","LOC":(0,1,64,25638,4)}] |
|
640 |
|
641 # Generate MasterNode configuration |
|
642 try: |
|
643 masternode = GenerateConciseDCF(locations, (0, 1), nodelist, True) |
|
644 except ValueError, message: |
|
645 print "%s\nTest Failed!"%message |
|
646 sys.exit() |
|
647 |
|
648 # Get Text corresponding to MasterNode |
|
649 result = masternode.PrintString() |
|
650 |
|
651 # If reset has been choosen |
|
652 if reset: |
|
653 # Write Text into reference result file |
|
654 file = open("test_config/result.txt", "w") |
|
655 file.write(result) |
|
656 file.close() |
|
657 |
|
658 print "Reset Successful!" |
|
659 else: |
|
660 # Test each line of the result with the reference result |
|
661 test = [line.rstrip() for line in result.splitlines()] |
|
662 |
|
663 file = open("test_config/result.txt", "r") |
|
664 model = [line.rstrip() for line in file.readlines() if line.rstrip()] |
|
665 file.close() |
|
666 |
|
667 errors = 0 |
|
668 for i, line in enumerate(model): |
|
669 if i >= len(test): |
|
670 errors += 1 |
|
671 print "Line %d disappear :\n%s\n"%(i + 1, line) |
|
672 elif line != test[i]: |
|
673 errors += 1 |
|
674 print "Error on line %d :\n%s\nInstead of :\n%s\n"%(i + 1, test[i], line) |
|
675 for i in xrange(len(model), len(test)): |
|
676 errors += 1 |
|
677 print "Line %d appear :\n%s\n"%(i + 1, test[i]) |
|
678 |
|
679 if errors > 0: |
|
680 print "%d errors found.\nTest Failed!"%errors |
|
681 else: |
|
682 print "Test Successful!" |
|