generate_builtin.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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", "RequestHeader", "ResponseHeader", "NodeIdType"])
  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. # are the prerequisites in place? if not, postpone.
  47. def printableStructuredType(element):
  48. for child in element:
  49. if child.tag == "{http://opcfoundation.org/BinarySchema/}Field":
  50. typename = stripTypename(child.get("TypeName"))
  51. if typename not in printed_types:
  52. return False
  53. return True
  54. # There three types of types in the bsd file:
  55. # StructuredType, EnumeratedType OpaqueType
  56. def createEnumerated(element):
  57. valuemap = OrderedDict()
  58. name = "UA_" + element.get("Name")
  59. enum_types.append(name)
  60. print("// " + name, end='\n', file=fh)
  61. for child in element:
  62. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  63. print("// " + child.text, end='\n', file=fh)
  64. if child.tag == "{http://opcfoundation.org/BinarySchema/}EnumeratedValue":
  65. valuemap[name + "_" + child.get("Name")] = child.get("Value")
  66. valuemap = OrderedDict(sorted(valuemap.iteritems(), key=lambda (k,v): int(v)))
  67. print("typedef UA_UInt32 " + name + ";", end='\n', file=fh);
  68. print("enum " + name + "_enum { \n" + ",\n\t".join(map(lambda (key, value) : key + " = " + value, valuemap.iteritems())) + "\n};\n", end='\n', file=fh)
  69. return
  70. def createStructured(element):
  71. valuemap = OrderedDict()
  72. name = "UA_" + element.get("Name")
  73. print("// " + name, end='\n', file=fh)
  74. lengthfields = set()
  75. for child in element:
  76. if child.get("LengthField"):
  77. lengthfields.add(child.get("LengthField"))
  78. for child in element:
  79. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  80. print("// " + child.text, end='\n', file=fh)
  81. elif child.tag == "{http://opcfoundation.org/BinarySchema/}Field":
  82. if child.get("Name") in lengthfields:
  83. continue
  84. childname = camlCase2AdaCase(child.get("Name"))
  85. if childname in printed_types:
  86. childname = childname + "_Value" # attributes may not have the name of a type
  87. typename = stripTypename(child.get("TypeName"))
  88. if childname == "Response_Header" or childname == "Request_Header":
  89. continue
  90. if typename in indefinite_types:
  91. valuemap[childname] = typename + "*"
  92. elif child.get("LengthField"):
  93. valuemap[childname] = typename + "**"
  94. else:
  95. valuemap[childname] = typename
  96. # if "Response" in name[len(name)-9:]:
  97. # print("type " + name + " is new Response_Base with "),
  98. # elif "Request" in name[len(name)-9:]:
  99. # print ("type " + name + " is new Request_Base with "),
  100. # else:
  101. # print ("type " + name + " is new UA_Builtin with "),
  102. print("typedef struct T_" + name + " {", end='\n', file=fh)
  103. if len(valuemap) > 0:
  104. for n,t in valuemap.iteritems():
  105. if t.find("**") != -1:
  106. print("\t" + "UInt32 " + n + "_size;", end='\n', file=fh)
  107. print("\t" + "UA_" + t + " " + n + ";", end='\n', file=fh)
  108. else:
  109. print("// null record", end='\n', file=fh)
  110. print("} " + name + ";", end='\n', file=fh)
  111. print("Int32 " + name + "_calcSize(" + name + " const * ptr);", end='\n', file=fh)
  112. print("Int32 " + name + "_encode(" + name + " const * src, Int32* pos, char* dst);", end='\n', file=fh)
  113. print("Int32 " + name + "_decode(char const * src, UInt32* pos, " + name + "* dst);", end='\n', file=fh)
  114. if "Response" in name[len(name)-9:]:
  115. print("Int32 " + name + "_calcSize(" + name + " const * ptr) {\n\treturn UA_ResponseHeader_getSize()", end='', file=fc)
  116. elif "Request" in name[len(name)-9:]:
  117. print("Int32 " + name + "_calcSize(" + name + " const * ptr) {\n\treturn UA_RequestHeader_getSize()", end='', file=fc)
  118. else:
  119. # code
  120. print("Int32 " + name + "_calcSize(" + name + " const * ptr) {\n\treturn 0", end='', file=fc)
  121. # code _calcSize
  122. for n,t in valuemap.iteritems():
  123. if t in elementary_size:
  124. print('\n\t + sizeof(UA_' + t + ") // " + n, end='', file=fc)
  125. else:
  126. if t in enum_types:
  127. print('\n\t + 4 //' + n, end='', file=fc) # enums are all 32 bit
  128. elif t.find("**") != -1:
  129. print("\n\t + 4 //" + n + "_size", end='', file=fc),
  130. print("\n\t + UA_Array_calcSize(ptr->" + n + "_size, UA_" + t[0:t.find("*")].upper() + ", (void**) ptr->" + n +")", end='', file=fc)
  131. elif t.find("*") != -1:
  132. print('\n\t + ' + "UA_" + t[0:t.find("*")] + "_calcSize(ptr->" + n + ')', end='', file=fc)
  133. else:
  134. print('\n\t + ' + "UA_" + t + "_calcSize(&(ptr->" + n + '))', end='', file=fc)
  135. print("\n\t;\n};\n", end='\n', file=fc)
  136. print("Int32 "+name+"_encode("+name+" const * src, Int32* pos, char* dst) {\n\tInt32 retval=0;", end='\n', file=fc)
  137. # code _encode
  138. for n,t in valuemap.iteritems():
  139. if t in elementary_size:
  140. print('\tretval |= UA_'+t+'_encode(&(src->'+n+'),pos,dst);', end='\n', file=fc)
  141. else:
  142. if t in enum_types:
  143. print('\tretval |= UA_'+t+'_encode(&(src->'+n+'));', end='\n', file=fc)
  144. elif t.find("**") != -1:
  145. print('\tretval |= UA_Int32_encode(&(src->'+n+'_size),pos,dst); // encode size', end='\n', file=fc)
  146. print("\tretval |= UA_Array_encode((void**) (src->"+n+"),src->"+n+"_size, UA_" + t[0:t.find("*")].upper()+",pos,dst);", end='\n', file=fc)
  147. elif t.find("*") != -1:
  148. print('\tretval |= UA_' + t[0:t.find("*")] + "_encode(src->" + n + ',pos,dst);', end='\n', file=fc)
  149. else:
  150. print('\tretval |= UA_'+t+"_encode(&(src->"+n+"),pos,dst);", end='\n', file=fc)
  151. print("\treturn retval;\n};\n", end='\n', file=fc)
  152. def createOpaque(element):
  153. name = "UA_" + element.get("Name")
  154. print("// " + name , end='\n', file=fh)
  155. for child in element:
  156. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  157. print("// " + child.text, end='\n', file=fh)
  158. print("typedef void* " + name + ";\n", end='\n', file=fh)
  159. return
  160. ns = {"opc": "http://opcfoundation.org/BinarySchema/"}
  161. tree = etree.parse(sys.argv[1])
  162. types = tree.xpath("/opc:TypeDictionary/*[not(self::opc:Import)]", namespaces=ns)
  163. fh = open(sys.argv[2] + ".h",'w');
  164. fc = open(sys.argv[2] + ".c",'w');
  165. print('#include "' + sys.argv[2] + '.h"', end='\n', file=fc);
  166. # types for which we create a vector type
  167. arraytypes = set()
  168. fields = tree.xpath("//opc:Field", namespaces=ns)
  169. for field in fields:
  170. if field.get("LengthField"):
  171. arraytypes.add(stripTypename(field.get("TypeName")))
  172. deferred_types = OrderedDict()
  173. print('#ifndef OPCUA_H_', end='\n', file=fh)
  174. print('#define OPCUA_H_', end='\n', file=fh)
  175. print('#include "opcua_basictypes.h"', end='\n', file=fh)
  176. print('#include "opcua_namespace_0.h"', end='\n', file=fh);
  177. for element in types:
  178. name = element.get("Name")
  179. if skipType(name):
  180. continue
  181. if element.tag == "{http://opcfoundation.org/BinarySchema/}EnumeratedType":
  182. createEnumerated(element)
  183. printed_types.add(name)
  184. elif element.tag == "{http://opcfoundation.org/BinarySchema/}StructuredType":
  185. if printableStructuredType(element):
  186. createStructured(element)
  187. printed_types.add(name)
  188. else: # the record contains types that were not yet detailed
  189. deferred_types[name] = element
  190. continue
  191. elif element.tag == "{http://opcfoundation.org/BinarySchema/}OpaqueType":
  192. createOpaque(element)
  193. printed_types.add(name)
  194. #if name in arraytypes:
  195. # print "package ListOf" + name + " is new Types.Arrays.UA_Builtin_Arrays(" + name + ");\n"
  196. for name, element in deferred_types.iteritems():
  197. createStructured(element)
  198. # if name in arraytypes:
  199. # print "package ListOf" + name + " is new Types.Arrays.UA_Builtin_Arrays(" + name + ");\n"
  200. print('#endif /* OPCUA_H_ */', end='\n', file=fh)
  201. fh.close()
  202. fc.close()