generate_builtin.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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)", end='\n', file=fc)
  80. print("UA_TYPE_METHOD_INIT_AS("+name+", UA_UInt32)", end='\n', file=fc)
  81. print("UA_TYPE_METHOD_NEW_DEFAULT("+name+")\n", end='\n', file=fc)
  82. return
  83. def createStructured(element):
  84. valuemap = OrderedDict()
  85. name = "UA_" + element.get("Name")
  86. print("\n/*** " + name + " ***/", end='\n', file=fh)
  87. lengthfields = set()
  88. for child in element:
  89. if child.get("LengthField"):
  90. lengthfields.add(child.get("LengthField"))
  91. for child in element:
  92. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  93. print("/* " + child.text + " */", end='\n', file=fh)
  94. elif child.tag == "{http://opcfoundation.org/BinarySchema/}Field":
  95. if child.get("Name") in lengthfields:
  96. continue
  97. childname = camlCase2CCase(child.get("Name"))
  98. #if childname in printed_types:
  99. # childname = childname + "_Value" # attributes may not have the name of a type
  100. typename = stripTypename(child.get("TypeName"))
  101. if typename in structured_types:
  102. valuemap[childname] = typename + "*"
  103. elif typename in indefinite_types:
  104. valuemap[childname] = typename + "*"
  105. elif child.get("LengthField"):
  106. valuemap[childname] = typename + "**"
  107. else:
  108. valuemap[childname] = typename
  109. # if "Response" in name[len(name)-9:]:
  110. # print("type " + name + " is new Response_Base with "),
  111. # elif "Request" in name[len(name)-9:]:
  112. # print ("type " + name + " is new Request_Base with "),
  113. # else:
  114. # print ("type " + name + " is new UA_Builtin with "),
  115. print("typedef struct T_" + name + " {", end='\n', file=fh)
  116. if len(valuemap) > 0:
  117. for n,t in valuemap.iteritems():
  118. if t.find("**") != -1:
  119. print("\t" + "UA_Int32 " + n + "Size;", end='\n', file=fh)
  120. print("\t" + "UA_" + t + " " + n + ";", end='\n', file=fh)
  121. else:
  122. print("\t/* null record */", end='\n', file=fh)
  123. print("\tUA_Int32 NullRecord; /* avoiding warnings */", end='\n', file=fh)
  124. print("} " + name + ";", end='\n', file=fh)
  125. print("UA_Int32 " + name + "_calcSize(" + name + " const * ptr);", end='\n', file=fh)
  126. print("UA_Int32 " + name + "_encode(" + name + " const * src, UA_Int32* pos, UA_Byte* dst);", end='\n', file=fh)
  127. print("UA_Int32 " + name + "_decode(UA_Byte const * src, UA_Int32* pos, " + name + "* dst);", end='\n', file=fh)
  128. print("UA_Int32 " + name + "_delete("+ name + "* p);", end='\n', file=fh)
  129. print("UA_Int32 " + name + "_deleteMembers(" + name + "* p);", end='\n', file=fh)
  130. print("UA_Int32 " + name + "_init("+ name + " * p);", end='\n', file=fh)
  131. print("UA_Int32 " + name + "_new(" + name + " ** p);", end='\n', file=fh)
  132. print("UA_Int32 " + name + "_calcSize(" + name + " const * ptr) {", end='', file=fc)
  133. print("\n\tif(ptr==UA_NULL){return sizeof("+ name +");}", end='', file=fc)
  134. print("\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 + 0 //" + n + "Size is included in UA_Array_calcSize", 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("UA_Int32 "+name+"_encode("+name+" const * src, UA_Int32* pos, UA_Byte* dst) {\n\tUA_Int32 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('\t//retval |= UA_Int32_encode(&(src->'+n+'Size),pos,dst); // encode size managed by UA_Array_encode', 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. # code _decode
  167. print("UA_Int32 "+name+"_decode(UA_Byte const * src, UA_Int32* pos, " + name + "* dst) {\n\tUA_Int32 retval = UA_SUCCESS;", end='\n', file=fc)
  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. #allocate memory for array
  177. print('\tretval |= UA_alloc((void**)&(dst->' + n + "),dst->" + n + "Size*sizeof(void*));", 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. #allocate memory using new
  181. print('\tretval |= UA_'+ t[0:t.find("*")] +"_new(&(dst->" + n + "));", end='\n', file=fc)
  182. print('\tretval |= UA_' + t[0:t.find("*")] + "_decode(src,pos,dst->"+ n +");", end='\n', file=fc)
  183. else:
  184. print('\tretval |= UA_'+t+"_decode(src,pos,&(dst->"+n+"));", end='\n', file=fc)
  185. print("\treturn retval;\n}\n", end='\n', file=fc)
  186. # code _delete and _deleteMembers
  187. print('UA_Int32 '+name+'_delete('+name+'''* p) {
  188. UA_Int32 retval = UA_SUCCESS;
  189. retval |= '''+name+'''_deleteMembers(p);
  190. retval |= UA_free(p);
  191. return retval;
  192. }''', end='\n', file=fc)
  193. print("UA_Int32 "+name+"_deleteMembers(" + name + "* p) {\n\tUA_Int32 retval = UA_SUCCESS;", end='\n', file=fc)
  194. for n,t in valuemap.iteritems():
  195. if t not in elementary_size:
  196. if t.find("**") != -1:
  197. print("\tretval |= UA_Array_delete((void**)p->"+n+",p->"+n+"Size);", end='\n', file=fc) #not tested
  198. elif t.find("*") != -1:
  199. print('\tretval |= UA_' + t[0:t.find("*")] + "_delete(p->"+n+");", end='\n', file=fc)
  200. else:
  201. print('\tretval |= UA_' + t + "_deleteMembers(&(p->"+n+"));", end='\n', file=fc)
  202. print("\treturn retval;\n}\n", end='\n', file=fc)
  203. # code _init
  204. print("UA_Int32 "+name+"_init(" + name + " * p) {\n\tUA_Int32 retval = UA_SUCCESS;", end='\n', file=fc)
  205. for n,t in valuemap.iteritems():
  206. if t in elementary_size:
  207. print('\tretval |= UA_'+t+'_init(&(p->'+n+'));', end='\n', file=fc)
  208. else:
  209. if t in enum_types:
  210. print('\tretval |= UA_'+t+'_init(&(p->'+n+'));', end='\n', file=fc)
  211. elif t.find("**") != -1:
  212. print('\tp->'+n+'Size=0;', end='\n', file=fc)
  213. print("\tp->"+n+"=UA_NULL;", end='\n', file=fc)
  214. elif t.find("*") != -1:
  215. print("\tp->"+n+"=UA_NULL;", end='\n', file=fc)
  216. else:
  217. print('\tretval |= UA_'+t+"_init(&(p->"+n+"));", end='\n', file=fc)
  218. print("\treturn retval;\n}\n", end='\n', file=fc)
  219. # code _new
  220. print("UA_TYPE_METHOD_NEW_DEFAULT(" + name + ")", end='\n', file=fc)
  221. def createOpaque(element):
  222. name = "UA_" + element.get("Name")
  223. print("\n/*** " + name + " ***/", end='\n', file=fh)
  224. for child in element:
  225. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  226. print("/* " + child.text + " */", end='\n', file=fh)
  227. print("typedef UA_ByteString " + name + ";", end='\n', file=fh)
  228. print("UA_TYPE_METHOD_PROTOTYPES (" + name + ")", end='\n', file=fh)
  229. print("UA_TYPE_METHOD_CALCSIZE_AS("+name+", UA_ByteString)", end='\n', file=fc)
  230. print("UA_TYPE_METHOD_ENCODE_AS("+name+", UA_ByteString)", end='\n', file=fc)
  231. print("UA_TYPE_METHOD_DECODE_AS("+name+", UA_ByteString)", end='\n', file=fc)
  232. print("UA_TYPE_METHOD_DELETE_AS("+name+", UA_ByteString)", end='\n', file=fc)
  233. print("UA_TYPE_METHOD_DELETEMEMBERS_AS("+name+", UA_ByteString)", end='\n', file=fc)
  234. print("UA_TYPE_METHOD_INIT_AS("+name+", UA_ByteString)", end='\n', file=fc)
  235. print("UA_TYPE_METHOD_NEW_DEFAULT("+name+")\n", end='\n', file=fc)
  236. return
  237. ns = {"opc": "http://opcfoundation.org/BinarySchema/"}
  238. tree = etree.parse(sys.argv[1])
  239. types = tree.xpath("/opc:TypeDictionary/*[not(self::opc:Import)]", namespaces=ns)
  240. fh = open(sys.argv[2] + ".h",'w');
  241. fc = open(sys.argv[2] + ".c",'w');
  242. print('#include "' + sys.argv[2] + '.h"', end='\n', file=fc);
  243. # types for which we create a vector type
  244. arraytypes = set()
  245. fields = tree.xpath("//opc:Field", namespaces=ns)
  246. for field in fields:
  247. if field.get("LengthField"):
  248. arraytypes.add(stripTypename(field.get("TypeName")))
  249. deferred_types = OrderedDict()
  250. print('#ifndef OPCUA_H_', end='\n', file=fh)
  251. print('#define OPCUA_H_', end='\n', file=fh)
  252. print('#include "opcua_basictypes.h"', end='\n', file=fh)
  253. print('#include "opcua_namespace_0.h"', end='\n', file=fh);
  254. #plugin handling
  255. import os
  256. files = [f for f in os.listdir('.') if os.path.isfile(f) and f[-3:] == ".py" and f[:7] == "plugin_"]
  257. plugin_types = []
  258. packageForType = OrderedDict()
  259. for f in files:
  260. package = f[:-3]
  261. exec "import " + package
  262. exec "pluginSetup = " + package + ".setup()"
  263. if pluginSetup["pluginType"] == "structuredObject":
  264. plugin_types.append(pluginSetup["tagName"])
  265. packageForType[pluginSetup["tagName"]] = [package,pluginSetup]
  266. print("Custom object creation for tag " + pluginSetup["tagName"] + " imported from package " + package)
  267. #end plugin handling
  268. for element in types:
  269. name = element.get("Name")
  270. if skipType(name):
  271. continue
  272. if element.tag == "{http://opcfoundation.org/BinarySchema/}EnumeratedType":
  273. createEnumerated(element)
  274. printed_types.add(name)
  275. elif element.tag == "{http://opcfoundation.org/BinarySchema/}StructuredType":
  276. if printableStructuredType(element):
  277. createStructured(element)
  278. structured_types.append(name)
  279. printed_types.add(name)
  280. else: # the record contains types that were not yet detailed
  281. deferred_types[name] = element
  282. continue
  283. elif element.tag == "{http://opcfoundation.org/BinarySchema/}OpaqueType":
  284. createOpaque(element)
  285. printed_types.add(name)
  286. #if name in arraytypes:
  287. # print "package ListOf" + name + " is new Types.Arrays.UA_Builtin_Arrays(" + name + ");\n"
  288. for name, element in deferred_types.iteritems():
  289. if name in plugin_types:
  290. #execute plugin if registered
  291. exec "ret = " + packageForType[name][0]+"."+packageForType[name][1]["functionCall"]
  292. if ret == "default":
  293. createStructured(element)
  294. else:
  295. createStructured(element)
  296. # if name in arraytypes:
  297. # print "package ListOf" + name + " is new Types.Arrays.UA_Builtin_Arrays(" + name + ");\n"
  298. print('#endif /* OPCUA_H_ */', end='\n', file=fh)
  299. fh.close()
  300. fc.close()