Browse Source

fix python3 support for the namespace generation

Julius Pfrommer 8 years ago
parent
commit
f47c6dc983

+ 20 - 23
tools/pyUANamespace/generate_open62541CCode.py

@@ -16,40 +16,37 @@
 ### this program.
 ###
 
+from __future__ import print_function
 from sys import argv, exit
 from os import path
 from ua_namespace import *
 from logger import *
 
 def usage():
-  print "Script usage:"
-  print "generate_open62541CCode [-i <ignorefile> | -b <blacklistfile>] <namespace XML> [namespace.xml[ namespace.xml[...]]] <output file>"
-  print ""
-  print "generate_open62541CCode will first read all XML files passed on the command line, then "
-  print "link and check the namespace. All nodes that fullfill the basic requirements will then be"
-  print "printed as C-Code intended to be included in the open62541 OPC-UA Server that will"
-  print "initialize the corresponding name space."
-  print ""
-  print "Manditory Arguments:"
-  print "<namespace XML>    At least one Namespace XML file must be passed."
-  print "<output file>      The basename for the <output file>.c and <output file>.h files to be generated."
-  print "                   This will also be the function name used in the header and c-file."
-  print ""
-  print ""
-  print "Additional Arguments:"
-  print """   -i <ignoreFile>     Loads a list of NodeIDs stored in ignoreFile (one NodeID per line)
+  print("Script usage:")
+  print("generate_open62541CCode [-i <ignorefile> | -b <blacklistfile>] <namespace XML> [namespace.xml[ namespace.xml[...]]] <output file>\n")
+  print("generate_open62541CCode will first read all XML files passed on the command line, then ")
+  print("link and check the namespace. All nodes that fullfill the basic requirements will then be")
+  print("printed as C-Code intended to be included in the open62541 OPC-UA Server that will")
+  print("initialize the corresponding name space.\n")
+  print("Manditory Arguments:")
+  print("<namespace XML>    At least one Namespace XML file must be passed.")
+  print("<output file>      The basename for the <output file>.c and <output file>.h files to be generated.")
+  print("                   This will also be the function name used in the header and c-file.\n\n")
+  print("Additional Arguments:")
+  print("""   -i <ignoreFile>     Loads a list of NodeIDs stored in ignoreFile (one NodeID per line)
                        The compiler will assume that these Nodes have been created externally
                        and not generate any code for them. They will however be linked to
-                       from other nodes."""
-  print """   -b <blacklistFile>  Loads a list of NodeIDs stored in blacklistFile (one NodeID per line)
+                       from other nodes.""")
+  print("""   -b <blacklistFile>  Loads a list of NodeIDs stored in blacklistFile (one NodeID per line)
                        Any of the nodeIds encountered in this file will be removed from the namespace
-                       prior to compilation. Any references to these nodes will also be removed"""
-  print """   -s <attribute>  Suppresses the generation of some node attributes. Currently supported
+                       prior to compilation. Any references to these nodes will also be removed""")
+  print("""   -s <attribute>  Suppresses the generation of some node attributes. Currently supported
                        options are 'description', 'browseName', 'displayName', 'writeMask', 'userWriteMask'
-                       and 'nodeid'."""
-  print """   namespaceXML Any number of namespace descriptions in XML format. Note that the
+                       and 'nodeid'.""")
+  print("""   namespaceXML Any number of namespace descriptions in XML format. Note that the
                        last description of a node encountered will be used and all prior definitions
-                       are discarded."""
+                       are discarded.""")
 
 if __name__ == '__main__':
   # Check if the parameters given correspond to actual files

+ 3 - 2
tools/pyUANamespace/logger.py

@@ -16,6 +16,7 @@
 ### this program.
 ###
 
+from __future__ import print_function
 import inspect
 
 ###
@@ -40,6 +41,6 @@ def log(callee, logstr, level=LOG_LEVEL_DEBUG):
             }
   if level <= GLOBAL_LOG_LEVEL:
     if prefixes.has_key(level):
-      print str(prefixes[level]) + callee.__class__.__name__ + "." + inspect.stack()[1][3] +  "(): " + logstr
+      print(str(prefixes[level]) + callee.__class__.__name__ + "." + inspect.stack()[1][3] +  "(): " + logstr)
     else:
-      print callee.__class__.__name__  + "." + inspect.stack()[1][3] + "(): " + logstr
+      print(callee.__class__.__name__  + "." + inspect.stack()[1][3] + "(): " + logstr)

+ 5 - 0
tools/pyUANamespace/ua_builtin_types.py

@@ -16,6 +16,7 @@
 ### this program.
 ###
 
+import sys
 import xml.dom.minidom as dom
 from ua_constants import *
 from logger import *
@@ -29,6 +30,10 @@ def getNextElementNode(xmlvalue):
     xmlvalue = xmlvalue.nextSibling
   return xmlvalue
 
+if sys.version_info[0] >= 3:
+  # strings are already parsed to unicode
+  def unicode(s):
+    return s
 
 class opcua_value_t():
   value = None

+ 12 - 8
tools/pyUANamespace/ua_namespace.py

@@ -16,7 +16,8 @@
 ### this program.
 ###
 
-
+from __future__ import print_function
+import sys
 from time import struct_time, strftime, strptime, mktime
 from struct import pack as structpack
 
