author | lbessard |
Fri, 21 Dec 2007 18:06:11 +0100 | |
changeset 84 | 8bc2669828e9 |
parent 80 | d7eb6e22b02e |
child 150 | 204d515df3dd |
permissions | -rw-r--r-- |
58 | 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: |
|
61 | 367 |
numbit = loc[3] |
58 | 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) |
|
61 | 374 |
if location["IEC_TYPE"] != "BOOL" and entryinfos["type"] != COlocationtype: |
58 | 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 |
# Add PDO to MasterMapping |
|
399 |
if cobid not in self.MasterMapping.keys(): |
|
80 | 400 |
# Verify that PDO transmit type is conform to sync_TPDOs |
401 |
transmittype = self.NodeList.GetSlaveNodeEntry(locationinfos["nodeid"], index - 0x200, 2) |
|
402 |
if sync_TPDOs and transmittype != 0x01 or transmittype != 0xFF: |
|
403 |
if sync_TPDOs: |
|
404 |
# Change TransmitType to SYNCHRONE |
|
405 |
data, nbparams = GeneratePDOMappingDCF(index - 0x200, cobid, 0x01, []) |
|
406 |
else: |
|
407 |
# Change TransmitType to ASYCHRONE |
|
408 |
data, nbparams = GeneratePDOMappingDCF(index - 0x200, cobid, 0xFF, []) |
|
409 |
||
410 |
# Add entry to slave dcf to change transmit type of |
|
411 |
self.AddParamsToDCF(locationinfos["nodeid"], data, nbparams) |
|
412 |
||
58 | 413 |
mapping = [None] |
414 |
values = node.GetEntry(index) |
|
415 |
# Store the size of each entry mapped in PDO |
|
416 |
for value in values[1:]: |
|
78 | 417 |
if value != 0: |
418 |
mapping.append(value % 0x100) |
|
58 | 419 |
self.MasterMapping[cobid] = {"type" : InvertPDOType[locationinfos["pdotype"]], "mapping" : mapping} |
420 |
||
421 |
# Indicate that this PDO entry must be saved |
|
422 |
self.MasterMapping[cobid]["mapping"][subindex] = (locationinfos["type"], name) |
|
423 |
||
424 |
else: |
|
425 |
# Add location to those that haven't been mapped yet |
|
426 |
if locationinfos["nodeid"] not in self.LocationsNotMapped.keys(): |
|
427 |
self.LocationsNotMapped[locationinfos["nodeid"]] = {TPDO : [], RPDO : []} |
|
428 |
self.LocationsNotMapped[locationinfos["nodeid"]][locationinfos["pdotype"]].append((name, locationinfos)) |
|
429 |
||
430 |
#------------------------------------------------------------------------------- |
|
431 |
# Build concise DCF for the others locations |
|
432 |
#------------------------------------------------------------------------------- |
|
433 |
||
434 |
for nodeid, locations in self.LocationsNotMapped.items(): |
|
61 | 435 |
node = self.NodeList.SlaveNodes[nodeid]["Node"] |
58 | 436 |
|
437 |
# Initialize number of params and data to add to node DCF |
|
438 |
nbparams = 0 |
|
439 |
dataparams = "" |
|
440 |
||
441 |
# Generate the best PDO mapping for each type of PDO |
|
442 |
for pdotype in (TPDO, RPDO): |
|
443 |
pdosize = 0 |
|
444 |
pdomapping = [] |
|
445 |
for name, loc_infos in locations[pdotype]: |
|
446 |
pdosize += loc_infos["size"] |
|
447 |
# If pdo's size > 64 bits |
|
448 |
if pdosize > 64: |
|
449 |
# Generate a new PDO Mapping |
|
450 |
data, nbaddedparams = self.AddPDOMapping(nodeid, pdotype, pdomapping, sync_TPDOs) |
|
451 |
dataparams += data |
|
452 |
nbparams += nbaddedparams |
|
453 |
pdosize = loc_infos["size"] |
|
454 |
pdomapping = [(name, loc_infos)] |
|
455 |
else: |
|
456 |
pdomapping.append((name, loc_infos)) |
|
457 |
# If there isn't locations yet but there is still a PDO to generate |
|
458 |
if len(pdomapping) > 0: |
|
459 |
# Generate a new PDO Mapping |
|
460 |
data, nbaddedparams = self.AddPDOMapping(nodeid, pdotype, pdomapping, sync_TPDOs) |
|
461 |
dataparams += data |
|
462 |
nbparams += nbaddedparams |
|
463 |
||
464 |
# Add number of params and data to node DCF |
|
465 |
self.AddParamsToDCF(nodeid, dataparams, nbparams) |
|
466 |
||
467 |
#------------------------------------------------------------------------------- |
|
468 |
# Master Node Configuration |
|
469 |
#------------------------------------------------------------------------------- |
|
470 |
||
471 |
# Generate Master's Configuration from informations stored in MasterMapping |
|
472 |
for cobid, pdo_infos in self.MasterMapping.items(): |
|
473 |
# Get next PDO index in MasterNode for this PDO type |
|
474 |
current_idx = self.CurrentPDOParamsIdx[pdo_infos["type"]] |
|
475 |
||
476 |
# Search if there is already a PDO in MasterNode with this cob id |
|
477 |
for idx in GetNodePDOIndexes(self.MasterNode, pdo_infos["type"], True): |
|
478 |
if self.MasterNode.GetEntry(idx, 1) == cobid: |
|
479 |
current_idx = idx |
|
480 |
||
481 |
# Add a PDO to MasterNode if not PDO have been found |
|
482 |
if current_idx == self.CurrentPDOParamsIdx[pdo_infos["type"]]: |
|
483 |
addinglist = [current_idx, current_idx + 0x200] |
|
484 |
self.Manager.ManageEntriesOfCurrent(addinglist, [], self.MasterNode) |
|
485 |
self.MasterNode.SetEntry(current_idx, 0x01, cobid) |
|
486 |
||
487 |
# Increment the number of PDO for this PDO type |
|
488 |
self.CurrentPDOParamsIdx[pdo_infos["type"]] += 1 |
|
489 |
||
490 |
# Change the transmit type of the PDO |
|
491 |
if sync_TPDOs: |
|
492 |
self.MasterNode.SetEntry(current_idx, 0x02, 0x01) |
|
493 |
else: |
|
494 |
self.MasterNode.SetEntry(current_idx, 0x02, 0xFF) |
|
495 |
||
496 |
# Add some subentries to PDO mapping if there is not enough |
|
59
b6ff896ff58b
Enhancements in CanFestival plugin. Now PLC with CanFestival plugin compiles and run, exchanging CanOpen PDOs
etisserant
parents:
58
diff
changeset
|
497 |
if len(pdo_infos["mapping"]) > 1: |
b6ff896ff58b
Enhancements in CanFestival plugin. Now PLC with CanFestival plugin compiles and run, exchanging CanOpen PDOs
etisserant
parents:
58
diff
changeset
|
498 |
self.Manager.AddSubentriesToCurrent(current_idx + 0x200, len(pdo_infos["mapping"]) - 1, self.MasterNode) |
58 | 499 |
|
500 |
# Generate MasterNode's PDO mapping |
|
501 |
for subindex, variable in enumerate(pdo_infos["mapping"]): |
|
502 |
if subindex == 0: |
|
503 |
continue |
|
504 |
new_index = False |
|
505 |
||
506 |
if type(variable) == IntType: |
|
507 |
# If variable is an integer then variable is unexpected |
|
508 |
self.MasterNode.SetEntry(current_idx + 0x200, subindex, self.TrashVariables[variable]) |
|
509 |
else: |
|
510 |
typeidx, varname = variable |
|
511 |
variable_infos = self.IECLocations[varname] |
|
512 |
||
513 |
# Calculate base index for storing variable |
|
514 |
mapvariableidx = VariableStartIndex[variable_infos["pdotype"]] + \ |
|
515 |
VariableTypeOffset[variable_infos["sizelocation"]] * VariableIncrement + \ |
|
516 |
variable_infos["nodeid"] |
|
517 |
||
518 |
# Search for an entry that has an empty subindex |
|
519 |
while mapvariableidx < VariableStartIndex[variable_infos["pdotype"]] + 0x2000: |
|
520 |
# Entry doesn't exist |
|
521 |
if not self.MasterNode.IsEntry(mapvariableidx): |
|
522 |
# Generate entry name |
|
523 |
indexname = "%s%s%s_%d"%(VariableDirText[variable_infos["pdotype"]], |
|
524 |
variable_infos["sizelocation"], |
|
525 |
'_'.join(map(str,current_location)), |
|
526 |
variable_infos["nodeid"]) |
|
527 |
# Add entry to MasterNode |
|
528 |
self.Manager.AddMapVariableToCurrent(mapvariableidx, indexname, 3, 1, self.MasterNode) |
|
529 |
new_index = True |
|
530 |
nbsubentries = self.MasterNode.GetEntry(mapvariableidx, 0x00) |
|
531 |
else: |
|
532 |
# Get Number of subentries already defined |
|
533 |
nbsubentries = self.MasterNode.GetEntry(mapvariableidx, 0x00) |
|
534 |
# if entry is full, go to next entry possible or stop now |
|
535 |
if nbsubentries == 0xFF: |
|
536 |
mapvariableidx += 8 * VariableIncrement |
|
537 |
else: |
|
538 |
break |
|
539 |
||
540 |
# Verify that a not full entry has been found |
|
541 |
if mapvariableidx < VariableStartIndex[variable_infos["pdotype"]] + 0x2000: |
|
542 |
# Generate subentry name |
|
543 |
if variable_infos["bit"] != None: |
|
544 |
subindexname = "%(index)d_%(subindex)d_%(bit)d"%variable_infos |
|
545 |
else: |
|
546 |
subindexname = "%(index)d_%(subindex)d"%variable_infos |
|
547 |
# If entry have just been created, no subentry have to be added |
|
548 |
if not new_index: |
|
549 |
self.Manager.AddSubentriesToCurrent(mapvariableidx, 1, self.MasterNode) |
|
550 |
nbsubentries += 1 |
|
551 |
# Add informations to the new subentry created |
|
552 |
self.MasterNode.SetMappingEntry(mapvariableidx, nbsubentries, values = {"name" : subindexname}) |
|
553 |
self.MasterNode.SetMappingEntry(mapvariableidx, nbsubentries, values = {"type" : typeidx}) |
|
554 |
||
555 |
# Set value of the PDO mapping |
|
556 |
typeinfos = self.Manager.GetEntryInfos(typeidx) |
|
557 |
if typeinfos != None: |
|
558 |
value = (mapvariableidx << 16) + ((nbsubentries) << 8) + typeinfos["size"] |
|
559 |
self.MasterNode.SetEntry(current_idx + 0x200, subindex, value) |
|
560 |
||
561 |
def GenerateConciseDCF(locations, current_location, nodelist, sync_TPDOs, nodename): |
|
562 |
""" |
|
563 |
Fills a CanFestival network editor model, with DCF with requested PDO mappings. |
|
564 |
@param locations: List of complete variables locations \ |
|
565 |
[{"IEC_TYPE" : the IEC type (i.e. "INT", "STRING", ...) |
|
566 |
"NAME" : name of the variable (generally "__IW0_1_2" style) |
|
567 |
"DIR" : direction "Q","I" or "M" |
|
568 |
"SIZE" : size "X", "B", "W", "D", "L" |
|
569 |
"LOC" : tuple of interger for IEC location (0,1,2,...) |
|
570 |
}, ...] |
|
571 |
@param nodelist: CanFestival network editor model |
|
572 |
@return: a modified copy of the given CanFestival network editor model |
|
573 |
""" |
|
574 |
||
575 |
dcfgenerator = ConciseDCFGenerator(nodelist, nodename) |
|
576 |
dcfgenerator.GenerateDCF(locations, current_location, sync_TPDOs) |
|
577 |
return dcfgenerator.GetMasterNode() |
|
578 |
||
579 |
if __name__ == "__main__": |
|
580 |
import os, sys, getopt |
|
581 |
||
582 |
def usage(): |
|
583 |
print """ |
|
584 |
Usage of config_utils.py test : |
|
585 |
||
586 |
%s [options] |
|
587 |
||
588 |
Options: |
|
589 |
--help (-h) |
|
590 |
Displays help informations for config_utils |
|
591 |
||
592 |
--reset (-r) |
|
593 |
Reset the reference result of config_utils test. |
|
594 |
Use with caution. Be sure that config_utils |
|
595 |
is currently working properly. |
|
596 |
"""%sys.argv[0] |
|
597 |
||
598 |
# Boolean that indicate if reference result must be redefined |
|
599 |
reset = False |
|
600 |
||
601 |
# Extract command options |
|
602 |
try: |
|
603 |
opts, args = getopt.getopt(sys.argv[1:], "hr", ["help","reset"]) |
|
604 |
except getopt.GetoptError: |
|
605 |
# print help information and exit: |
|
606 |
usage() |
|
607 |
sys.exit(2) |
|
608 |
||
609 |
# Test each option |
|
610 |
for o, a in opts: |
|
611 |
if o in ("-h", "--help"): |
|
612 |
usage() |
|
613 |
sys.exit() |
|
614 |
elif o in ("-r", "--reset"): |
|
615 |
reset = True |
|
616 |
||
617 |
# Extract workspace base folder |
|
618 |
base_folder = sys.path[0] |
|
619 |
for i in xrange(3): |
|
620 |
base_folder = os.path.split(base_folder)[0] |
|
621 |
# Add CanFestival folder to search pathes |
|
622 |
sys.path.append(os.path.join(base_folder, "CanFestival-3", "objdictgen")) |
|
623 |
||
624 |
from nodemanager import * |
|
625 |
from nodelist import * |
|
626 |
||
627 |
# Open the test nodelist contained into test_config folder |
|
628 |
manager = NodeManager() |
|
629 |
nodelist = NodeList(manager) |
|
630 |
result = nodelist.LoadProject("test_config") |
|
631 |
||
632 |
# List of locations, we try to map for test |
|
633 |
locations = [{"IEC_TYPE":"BYTE","NAME":"__IB0_1_64_24576_1","DIR":"I","SIZE":"B","LOC":(0,1,64,24576,1)}, |
|
634 |
{"IEC_TYPE":"INT","NAME":"__IW0_1_64_25601_2","DIR":"I","SIZE":"W","LOC":(0,1,64,25601,2)}, |
|
635 |
{"IEC_TYPE":"INT","NAME":"__IW0_1_64_25601_3","DIR":"I","SIZE":"W","LOC":(0,1,64,25601,3)}, |
|
636 |
{"IEC_TYPE":"INT","NAME":"__QW0_1_64_25617_2","DIR":"Q","SIZE":"W","LOC":(0,1,64,25617,1)}, |
|
637 |
{"IEC_TYPE":"BYTE","NAME":"__IB0_1_64_24578_1","DIR":"I","SIZE":"B","LOC":(0,1,64,24578,1)}, |
|
638 |
{"IEC_TYPE":"UDINT","NAME":"__ID0_1_64_25638_1","DIR":"I","SIZE":"D","LOC":(0,1,64,25638,1)}, |
|
639 |
{"IEC_TYPE":"UDINT","NAME":"__ID0_1_64_25638_2","DIR":"I","SIZE":"D","LOC":(0,1,64,25638,2)}, |
|
640 |
{"IEC_TYPE":"UDINT","NAME":"__ID0_1_64_25638_3","DIR":"I","SIZE":"D","LOC":(0,1,64,25638,3)}, |
|
641 |
{"IEC_TYPE":"UDINT","NAME":"__ID0_1_64_25638_4","DIR":"I","SIZE":"D","LOC":(0,1,64,25638,4)}] |
|
642 |
||
643 |
# Generate MasterNode configuration |
|
644 |
try: |
|
645 |
masternode = GenerateConciseDCF(locations, (0, 1), nodelist, True) |
|
646 |
except ValueError, message: |
|
647 |
print "%s\nTest Failed!"%message |
|
648 |
sys.exit() |
|
649 |
||
650 |
# Get Text corresponding to MasterNode |
|
651 |
result = masternode.PrintString() |
|
652 |
||
653 |
# If reset has been choosen |
|
654 |
if reset: |
|
655 |
# Write Text into reference result file |
|
656 |
file = open("test_config/result.txt", "w") |
|
657 |
file.write(result) |
|
658 |
file.close() |
|
659 |
||
660 |
print "Reset Successful!" |
|
661 |
else: |
|
662 |
# Test each line of the result with the reference result |
|
663 |
test = [line.rstrip() for line in result.splitlines()] |
|
664 |
||
665 |
file = open("test_config/result.txt", "r") |
|
666 |
model = [line.rstrip() for line in file.readlines() if line.rstrip()] |
|
667 |
file.close() |
|
668 |
||
669 |
errors = 0 |
|
670 |
for i, line in enumerate(model): |
|
671 |
if i >= len(test): |
|
672 |
errors += 1 |
|
673 |
print "Line %d disappear :\n%s\n"%(i + 1, line) |
|
674 |
elif line != test[i]: |
|
675 |
errors += 1 |
|
676 |
print "Error on line %d :\n%s\nInstead of :\n%s\n"%(i + 1, test[i], line) |
|
677 |
for i in xrange(len(model), len(test)): |
|
678 |
errors += 1 |
|
679 |
print "Line %d appear :\n%s\n"%(i + 1, test[i]) |
|
680 |
||
681 |
if errors > 0: |
|
682 |
print "%d errors found.\nTest Failed!"%errors |
|
683 |
else: |
|
684 |
print "Test Successful!" |