generate_builtin.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. # 3) Print structure
  132. if len(membermap) > 0:
  133. printh("typedef struct %(name)s {")
  134. for n,t in membermap.iteritems():
  135. if t.find("*") != -1:
  136. printh("\t" + "UA_Int32 " + n + "Size;")
  137. printh("\t%(t)s %(n)s;")
  138. printh("} %(name)s;")
  139. else:
  140. printh("typedef void* %(name)s;")
  141. # 3) function prototypes
  142. printh("UA_TYPE_PROTOTYPES(" + name + ")")
  143. printh("UA_TYPE_BINARY_ENCODING(" + name + ")")
  144. if args.with_xml:
  145. printh("UA_TYPE_XML_ENCODING(" + name + ")\n")
  146. # 4) CalcSizeBinary
  147. printc('''UA_UInt32 %(name)s_calcSizeBinary(%(name)s const * ptr) {
  148. return 0''')
  149. has_fixed_size = True
  150. for n,t in membermap.iteritems():
  151. if t in fixed_size:
  152. printc('\t + sizeof(%(t)s) // %(n)s')
  153. elif t.find("*") != -1:
  154. printc('\t + UA_Array_calcSizeBinary(ptr->%(n)sSize,&UA_TYPES['+ t[0:t.find("*")].upper() +
  155. "],ptr->%(n)s)")
  156. has_fixed_size = False
  157. else:
  158. printc('\t + %(t)s_calcSizeBinary(&ptr->%(n)s)')
  159. has_fixed_size = False
  160. printc("\t;\n}\n")
  161. if has_fixed_size:
  162. fixed_size.add(name)
  163. # 5) EncodeBinary
  164. printc('''UA_StatusCode %(name)s_encodeBinary(%(name)s const * src, UA_ByteString* dst, UA_UInt32 *offset) {
  165. UA_StatusCode retval = UA_STATUSCODE_GOOD;''')
  166. for n,t in membermap.iteritems():
  167. if t.find("*") != -1:
  168. printc("\tretval |= UA_Array_encodeBinary(src->%(n)s,src->%(n)sSize,&UA_TYPES[" + t[0:t.find("*")].upper() + "],dst,offset);")
  169. else:
  170. printc('\tretval |= %(t)s_encodeBinary(&src->%(n)s,dst,offset);')
  171. printc("\treturn retval;\n}\n")
  172. # 6) DecodeBinary
  173. printc('''UA_StatusCode %(name)s_decodeBinary(UA_ByteString const * src, UA_UInt32 *offset, %(name)s * dst) {
  174. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  175. %(name)s_init(dst);''')
  176. printc('\t'+name+'_init(dst);')
  177. for n,t in membermap.iteritems():
  178. if t.find("*") != -1:
  179. printc('\tretval |= UA_Int32_decodeBinary(src,offset,&dst->%(n)sSize);')
  180. printc('\tif(!retval) { retval |= UA_Array_decodeBinary(src,offset,dst->%(n)sSize,&UA_TYPES[' + t[0:t.find("*")].upper() + '],(void**)&dst->%(n)s); }')
  181. printc('\tif(retval) { dst->%(n)sSize = -1; }') # arrays clean up internally. But the size needs to be set here for the eventual deleteMembers.
  182. else:
  183. printc('\tretval |= %(t)s_decodeBinary(src,offset,&dst->%(n)s);')
  184. printc("\tif(retval) %(name)s_deleteMembers(dst);")
  185. printc("\treturn retval;\n}\n")
  186. # 7) Xml
  187. if args.with_xml:
  188. printc('''UA_TYPE_METHOD_CALCSIZEXML_NOTIMPL(%(name)s)
  189. UA_TYPE_METHOD_ENCODEXML_NOTIMPL(%(name)s)
  190. UA_TYPE_METHOD_DECODEXML_NOTIMPL(%(name)s)''')
  191. # 8) Delete
  192. printc('''void %(name)s_delete(%(name)s *p) {
  193. %(name)s_deleteMembers(p);
  194. UA_free(p);\n}\n''')
  195. # 9) DeleteMembers
  196. printc('''void %(name)s_deleteMembers(%(name)s *p) {''')
  197. for n,t in membermap.iteritems():
  198. if not t in fixed_size: # dynamic size on the wire
  199. if t.find("*") != -1:
  200. printc("\tUA_Array_delete((void*)p->%(n)s,p->%(n)sSize,&UA_TYPES["+t[0:t.find("*")].upper()+"]);")
  201. else:
  202. printc('\t%(t)s_deleteMembers(&p->%(n)s);')
  203. printc("}\n")
  204. # 10) Init
  205. printc('''void %(name)s_init(%(name)s *p) {
  206. if(!p) return;''')
  207. for n,t in membermap.iteritems():
  208. if t.find("*") != -1:
  209. printc('\tp->%(n)sSize = -1;')
  210. printc('\tp->%(n)s = UA_NULL;')
  211. else:
  212. printc('\t%(t)s_init(&p->%(n)s);')
  213. printc("}\n")
  214. # 11) New
  215. printc("UA_TYPE_NEW_DEFAULT(%(name)s)")
  216. # 12) Copy
  217. printc('''UA_StatusCode %(name)s_copy(const %(name)s *src,%(name)s *dst) {
  218. UA_StatusCode retval = UA_STATUSCODE_GOOD;''')
  219. printc("\t%(name)s_init(dst);")
  220. for n,t in membermap.iteritems():
  221. if t.find("*") != -1:
  222. printc('\tdst->%(n)sSize = src->%(n)sSize;')
  223. printc("\tretval |= UA_Array_copy(src->%(n)s, src->%(n)sSize,&UA_TYPES[" + t[0:t.find("*")].upper() + "],(void**)&dst->%(n)s);")
  224. continue
  225. if not t in fixed_size: # there are members of variable size
  226. printc('\tretval |= %(t)s_copy(&src->%(n)s,&dst->%(n)s);')
  227. continue
  228. printc("\tdst->%(n)s = src->%(n)s;")
  229. printc('''\tif(retval)
  230. \t%(name)s_deleteMembers(dst);''')
  231. printc("\treturn retval;\n}\n")
  232. # 13) Print
  233. printc('''#ifdef DEBUG''')
  234. printc('''void %(name)s_print(const %(name)s *p, FILE *stream) {
  235. fprintf(stream, "(%(name)s){");''')
  236. for i,(n,t) in enumerate(membermap.iteritems()):
  237. if t.find("*") != -1:
  238. printc('\tUA_Int32_print(&p->%(n)sSize, stream);')
  239. printc("\tUA_Array_print(p->%(n)s, p->%(n)sSize, &UA_TYPES[" + t[0:t.find("*")].upper()+"], stream);")
  240. else:
  241. printc('\t%(t)s_print(&p->%(n)s,stream);')
  242. if i == len(membermap)-1:
  243. continue
  244. printc('\tfprintf(stream, ",");')
  245. printc('''\tfprintf(stream, "}");\n}''')
  246. printc('#endif');
  247. printc('''\n''')
  248. shortname = args.outfile.split("/")[-1]
  249. print(shortname)
  250. printh('''/**
  251. * @file %(shortname)s.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 ''' + shortname.upper() + '''_H_
  259. #define ''' + shortname.upper() + '''_H_
  260. #include "ua_types.h"
  261. #include "ua_types_encoding_binary.h"
  262. /** @ingroup ''' + shortname.split("_")[1] + '''
  263. *
  264. * @defgroup ''' + shortname + ''' Generated Types
  265. *
  266. * @brief Data structures that are autogenerated from an XML-Schema.
  267. * @{
  268. */''')
  269. if args.with_xml:
  270. printh('#include "ua_types_encoding_xml.h"')
  271. if args.additional_includes:
  272. for incl in args.additional_includes.split(","):
  273. printh("#include \"" + incl + "\"")
  274. printc('''/**
  275. * @file '''+sys.argv[2]+'''.c
  276. *
  277. * @brief Autogenerated function implementations to manage the data types defined in the UA standard
  278. *
  279. * Generated from '''+sys.argv[1]+''' with script '''+sys.argv[0]+'''
  280. * on host '''+platform.uname()[1]+''' by user '''+getpass.getuser()+''' at '''+ time.strftime("%Y-%m-%d %I:%M:%S")+'''
  281. */
  282. #include "''' + args.outfile.split("/")[-1] + '''.h"
  283. #include "ua_namespace_0.h"
  284. #include "ua_util.h"\n''')
  285. # types for which we create a vector type
  286. arraytypes = set()
  287. fields = tree.xpath("//opc:Field", namespaces=ns)
  288. for field in fields:
  289. if field.get("LengthField"):
  290. arraytypes.add(stripTypename(field.get("TypeName")))
  291. deferred_types = OrderedDict()
  292. #plugin handling
  293. import os
  294. files = [f for f in os.listdir('.') if os.path.isfile(f) and f[-3:] == ".py" and f[:7] == "plugin_"]
  295. plugin_types = []
  296. packageForType = OrderedDict()
  297. for f in files:
  298. package = f[:-3]
  299. exec "import " + package
  300. exec "pluginSetup = " + package + ".setup()"
  301. if pluginSetup["pluginType"] == "structuredObject":
  302. plugin_types.append(pluginSetup["tagName"])
  303. packageForType[pluginSetup["tagName"]] = [package,pluginSetup]
  304. print("Custom object creation for tag " + pluginSetup["tagName"] + " imported from package " + package)
  305. #end plugin handling
  306. for element in types:
  307. name = element.get("Name")
  308. if skipType(name):
  309. continue
  310. if element.tag == "{http://opcfoundation.org/BinarySchema/}EnumeratedType":
  311. createEnumerated(element)
  312. existing_types.add(name)
  313. elif element.tag == "{http://opcfoundation.org/BinarySchema/}StructuredType":
  314. if printableStructuredType(element):
  315. createStructured(element)
  316. existing_types.add(name)
  317. else: # the record contains types that were not yet detailed
  318. deferred_types[name] = element
  319. continue
  320. elif element.tag == "{http://opcfoundation.org/BinarySchema/}OpaqueType":
  321. createOpaque(element)
  322. existing_types.add(name)
  323. for name, element in deferred_types.iteritems():
  324. if name in plugin_types:
  325. #execute plugin if registered
  326. exec "ret = " + packageForType[name][0]+"."+packageForType[name][1]["functionCall"]
  327. if ret == "default":
  328. createStructured(element)
  329. existing_types.add(name)
  330. else:
  331. createStructured(element)
  332. existing_types.add(name)
  333. printh('/// @} /* end of group */')
  334. printh('#endif')
  335. fh.close()
  336. fc.close()