generate_builtin.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. import inspect
  10. import argparse
  11. parser = argparse.ArgumentParser()
  12. parser.add_argument('--export-prototypes', action='store_true', help='make the prototypes (init, delete, copy, ..) of generated types visible for users of the library')
  13. parser.add_argument('--with-xml', action='store_true', help='generate xml encoding')
  14. parser.add_argument('--with-json', action='store_true', help='generate json encoding')
  15. parser.add_argument('--only-nano', action='store_true', help='generate only the types for the nano profile')
  16. parser.add_argument('--only-needed', action='store_true', help='generate only types needed for compile')
  17. parser.add_argument('--additional-includes', action='store', help='include additional header files (separated by comma)')
  18. parser.add_argument('types', help='path/to/Opc.Ua.Types.bsd')
  19. parser.add_argument('outfile', help='outfile w/o extension')
  20. args = parser.parse_args()
  21. ns = {"opc": "http://opcfoundation.org/BinarySchema/"}
  22. tree = etree.parse(args.types)
  23. types = tree.xpath("/opc:TypeDictionary/*[not(self::opc:Import)]", namespaces=ns)
  24. fh = open(args.outfile + ".h",'w')
  25. fc = open(args.outfile + ".c",'w')
  26. # dirty hack. we go up the call frames to access local variables of the calling
  27. # function. this allows to shorten code and get %()s replaces with less clutter.
  28. def printh(string):
  29. print(string % inspect.currentframe().f_back.f_locals, end='\n', file=fh)
  30. def printc(string):
  31. print(string % inspect.currentframe().f_back.f_locals, end='\n', file=fc)
  32. # types that are coded manually
  33. from type_lists import existing_types
  34. # whitelist for "only needed" profile
  35. from type_lists import only_needed_types
  36. # some types are omitted (pretend they exist already)
  37. existing_types.add("NodeIdType")
  38. fixed_size = set(["UA_Boolean", "UA_SByte", "UA_Byte", "UA_Int16", "UA_UInt16",
  39. "UA_Int32", "UA_UInt32", "UA_Int64", "UA_UInt64", "UA_Float",
  40. "UA_Double", "UA_DateTime", "UA_Guid", "UA_StatusCode"])
  41. # types we do not want to autogenerate
  42. def skipType(name):
  43. if name in existing_types:
  44. return True
  45. if "Test" in name: #skip all Test types
  46. return True
  47. if re.search("NodeId$", name) != None:
  48. return True
  49. if args.only_needed and not(name in only_needed_types):
  50. return True
  51. return False
  52. def stripTypename(tn):
  53. return tn[tn.find(":")+1:]
  54. def camlCase2CCase(item):
  55. if item in ["Float","Double"]:
  56. return "my" + item
  57. return item[:1].lower() + item[1:] if item else ''
  58. # are the types we need already in place? if not, postpone.
  59. def printableStructuredType(element):
  60. for child in element:
  61. if child.tag == "{http://opcfoundation.org/BinarySchema/}Field":
  62. typename = stripTypename(child.get("TypeName"))
  63. if typename not in existing_types:
  64. return False
  65. return True
  66. def createEnumerated(element):
  67. valuemap = OrderedDict()
  68. name = "UA_" + element.get("Name")
  69. fixed_size.add(name)
  70. printh("") # newline
  71. for child in element:
  72. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  73. printh("/** @brief " + child.text + " */")
  74. if child.tag == "{http://opcfoundation.org/BinarySchema/}EnumeratedValue":
  75. valuemap[name + "_" + child.get("Name")] = child.get("Value")
  76. valuemap = OrderedDict(sorted(valuemap.iteritems(), key=lambda (k,v): int(v)))
  77. # printh("typedef UA_Int32 " + name + ";")
  78. printh("typedef enum " + name + " { \n\t" +
  79. ",\n\t".join(map(lambda (key, value) : key.upper() + " = " + value, valuemap.iteritems())) +
  80. "\n} " + name + ";")
  81. if args.export_prototypes:
  82. printh("UA_TYPE_PROTOTYPES(" + name + ")")
  83. else:
  84. printh("UA_TYPE_PROTOTYPES_NOEXPORT(" + name + ")")
  85. printh("UA_TYPE_BINARY_ENCODING(" + name + ")")
  86. printc("UA_TYPE_AS(" + name + ", UA_Int32)")
  87. printc("UA_TYPE_BINARY_ENCODING_AS(" + name + ", UA_Int32)")
  88. if args.with_xml:
  89. printh("UA_TYPE_XML_ENCODING(" + name + ")\n")
  90. printc('''UA_TYPE_METHOD_CALCSIZEXML_NOTIMPL(%(name)s)
  91. UA_TYPE_METHOD_ENCODEXML_NOTIMPL(%(name)s)
  92. UA_TYPE_METHOD_DECODEXML_NOTIMPL(%(name)s\n)''')
  93. def createOpaque(element):
  94. name = "UA_" + element.get("Name")
  95. printh("") # newline
  96. for child in element:
  97. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  98. printh("/** @brief " + child.text + " */")
  99. printh("typedef UA_ByteString %(name)s;")
  100. printh("UA_TYPE_PROTOTYPES(%(name)s)")
  101. printh("UA_TYPE_BINARY_ENCODING(%(name)s)")
  102. printc("UA_TYPE_AS(%(name)s, UA_ByteString)")
  103. printc("UA_TYPE_BINARY_ENCODING_AS(%(name)s, UA_ByteString)")
  104. if args.with_xml:
  105. printh("UA_TYPE_XML_ENCODING(" + name + ")\n")
  106. printc('''UA_TYPE_METHOD_CALCSIZEXML_NOTIMPL(%(name)s)
  107. UA_TYPE_METHOD_ENCODEXML_NOTIMPL(%(name)s)
  108. UA_TYPE_METHOD_DECODEXML_NOTIMPL(%(name)s)\n''')
  109. def createStructured(element):
  110. name = "UA_" + element.get("Name")
  111. # 1) Are there arrays in the type?
  112. lengthfields = set()
  113. for child in element:
  114. if child.get("LengthField"):
  115. lengthfields.add(child.get("LengthField"))
  116. # 2) Store members in membermap (name->type).
  117. membermap = OrderedDict()
  118. printh("") # newline
  119. for child in element:
  120. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  121. printh("/** @brief " + child.text + " */")
  122. elif child.tag == "{http://opcfoundation.org/BinarySchema/}Field":
  123. if child.get("Name") in lengthfields:
  124. continue
  125. childname = camlCase2CCase(child.get("Name"))
  126. typename = stripTypename(child.get("TypeName"))
  127. if child.get("LengthField"):
  128. membermap[childname] = "UA_" + typename + "*"
  129. else:
  130. membermap[childname] = "UA_" + typename
  131. # fixed size?
  132. has_fixed_size = True
  133. for n,t in membermap.iteritems():
  134. if t not in fixed_size:
  135. has_fixed_size = False
  136. if has_fixed_size:
  137. fixed_size.add(name)
  138. # 3) Print structure
  139. if len(membermap) > 0:
  140. if has_fixed_size:
  141. printh("#pragma pack (push)\n#pragma pack(1)")
  142. printh("typedef struct %(name)s {")
  143. for n,t in membermap.iteritems():
  144. if t.find("*") != -1:
  145. printh("\t" + "UA_Int32 " + n + "Size;")
  146. printh("\t%(t)s %(n)s;")
  147. printh("} %(name)s;")
  148. if has_fixed_size:
  149. printh("#pragma pack (pop)")
  150. else:
  151. printh("typedef void* %(name)s;")
  152. # 3) function prototypes
  153. printh("UA_TYPE_PROTOTYPES(" + name + ")")
  154. printh("UA_TYPE_BINARY_ENCODING(" + name + ")")
  155. if args.with_xml:
  156. printh("UA_TYPE_XML_ENCODING(" + name + ")\n")
  157. # 4) CalcSizeBinary
  158. printc('''UA_UInt32 %(name)s_calcSizeBinary(%(name)s const * ptr) {
  159. return 0''')
  160. for n,t in membermap.iteritems():
  161. if t in fixed_size:
  162. printc('\t + sizeof(%(t)s) // %(n)s')
  163. elif t.find("*") != -1:
  164. printc('\t + UA_Array_calcSizeBinary(ptr->%(n)sSize,&UA_TYPES['+ t[0:t.find("*")].upper() +
  165. "],ptr->%(n)s)")
  166. else:
  167. printc('\t + %(t)s_calcSizeBinary(&ptr->%(n)s)')
  168. printc("\t;\n}\n")
  169. # 5) EncodeBinary
  170. printc('''UA_StatusCode %(name)s_encodeBinary(%(name)s const * src, UA_ByteString* dst, UA_UInt32 *offset) {
  171. UA_StatusCode retval = UA_STATUSCODE_GOOD;''')
  172. for n,t in membermap.iteritems():
  173. if t.find("*") != -1:
  174. printc("\tretval |= UA_Array_encodeBinary(src->%(n)s,src->%(n)sSize,&UA_TYPES[" + t[0:t.find("*")].upper() + "],dst,offset);")
  175. else:
  176. printc('\tretval |= %(t)s_encodeBinary(&src->%(n)s,dst,offset);')
  177. printc("\treturn retval;\n}\n")
  178. # 6) DecodeBinary
  179. printc('''UA_StatusCode %(name)s_decodeBinary(UA_ByteString const * src, UA_UInt32 *offset, %(name)s * dst) {
  180. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  181. %(name)s_init(dst);''')
  182. printc('\t'+name+'_init(dst);')
  183. for n,t in membermap.iteritems():
  184. if t.find("*") != -1:
  185. printc('\tretval |= UA_Int32_decodeBinary(src,offset,&dst->%(n)sSize);')
  186. printc('\tif(!retval) { retval |= UA_Array_decodeBinary(src,offset,dst->%(n)sSize,&UA_TYPES[' + t[0:t.find("*")].upper() + '],(void**)&dst->%(n)s); }')
  187. printc('\tif(retval) { dst->%(n)sSize = -1; }') # arrays clean up internally. But the size needs to be set here for the eventual deleteMembers.
  188. else:
  189. printc('\tretval |= %(t)s_decodeBinary(src,offset,&dst->%(n)s);')
  190. printc("\tif(retval) %(name)s_deleteMembers(dst);")
  191. printc("\treturn retval;\n}\n")
  192. # 7) Xml
  193. if args.with_xml:
  194. printc('''UA_TYPE_METHOD_CALCSIZEXML_NOTIMPL(%(name)s)
  195. UA_TYPE_METHOD_ENCODEXML_NOTIMPL(%(name)s)
  196. UA_TYPE_METHOD_DECODEXML_NOTIMPL(%(name)s)''')
  197. # 8) Delete
  198. printc('''void %(name)s_delete(%(name)s *p) {
  199. %(name)s_deleteMembers(p);
  200. UA_free(p);\n}\n''')
  201. # 9) DeleteMembers
  202. printc('''void %(name)s_deleteMembers(%(name)s *p) {''')
  203. for n,t in membermap.iteritems():
  204. if not t in fixed_size: # dynamic size on the wire
  205. if t.find("*") != -1:
  206. printc("\tUA_Array_delete((void*)p->%(n)s,p->%(n)sSize,&UA_TYPES["+t[0:t.find("*")].upper()+"]);")
  207. else:
  208. printc('\t%(t)s_deleteMembers(&p->%(n)s);')
  209. printc("}\n")
  210. # 10) Init
  211. printc('''void %(name)s_init(%(name)s *p) {
  212. if(!p) return;''')
  213. for n,t in membermap.iteritems():
  214. if t.find("*") != -1:
  215. printc('\tp->%(n)sSize = -1;')
  216. printc('\tp->%(n)s = UA_NULL;')
  217. else:
  218. printc('\t%(t)s_init(&p->%(n)s);')
  219. printc("}\n")
  220. # 11) New
  221. printc("UA_TYPE_NEW_DEFAULT(%(name)s)")
  222. # 12) Copy
  223. printc('''UA_StatusCode %(name)s_copy(const %(name)s *src,%(name)s *dst) {
  224. UA_StatusCode retval = UA_STATUSCODE_GOOD;''')
  225. printc("\t%(name)s_init(dst);")
  226. for n,t in membermap.iteritems():
  227. if t.find("*") != -1:
  228. printc('\tdst->%(n)sSize = src->%(n)sSize;')
  229. printc("\tretval |= UA_Array_copy(src->%(n)s, src->%(n)sSize,&UA_TYPES[" + t[0:t.find("*")].upper() + "],(void**)&dst->%(n)s);")
  230. continue
  231. if not t in fixed_size: # there are members of variable size
  232. printc('\tretval |= %(t)s_copy(&src->%(n)s,&dst->%(n)s);')
  233. continue
  234. printc("\tdst->%(n)s = src->%(n)s;")
  235. printc('''\tif(retval)
  236. \t%(name)s_deleteMembers(dst);''')
  237. printc("\treturn retval;\n}\n")
  238. # 13) Print
  239. printc('''#ifdef DEBUG''')
  240. printc('''void %(name)s_print(const %(name)s *p, FILE *stream) {
  241. fprintf(stream, "(%(name)s){");''')
  242. for i,(n,t) in enumerate(membermap.iteritems()):
  243. if t.find("*") != -1:
  244. printc('\tUA_Int32_print(&p->%(n)sSize, stream);')
  245. printc("\tUA_Array_print(p->%(n)s, p->%(n)sSize, &UA_TYPES[" + t[0:t.find("*")].upper()+"], stream);")
  246. else:
  247. printc('\t%(t)s_print(&p->%(n)s,stream);')
  248. if i == len(membermap)-1:
  249. continue
  250. printc('\tfprintf(stream, ",");')
  251. printc('''\tfprintf(stream, "}");\n}''')
  252. printc('#endif');
  253. printc('''\n''')
  254. shortname = args.outfile.split("/")[-1]
  255. print(shortname)
  256. printh('''/**
  257. * @file %(shortname)s.h
  258. *
  259. * @brief Autogenerated data types defined in the UA standard
  260. *
  261. * Generated from '''+sys.argv[1]+''' with script '''+sys.argv[0]+'''
  262. * on host '''+platform.uname()[1]+''' by user '''+getpass.getuser()+''' at '''+ time.strftime("%Y-%m-%d %I:%M:%S")+'''
  263. */
  264. #ifndef ''' + shortname.upper() + '''_H_
  265. #define ''' + shortname.upper() + '''_H_
  266. #include "ua_types.h"
  267. #include "ua_types_encoding_binary.h"
  268. /** @ingroup ''' + shortname.split("_")[1] + '''
  269. *
  270. * @defgroup ''' + shortname + ''' Generated Types
  271. *
  272. * @brief Data structures that are autogenerated from an XML-Schema.
  273. * @{
  274. */''')
  275. if args.with_xml:
  276. printh('#include "ua_types_encoding_xml.h"')
  277. if args.additional_includes:
  278. for incl in args.additional_includes.split(","):
  279. printh("#include \"" + incl + "\"")
  280. printc('''/**
  281. * @file '''+sys.argv[2]+'''.c
  282. *
  283. * @brief Autogenerated function implementations to manage the data types defined in the UA standard
  284. *
  285. * Generated from '''+sys.argv[1]+''' with script '''+sys.argv[0]+'''
  286. * on host '''+platform.uname()[1]+''' by user '''+getpass.getuser()+''' at '''+ time.strftime("%Y-%m-%d %I:%M:%S")+'''
  287. */
  288. #include "''' + args.outfile.split("/")[-1] + '''.h"
  289. #include "ua_types_internal.h"
  290. #include "ua_namespace_0.h"
  291. #include "ua_util.h"\n''')
  292. # types for which we create a vector type
  293. arraytypes = set()
  294. fields = tree.xpath("//opc:Field", namespaces=ns)
  295. for field in fields:
  296. if field.get("LengthField"):
  297. arraytypes.add(stripTypename(field.get("TypeName")))
  298. deferred_types = OrderedDict()
  299. #plugin handling
  300. import os
  301. files = [f for f in os.listdir('.') if os.path.isfile(f) and f[-3:] == ".py" and f[:7] == "plugin_"]
  302. plugin_types = []
  303. packageForType = OrderedDict()
  304. for f in files:
  305. package = f[:-3]
  306. exec "import " + package
  307. exec "pluginSetup = " + package + ".setup()"
  308. if pluginSetup["pluginType"] == "structuredObject":
  309. plugin_types.append(pluginSetup["tagName"])
  310. packageForType[pluginSetup["tagName"]] = [package,pluginSetup]
  311. print("Custom object creation for tag " + pluginSetup["tagName"] + " imported from package " + package)
  312. #end plugin handling
  313. for element in types:
  314. name = element.get("Name")
  315. if skipType(name):
  316. continue
  317. if element.tag == "{http://opcfoundation.org/BinarySchema/}EnumeratedType":
  318. createEnumerated(element)
  319. existing_types.add(name)
  320. elif element.tag == "{http://opcfoundation.org/BinarySchema/}StructuredType":
  321. if printableStructuredType(element):
  322. createStructured(element)
  323. existing_types.add(name)
  324. else: # the record contains types that were not yet detailed
  325. deferred_types[name] = element
  326. continue
  327. elif element.tag == "{http://opcfoundation.org/BinarySchema/}OpaqueType":
  328. createOpaque(element)
  329. existing_types.add(name)
  330. for name, element in deferred_types.iteritems():
  331. if name in plugin_types:
  332. #execute plugin if registered
  333. exec "ret = " + packageForType[name][0]+"."+packageForType[name][1]["functionCall"]
  334. if ret == "default":
  335. createStructured(element)
  336. existing_types.add(name)
  337. else:
  338. createStructured(element)
  339. existing_types.add(name)
  340. printh('/// @} /* end of group */')
  341. printh('#endif')
  342. fh.close()
  343. fc.close()