backend_open62541.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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 os.path import basename
  22. import logging
  23. import codecs
  24. try:
  25. from StringIO import StringIO
  26. except ImportError:
  27. from io import StringIO
  28. logger = logging.getLogger(__name__)
  29. from nodes import *
  30. from nodeset import *
  31. from backend_open62541_nodes import generateNodeCode_begin, generateNodeCode_finish, generateReferenceCode
  32. # Kahn's algorithm: https://algocoding.wordpress.com/2015/04/05/topological-sorting-python/
  33. def sortNodes(nodeset):
  34. # Ensure that every reference has an inverse reference in the target
  35. for u in nodeset.nodes.values():
  36. for ref in u.references:
  37. back = Reference(ref.target, ref.referenceType, ref.source, not ref.isForward)
  38. nodeset.nodes[ref.target].references.add(back) # ref set does not make a duplicate entry
  39. # reverse hastypedefinition references to treat only forward references
  40. hasTypeDef = NodeId("ns=0;i=40")
  41. for u in nodeset.nodes.values():
  42. for ref in u.references:
  43. if ref.referenceType == hasTypeDef:
  44. ref.isForward = not ref.isForward
  45. # Only hierarchical types...
  46. relevant_refs = nodeset.getRelevantOrderingReferences()
  47. # determine in-degree of unfulfilled references
  48. L = [node for node in nodeset.nodes.values() if node.hidden] # ordered list of nodes
  49. R = {node.id: node for node in nodeset.nodes.values() if not node.hidden} # remaining nodes
  50. in_degree = {id: 0 for id in R.keys()}
  51. for u in R.values(): # for each node
  52. for ref in u.references:
  53. if not ref.referenceType in relevant_refs:
  54. continue
  55. if nodeset.nodes[ref.target].hidden:
  56. continue
  57. if ref.isForward:
  58. continue
  59. in_degree[u.id] += 1
  60. # Print ReferenceType and DataType nodes first. They may be required even
  61. # though there is no reference to them. For example if the referencetype is
  62. # used in a reference, it must exist. A Variable node may point to a
  63. # DataTypeNode in the datatype attribute and not via an explicit reference.
  64. Q = {node for node in R.values() if in_degree[node.id] == 0 and
  65. (isinstance(node, ReferenceTypeNode) or isinstance(node, DataTypeNode))}
  66. while Q:
  67. u = Q.pop() # choose node of zero in-degree and 'remove' it from graph
  68. L.append(u)
  69. del R[u.id]
  70. for ref in u.references:
  71. if not ref.referenceType in relevant_refs:
  72. continue
  73. if nodeset.nodes[ref.target].hidden:
  74. continue
  75. if not ref.isForward:
  76. continue
  77. in_degree[ref.target] -= 1
  78. if in_degree[ref.target] == 0:
  79. Q.add(R[ref.target])
  80. # Order the remaining nodes
  81. Q = {node for node in R.values() if in_degree[node.id] == 0}
  82. while Q:
  83. u = Q.pop() # choose node of zero in-degree and 'remove' it from graph
  84. L.append(u)
  85. del R[u.id]
  86. for ref in u.references:
  87. if not ref.referenceType in relevant_refs:
  88. continue
  89. if nodeset.nodes[ref.target].hidden:
  90. continue
  91. if not ref.isForward:
  92. continue
  93. in_degree[ref.target] -= 1
  94. if in_degree[ref.target] == 0:
  95. Q.add(R[ref.target])
  96. # reverse hastype references
  97. for u in nodeset.nodes.values():
  98. for ref in u.references:
  99. if ref.referenceType == hasTypeDef:
  100. ref.isForward = not ref.isForward
  101. if len(L) != len(nodeset.nodes.values()):
  102. print(len(L))
  103. stillOpen = ""
  104. for id in in_degree:
  105. if in_degree[id] == 0:
  106. continue
  107. node = nodeset.nodes[id]
  108. stillOpen += node.browseName.name + "/" + str(node.id) + " = " + str(in_degree[id]) + \
  109. " " + str(node.references) + "\r\n"
  110. raise Exception("Node graph is circular on the specified references. Still open nodes:\r\n" + stillOpen)
  111. return L
  112. ###################
  113. # Generate C Code #
  114. ###################
  115. def generateOpen62541Code(nodeset, outfilename, generate_ns0=False, internal_headers=False, typesArray=[], max_string_length=0):
  116. outfilebase = basename(outfilename)
  117. # Printing functions
  118. outfileh = codecs.open(outfilename + ".h", r"w+", encoding='utf-8')
  119. outfilec = StringIO()
  120. def writeh(line):
  121. print(unicode(line), end='\n', file=outfileh)
  122. def writec(line):
  123. print(unicode(line), end='\n', file=outfilec)
  124. additionalHeaders = ""
  125. if len(typesArray) > 0:
  126. for arr in set(typesArray):
  127. if arr == "UA_TYPES":
  128. continue
  129. additionalHeaders += """#include "%s_generated.h"\n""" % arr.lower()
  130. # Print the preamble of the generated code
  131. writeh("""/* WARNING: This is a generated file.
  132. * Any manual changes will be overwritten. */
  133. #ifndef %s_H_
  134. #define %s_H_
  135. """ % (outfilebase.upper(), outfilebase.upper()))
  136. if internal_headers:
  137. writeh("""
  138. #ifdef UA_NO_AMALGAMATION
  139. # include "ua_server.h"
  140. # include "ua_types_encoding_binary.h"
  141. #else
  142. # include "open62541.h"
  143. /* The following declarations are in the open62541.c file so here's needed when compiling nodesets externally */
  144. # ifndef UA_Nodestore_remove //this definition is needed to hide this code in the amalgamated .c file
  145. typedef UA_StatusCode (*UA_exchangeEncodeBuffer)(void *handle, UA_Byte **bufPos,
  146. const UA_Byte **bufEnd);
  147. UA_StatusCode
  148. UA_encodeBinary(const void *src, const UA_DataType *type,
  149. UA_Byte **bufPos, const UA_Byte **bufEnd,
  150. UA_exchangeEncodeBuffer exchangeCallback,
  151. void *exchangeHandle) UA_FUNC_ATTR_WARN_UNUSED_RESULT;
  152. UA_StatusCode
  153. UA_decodeBinary(const UA_ByteString *src, size_t *offset, void *dst,
  154. const UA_DataType *type, size_t customTypesSize,
  155. const UA_DataType *customTypes) UA_FUNC_ATTR_WARN_UNUSED_RESULT;
  156. size_t
  157. UA_calcSizeBinary(void *p, const UA_DataType *type);
  158. const UA_DataType *
  159. UA_findDataTypeByBinary(const UA_NodeId *typeId);
  160. # endif // UA_Nodestore_remove
  161. #endif
  162. %s
  163. """ % (additionalHeaders))
  164. else:
  165. writeh("""
  166. #include "open62541.h"
  167. """)
  168. writeh("""
  169. #ifdef __cplusplus
  170. extern "C" {
  171. #endif
  172. extern UA_StatusCode %s(UA_Server *server);
  173. #ifdef __cplusplus
  174. }
  175. #endif
  176. #endif /* %s_H_ */""" % \
  177. (outfilebase, outfilebase.upper()))
  178. writec("""/* WARNING: This is a generated file.
  179. * Any manual changes will be overwritten. */
  180. #include "%s.h"
  181. """ % (outfilebase))
  182. # Loop over the sorted nodes
  183. logger.info("Reordering nodes for minimal dependencies during printing")
  184. sorted_nodes = sortNodes(nodeset)
  185. logger.info("Writing code for nodes and references")
  186. functionNumber = 0
  187. parentreftypes = getSubTypesOf(nodeset, nodeset.getNodeByBrowseName("HierarchicalReferences"))
  188. parentreftypes = list(map(lambda x: x.id, parentreftypes))
  189. printed_ids = set()
  190. for node in sorted_nodes:
  191. printed_ids.add(node.id)
  192. parentref = node.popParentRef(parentreftypes)
  193. if not node.hidden:
  194. writec("\n/* " + str(node.displayName) + " - " + str(node.id) + " */")
  195. code = generateNodeCode_begin(node, nodeset, max_string_length, generate_ns0, parentref)
  196. if code is None:
  197. writec("/* Ignored. No parent */")
  198. nodeset.hide_node(node.id)
  199. continue
  200. else:
  201. writec("\nstatic UA_StatusCode function_" + outfilebase + "_" + str(functionNumber) + "_begin(UA_Server *server, UA_UInt16* ns) {")
  202. if isinstance(node, MethodNode):
  203. writec("#ifdef UA_ENABLE_METHODCALLS")
  204. writec(code)
  205. # Print inverse references leading to this node
  206. for ref in node.references:
  207. if ref.target not in printed_ids:
  208. continue
  209. if node.hidden and nodeset.nodes[ref.target].hidden:
  210. continue
  211. writec(generateReferenceCode(ref))
  212. if node.hidden:
  213. continue
  214. writec("return retVal;")
  215. if isinstance(node, MethodNode):
  216. writec("#else")
  217. writec("return UA_STATUSCODE_GOOD;")
  218. writec("#endif /* UA_ENABLE_METHODCALLS */")
  219. writec("}");
  220. writec("\nstatic UA_StatusCode function_" + outfilebase + "_" + str(functionNumber) + "_finish(UA_Server *server, UA_UInt16* ns) {")
  221. if isinstance(node, MethodNode):
  222. writec("#ifdef UA_ENABLE_METHODCALLS")
  223. writec("return " + generateNodeCode_finish(node))
  224. if isinstance(node, MethodNode):
  225. writec("#else")
  226. writec("return UA_STATUSCODE_GOOD;")
  227. writec("#endif /* UA_ENABLE_METHODCALLS */")
  228. writec("}");
  229. functionNumber = functionNumber + 1
  230. writec("""
  231. UA_StatusCode %s(UA_Server *server) {
  232. UA_StatusCode retVal = UA_STATUSCODE_GOOD;""" % (outfilebase))
  233. # Generate namespaces (don't worry about duplicates)
  234. writec("/* Use namespace ids generated by the server */")
  235. writec("UA_UInt16 ns[" + str(len(nodeset.namespaces)) + "];")
  236. for i, nsid in enumerate(nodeset.namespaces):
  237. nsid = nsid.replace("\"", "\\\"")
  238. writec("ns[" + str(i) + "] = UA_Server_addNamespace(server, \"" + nsid + "\");")
  239. for i in range(0, functionNumber):
  240. writec("retVal |= function_" + outfilebase + "_" + str(i) + "_begin(server, ns);")
  241. for i in reversed(range(0, functionNumber)):
  242. writec("retVal |= function_" + outfilebase + "_" + str(i) + "_finish(server, ns);")
  243. writec("return retVal;\n}")
  244. outfileh.close()
  245. fullCode = outfilec.getvalue()
  246. outfilec.close()
  247. outfilec = codecs.open(outfilename + ".c", r"w+", encoding='utf-8')
  248. outfilec.write(fullCode)
  249. outfilec.close()