generate_builtin.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. def camlCase2AdaCase(item):
  45. (newitem, n) = re.subn("(?<!^)(?<![A-Z])([A-Z])", "_\\1", item)
  46. return newitem
  47. def camlCase2CCase(item):
  48. if item in ["Float","Double"]:
  49. return "my" + item
  50. return item[:1].lower() + item[1:] if item else ''
  51. # are the prerequisites in place? if not, postpone.
  52. def printableStructuredType(element):
  53. for child in element:
  54. if child.tag == "{http://opcfoundation.org/BinarySchema/}Field":
  55. typename = stripTypename(child.get("TypeName"))
  56. if typename not in printed_types:
  57. return False
  58. return True
  59. # There three types of types in the bsd file:
  60. # StructuredType, EnumeratedType OpaqueType
  61. def createEnumerated(element):
  62. valuemap = OrderedDict()
  63. name = "UA_" + element.get("Name")
  64. enum_types.append(name)
  65. print("\n/*** " + name + " ***/", end='\n', file=fh)
  66. for child in element:
  67. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  68. print("/* " + child.text + " */", end='\n', file=fh)
  69. if child.tag == "{http://opcfoundation.org/BinarySchema/}EnumeratedValue":
  70. valuemap[name + "_" + child.get("Name")] = child.get("Value")
  71. valuemap = OrderedDict(sorted(valuemap.iteritems(), key=lambda (k,v): int(v)))
  72. print("typedef UA_UInt32 " + name + ";", end='\n', file=fh);
  73. print("enum " + name + "_enum { \n\t" + ",\n\t".join(map(lambda (key, value) : key.upper() + " = " + value, valuemap.iteritems())) + "\n};", end='\n', file=fh)
  74. print("UA_TYPE_METHOD_PROTOTYPES (" + name + ")", end='\n', file=fh)
  75. print("UA_TYPE_METHOD_CALCSIZE_AS("+name+", UA_UInt32)", end='\n', file=fc)
  76. print("UA_TYPE_METHOD_ENCODE_AS("+name+", UA_UInt32)", end='\n', file=fc)
  77. print("UA_TYPE_METHOD_DECODE_AS("+name+", UA_UInt32)", end='\n', file=fc)
  78. print("UA_TYPE_METHOD_DELETE_AS("+name+", UA_UInt32)", end='\n', file=fc)
  79. print("UA_TYPE_METHOD_DELETEMEMBERS_AS("+name+", UA_UInt32)\n", end='\n', file=fc)
  80. return
  81. def createStructured(element):
  82. valuemap = OrderedDict()
  83. name = "UA_" + element.get("Name")
  84. print("\n/*** " + name + " ***/", end='\n', file=fh)
  85. lengthfields = set()
  86. for child in element:
  87. if child.get("LengthField"):
  88. lengthfields.add(child.get("LengthField"))
  89. for child in element:
  90. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  91. print("/* " + child.text + " */", end='\n', file=fh)
  92. elif child.tag == "{http://opcfoundation.org/BinarySchema/}Field":
  93. if child.get("Name") in lengthfields:
  94. continue
  95. childname = camlCase2CCase(child.get("Name"))
  96. #if childname in printed_types:
  97. # childname = childname + "_Value" # attributes may not have the name of a type
  98. typename = stripTypename(child.get("TypeName"))
  99. if typename in structured_types:
  100. valuemap[childname] = typename + "*"
  101. elif typename in indefinite_types:
  102. valuemap[childname] = typename + "*"
  103. elif child.get("LengthField"):
  104. valuemap[childname] = typename + "**"
  105. else:
  106. valuemap[childname] = typename
  107. # if "Response" in name[len(name)-9:]:
  108. # print("type " + name + " is new Response_Base with "),
  109. # elif "Request" in name[len(name)-9:]:
  110. # print ("type " + name + " is new Request_Base with "),
  111. # else:
  112. # print ("type " + name + " is new UA_Builtin with "),
  113. print("typedef struct T_" + name + " {", end='\n', file=fh)
  114. if len(valuemap) > 0:
  115. for n,t in valuemap.iteritems():
  116. if t.find("**") != -1:
  117. print("\t" + "UA_Int32 " + n + "Size;", end='\n', file=fh)
  118. print("\t" + "UA_" + t + " " + n + ";", end='\n', file=fh)
  119. else:
  120. print("\t/* null record */", end='\n', file=fh)
  121. print("\tUA_Int32 NullRecord; /* avoiding warnings */", end='\n', file=fh)
  122. print("} " + name + ";", end='\n', file=fh)
  123. print("UA_Int32 " + name + "_calcSize(" + name + " const * ptr);", end='\n', file=fh)
  124. print("UA_Int32 " + name + "_encode(" + name + " const * src, UA_Int32* pos, char* dst);", end='\n', file=fh)
  125. print("UA_Int32 " + name + "_decode(char const * src, UA_Int32* pos, " + name + "* dst);", end='\n', file=fh)
  126. if "Response" in name[len(name)-9:]:
  127. #Sten: not sure how to get it, actually we need to solve it on a higher level
  128. #print("UA_Int32 " + name + "_calcSize(" + name + " const * ptr) {\n\treturn UA_ResponseHeader_getSize()", end='', file=fc)
  129. print("UA_Int32 " + name + "_calcSize(" + name + " const * ptr) {\n\treturn 0", end='', file=fc)
  130. elif "Request" in name[len(name)-9:]:
  131. #Sten: dito
  132. #print("UA_Int32 " + name + "_calcSize(" + name + " const * ptr) {\n\treturn UA_RequestHeader_getSize()", end='', file=fc)
  133. print("UA_Int32 " + name + "_calcSize(" + name + " const * ptr) {\n\treturn 0", end='', file=fc)
  134. else:
  135. # code
  136. print("UA_Int32 " + name + "_calcSize(" + name + " const * ptr) {\n\treturn 0", end='', file=fc)
  137. # code _calcSize
  138. for n,t in valuemap.iteritems():
  139. if t in elementary_size:
  140. print('\n\t + sizeof(UA_' + t + ") // " + n, end='', file=fc)
  141. else:
  142. if t in enum_types:
  143. print('\n\t + 4 //' + n, end='', file=fc) # enums are all 32 bit
  144. elif t.find("**") != -1:
  145. print("\n\t + 0 //" + n + "Size is included in UA_Array_calcSize", end='', file=fc),
  146. print("\n\t + UA_Array_calcSize(ptr->" + n + "Size, UA_" + t[0:t.find("*")].upper() + ", (void const**) ptr->" + n +")", end='', file=fc)
  147. elif t.find("*") != -1:
  148. print('\n\t + ' + "UA_" + t[0:t.find("*")] + "_calcSize(ptr->" + n + ')', end='', file=fc)
  149. else:
  150. print('\n\t + ' + "UA_" + t + "_calcSize(&(ptr->" + n + '))', end='', file=fc)
  151. print("\n\t;\n}\n", end='\n', file=fc)
  152. print("UA_Int32 "+name+"_encode("+name+" const * src, UA_Int32* pos, char* dst) {\n\tUA_Int32 retval = UA_SUCCESS;", end='\n', file=fc)
  153. # code _encode
  154. for n,t in valuemap.iteritems():
  155. if t in elementary_size:
  156. print('\tretval |= UA_'+t+'_encode(&(src->'+n+'),pos,dst);', end='\n', file=fc)
  157. else:
  158. if t in enum_types:
  159. print('\tretval |= UA_'+t+'_encode(&(src->'+n+'),pos,dst);', end='\n', file=fc)
  160. elif t.find("**") != -1:
  161. print('\tretval |= UA_Int32_encode(&(src->'+n+'Size),pos,dst); // encode size', end='\n', file=fc)
  162. print("\tretval |= UA_Array_encode((void const**) (src->"+n+"),src->"+n+"Size, UA_" + t[0:t.find("*")].upper()+",pos,dst);", end='\n', file=fc)
  163. elif t.find("*") != -1:
  164. print('\tretval |= UA_' + t[0:t.find("*")] + "_encode(src->" + n + ',pos,dst);', end='\n', file=fc)
  165. else:
  166. print('\tretval |= UA_'+t+"_encode(&(src->"+n+"),pos,dst);", end='\n', file=fc)
  167. print("\treturn retval;\n}\n", end='\n', file=fc)
  168. print("UA_Int32 "+name+"_decode(char const * src, UA_Int32* pos, " + name + "* dst) {\n\tUA_Int32 retval = UA_SUCCESS;", end='\n', file=fc)
  169. # code _decode
  170. for n,t in valuemap.iteritems():
  171. if t in elementary_size:
  172. print('\tretval |= UA_'+t+'_decode(src,pos,&(dst->'+n+'));', end='\n', file=fc)
  173. else:
  174. if t in enum_types:
  175. print('\tretval |= UA_'+t+'_decode(src,pos,&(dst->'+n+'));', end='\n', file=fc)
  176. elif t.find("**") != -1:
  177. print('\tretval |= UA_Int32_decode(src,pos,&(dst->'+n+'Size)); // decode size', end='\n', file=fc)
  178. 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
  179. elif t.find("*") != -1:
  180. print('\tretval |= UA_' + t[0:t.find("*")] + "_decode(src,pos,dst->"+ n +");", end='\n', file=fc)
  181. else:
  182. print('\tretval |= UA_'+t+"_decode(src,pos,&(dst->"+n+"));", end='\n', file=fc)
  183. print("\treturn retval;\n}\n", end='\n', file=fc)
  184. def createOpaque(element):
  185. name = "UA_" + element.get("Name")
  186. print("\n/*** " + name + " ***/", end='\n', file=fh)
  187. for child in element:
  188. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  189. print("/* " + child.text + " */", end='\n', file=fh)
  190. print("typedef UA_ByteString " + name + ";", end='\n', file=fh)
  191. print("UA_TYPE_METHOD_PROTOTYPES (" + name + ")", end='\n', file=fh)
  192. print("UA_TYPE_METHOD_CALCSIZE_AS("+name+", UA_ByteString)", end='\n', file=fc)
  193. print("UA_TYPE_METHOD_ENCODE_AS("+name+", UA_ByteString)", end='\n', file=fc)
  194. print("UA_TYPE_METHOD_DECODE_AS("+name+", UA_ByteString)", end='\n', file=fc)
  195. print("UA_TYPE_METHOD_DELETE_AS("+name+", UA_ByteString)", end='\n', file=fc)
  196. print("UA_TYPE_METHOD_DELETEMEMBERS_AS("+name+", UA_ByteString)\n", end='\n', file=fc)
  197. return
  198. ns = {"opc": "http://opcfoundation.org/BinarySchema/"}
  199. tree = etree.parse(sys.argv[1])
  200. types = tree.xpath("/opc:TypeDictionary/*[not(self::opc:Import)]", namespaces=ns)
  201. fh = open(sys.argv[2] + ".h",'w');
  202. fc = open(sys.argv[2] + ".c",'w');
  203. print('#include "' + sys.argv[2] + '.h"', end='\n', file=fc);
  204. # types for which we create a vector type
  205. arraytypes = set()
  206. fields = tree.xpath("//opc:Field", namespaces=ns)
  207. for field in fields:
  208. if field.get("LengthField"):
  209. arraytypes.add(stripTypename(field.get("TypeName")))
  210. deferred_types = OrderedDict()
  211. print('#ifndef OPCUA_H_', end='\n', file=fh)
  212. print('#define OPCUA_H_', end='\n', file=fh)
  213. print('#include "opcua_basictypes.h"', end='\n', file=fh)
  214. print('#include "opcua_namespace_0.h"', end='\n', file=fh);
  215. for element in types:
  216. name = element.get("Name")
  217. if skipType(name):
  218. continue
  219. if element.tag == "{http://opcfoundation.org/BinarySchema/}EnumeratedType":
  220. createEnumerated(element)
  221. printed_types.add(name)
  222. elif element.tag == "{http://opcfoundation.org/BinarySchema/}StructuredType":
  223. if printableStructuredType(element):
  224. createStructured(element)
  225. structured_types.append(name)
  226. printed_types.add(name)
  227. else: # the record contains types that were not yet detailed
  228. deferred_types[name] = element
  229. continue
  230. elif element.tag == "{http://opcfoundation.org/BinarySchema/}OpaqueType":
  231. createOpaque(element)
  232. printed_types.add(name)
  233. #if name in arraytypes:
  234. # print "package ListOf" + name + " is new Types.Arrays.UA_Builtin_Arrays(" + name + ");\n"
  235. for name, element in deferred_types.iteritems():
  236. createStructured(element)
  237. # if name in arraytypes:
  238. # print "package ListOf" + name + " is new Types.Arrays.UA_Builtin_Arrays(" + name + ");\n"
  239. print('#endif /* OPCUA_H_ */', end='\n', file=fh)
  240. fh.close()
  241. fc.close()