generate_builtin.py 12 KB

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