generate_builtin.py 14 KB

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