generate_builtin.py 17 KB

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