backend_open62541.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. #!/usr/bin/env/python
  2. # -*- coding: utf-8 -*-
  3. ###
  4. ### Authors:
  5. ### - Chris Iatrou (ichrispa@core-vector.net)
  6. ### - Julius Pfrommer
  7. ### - Stefan Profanter (profanter@fortiss.org)
  8. ###
  9. ### This program was created for educational purposes and has been
  10. ### contributed to the open62541 project by the author. All licensing
  11. ### terms for this source is inherited by the terms and conditions
  12. ### specified for by the open62541 project (see the projects readme
  13. ### file for more information on the LGPL terms and restrictions).
  14. ###
  15. ### This program is not meant to be used in a production environment. The
  16. ### author is not liable for any complications arising due to the use of
  17. ### this program.
  18. ###
  19. from __future__ import print_function
  20. import string
  21. from collections import deque
  22. from os.path import basename
  23. import logging
  24. logger = logging.getLogger(__name__)
  25. from constants import *
  26. from nodes import *
  27. from nodeset import *
  28. from backend_open62541_nodes import generateNodeCode, generateReferenceCode
  29. ##############
  30. # Sort Nodes #
  31. ##############
  32. # Select the references that shall be generated after this node in the ordering
  33. # If both nodes of the reference are hidden we assume that the references between
  34. # those nodes are already setup. Still print if only the target node is hidden,
  35. # because we need that reference.
  36. def selectPrintRefs(nodeset, L, node):
  37. printRefs = []
  38. for ref in node.references:
  39. targetnode = nodeset.nodes[ref.target]
  40. if node.hidden and targetnode.hidden:
  41. continue
  42. if not targetnode.hidden and not targetnode in L:
  43. continue
  44. printRefs.append(ref)
  45. for ref in node.inverseReferences:
  46. targetnode = nodeset.nodes[ref.target]
  47. if node.hidden and targetnode.hidden:
  48. continue
  49. if not targetnode.hidden and not targetnode in L:
  50. continue
  51. printRefs.append(ref)
  52. return printRefs
  53. def addTypeRef(nodeset, type_refs, dataTypeId, referencedById):
  54. if not dataTypeId in type_refs:
  55. type_refs[dataTypeId] = [referencedById]
  56. else:
  57. type_refs[dataTypeId].append(referencedById)
  58. def reorderNodesMinDependencies(nodeset):
  59. # Kahn's algorithm
  60. # https://algocoding.wordpress.com/2015/04/05/topological-sorting-python/
  61. relevant_types = nodeset.getRelevantOrderingReferences()
  62. # determine in-degree
  63. in_degree = {u.id: 0 for u in nodeset.nodes.values()}
  64. dataType_refs = {}
  65. hiddenCount = 0
  66. for u in nodeset.nodes.values(): # of each node
  67. if u.hidden:
  68. hiddenCount += 1
  69. continue
  70. hasTypeDef = None
  71. for ref in u.references:
  72. if ref.referenceType.i == 40:
  73. hasTypeDef = ref.target
  74. elif (ref.referenceType in relevant_types and ref.isForward) and not nodeset.nodes[ref.target].hidden:
  75. in_degree[ref.target] += 1
  76. if hasTypeDef is not None and not nodeset.nodes[hasTypeDef].hidden:
  77. # we cannot print the node u because it first needs the variable type node
  78. in_degree[u.id] += 1
  79. if isinstance(u, VariableNode) and u.dataType is not None:
  80. dataTypeNode = nodeset.getDataTypeNode(u.dataType)
  81. if dataTypeNode is not None and not dataTypeNode.hidden:
  82. # we cannot print the node u because it first needs the data type node
  83. in_degree[u.id] += 1
  84. # to be able to decrement the in_degree count, we need to store it here
  85. addTypeRef(nodeset, dataType_refs,dataTypeNode.id, u.id)
  86. # collect nodes with zero in-degree
  87. Q = deque()
  88. for id in in_degree:
  89. if in_degree[id] == 0:
  90. # print referencetypenodes first
  91. n = nodeset.nodes[id]
  92. if isinstance(n, ReferenceTypeNode):
  93. Q.append(nodeset.nodes[id])
  94. else:
  95. Q.appendleft(nodeset.nodes[id])
  96. L = [] # list for order of nodes
  97. while Q:
  98. u = Q.pop() # choose node of zero in-degree
  99. # decide which references to print now based on the ordering
  100. u.printRefs = selectPrintRefs(nodeset, L, u)
  101. if u.hidden:
  102. continue
  103. L.append(u) # and 'remove' it from graph
  104. if isinstance(u, DataTypeNode):
  105. # decrement all the nodes which depend on this datatype
  106. if u.id in dataType_refs:
  107. for n in dataType_refs[u.id]:
  108. if not nodeset.nodes[n].hidden:
  109. in_degree[n] -= 1
  110. if in_degree[n] == 0:
  111. Q.append(nodeset.nodes[n])
  112. del dataType_refs[u.id]
  113. for ref in u.inverseReferences:
  114. if ref.referenceType.i == 40:
  115. if not nodeset.nodes[ref.target].hidden:
  116. in_degree[ref.target] -= 1
  117. if in_degree[ref.target] == 0:
  118. Q.append(nodeset.nodes[ref.target])
  119. for ref in u.references:
  120. if (ref.referenceType in relevant_types and ref.isForward):
  121. if not nodeset.nodes[ref.target].hidden:
  122. in_degree[ref.target] -= 1
  123. if in_degree[ref.target] == 0:
  124. Q.append(nodeset.nodes[ref.target])
  125. if len(L) + hiddenCount != len(nodeset.nodes.values()):
  126. stillOpen = ""
  127. for id in in_degree:
  128. if in_degree[id] == 0:
  129. continue
  130. node = nodeset.nodes[id]
  131. stillOpen += node.browseName.name + "/" + str(node.id) + " = " + str(in_degree[id]) + "\r\n"
  132. raise Exception("Node graph is circular on the specified references. Still open nodes:\r\n" + stillOpen)
  133. return L
  134. ###################
  135. # Generate C Code #
  136. ###################
  137. def generateOpen62541Code(nodeset, outfilename, supressGenerationOfAttribute=[], generate_ns0=False, internal_headers=False, typesArray=[], max_string_length=0):
  138. outfilebase = basename(outfilename)
  139. # Printing functions
  140. outfileh = open(outfilename + ".h", r"w+")
  141. outfilec = open(outfilename + ".c", r"w+")
  142. def writeh(line):
  143. print(unicode(line).encode('utf8'), end='\n', file=outfileh)
  144. def writec(line):
  145. print(unicode(line).encode('utf8'), end='\n', file=outfilec)
  146. additionalHeaders = ""
  147. if len(typesArray) > 0:
  148. for arr in set(typesArray):
  149. if arr == "UA_TYPES":
  150. continue
  151. additionalHeaders += """#include "%s_generated.h"\n""" % arr.lower()
  152. # Print the preamble of the generated code
  153. writeh("""/* WARNING: This is a generated file.
  154. * Any manual changes will be overwritten. */
  155. #ifndef %s_H_
  156. #define %s_H_
  157. """ % (outfilebase.upper(), outfilebase.upper()))
  158. if internal_headers:
  159. writeh("""
  160. #ifdef UA_NO_AMALGAMATION
  161. #include "ua_server.h"
  162. #include "ua_types_encoding_binary.h"
  163. %s
  164. #else
  165. #include "open62541.h"
  166. #endif
  167. """ % (additionalHeaders))
  168. else:
  169. writeh("""
  170. #include "open62541.h"
  171. """)
  172. writeh("""
  173. extern UA_StatusCode %s(UA_Server *server);
  174. #endif /* %s_H_ */""" % \
  175. (outfilebase, outfilebase.upper()))
  176. writec("""/* WARNING: This is a generated file.
  177. * Any manual changes will be overwritten. */
  178. #include "%s.h"
  179. UA_StatusCode %s(UA_Server *server) { // NOLINT
  180. UA_StatusCode retVal = UA_STATUSCODE_GOOD;
  181. """ % (outfilebase, outfilebase))
  182. parentrefs = getSubTypesOf(nodeset, nodeset.getNodeByBrowseName("HierarchicalReferences"))
  183. parentrefs = map(lambda x: x.id, parentrefs)
  184. # Generate namespaces (don't worry about duplicates)
  185. writec("/* Use namespace ids generated by the server */")
  186. for i, nsid in enumerate(nodeset.namespaces):
  187. nsid = nsid.replace("\"", "\\\"")
  188. writec("UA_UInt16 ns" + str(i) + " = UA_Server_addNamespace(server, \"" + nsid + "\");")
  189. # Loop over the sorted nodes
  190. logger.info("Reordering nodes for minimal dependencies during printing")
  191. sorted_nodes = reorderNodesMinDependencies(nodeset)
  192. logger.info("Writing code for nodes and references")
  193. for node in sorted_nodes:
  194. # Print node
  195. if not node.hidden:
  196. writec("\n/* " + str(node.displayName) + " - " + str(node.id) + " */")
  197. code = generateNodeCode(node, supressGenerationOfAttribute, generate_ns0, parentrefs, nodeset, max_string_length)
  198. if code is None:
  199. writec("/* Ignored. No parent */")
  200. nodeset.hide_node(node.id)
  201. continue
  202. else:
  203. writec(code)
  204. # Print inverse references leading to this node
  205. for ref in node.printRefs:
  206. writec(generateReferenceCode(ref))
  207. # Finalize the generated source
  208. writec("return retVal;")
  209. writec("} // closing nodeset()")
  210. outfileh.close()
  211. outfilec.close()