@@ -112,8 +113,11 @@ class opcua_namespace():
       if al.nodeType == al.ELEMENT_NODE:
         if al.hasAttribute("Alias"):
           aliasst = al.getAttribute("Alias")
-          aliasnd = unicode(al.firstChild.data)
-          if not self.aliases.has_key(aliasst):
+          if sys.version_info[0] < 3:
+            aliasnd = unicode(al.firstChild.data)
+          else:
+            aliasnd = al.firstChild.data
+          if not aliasst in self.aliases:
             self.aliases[aliasst] = aliasnd
             log(self, "Added new alias \"" + str(aliasst) + "\" == \"" + str(aliasnd) + "\"")
           else:
@@ -195,7 +199,7 @@ class opcua_namespace():
     else:
       id = opcua_node_id_t(id)
 
-    if self.nodeids.has_key(str(id)):
+    if str(id) in self.nodeids:
       # Normal behavior: Do not allow duplicates, first one wins
       #log(self,  "XMLElement with duplicate ID " + str(id) + " found, node will not be created!", LOG_LEVEL_ERROR)
       #return
@@ -294,7 +298,7 @@ class opcua_namespace():
         log(self, "XML Element or NodeType " + ndType + " is unknown and will be ignored", LOG_LEVEL_WARN)
         continue
 
-      if not typedict.has_key(ndType):
+      if not ndType in typedict:
         typedict[ndType] = 1
       else:
         typedict[ndType] = typedict[ndType] + 1
@@ -737,17 +741,17 @@ class testing:
     while (len(ns) < len(allnodes)):
       i = i + 1;
       tmp = [];
-      print "Iteration: " + str(i)
+      print("Iteration: " + str(i))
       for n in ns:
         tmp.append(n)
         for r in n.getReferences():
           if (not r.target() in tmp):
            tmp.append(r.target())
-      print "...tmp, " + str(len(tmp)) + " nodes discovered"
+      print("...tmp, " + str(len(tmp)) + " nodes discovered")
       ns = []
       for n in tmp:
         ns.append(n)
-      print "...done, " + str(len(ns)) + " nodes discovered"
+      print("...done, " + str(len(ns)) + " nodes discovered")
 
     log(self, "Phase 5: Printing pretty graph")
     self.namespace.printDotGraphWalk(depth=1, rootNode=self.namespace.getNodeByIDString("i=84"), followInverse=False, excludeNodeIds=["i=29", "i=22", "i=25"])

+ 14 - 6
tools/pyUANamespace/ua_node_types.py

@@ -16,6 +16,7 @@
 ### this program.
 ###
 
+import sys
 from logger import *;
 from ua_builtin_types import *;
 from open62541_MacroHelper import open62541_MacroHelper
@@ -144,7 +145,7 @@ class opcua_referencePointer_t():
     if other.target() == self.target():
       if other.referenceType() == self.referenceType():
         if other.isForward() == self.isForward():
-	  return 0
+          return 0
     return 1
 
 
@@ -412,7 +413,9 @@ class opcua_node_t:
     """
     if isinstance(data, str):
       self.__node_browseName__ = data
-    return self.__node_browseName__.encode('utf-8')
+    if sys.version_info[0] < 3:
+      return self.__node_browseName__.encode('utf-8')
+    return self.__node_browseName__
 
   def displayName(self, data=None):
     """ Sets the display name attribute if data is passed.
@@ -669,16 +672,16 @@ class opcua_node_t:
       code = code + self.printOpen62541CCode_Subtype(unPrintedReferences = unPrintedReferences, bootstrapping = False)
       code.append("       UA_NULL);") # createdNodeId, wraps up the UA_Server_add<XYType>Node() call
       if self.nodeClass() == NODE_CLASS_METHOD:
-	code.append("#endif //ENABLE_METHODCALL") # ifdef added by codegen when methods are detected
+        code.append("#endif //ENABLE_METHODCALL") # ifdef added by codegen when methods are detected
       # Parent to child reference is added by the server, do not reprint that reference
       if parentRef in unPrintedReferences:
         unPrintedReferences.remove(parentRef)
       # the UA_Server_addNode function will use addReference which creates a biderectional reference; remove any inverse
       # references to our parent to avoid duplicate refs
       for ref in self.getReferences():
-	if ref.target() == parentNode and ref.referenceType() == parentRef.referenceType() and ref.isForward() == False:
-	  while ref in unPrintedReferences:
-	    unPrintedReferences.remove(ref)
+        if ref.target() == parentNode and ref.referenceType() == parentRef.referenceType() and ref.isForward() == False:
+          while ref in unPrintedReferences:
+            unPrintedReferences.remove(ref)
     # Otherwise use the "Bootstrapping" method and we will get registered with other nodes later.
     else:
       code = code + self.printOpen62541CCode_SubtypeEarly(bootstrapping = True)
@@ -897,6 +900,11 @@ class opcua_node_object_t(opcua_node_t):
     code.append(self.getCodePrintableID() + "->eventNotifier = (UA_Byte) " + str(self.eventNotifier()) + ";")
     return code
 
+if sys.version_info[0] >= 3:
+  # strings are already parsed to unicode
+  def unicode(s):
+    return s
+
 class opcua_node_variable_t(opcua_node_t):
   __value__               = 0
   __dataType__            = None