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 PDOTypeBaseIndex = {RPDO : 0x1400, TPDO : 0x1800} |
|
40 PDOTypeBaseCobId = {RPDO : 0x200, TPDO : 0x180} |
|
41 |
|
42 VariableIncrement = 0x100 |
|
43 VariableStartIndex = {TPDO : 0x2000, RPDO : 0x4000} |
|
44 VariableDirText = {TPDO : "__I", RPDO : "__Q"} |
|
45 VariableTypeOffset = dict(zip(["","X","B","W","D","L"], range(6))) |
|
46 |
|
47 TrashVariables = [(1, 0x01), (8, 0x05), (16, 0x06), (32, 0x07), (64, 0x1B)] |
|
48 |
|
49 #------------------------------------------------------------------------------- |
|
50 # Specific exception for PDO mapping errors |
|
51 #------------------------------------------------------------------------------- |
|
52 |
|
53 class PDOmappingException(Exception): |
|
54 pass |
|
55 |
|
56 |
|
57 def LE_to_BE(value, size): |
|
58 """ |
|
59 Convert Little Endian to Big Endian |
|
60 @param value: value expressed in integer |
|
61 @param size: number of bytes generated |
|
62 @return: a string containing the value converted |
|
63 """ |
|
64 |
|
65 data = ("%" + str(size * 2) + "." + str(size * 2) + "X") % value |
|
66 list_car = [data[i:i+2] for i in xrange(0, len(data), 2)] |
|
67 list_car.reverse() |
|
68 return "".join([chr(int(car, 16)) for car in list_car]) |
|
69 |
|
70 |
|
71 def GetNodePDOIndexes(node, type, parameters = False): |
|
72 """ |
|
73 Find the PDO indexes of a node |
|
74 @param node: node |
|
75 @param type: type of PDO searched (RPDO or TPDO or both) |
|
76 @param parameters: indicate which indexes are expected (PDO paramaters : True or PDO mappings : False) |
|
77 @return: a list of indexes found |
|
78 """ |
|
79 |
|
80 indexes = [] |
|
81 if type & RPDO: |
|
82 indexes.extend([idx for idx in node.GetIndexes() if 0x1400 <= idx <= 0x15FF]) |
|
83 if type & TPDO: |
|
84 indexes.extend([idx for idx in node.GetIndexes() if 0x1800 <= idx <= 0x19FF]) |
|
85 if not parameters: |
|
86 return [idx + 0x200 for idx in indexes] |
|
87 else: |
|
88 return indexes |
|
89 |
|
90 |
|
91 def SearchNodePDOMapping(loc_infos, node): |
|
92 """ |
|
93 Find the PDO indexes of a node |
|
94 @param node: node |
|
95 @param type: type of PDO searched (RPDO or TPDO or both) |
|
96 @param parameters: indicate which indexes are expected (PDO paramaters : True or PDO mappings : False) |
|
97 @return: a list of indexes found |
|
98 """ |
|
99 |
|
100 model = (loc_infos["index"] << 16) + (loc_infos["subindex"] << 8) |
|
101 |
|
102 for PDOidx in GetNodePDOIndexes(node, loc_infos["pdotype"]): |
|
103 values = node.GetEntry(PDOidx) |
|
104 if values != None: |
|
105 for subindex, mapping in enumerate(values): |
|
106 if subindex != 0 and mapping & 0xFFFFFF00 == model: |
|
107 return PDOidx, subindex |
|
108 return None |
|
109 |
|
110 |
|
111 def GeneratePDOMappingDCF(idx, cobid, transmittype, pdomapping): |
|
112 """ |
|
113 Build concise DCF value for configuring a PDO |
|
114 @param idx: index of PDO parameters |
|
115 @param cobid: PDO generated COB ID |
|
116 @param transmittype : PDO transmit type |
|
117 @param pdomapping: list of PDO mappings |
|
118 @return: a tuple of value and number of parameters to add to DCF |
|
119 """ |
|
120 |
|
121 # Create entry for RPDO or TPDO parameters and Disable PDO |
|
122 dcfdata = LE_to_BE(idx, 2) + LE_to_BE(0x01, 1) + LE_to_BE(0x04, 4) + LE_to_BE(0x80000000 + cobid, 4) |
|
123 # Set Transmit type synchrone |
|
124 dcfdata += LE_to_BE(idx, 2) + LE_to_BE(0x02, 1) + LE_to_BE(0x01, 4) + LE_to_BE(transmittype, 1) |
|
125 # Re-Enable PDO |
|
126 # ---- INDEX ----- --- SUBINDEX ---- ----- SIZE ------ ------ DATA ------ |
|
127 dcfdata += LE_to_BE(idx, 2) + LE_to_BE(0x01, 1) + LE_to_BE(0x04, 4) + LE_to_BE(cobid, 4) |
|
128 nbparams = 3 |
|
129 if len(pdomapping) > 0: |
|
130 dcfdata += LE_to_BE(idx + 0x200, 2) + LE_to_BE(0x00, 1) + LE_to_BE(0x01, 4) + LE_to_BE(len(pdomapping), 1) |
|
131 nbparams += 1 |
|
132 # Map Variables |
|
133 for subindex, (name, loc_infos) in enumerate(pdomapping): |
|
134 value = (loc_infos["index"] << 16) + (loc_infos["subindex"] << 8) + loc_infos["size"] |
|
135 dcfdata += LE_to_BE(idx + 0x200, 2) + LE_to_BE(subindex + 1, 1) + LE_to_BE(0x04, 4) + LE_to_BE(value, 4) |
|
136 nbparams += 1 |
|
137 return dcfdata, nbparams |
|
138 |
|
139 class ConciseDCFGenerator: |
|
140 |
|
141 def __init__(self, nodelist, nodename): |
|
142 # Dictionary of location informations classed by name |
|
143 self.IECLocations = {} |
|
144 # Dictionary of location that have not been mapped yet |
|
145 self.LocationsNotMapped = {} |
|
146 # Dictionary of location informations classed by name |
|
147 self.MasterMapping = {} |
|
148 # List of COB IDs available |
|
149 self.ListCobIDAvailable = range(0x180, 0x580) |
|
150 # Dictionary of mapping value where unexpected variables are stored |
|
151 self.TrashVariables = {} |
|
152 # Dictionary of pointed variables |
|
153 self.PointedVariables = {} |
|
154 |
|
155 self.NodeList = nodelist |
|
156 self.Manager = self.NodeList.Manager |
|
157 self.MasterNode = self.Manager.GetCurrentNodeCopy() |
|
158 self.MasterNode.SetNodeName(nodename) |
|
159 self.PrepareMasterNode() |
|
160 |
|
161 def GetPointedVariables(self): |
|
162 return self.PointedVariables |
|
163 |
|
164 def RemoveUsedNodeCobId(self, node): |
|
165 """ |
|
166 Remove all PDO COB ID used by the given node from the list of available COB ID |
|
167 @param node: node |
|
168 @return: a tuple of number of RPDO and TPDO for the node |
|
169 """ |
|
170 |
|
171 # Get list of all node TPDO and RPDO indexes |
|
172 nodeRpdoIndexes = GetNodePDOIndexes(node, RPDO, True) |
|
173 nodeTpdoIndexes = GetNodePDOIndexes(node, TPDO, True) |
|
174 |
|
175 # Mark all the COB ID of the node already mapped PDO as not available |
|
176 for PdoIdx in nodeRpdoIndexes + nodeTpdoIndexes: |
|
177 pdo_cobid = node.GetEntry(PdoIdx, 0x01) |
|
178 # Extract COB ID, if PDO isn't active |
|
179 if pdo_cobid > 0x600 : |
|
180 pdo_cobid -= 0x80000000 |
|
181 # Remove COB ID from the list of available COB ID |
|
182 if pdo_cobid in self.ListCobIDAvailable: |
|
183 self.ListCobIDAvailable.remove(pdo_cobid) |
|
184 |
|
185 return len(nodeRpdoIndexes), len(nodeTpdoIndexes) |
|
186 |
|
187 |
|
188 def PrepareMasterNode(self): |
|
189 """ |
|
190 Add mandatory entries for DCF generation into MasterNode. |
|
191 """ |
|
192 |
|
193 # Adding DCF entry into Master node |
|
194 if not self.MasterNode.IsEntry(0x1F22): |
|
195 self.MasterNode.AddEntry(0x1F22, 1, "") |
|
196 self.Manager.AddSubentriesToCurrent(0x1F22, 127, self.MasterNode) |
|
197 |
|
198 # Adding trash mappable variables for unused mapped datas |
|
199 idxTrashVariables = 0x2000 + self.MasterNode.GetNodeID() |
|
200 # Add an entry for storing unexpected all variable |
|
201 self.Manager.AddMapVariableToCurrent(idxTrashVariables, self.MasterNode.GetNodeName()+"_trashvariables", 3, len(TrashVariables), self.MasterNode) |
|
202 for subidx, (size, typeidx) in enumerate(TrashVariables): |
|
203 # Add a subentry for storing unexpected variable of this size |
|
204 self.Manager.SetCurrentEntry(idxTrashVariables, subidx + 1, "TRASH%d" % size, "name", None, self.MasterNode) |
|
205 self.Manager.SetCurrentEntry(idxTrashVariables, subidx + 1, typeidx, "type", None, self.MasterNode) |
|
206 # Store the mapping value for this entry |
|
207 self.TrashVariables[size] = (idxTrashVariables << 16) + ((subidx + 1) << 8) + size |
|
208 |
|
209 RPDOnumber, TPDOnumber = self.RemoveUsedNodeCobId(self.MasterNode) |
|
210 |
|
211 # Store the indexes of the first RPDO and TPDO available for MasterNode |
|
212 self.CurrentPDOParamsIdx = {RPDO : 0x1400 + RPDOnumber, TPDO : 0x1800 + TPDOnumber} |
|
213 |
|
214 # Prepare MasterNode with all nodelist slaves |
|
215 for idx, (nodeid, nodeinfos) in enumerate(self.NodeList.SlaveNodes.items()): |
|
216 node = nodeinfos["Node"] |
|
217 node.SetNodeID(nodeid) |
|
218 |
|
219 RPDOnumber, TPDOnumber = self.RemoveUsedNodeCobId(node) |
|
220 |
|
221 # Get Slave's default SDO server parameters |
|
222 RSDO_cobid = node.GetEntry(0x1200,0x01) |
|
223 if not RSDO_cobid: |
|
224 RSDO_cobid = 0x600 + nodeid |
|
225 TSDO_cobid = node.GetEntry(0x1200,0x02) |
|
226 if not TSDO_cobid: |
|
227 TSDO_cobid = 0x580 + nodeid |
|
228 |
|
229 # Configure Master's SDO parameters entries |
|
230 self.Manager.ManageEntriesOfCurrent([0x1280 + idx], [], self.MasterNode) |
|
231 self.MasterNode.SetEntry(0x1280 + idx, 0x01, RSDO_cobid) |
|
232 self.MasterNode.SetEntry(0x1280 + idx, 0x02, TSDO_cobid) |
|
233 self.MasterNode.SetEntry(0x1280 + idx, 0x03, nodeid) |
|
234 |
|
235 |
|
236 def GetMasterNode(self): |
|
237 """ |
|
238 Return MasterNode. |
|
239 """ |
|
240 return self.MasterNode |
|
241 |
|
242 def AddParamsToDCF(self, nodeid, data, nbparams): |
|
243 """ |
|
244 Add entry to DCF, for the requested nodeID |
|
245 @param nodeid: id of the slave (int) |
|
246 @param data: data to add to slave DCF (string) |
|
247 @param nbparams: number of params added to slave DCF (int) |
|
248 """ |
|
249 # Get current DCF for slave |
|
250 nodeDCF = self.MasterNode.GetEntry(0x1F22, nodeid) |
|
251 |
|
252 # Extract data and number of params in current DCF |
|
253 if nodeDCF != None and nodeDCF != '': |
|
254 tmpnbparams = [i for i in nodeDCF[:4]] |
|
255 tmpnbparams.reverse() |
|
256 nbparams += int(''.join(["%2.2x"%ord(i) for i in tmpnbparams]), 16) |
|
257 data = nodeDCF[4:] + data |
|
258 |
|
259 # Build new DCF |
|
260 dcf = LE_to_BE(nbparams, 0x04) + data |
|
261 # Set new DCF for slave |
|
262 self.MasterNode.SetEntry(0x1F22, nodeid, dcf) |
|
263 |
|
264 def GetEmptyPDO(self, nodeid, pdotype, start_index=None): |
|
265 """ |
|
266 Search a not configured PDO for a slave |
|
267 @param node: the slave node object |
|
268 @param pdotype: type of PDO to generated (RPDO or TPDO) |
|
269 @param start_index: Index where search must start (default: None) |
|
270 @return tuple of PDO index, COB ID and number of subindex defined |
|
271 """ |
|
272 # If no start_index defined, start with PDOtype base index |
|
273 if start_index is None: |
|
274 index = PDOTypeBaseIndex[pdotype] |
|
275 else: |
|
276 index = start_index |
|
277 |
|
278 # Search for all PDO possible index until find a configurable PDO |
|
279 # starting from start_index |
|
280 while index < PDOTypeBaseIndex[pdotype] + 0x200: |
|
281 values = self.NodeList.GetSlaveNodeEntry(nodeid, index + 0x200) |
|
282 if values != None and values[0] > 0: |
|
283 # Check that all subindex upper than 0 equal 0 => configurable PDO |
|
284 if reduce(lambda x, y: x and y, map(lambda x: x == 0, values[1:]), True): |
|
285 cobid = self.NodeList.GetSlaveNodeEntry(nodeid, index, 1) |
|
286 # If no COB ID defined in PDO, generate a new one (not used) |
|
287 if cobid == 0: |
|
288 if len(self.ListCobIDAvailable) == 0: |
|
289 return None |
|
290 # Calculate COB ID from standard values |
|
291 if index < PDOTypeBaseIndex[pdotype] + 4: |
|
292 cobid = PDOTypeBaseCobId[pdotype] + 0x100 * (index - PDOTypeBaseIndex[pdotype]) + nodeid |
|
293 if cobid not in self.ListCobIDAvailable: |
|
294 cobid = self.ListCobIDAvailable.pop(0) |
|
295 return index, cobid, values[0] |
|
296 index += 1 |
|
297 return None |
|
298 |
|
299 def AddPDOMapping(self, nodeid, pdotype, pdoindex, pdocobid, pdomapping, sync_TPDOs): |
|
300 """ |
|
301 Record a new mapping request for a slave, and add related slave config to the DCF |
|
302 @param nodeid: id of the slave (int) |
|
303 @param pdotype: type of PDO to generated (RPDO or TPDO) |
|
304 @param pdomapping: list od variables to map with PDO |
|
305 """ |
|
306 # Add an entry to MasterMapping |
|
307 self.MasterMapping[pdocobid] = {"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(pdoindex, pdocobid, 0x01, pdomapping) |
|
313 else: |
|
314 return GeneratePDOMappingDCF(pdoindex, pdocobid, 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 PDOmappingException, _("Type conflict 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 (2, 3, 4): |
|
341 raise PDOmappingException, _("Bad location size : %s") % str(loc) |
|
342 elif len(loc) == 2: |
|
343 continue |
|
344 |
|
345 direction = location["DIR"] |
|
346 |
|
347 sizelocation = location["SIZE"] |
|
348 |
|
349 # Extract and check nodeid |
|
350 nodeid, index, subindex = loc[:3] |
|
351 |
|
352 # Check Id is in slave node list |
|
353 if nodeid not in self.NodeList.SlaveNodes.keys(): |
|
354 raise PDOmappingException, _("Non existing node ID : %d (variable %s)") % (nodeid,name) |
|
355 |
|
356 # Get the model for this node (made from EDS) |
|
357 node = self.NodeList.SlaveNodes[nodeid]["Node"] |
|
358 |
|
359 # Extract and check index and subindex |
|
360 if not node.IsEntry(index, subindex): |
|
361 raise PDOmappingException, _("No such index/subindex (%x,%x) in ID : %d (variable %s)") % (index,subindex,nodeid,name) |
|
362 |
|
363 # Get the entry info |
|
364 subentry_infos = node.GetSubentryInfos(index, subindex) |
|
365 |
|
366 # If a PDO mappable |
|
367 if subentry_infos and subentry_infos["pdo"]: |
|
368 if sizelocation == "X" and len(loc) > 3: |
|
369 numbit = loc[3] |
|
370 elif sizelocation != "X" and len(loc) > 3: |
|
371 raise PDOmappingException, _("Cannot set bit offset for non bool '%s' variable (ID:%d,Idx:%x,sIdx:%x))") % (name,nodeid,index,subindex) |
|
372 else: |
|
373 numbit = None |
|
374 |
|
375 if location["IEC_TYPE"] != "BOOL" and subentry_infos["type"] != COlocationtype: |
|
376 raise PDOmappingException, _("Invalid type \"%s\"-> %d != %d for location\"%s\"") % (location["IEC_TYPE"], COlocationtype, subentry_infos["type"] , name) |
|
377 |
|
378 typeinfos = node.GetEntryInfos(COlocationtype) |
|
379 self.IECLocations[name] = {"type":COlocationtype, "pdotype":SlavePDOType[direction], |
|
380 "nodeid": nodeid, "index": index,"subindex": subindex, |
|
381 "bit": numbit, "size": typeinfos["size"], "sizelocation": sizelocation} |
|
382 else: |
|
383 raise PDOmappingException, _("Not PDO mappable variable : '%s' (ID:%d,Idx:%x,sIdx:%x))") % (name,nodeid,index,subindex) |
|
384 |
|
385 #------------------------------------------------------------------------------- |
|
386 # Search for locations already mapped |
|
387 #------------------------------------------------------------------------------- |
|
388 |
|
389 for name, locationinfos in self.IECLocations.items(): |
|
390 node = self.NodeList.SlaveNodes[locationinfos["nodeid"]]["Node"] |
|
391 |
|
392 # Search if slave has a PDO mapping this locations |
|
393 result = SearchNodePDOMapping(locationinfos, node) |
|
394 if result != None: |
|
395 index, subindex = result |
|
396 # Get COB ID of the PDO |
|
397 cobid = self.NodeList.GetSlaveNodeEntry(locationinfos["nodeid"], index - 0x200, 1) |
|
398 |
|
399 # Add PDO to MasterMapping |
|
400 if cobid not in self.MasterMapping.keys(): |
|
401 # Verify that PDO transmit type is conform to sync_TPDOs |
|
402 transmittype = self.NodeList.GetSlaveNodeEntry(locationinfos["nodeid"], index - 0x200, 2) |
|
403 if sync_TPDOs and transmittype != 0x01 or transmittype != 0xFF: |
|
404 if sync_TPDOs: |
|
405 # Change TransmitType to SYNCHRONE |
|
406 data, nbparams = GeneratePDOMappingDCF(index - 0x200, cobid, 0x01, []) |
|
407 else: |
|
408 # Change TransmitType to ASYCHRONE |
|
409 data, nbparams = GeneratePDOMappingDCF(index - 0x200, cobid, 0xFF, []) |
|
410 |
|
411 # Add entry to slave dcf to change transmit type of |
|
412 self.AddParamsToDCF(locationinfos["nodeid"], data, nbparams) |
|
413 |
|
414 mapping = [None] |
|
415 values = node.GetEntry(index) |
|
416 # Store the size of each entry mapped in PDO |
|
417 for value in values[1:]: |
|
418 if value != 0: |
|
419 mapping.append(value % 0x100) |
|
420 self.MasterMapping[cobid] = {"type" : InvertPDOType[locationinfos["pdotype"]], "mapping" : mapping} |
|
421 |
|
422 # Indicate that this PDO entry must be saved |
|
423 if locationinfos["bit"] is not None: |
|
424 if not isinstance(self.MasterMapping[cobid]["mapping"][subindex], ListType): |
|
425 self.MasterMapping[cobid]["mapping"][subindex] = [1] * self.MasterMapping[cobid]["mapping"][subindex] |
|
426 if locationinfos["bit"] < len(self.MasterMapping[cobid]["mapping"][subindex]): |
|
427 self.MasterMapping[cobid]["mapping"][subindex][locationinfos["bit"]] = (locationinfos["type"], name) |
|
428 else: |
|
429 self.MasterMapping[cobid]["mapping"][subindex] = (locationinfos["type"], name) |
|
430 |
|
431 else: |
|
432 # Add location to those that haven't been mapped yet |
|
433 if locationinfos["nodeid"] not in self.LocationsNotMapped.keys(): |
|
434 self.LocationsNotMapped[locationinfos["nodeid"]] = {TPDO : [], RPDO : []} |
|
435 self.LocationsNotMapped[locationinfos["nodeid"]][locationinfos["pdotype"]].append((name, locationinfos)) |
|
436 |
|
437 #------------------------------------------------------------------------------- |
|
438 # Build concise DCF for the others locations |
|
439 #------------------------------------------------------------------------------- |
|
440 |
|
441 for nodeid, locations in self.LocationsNotMapped.items(): |
|
442 node = self.NodeList.SlaveNodes[nodeid]["Node"] |
|
443 |
|
444 # Initialize number of params and data to add to node DCF |
|
445 nbparams = 0 |
|
446 dataparams = "" |
|
447 |
|
448 # Generate the best PDO mapping for each type of PDO |
|
449 for pdotype in (TPDO, RPDO): |
|
450 if len(locations[pdotype]) > 0: |
|
451 pdosize = 0 |
|
452 pdomapping = [] |
|
453 result = self.GetEmptyPDO(nodeid, pdotype) |
|
454 if result is None: |
|
455 raise PDOmappingException, _("Unable to define PDO mapping for node %02x") % nodeid |
|
456 pdoindex, pdocobid, pdonbparams = result |
|
457 for name, loc_infos in locations[pdotype]: |
|
458 pdosize += loc_infos["size"] |
|
459 # If pdo's size > 64 bits |
|
460 if pdosize > 64 or len(pdomapping) >= pdonbparams: |
|
461 # Generate a new PDO Mapping |
|
462 data, nbaddedparams = self.AddPDOMapping(nodeid, pdotype, pdoindex, pdocobid, pdomapping, sync_TPDOs) |
|
463 dataparams += data |
|
464 nbparams += nbaddedparams |
|
465 pdosize = loc_infos["size"] |
|
466 pdomapping = [(name, loc_infos)] |
|
467 result = self.GetEmptyPDO(nodeid, pdotype, pdoindex + 1) |
|
468 if result is None: |
|
469 raise PDOmappingException, _("Unable to define PDO mapping for node %02x") % nodeid |
|
470 pdoindex, pdocobid, pdonbparams = result |
|
471 else: |
|
472 pdomapping.append((name, loc_infos)) |
|
473 # If there isn't locations yet but there is still a PDO to generate |
|
474 if len(pdomapping) > 0: |
|
475 # Generate a new PDO Mapping |
|
476 data, nbaddedparams = self.AddPDOMapping(nodeid, pdotype, pdoindex, pdocobid, pdomapping, sync_TPDOs) |
|
477 dataparams += data |
|
478 nbparams += nbaddedparams |
|
479 |
|
480 # Add number of params and data to node DCF |
|
481 self.AddParamsToDCF(nodeid, dataparams, nbparams) |
|
482 |
|
483 #------------------------------------------------------------------------------- |
|
484 # Master Node Configuration |
|
485 #------------------------------------------------------------------------------- |
|
486 |
|
487 # Generate Master's Configuration from informations stored in MasterMapping |
|
488 for cobid, pdo_infos in self.MasterMapping.items(): |
|
489 # Get next PDO index in MasterNode for this PDO type |
|
490 current_idx = self.CurrentPDOParamsIdx[pdo_infos["type"]] |
|
491 |
|
492 # Search if there is already a PDO in MasterNode with this cob id |
|
493 for idx in GetNodePDOIndexes(self.MasterNode, pdo_infos["type"], True): |
|
494 if self.MasterNode.GetEntry(idx, 1) == cobid: |
|
495 current_idx = idx |
|
496 |
|
497 # Add a PDO to MasterNode if not PDO have been found |
|
498 if current_idx == self.CurrentPDOParamsIdx[pdo_infos["type"]]: |
|
499 addinglist = [current_idx, current_idx + 0x200] |
|
500 self.Manager.ManageEntriesOfCurrent(addinglist, [], self.MasterNode) |
|
501 self.MasterNode.SetEntry(current_idx, 0x01, cobid) |
|
502 |
|
503 # Increment the number of PDO for this PDO type |
|
504 self.CurrentPDOParamsIdx[pdo_infos["type"]] += 1 |
|
505 |
|
506 # Change the transmit type of the PDO |
|
507 if sync_TPDOs: |
|
508 self.MasterNode.SetEntry(current_idx, 0x02, 0x01) |
|
509 else: |
|
510 self.MasterNode.SetEntry(current_idx, 0x02, 0xFF) |
|
511 |
|
512 mapping = [] |
|
513 for item in pdo_infos["mapping"]: |
|
514 if isinstance(item, ListType): |
|
515 mapping.extend(item) |
|
516 else: |
|
517 mapping.append(item) |
|
518 |
|
519 # Add some subentries to PDO mapping if there is not enough |
|
520 if len(mapping) > 1: |
|
521 self.Manager.AddSubentriesToCurrent(current_idx + 0x200, len(mapping) - 1, self.MasterNode) |
|
522 |
|
523 # Generate MasterNode's PDO mapping |
|
524 for subindex, variable in enumerate(mapping): |
|
525 if subindex == 0: |
|
526 continue |
|
527 new_index = False |
|
528 |
|
529 if isinstance(variable, (IntType, LongType)): |
|
530 # If variable is an integer then variable is unexpected |
|
531 self.MasterNode.SetEntry(current_idx + 0x200, subindex, self.TrashVariables[variable]) |
|
532 else: |
|
533 typeidx, varname = variable |
|
534 variable_infos = self.IECLocations[varname] |
|
535 |
|
536 # Calculate base index for storing variable |
|
537 mapvariableidx = VariableStartIndex[variable_infos["pdotype"]] + \ |
|
538 VariableTypeOffset[variable_infos["sizelocation"]] * VariableIncrement + \ |
|
539 variable_infos["nodeid"] |
|
540 |
|
541 # Generate entry name |
|
542 indexname = "%s%s%s_%d"%(VariableDirText[variable_infos["pdotype"]], |
|
543 variable_infos["sizelocation"], |
|
544 '_'.join(map(str,current_location)), |
|
545 variable_infos["nodeid"]) |
|
546 |
|
547 # Search for an entry that has an empty subindex |
|
548 while mapvariableidx < VariableStartIndex[variable_infos["pdotype"]] + 0x2000: |
|
549 # Entry doesn't exist |
|
550 if not self.MasterNode.IsEntry(mapvariableidx): |
|
551 # Add entry to MasterNode |
|
552 self.Manager.AddMapVariableToCurrent(mapvariableidx, "beremiz"+indexname, 3, 1, self.MasterNode) |
|
553 new_index = True |
|
554 nbsubentries = self.MasterNode.GetEntry(mapvariableidx, 0x00) |
|
555 else: |
|
556 # Get Number of subentries already defined |
|
557 nbsubentries = self.MasterNode.GetEntry(mapvariableidx, 0x00) |
|
558 # if entry is full, go to next entry possible or stop now |
|
559 if nbsubentries == 0xFF: |
|
560 mapvariableidx += 8 * VariableIncrement |
|
561 else: |
|
562 break |
|
563 |
|
564 # Verify that a not full entry has been found |
|
565 if mapvariableidx < VariableStartIndex[variable_infos["pdotype"]] + 0x2000: |
|
566 # Generate subentry name |
|
567 if variable_infos["bit"] != None: |
|
568 subindexname = "%(index)d_%(subindex)d_%(bit)d"%variable_infos |
|
569 else: |
|
570 subindexname = "%(index)d_%(subindex)d"%variable_infos |
|
571 # If entry have just been created, no subentry have to be added |
|
572 if not new_index: |
|
573 self.Manager.AddSubentriesToCurrent(mapvariableidx, 1, self.MasterNode) |
|
574 nbsubentries += 1 |
|
575 # Add informations to the new subentry created |
|
576 self.MasterNode.SetMappingEntry(mapvariableidx, nbsubentries, values = {"name" : subindexname}) |
|
577 self.MasterNode.SetMappingEntry(mapvariableidx, nbsubentries, values = {"type" : typeidx}) |
|
578 |
|
579 # Set value of the PDO mapping |
|
580 typeinfos = self.Manager.GetEntryInfos(typeidx) |
|
581 if typeinfos != None: |
|
582 value = (mapvariableidx << 16) + ((nbsubentries) << 8) + typeinfos["size"] |
|
583 self.MasterNode.SetEntry(current_idx + 0x200, subindex, value) |
|
584 |
|
585 # Add variable to pointed variables |
|
586 self.PointedVariables[(mapvariableidx, nbsubentries)] = "%s_%s"%(indexname, subindexname) |
|
587 |
|
588 def GenerateConciseDCF(locations, current_location, nodelist, sync_TPDOs, nodename): |
|
589 """ |
|
590 Fills a CanFestival network editor model, with DCF with requested PDO mappings. |
|
591 @param locations: List of complete variables locations \ |
|
592 [{"IEC_TYPE" : the IEC type (i.e. "INT", "STRING", ...) |
|
593 "NAME" : name of the variable (generally "__IW0_1_2" style) |
|
594 "DIR" : direction "Q","I" or "M" |
|
595 "SIZE" : size "X", "B", "W", "D", "L" |
|
596 "LOC" : tuple of interger for IEC location (0,1,2,...) |
|
597 }, ...] |
|
598 @param nodelist: CanFestival network editor model |
|
599 @return: a modified copy of the given CanFestival network editor model |
|
600 """ |
|
601 |
|
602 dcfgenerator = ConciseDCFGenerator(nodelist, nodename) |
|
603 dcfgenerator.GenerateDCF(locations, current_location, sync_TPDOs) |
|
604 masternode,pointers = dcfgenerator.GetMasterNode(), dcfgenerator.GetPointedVariables() |
|
605 # allow access to local OD from Master PLC |
|
606 pointers.update(LocalODPointers(locations, current_location, masternode)) |
|
607 return masternode,pointers |
|
608 |
|
609 def LocalODPointers(locations, current_location, slave): |
|
610 IECLocations = {} |
|
611 pointers = {} |
|
612 for location in locations: |
|
613 COlocationtype = IECToCOType[location["IEC_TYPE"]] |
|
614 name = location["NAME"] |
|
615 if name in IECLocations: |
|
616 if IECLocations[name] != COlocationtype: |
|
617 raise PDOmappingException, _("Type conflict for location \"%s\"") % name |
|
618 else: |
|
619 # Get only the part of the location that concern this node |
|
620 loc = location["LOC"][len(current_location):] |
|
621 # loc correspond to (ID, INDEX, SUBINDEX [,BIT]) |
|
622 if len(loc) not in (2, 3, 4): |
|
623 raise PDOmappingException, _("Bad location size : %s") % str(loc) |
|
624 elif len(loc) != 2: |
|
625 continue |
|
626 |
|
627 # Extract and check nodeid |
|
628 index, subindex = loc[:2] |
|
629 |
|
630 # Extract and check index and subindex |
|
631 if not slave.IsEntry(index, subindex): |
|
632 raise PDOmappingException, _("No such index/subindex (%x,%x) (variable %s)") % (index, subindex, name) |
|
633 |
|
634 # Get the entry info |
|
635 subentry_infos = slave.GetSubentryInfos(index, subindex) |
|
636 if subentry_infos["type"] != COlocationtype: |
|
637 raise PDOmappingException, _("Invalid type \"%s\"-> %d != %d for location\"%s\"") % (location["IEC_TYPE"], COlocationtype, subentry_infos["type"] , name) |
|
638 |
|
639 IECLocations[name] = COlocationtype |
|
640 pointers[(index, subindex)] = name |
|
641 return pointers |
|
642 |
|
643 if __name__ == "__main__": |
|
644 import os, sys, getopt |
|
645 |
|
646 def usage(): |
|
647 print """ |
|
648 Usage of config_utils.py test : |
|
649 |
|
650 %s [options] |
|
651 |
|
652 Options: |
|
653 --help (-h) |
|
654 Displays help informations for config_utils |
|
655 |
|
656 --reset (-r) |
|
657 Reset the reference result of config_utils test. |
|
658 Use with caution. Be sure that config_utils |
|
659 is currently working properly. |
|
660 """%sys.argv[0] |
|
661 |
|
662 # Boolean that indicate if reference result must be redefined |
|
663 reset = False |
|
664 |
|
665 # Extract command options |
|
666 try: |
|
667 opts, args = getopt.getopt(sys.argv[1:], "hr", ["help","reset"]) |
|
668 except getopt.GetoptError: |
|
669 # print help information and exit: |
|
670 usage() |
|
671 sys.exit(2) |
|
672 |
|
673 # Test each option |
|
674 for o, a in opts: |
|
675 if o in ("-h", "--help"): |
|
676 usage() |
|
677 sys.exit() |
|
678 elif o in ("-r", "--reset"): |
|
679 reset = True |
|
680 |
|
681 # Extract workspace base folder |
|
682 base_folder = sys.path[0] |
|
683 for i in xrange(3): |
|
684 base_folder = os.path.split(base_folder)[0] |
|
685 # Add CanFestival folder to search pathes |
|
686 sys.path.append(os.path.join(base_folder, "CanFestival-3", "objdictgen")) |
|
687 |
|
688 from nodemanager import * |
|
689 from nodelist import * |
|
690 |
|
691 # Open the test nodelist contained into test_config folder |
|
692 manager = NodeManager() |
|
693 nodelist = NodeList(manager) |
|
694 result = nodelist.LoadProject("test_config") |
|
695 |
|
696 # List of locations, we try to map for test |
|
697 locations = [{"IEC_TYPE":"BYTE","NAME":"__IB0_1_64_24576_1","DIR":"I","SIZE":"B","LOC":(0,1,64,24576,1)}, |
|
698 {"IEC_TYPE":"INT","NAME":"__IW0_1_64_25601_2","DIR":"I","SIZE":"W","LOC":(0,1,64,25601,2)}, |
|
699 {"IEC_TYPE":"INT","NAME":"__IW0_1_64_25601_3","DIR":"I","SIZE":"W","LOC":(0,1,64,25601,3)}, |
|
700 {"IEC_TYPE":"INT","NAME":"__QW0_1_64_25617_2","DIR":"Q","SIZE":"W","LOC":(0,1,64,25617,1)}, |
|
701 {"IEC_TYPE":"BYTE","NAME":"__IB0_1_64_24578_1","DIR":"I","SIZE":"B","LOC":(0,1,64,24578,1)}, |
|
702 {"IEC_TYPE":"UDINT","NAME":"__ID0_1_64_25638_1","DIR":"I","SIZE":"D","LOC":(0,1,64,25638,1)}, |
|
703 {"IEC_TYPE":"UDINT","NAME":"__ID0_1_64_25638_2","DIR":"I","SIZE":"D","LOC":(0,1,64,25638,2)}, |
|
704 {"IEC_TYPE":"UDINT","NAME":"__ID0_1_64_25638_3","DIR":"I","SIZE":"D","LOC":(0,1,64,25638,3)}, |
|
705 {"IEC_TYPE":"UDINT","NAME":"__ID0_1_64_25638_4","DIR":"I","SIZE":"D","LOC":(0,1,64,25638,4)}, |
|
706 {"IEC_TYPE":"UDINT","NAME":"__ID0_1_4096_0","DIR":"I","SIZE":"D","LOC":(0,1,4096,0)}] |
|
707 |
|
708 # Generate MasterNode configuration |
|
709 try: |
|
710 masternode, pointedvariables = GenerateConciseDCF(locations, (0, 1), nodelist, True, "TestNode") |
|
711 except ValueError, message: |
|
712 print "%s\nTest Failed!"%message |
|
713 sys.exit() |
|
714 |
|
715 import pprint |
|
716 # Get Text corresponding to MasterNode |
|
717 result_node = masternode.PrintString() |
|
718 result_vars = pprint.pformat(pointedvariables) |
|
719 result = result_node + "\n********POINTERS*********\n" + result_vars + "\n" |
|
720 |
|
721 # If reset has been choosen |
|
722 if reset: |
|
723 # Write Text into reference result file |
|
724 testfile = open("test_config/result.txt", "w") |
|
725 testfile.write(result) |
|
726 testfile.close() |
|
727 |
|
728 print "Reset Successful!" |
|
729 else: |
|
730 import os |
|
731 |
|
732 testfile = open("test_config/result_tmp.txt", "w") |
|
733 testfile.write(result) |
|
734 testfile.close() |
|
735 |
|
736 os.system("diff test_config/result.txt test_config/result_tmp.txt") |
|
737 os.remove("test_config/result_tmp.txt") |
|