generate_builtin.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. from __future__ import print_function
  2. import sys
  3. from collections import OrderedDict
  4. import re
  5. from lxml import etree
  6. if len(sys.argv) != 3:
  7. print("Usage: python generate_builtin.py <path/to/Opc.Ua.Types.bsd> <outfile w/o extension>", file=sys.stdout)
  8. exit(0)
  9. # types that are coded manually
  10. exclude_types = set(["Boolean", "SByte", "Byte", "Int16", "UInt16", "Int32", "UInt32",
  11. "Int64", "UInt64", "Float", "Double", "String", "DateTime", "Guid",
  12. "ByteString", "XmlElement", "NodeId", "ExpandedNodeId", "StatusCode",
  13. "QualifiedName", "LocalizedText", "ExtensionObject", "DataValue",
  14. "Variant", "DiagnosticInfo", "IntegerId"])
  15. elementary_size = dict()
  16. elementary_size["Boolean"] = 1;
  17. elementary_size["SByte"] = 1;
  18. elementary_size["Byte"] = 1;
  19. elementary_size["Int16"] = 2;
  20. elementary_size["UInt16"] = 2;
  21. elementary_size["Int32"] = 4;
  22. elementary_size["UInt32"] = 4;
  23. elementary_size["Int64"] = 8;
  24. elementary_size["UInt64"] = 8;
  25. elementary_size["Float"] = 4;
  26. elementary_size["Double"] = 8;
  27. elementary_size["DateTime"] = 8;
  28. elementary_size["StatusCode"] = 4;
  29. # indefinite_types = ["NodeId", "ExpandedNodeId", "QualifiedName", "LocalizedText", "ExtensionObject", "DataValue", "Variant", "DiagnosticInfo"]
  30. indefinite_types = ["ExpandedNodeId", "QualifiedName", "ExtensionObject", "DataValue", "Variant", "DiagnosticInfo"]
  31. enum_types = []
  32. structured_types = []
  33. # indefinite types cannot be directly contained in a record as they don't have a definite size
  34. printed_types = exclude_types # types that were already printed and which we can use in the structures to come
  35. # types we do not want to autogenerate
  36. def skipType(name):
  37. if name in exclude_types:
  38. return True
  39. if re.search("NodeId$", name) != None:
  40. return True
  41. return False
  42. def stripTypename(tn):
  43. return tn[tn.find(":")+1:]
  44. # are the prerequisites in place? if not, postpone.
  45. def printableStructuredType(element):
  46. for child in element:
  47. if child.tag == "{http://opcfoundation.org/BinarySchema/}Field":
  48. typename = stripTypename(child.get("TypeName"))
  49. if typename not in printed_types:
  50. return False
  51. return True
  52. # There three types of types in the bsd file:
  53. # StructuredType, EnumeratedType OpaqueType
  54. def createEnumerated(element):
  55. valuemap = OrderedDict()
  56. name = "UA_" + element.get("Name")
  57. enum_types.append(name)
  58. print("\n/*** " + name + " ***/", end='\n', file=fh)
  59. for child in element:
  60. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  61. print("/* " + child.text + " */", end='\n', file=fh)
  62. if child.tag == "{http://opcfoundation.org/BinarySchema/}EnumeratedValue":
  63. valuemap[name + "_" + child.get("Name")] = child.get("Value")
  64. valuemap = OrderedDict(sorted(valuemap.iteritems(), key=lambda (k,v): int(v)))
  65. print("typedef UA_UInt32 " + name + ";", end='\n', file=fh);
  66. print("enum " + name + "_enum { \n\t" + ",\n\t".join(map(lambda (key, value) : key + " = " + value, valuemap.iteritems())) + "\n};", end='\n', file=fh)
  67. print("UA_TYPE_METHOD_PROTOTYPES (" + name + ")", end='\n', file=fh)
  68. print("UA_TYPE_METHOD_CALCSIZE_AS("+name+", UA_UInt32)", end='\n', file=fc)
  69. print("UA_TYPE_METHOD_ENCODE_AS("+name+", UA_UInt32)", end='\n', file=fc)
  70. print("UA_TYPE_METHOD_DECODE_AS("+name+", UA_UInt32)", end='\n', file=fc)
  71. print("UA_TYPE_METHOD_DELETE_AS("+name+", UA_UInt32)", end='\n', file=fc)
  72. print("UA_TYPE_METHOD_DELETEMEMBERS_AS("+name+", UA_UInt32)\n", end='\n', file=fc)
  73. return
  74. def createStructured(element):
  75. valuemap = OrderedDict()
  76. name = "UA_" + element.get("Name")
  77. print("\n/*** " + name + " ***/", end='\n', file=fh)
  78. lengthfields = set()
  79. for child in element:
  80. if child.get("LengthField"):
  81. lengthfields.add(child.get("LengthField"))
  82. for child in element:
  83. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  84. print("/* " + child.text + " */", end='\n', file=fh)
  85. elif child.tag == "{http://opcfoundation.org/BinarySchema/}Field":
  86. if child.get("Name") in lengthfields:
  87. continue
  88. childname = child.get("Name")
  89. #if childname in printed_types:
  90. # childname = childname + "_Value" # attributes may not have the name of a type
  91. typename = stripTypename(child.get("TypeName"))
  92. if typename in structured_types:
  93. valuemap[childname] = typename + "*"
  94. elif typename in indefinite_types:
  95. valuemap[childname] = typename + "*"
  96. elif child.get("LengthField"):
  97. valuemap[childname] = typename + "**"
  98. else:
  99. valuemap[childname] = typename
  100. # if "Response" in name[len(name)-9:]:
  101. # print("type " + name + " is new Response_Base with "),
  102. # elif "Request" in name[len(name)-9:]:
  103. # print ("type " + name + " is new Request_Base with "),
  104. # else:
  105. # print ("type " + name + " is new UA_Builtin with "),
  106. print("typedef struct T_" + name + " {", end='\n', file=fh)
  107. if len(valuemap) > 0:
  108. for n,t in valuemap.iteritems():
  109. if t.find("**") != -1:
  110. print("\t" + "UInt32 " + n + "Size;", end='\n', file=fh)
  111. print("\t" + "UA_" + t + " " + n + ";", end='\n', file=fh)
  112. else:
  113. print("\t/* null record */", end='\n', file=fh)
  114. print("\tUA_Int32 NullRecord; /* avoiding warnings */", end='\n', file=fh)
  115. print("} " + name + ";", end='\n', file=fh)
  116. print("Int32 " + name + "_calcSize(" + name + " const * ptr);", end='\n', file=fh)
  117. print("Int32 " + name + "_encode(" + name + " const * src, Int32* pos, char* dst);", end='\n', file=fh)
  118. print("Int32 " + name + "_decode(char const * src, UInt32* pos, " + name + "* dst);", end='\n', file=fh)
  119. if "Response" in name[len(name)-9:]:
  120. #Sten: not sure how to get it, actually we need to solve it on a higher level
  121. #print("Int32 " + name + "_calcSize(" + name + " const * ptr) {\n\treturn UA_ResponseHeader_getSize()", end='', file=fc)
  122. print("Int32 " + name + "_calcSize(" + name + " const * ptr) {\n\treturn 0", end='', file=fc)
  123. elif "Request" in name[len(name)-9:]:
  124. #Sten: dito
  125. #print("Int32 " + name + "_calcSize(" + name + " const * ptr) {\n\treturn UA_RequestHeader_getSize()", end='', file=fc)
  126. print("Int32 " + name + "_calcSize(" + name + " const * ptr) {\n\treturn 0", end='', file=fc)
  127. else:
  128. # code
  129. print("Int32 " + name + "_calcSize(" + name + " const * ptr) {\n\treturn 0", end='', file=fc)
  130. # code _calcSize
  131. for n,t in valuemap.iteritems():
  132. if t in elementary_size:
  133. print('\n\t + sizeof(UA_' + t + ") // " + n, end='', file=fc)
  134. else:
  135. if t in enum_types:
  136. print('\n\t + 4 //' + n, end='', file=fc) # enums are all 32 bit
  137. elif t.find("**") != -1:
  138. print("\n\t + 4 //" + n + "Size", end='', file=fc),
  139. print("\n\t + UA_Array_calcSize(ptr->" + n + "Size, UA_" + t[0:t.find("*")].upper() + ", (void const**) ptr->" + n +")", end='', file=fc)
  140. elif t.find("*") != -1:
  141. print('\n\t + ' + "UA_" + t[0:t.find("*")] + "_calcSize(ptr->" + n + ')', end='', file=fc)
  142. else:
  143. print('\n\t + ' + "UA_" + t + "_calcSize(&(ptr->" + n + '))', end='', file=fc)
  144. print("\n\t;\n};\n", end='\n', file=fc)
  145. print("Int32 "+name+"_encode("+name+" const * src, Int32* pos, char* dst) {\n\tInt32 retval = UA_SUCCESS;", end='\n', file=fc)
  146. # code _encode
  147. for n,t in valuemap.iteritems():
  148. if t in elementary_size:
  149. print('\tretval |= UA_'+t+'_encode(&(src->'+n+'),pos,dst);', end='\n', file=fc)
  150. else:
  151. if t in enum_types:
  152. print('\tretval |= UA_'+t+'_encode(&(src->'+n+'),pos,dst);', end='\n', file=fc)
  153. elif t.find("**") != -1:
  154. print('\tretval |= UA_Int32_encode(&(src->'+n+'Size),pos,dst); // encode size', end='\n', file=fc)
  155. print("\tretval |= UA_Array_encode((void const**) (src->"+n+"),src->"+n+"Size, UA_" + t[0:t.find("*")].upper()+",pos,dst);", end='\n', file=fc)
  156. elif t.find("*") != -1:
  157. print('\tretval |= UA_' + t[0:t.find("*")] + "_encode(src->" + n + ',pos,dst);', end='\n', file=fc)
  158. else:
  159. print('\tretval |= UA_'+t+"_encode(&(src->"+n+"),pos,dst);", end='\n', file=fc)
  160. print("\treturn retval;\n};\n", end='\n', file=fc)
  161. print("Int32 "+name+"_decode(char const * src, UInt32* pos, " + name + "* dst) {\n\tInt32 retval = UA_SUCCESS;", end='\n', file=fc)
  162. # code _decode
  163. for n,t in valuemap.iteritems():
  164. if t in elementary_size:
  165. print('\tretval |= UA_'+t+'_decode(src,pos,&(dst->'+n+'));', end='\n', file=fc)
  166. else:
  167. if t in enum_types:
  168. print('\tretval |= UA_'+t+'_decode(src,pos,&(dst->'+n+'));', end='\n', file=fc)
  169. elif t.find("**") != -1:
  170. print('\tretval |= UA_Int32_decode(src,pos,&(dst->'+n+'Size)); // decode size', end='\n', file=fc)
  171. print("\tretval |= UA_Array_decode(src,dst->"+n+"Size, UA_" + t[0:t.find("*")].upper()+",pos,(void const**) (dst->"+n+"));", end='\n', file=fc) #not tested
  172. elif t.find("*") != -1:
  173. print('\tretval |= UA_' + t[0:t.find("*")] + "_decode(src,pos,dst->"+ n +");", end='\n', file=fc)
  174. else:
  175. print('\tretval |= UA_'+t+"_decode(src,pos,&(dst->"+n+"));", end='\n', file=fc)
  176. print("\treturn retval;\n};\n", end='\n', file=fc)
  177. def createOpaque(element):
  178. name = "UA_" + element.get("Name")
  179. print("\n/*** " + name + " ***/", end='\n', file=fh)
  180. for child in element:
  181. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  182. print("/* " + child.text + " */", end='\n', file=fh)
  183. print("typedef UA_ByteString " + name + ";", end='\n', file=fh)
  184. print("UA_TYPE_METHOD_PROTOTYPES (" + name + ")", end='\n', file=fh)
  185. print("UA_TYPE_METHOD_CALCSIZE_AS("+name+", UA_ByteString)", end='\n', file=fc)
  186. print("UA_TYPE_METHOD_ENCODE_AS("+name+", UA_ByteString)", end='\n', file=fc)
  187. print("UA_TYPE_METHOD_DECODE_AS("+name+", UA_ByteString)", end='\n', file=fc)
  188. print("UA_TYPE_METHOD_DELETE_AS("+name+", UA_ByteString)", end='\n', file=fc)
  189. print("UA_TYPE_METHOD_DELETEMEMBERS_AS("+name+", UA_ByteString)\n", end='\n', file=fc)
  190. return
  191. ns = {"opc": "http://opcfoundation.org/BinarySchema/"}
  192. tree = etree.parse(sys.argv[1])
  193. types = tree.xpath("/opc:TypeDictionary/*[not(self::opc:Import)]", namespaces=ns)
  194. fh = open(sys.argv[2] + ".h",'w');
  195. fc = open(sys.argv[2] + ".c",'w');
  196. print('#include "' + sys.argv[2] + '.h"', end='\n', file=fc);
  197. # types for which we create a vector type
  198. arraytypes = set()
  199. fields = tree.xpath("//opc:Field", namespaces=ns)
  200. for field in fields:
  201. if field.get("LengthField"):
  202. arraytypes.add(stripTypename(field.get("TypeName")))
  203. deferred_types = OrderedDict()
  204. print('#ifndef OPCUA_H_', end='\n', file=fh)
  205. print('#define OPCUA_H_', end='\n', file=fh)
  206. print('#include "opcua_basictypes.h"', end='\n', file=fh)
  207. print('#include "opcua_namespace_0.h"', end='\n', file=fh);
  208. for element in types:
  209. name = element.get("Name")
  210. if skipType(name):
  211. continue
  212. if element.tag == "{http://opcfoundation.org/BinarySchema/}EnumeratedType":
  213. createEnumerated(element)
  214. printed_types.add(name)
  215. elif element.tag == "{http://opcfoundation.org/BinarySchema/}StructuredType":
  216. if printableStructuredType(element):
  217. createStructured(element)
  218. structured_types.append(name)
  219. printed_types.add(name)
  220. else: # the record contains types that were not yet detailed
  221. deferred_types[name] = element
  222. continue
  223. elif element.tag == "{http://opcfoundation.org/BinarySchema/}OpaqueType":
  224. createOpaque(element)
  225. printed_types.add(name)
  226. #if name in arraytypes:
  227. # print "package ListOf" + name + " is new Types.Arrays.UA_Builtin_Arrays(" + name + ");\n"
  228. for name, element in deferred_types.iteritems():
  229. createStructured(element)
  230. # if name in arraytypes:
  231. # print "package ListOf" + name + " is new Types.Arrays.UA_Builtin_Arrays(" + name + ");\n"
  232. print('#endif /* OPCUA_H_ */', end='\n', file=fh)
  233. fh.close()
  234. fc.close()