generate_builtin.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. from __future__ import print_function
  2. import sys
  3. import time
  4. import platform
  5. import getpass
  6. from collections import OrderedDict
  7. import re
  8. from lxml import etree
  9. if len(sys.argv) != 3:
  10. print("Usage: python generate_builtin.py <path/to/Opc.Ua.Types.bsd> <outfile w/o extension>", file=sys.stdout)
  11. exit(0)
  12. # types that are coded manually
  13. exclude_types = set(["Boolean", "SByte", "Byte", "Int16", "UInt16", "Int32", "UInt32",
  14. "Int64", "UInt64", "Float", "Double", "String", "DateTime", "Guid",
  15. "ByteString", "XmlElement", "NodeId", "ExpandedNodeId", "StatusCode",
  16. "QualifiedName", "LocalizedText", "ExtensionObject", "DataValue",
  17. "Variant", "DiagnosticInfo", "IntegerId"])
  18. elementary_size = {"Boolean":1, "SByte":1, "Byte":1, "Int16":2, "UInt16":2, "Int32":4, "UInt32":4,
  19. "Int64":8, "UInt64":8, "Float":4, "Double":8, "DateTime":8, "StatusCode":4}
  20. enum_types = []
  21. structured_types = []
  22. printed_types = exclude_types # types that were already printed and which we can use in the structures to come
  23. # types we do not want to autogenerate
  24. def skipType(name):
  25. if name in exclude_types:
  26. return True
  27. if re.search("NodeId$", name) != None:
  28. return True
  29. return False
  30. def stripTypename(tn):
  31. return tn[tn.find(":")+1:]
  32. def camlCase2CCase(item):
  33. if item in ["Float","Double"]:
  34. return "my" + item
  35. return item[:1].lower() + item[1:] if item else ''
  36. # are the types we need already in place? if not, postpone.
  37. def printableStructuredType(element):
  38. for child in element:
  39. if child.tag == "{http://opcfoundation.org/BinarySchema/}Field":
  40. typename = stripTypename(child.get("TypeName"))
  41. if typename not in printed_types:
  42. return False
  43. return True
  44. # There are three types of types in the bsd file:
  45. # StructuredType, EnumeratedType OpaqueType
  46. def createEnumerated(element):
  47. valuemap = OrderedDict()
  48. name = "UA_" + element.get("Name")
  49. enum_types.append(name)
  50. for child in element:
  51. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  52. print("/** @brief " + child.text + " */", end='\n', file=fh)
  53. if child.tag == "{http://opcfoundation.org/BinarySchema/}EnumeratedValue":
  54. valuemap[name + "_" + child.get("Name")] = child.get("Value")
  55. valuemap = OrderedDict(sorted(valuemap.iteritems(), key=lambda (k,v): int(v)))
  56. print("typedef UA_UInt32 " + name + ";", end='\n', file=fh);
  57. print("enum " + name + "_enum { \n\t" + ",\n\t".join(map(lambda (key, value) : key.upper() + " = " + value, valuemap.iteritems())) + "\n};", end='\n', file=fh)
  58. print("UA_TYPE_METHOD_PROTOTYPES (" + name + ")", end='\n', file=fh)
  59. print("UA_TYPE_METHOD_CALCSIZE_AS("+name+", UA_UInt32)", end='\n', file=fc)
  60. print("UA_TYPE_METHOD_ENCODEBINARY_AS("+name+", UA_UInt32)", end='\n', file=fc)
  61. print("UA_TYPE_METHOD_DECODEBINARY_AS("+name+", UA_UInt32)", end='\n', file=fc)
  62. print("UA_TYPE_METHOD_DELETE_AS("+name+", UA_UInt32)", end='\n', file=fc)
  63. print("UA_TYPE_METHOD_DELETEMEMBERS_AS("+name+", UA_UInt32)", end='\n', file=fc)
  64. print("UA_TYPE_METHOD_INIT_AS("+name+", UA_UInt32)", end='\n', file=fc)
  65. print("UA_TYPE_METHOD_COPY_AS("+name+", UA_UInt32)",'\n', file=fc)
  66. print("UA_TYPE_METHOD_NEW_DEFAULT("+name+")\n", end='\n', file=fc)
  67. return
  68. def createStructured(element):
  69. valuemap = OrderedDict()
  70. name = "UA_" + element.get("Name")
  71. print("\n", file=fh)
  72. lengthfields = set()
  73. for child in element:
  74. if child.get("LengthField"):
  75. lengthfields.add(child.get("LengthField"))
  76. for child in element:
  77. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  78. print("/** @brief " + child.text + " */", end='\n', file=fh)
  79. elif child.tag == "{http://opcfoundation.org/BinarySchema/}Field":
  80. if child.get("Name") in lengthfields:
  81. continue
  82. childname = camlCase2CCase(child.get("Name"))
  83. typename = stripTypename(child.get("TypeName"))
  84. if child.get("LengthField"):
  85. valuemap[childname] = typename + "**"
  86. else:
  87. valuemap[childname] = typename
  88. print("typedef struct " + name + " {", end='\n', file=fh)
  89. if len(valuemap) == 0:
  90. typename = stripTypename(element.get("BaseType"))
  91. childname = camlCase2CCase(typename)
  92. valuemap[childname] = typename
  93. for n,t in valuemap.iteritems():
  94. if t.find("**") != -1:
  95. print("\t" + "UA_Int32 " + n + "Size;", end='\n', file=fh)
  96. print("\t" + "UA_" + t + " " + n + ";", end='\n', file=fh)
  97. print("} " + name + ";", end='\n', file=fh)
  98. print("UA_Int32 " + name + "_calcSize(" + name + " const* ptr);", end='\n', file=fh)
  99. print("UA_Int32 " + name + "_encodeBinary(" + name + " const* src, UA_Int32* pos, UA_ByteString* dst);", end='\n', file=fh)
  100. print("UA_Int32 " + name + "_decodeBinary(UA_ByteString const* src, UA_Int32* pos, " + name + "* dst);", end='\n', file=fh)
  101. print("UA_Int32 " + name + "_delete("+ name + "* p);", end='\n', file=fh)
  102. print("UA_Int32 " + name + "_deleteMembers(" + name + "* p);", end='\n', file=fh)
  103. print("UA_Int32 " + name + "_init("+ name + " * p);", end='\n', file=fh)
  104. print("UA_Int32 " + name + "_new(" + name + " ** p);", end='\n', file=fh)
  105. print("UA_Int32 " + name + "_copy(" + name + "* src, " + name + "* dst);", end='\n', file=fh)
  106. print("UA_Int32 " + name + "_calcSize(" + name + " const * ptr) {", end='', file=fc)
  107. print("\n\tif(ptr==UA_NULL){return sizeof("+ name +");}", end='', file=fc)
  108. print("\n\treturn 0", end='', file=fc)
  109. # code _calcSize
  110. for n,t in valuemap.iteritems():
  111. if t in elementary_size:
  112. print('\n\t + sizeof(UA_' + t + ") // " + n, end='', file=fc)
  113. else:
  114. if t in enum_types:
  115. print('\n\t + 4 //' + n, end='', file=fc) # enums are all 32 bit
  116. elif t.find("**") != -1:
  117. print("\n\t + 0 //" + n + "Size is included in UA_Array_calcSize", end='', file=fc),
  118. print("\n\t + UA_Array_calcSize(ptr->" + n + "Size, UA_" + t[0:t.find("*")].upper() + ", (void const**) ptr->" + n +")", end='', file=fc)
  119. elif t.find("*") != -1:
  120. print('\n\t + ' + "UA_" + t[0:t.find("*")] + "_calcSize(ptr->" + n + ')', end='', file=fc)
  121. else:
  122. print('\n\t + ' + "UA_" + t + "_calcSize(&(ptr->" + n + '))', end='', file=fc)
  123. print("\n\t;\n}\n", end='\n', file=fc)
  124. print("UA_Int32 "+name+"_encodeBinary("+name+" const * src, UA_Int32* pos, UA_ByteString* dst) {\n\tUA_Int32 retval = UA_SUCCESS;", end='\n', file=fc)
  125. # code _encode
  126. for n,t in valuemap.iteritems():
  127. if t in elementary_size:
  128. print('\tretval |= UA_'+t+'_encodeBinary(&(src->'+n+'),pos,dst);', end='\n', file=fc)
  129. else:
  130. if t in enum_types:
  131. print('\tretval |= UA_'+t+'_encodeBinary(&(src->'+n+'),pos,dst);', end='\n', file=fc)
  132. elif t.find("**") != -1:
  133. print('\t//retval |= UA_Int32_encodeBinary(&(src->'+n+'Size),pos,dst); // encode size managed by UA_Array_encodeBinary', end='\n', file=fc)
  134. print("\tretval |= UA_Array_encodeBinary((void const**) (src->"+n+"),src->"+n+"Size, UA_" + t[0:t.find("*")].upper()+",pos,dst);", end='\n', file=fc)
  135. elif t.find("*") != -1:
  136. print('\tretval |= UA_' + t[0:t.find("*")] + "_encodeBinary(src->" + n + ',pos,dst);', end='\n', file=fc)
  137. else:
  138. print('\tretval |= UA_'+t+"_encodeBinary(&(src->"+n+"),pos,dst);", end='\n', file=fc)
  139. print("\treturn retval;\n}\n", end='\n', file=fc)
  140. # code _decode
  141. print("UA_Int32 "+name+"_decodeBinary(UA_ByteString const * src, UA_Int32* pos, " + name + "* dst) {\n\tUA_Int32 retval = UA_SUCCESS;", end='\n', file=fc)
  142. print('\t'+name+'_init(dst);', end='\n', file=fc)
  143. for n,t in valuemap.iteritems():
  144. if t in elementary_size:
  145. print('\tCHECKED_DECODE(UA_'+t+'_decodeBinary(src,pos,&(dst->'+n+')), '+name+'_deleteMembers(dst));', end='\n', file=fc)
  146. else:
  147. if t in enum_types:
  148. print('\tCHECKED_DECODE(UA_'+t+'_decodeBinary(src,pos,&(dst->'+n+')), '+name+'_deleteMembers(dst));', end='\n', file=fc)
  149. elif t.find("**") != -1:
  150. # decode size
  151. print('\tCHECKED_DECODE(UA_Int32_decodeBinary(src,pos,&(dst->'+n+'Size)), ' +
  152. name + '_deleteMembers(dst)); // decode size', end='\n', file=fc)
  153. # allocate memory for array
  154. print("\tCHECKED_DECODE(UA_Array_new((void***)&dst->"+n+", dst->"+n+"Size, UA_"+t[0:t.find("*")].upper()+"), dst->" +
  155. n + " = UA_NULL; "+name+'_deleteMembers(dst));', end='\n', file=fc)
  156. print("\tCHECKED_DECODE(UA_Array_decodeBinary(src,dst->"+n+"Size, UA_" + t[0:t.find("*")].upper() +
  157. ",pos,(void *** const) (&dst->"+n+")), "+name+'_deleteMembers(dst));', end='\n', file=fc)
  158. elif t.find("*") != -1:
  159. #allocate memory using new
  160. print('\tCHECKED_DECODE(UA_'+ t[0:t.find("*")] +"_new(&(dst->" + n + ")), "+name+'_deleteMembers(dst));', end='\n', file=fc)
  161. print('\tCHECKED_DECODE(UA_' + t[0:t.find("*")] + "_decodeBinary(src,pos,dst->"+ n +"), "+name+'_deleteMembers(dst));', end='\n', file=fc)
  162. else:
  163. print('\tCHECKED_DECODE(UA_'+t+"_decodeBinary(src,pos,&(dst->"+n+")), "+name+'_deleteMembers(dst));', end='\n', file=fc)
  164. print("\treturn retval;\n}\n", end='\n', file=fc)
  165. # code _delete and _deleteMembers
  166. print('UA_Int32 '+name+'_delete('+name+'''* p) {
  167. UA_Int32 retval = UA_SUCCESS;
  168. retval |= '''+name+'''_deleteMembers(p);
  169. retval |= UA_free(p);
  170. return retval;
  171. }''', end='\n', file=fc)
  172. print("UA_Int32 "+name+"_deleteMembers(" + name + "* p) {\n\tUA_Int32 retval = UA_SUCCESS;", end='\n', file=fc)
  173. for n,t in valuemap.iteritems():
  174. if t not in elementary_size:
  175. if t.find("**") != -1:
  176. print("\tretval |= UA_Array_delete((void***)&p->"+n+",p->"+n+"Size,UA_"+t[0:t.find("*")].upper()+"); p->"+n+" = UA_NULL;", end='\n', file=fc)
  177. elif t.find("*") != -1:
  178. print('\tretval |= UA_' + t[0:t.find("*")] + "_delete(p->"+n+");", end='\n', file=fc)
  179. else:
  180. print('\tretval |= UA_' + t + "_deleteMembers(&(p->"+n+"));", end='\n', file=fc)
  181. print("\treturn retval;\n}\n", end='\n', file=fc)
  182. # code _init
  183. print("UA_Int32 "+name+"_init(" + name + " * p) {\n\tUA_Int32 retval = UA_SUCCESS;", end='\n', file=fc)
  184. for n,t in valuemap.iteritems():
  185. if t in elementary_size:
  186. print('\tretval |= UA_'+t+'_init(&(p->'+n+'));', end='\n', file=fc)
  187. else:
  188. if t in enum_types:
  189. print('\tretval |= UA_'+t+'_init(&(p->'+n+'));', end='\n', file=fc)
  190. elif t.find("**") != -1:
  191. print('\tp->'+n+'Size=0;', end='\n', file=fc)
  192. print("\tp->"+n+"=UA_NULL;", end='\n', file=fc)
  193. elif t.find("*") != -1:
  194. print("\tp->"+n+"=UA_NULL;", end='\n', file=fc)
  195. else:
  196. print('\tretval |= UA_'+t+"_init(&(p->"+n+"));", end='\n', file=fc)
  197. print("\treturn retval;\n}\n", end='\n', file=fc)
  198. # code _new
  199. print("UA_TYPE_METHOD_NEW_DEFAULT(" + name + ")", end='\n', file=fc)
  200. # code _copy
  201. print("UA_Int32 "+name+"_copy(" + name + " * src," + name + " * dst) {\n\tUA_Int32 retval = UA_SUCCESS;", end='\n', file=fc)
  202. for n,t in valuemap.iteritems():
  203. if t in elementary_size:
  204. print('\tretval |= UA_'+t+'_copy(&(src->'+n+'),&(dst->'+n+'));', end='\n', file=fc)
  205. else:
  206. if t in enum_types:
  207. print('\tretval |= UA_'+t+'_copy(&(src->'+n+'),&(dst->'+n+'));', end='\n', file=fc)
  208. elif t.find("**") != -1:
  209. print('\tretval |= UA_Int32_copy(&(src->'+n+'Size),&(dst->'+n+'Size)); // size of following array', end='\n', file=fc)
  210. print("\tretval |= UA_Array_copy((void const* const*) (src->"+n+"), src->"+n+"Size," + "UA_" +
  211. t[0:t.find("*")].upper()+",(void***)&(dst->"+n+"));", end='\n', file=fc)
  212. elif t.find("*") != -1:
  213. print('\tretval |= UA_' + t[0:t.find("*")] + '_copy(src->' + n + ',dst->' + n + ');', end='\n', file=fc)
  214. else:
  215. print('\tretval |= UA_'+t+"_copy(&(src->"+n+"),&(dst->" + n + '));', end='\n', file=fc)
  216. print("\treturn retval;\n}\n", end='\n', file=fc)
  217. def createOpaque(element):
  218. name = "UA_" + element.get("Name")
  219. print("\n", file=fh)
  220. for child in element:
  221. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  222. print("/** @brief " + child.text + " */", end='\n', file=fh)
  223. print("typedef UA_ByteString " + name + ";", end='\n', file=fh)
  224. print("UA_TYPE_METHOD_PROTOTYPES (" + name + ")", end='\n', file=fh)
  225. print("UA_TYPE_METHOD_CALCSIZE_AS("+name+", UA_ByteString)", end='\n', file=fc)
  226. print("UA_TYPE_METHOD_ENCODEBINARY_AS("+name+", UA_ByteString)", end='\n', file=fc)
  227. print("UA_TYPE_METHOD_DECODEBINARY_AS("+name+", UA_ByteString)", end='\n', file=fc)
  228. print("UA_TYPE_METHOD_DELETE_AS("+name+", UA_ByteString)", end='\n', file=fc)
  229. print("UA_TYPE_METHOD_DELETEMEMBERS_AS("+name+", UA_ByteString)", end='\n', file=fc)
  230. print("UA_TYPE_METHOD_INIT_AS("+name+", UA_ByteString)", end='\n', file=fc)
  231. print("UA_TYPE_METHOD_COPY_AS("+name+", UA_ByteString)", end='\n', file=fc)
  232. print("UA_TYPE_METHOD_NEW_DEFAULT("+name+")\n", end='\n', file=fc)
  233. return
  234. ns = {"opc": "http://opcfoundation.org/BinarySchema/"}
  235. tree = etree.parse(sys.argv[1])
  236. types = tree.xpath("/opc:TypeDictionary/*[not(self::opc:Import)]", namespaces=ns)
  237. fh = open(sys.argv[2] + ".hgen",'w');
  238. fc = open(sys.argv[2] + ".cgen",'w');
  239. print('''/**
  240. * @file '''+sys.argv[2]+'''.h
  241. *
  242. * @brief Autogenerated data types defined in the UA standard
  243. *
  244. * Generated from '''+sys.argv[1]+''' with script '''+sys.argv[0]+'''
  245. * on host '''+platform.uname()[1]+''' by user '''+getpass.getuser()+''' at '''+ time.strftime("%Y-%m-%d %I:%M:%S")+'''
  246. */
  247. #ifndef OPCUA_H_
  248. #define OPCUA_H_
  249. #include "ua_basictypes.h"
  250. #include "ua_namespace_0.h"''', end='\n', file=fh);
  251. print('''/**
  252. * @file '''+sys.argv[2]+'''.c
  253. *
  254. * @brief Autogenerated function implementations to manage the data types defined in the UA standard
  255. *
  256. * Generated from '''+sys.argv[1]+''' with script '''+sys.argv[0]+'''
  257. * on host '''+platform.uname()[1]+''' by user '''+getpass.getuser()+''' at '''+ time.strftime("%Y-%m-%d %I:%M:%S")+'''
  258. */
  259. #include "''' + sys.argv[2] + '.h"', end='\n', file=fc);
  260. # types for which we create a vector type
  261. arraytypes = set()
  262. fields = tree.xpath("//opc:Field", namespaces=ns)
  263. for field in fields:
  264. if field.get("LengthField"):
  265. arraytypes.add(stripTypename(field.get("TypeName")))
  266. deferred_types = OrderedDict()
  267. #plugin handling
  268. import os
  269. files = [f for f in os.listdir('.') if os.path.isfile(f) and f[-3:] == ".py" and f[:7] == "plugin_"]
  270. plugin_types = []
  271. packageForType = OrderedDict()
  272. for f in files:
  273. package = f[:-3]
  274. exec "import " + package
  275. exec "pluginSetup = " + package + ".setup()"
  276. if pluginSetup["pluginType"] == "structuredObject":
  277. plugin_types.append(pluginSetup["tagName"])
  278. packageForType[pluginSetup["tagName"]] = [package,pluginSetup]
  279. print("Custom object creation for tag " + pluginSetup["tagName"] + " imported from package " + package)
  280. #end plugin handling
  281. for element in types:
  282. name = element.get("Name")
  283. if skipType(name):
  284. continue
  285. if element.tag == "{http://opcfoundation.org/BinarySchema/}EnumeratedType":
  286. createEnumerated(element)
  287. printed_types.add(name)
  288. elif element.tag == "{http://opcfoundation.org/BinarySchema/}StructuredType":
  289. if printableStructuredType(element):
  290. createStructured(element)
  291. structured_types.append(name)
  292. printed_types.add(name)
  293. else: # the record contains types that were not yet detailed
  294. deferred_types[name] = element
  295. continue
  296. elif element.tag == "{http://opcfoundation.org/BinarySchema/}OpaqueType":
  297. createOpaque(element)
  298. printed_types.add(name)
  299. for name, element in deferred_types.iteritems():
  300. if name in plugin_types:
  301. #execute plugin if registered
  302. exec "ret = " + packageForType[name][0]+"."+packageForType[name][1]["functionCall"]
  303. if ret == "default":
  304. createStructured(element)
  305. else:
  306. createStructured(element)
  307. print('#endif /* OPCUA_H_ */', end='\n', file=fh)
  308. fh.close()
  309. fc.close()