backend_open62541.py 8.4 KB

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