backend_open62541.py 10 KB

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