generate_datatypes.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. #!/usr/bin/env python
  2. # This Source Code Form is subject to the terms of the Mozilla Public
  3. # License, v. 2.0. If a copy of the MPL was not distributed with this
  4. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  5. from __future__ import print_function
  6. import sys
  7. import time
  8. import platform
  9. import getpass
  10. from collections import OrderedDict
  11. import re
  12. import xml.etree.ElementTree as etree
  13. import itertools
  14. import argparse
  15. from nodeset_compiler.opaque_type_mapping import opaque_type_mapping, get_base_type_for_opaque
  16. types = OrderedDict() # contains types that were already parsed
  17. typedescriptions = {} # contains type nodeids
  18. excluded_types = ["NodeIdType", "InstanceNode", "TypeNode", "Node", "ObjectNode",
  19. "ObjectTypeNode", "VariableNode", "VariableTypeNode", "ReferenceTypeNode",
  20. "MethodNode", "ViewNode", "DataTypeNode",
  21. "NumericRange", "NumericRangeDimensions",
  22. "UA_ServerDiagnosticsSummaryDataType", "UA_SamplingIntervalDiagnosticsDataType",
  23. "UA_SessionSecurityDiagnosticsDataType", "UA_SubscriptionDiagnosticsDataType",
  24. "UA_SessionDiagnosticsDataType"]
  25. builtin_types = ["Boolean", "SByte", "Byte", "Int16", "UInt16", "Int32", "UInt32",
  26. "Int64", "UInt64", "Float", "Double", "String", "DateTime", "Guid",
  27. "ByteString", "XmlElement", "NodeId", "ExpandedNodeId", "StatusCode",
  28. "QualifiedName", "LocalizedText", "ExtensionObject", "DataValue",
  29. "Variant", "DiagnosticInfo"]
  30. # If the type does not contain pointers, it can be copied with memcpy
  31. # (internally, not into the protocol message). This dict contains the sizes of
  32. # pointer-free types. Parsed types are added if they apply.
  33. builtin_pointerfree = ["Boolean", "SByte", "Byte", "Int16", "UInt16", "Int32", "UInt32",
  34. "Int64", "UInt64", "Float", "Double", "DateTime", "Guid", "StatusCode"]
  35. # Some types can be memcpy'd off the binary stream. That's especially important
  36. # for arrays. But we need to check if they contain padding and whether the
  37. # endianness is correct. This dict gives the C-statement that must be true for the
  38. # type to be overlayable. Parsed types are added if they apply.
  39. builtin_overlayable = {"Boolean": "true", "SByte": "true", "Byte": "true",
  40. "Int16": "UA_BINARY_OVERLAYABLE_INTEGER", "UInt16": "UA_BINARY_OVERLAYABLE_INTEGER",
  41. "Int32": "UA_BINARY_OVERLAYABLE_INTEGER", "UInt32": "UA_BINARY_OVERLAYABLE_INTEGER",
  42. "Int64": "UA_BINARY_OVERLAYABLE_INTEGER", "UInt64": "UA_BINARY_OVERLAYABLE_INTEGER",
  43. "Float": "UA_BINARY_OVERLAYABLE_FLOAT", "Double": "UA_BINARY_OVERLAYABLE_FLOAT",
  44. "DateTime": "UA_BINARY_OVERLAYABLE_INTEGER", "StatusCode": "UA_BINARY_OVERLAYABLE_INTEGER",
  45. "Guid": "(UA_BINARY_OVERLAYABLE_INTEGER && offsetof(UA_Guid, data2) == sizeof(UA_UInt32) && " + \
  46. "offsetof(UA_Guid, data3) == (sizeof(UA_UInt16) + sizeof(UA_UInt32)) && " + \
  47. "offsetof(UA_Guid, data4) == (2*sizeof(UA_UInt32)))"}
  48. ################
  49. # Type Classes #
  50. ################
  51. class StructMember(object):
  52. def __init__(self, name, memberType, isArray):
  53. self.name = name
  54. self.memberType = memberType
  55. self.isArray = isArray
  56. class Type(object):
  57. def __init__(self, outname, xml, namespace):
  58. self.name = xml.get("Name")
  59. self.ns0 = ("true" if namespace == 0 else "false")
  60. self.typeIndex = outname.upper() + "_" + self.name.upper()
  61. self.outname = outname
  62. self.description = ""
  63. self.pointerfree = "false"
  64. self.overlayable = "false"
  65. if self.name in builtin_types:
  66. self.builtin = "true"
  67. else:
  68. self.builtin = "false"
  69. self.members = [StructMember("", self, False)] # Returns one member: itself. Overwritten by some types.
  70. for child in xml:
  71. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  72. self.description = child.text
  73. break
  74. def datatype_c(self):
  75. xmlEncodingId = "0"
  76. binaryEncodingId = "0"
  77. if self.name in typedescriptions:
  78. description = typedescriptions[self.name]
  79. typeid = "{%s, UA_NODEIDTYPE_NUMERIC, {%s}}" % (description.namespaceid, description.nodeid)
  80. xmlEncodingId = description.xmlEncodingId
  81. binaryEncodingId = description.binaryEncodingId
  82. else:
  83. typeid = "{0, UA_NODEIDTYPE_NUMERIC, {0}}"
  84. return "{\n UA_TYPENAME(\"%s\") /* .typeName */\n" % self.name + \
  85. " " + typeid + ", /* .typeId */\n" + \
  86. " sizeof(UA_" + self.name + "), /* .memSize */\n" + \
  87. " " + self.typeIndex + ", /* .typeIndex */\n" + \
  88. " " + str(len(self.members)) + ", /* .membersSize */\n" + \
  89. " " + self.builtin + ", /* .builtin */\n" + \
  90. " " + self.pointerfree + ", /* .pointerFree */\n" + \
  91. " " + self.overlayable + ", /* .overlayable */\n" + \
  92. " " + binaryEncodingId + ", /* .binaryEncodingId */\n" + \
  93. " %s_members" % self.name + " /* .members */\n}"
  94. def members_c(self):
  95. if len(self.members)==0:
  96. return "#define %s_members NULL" % (self.name)
  97. members = "static UA_DataTypeMember %s_members[%s] = {" % (self.name, len(self.members))
  98. before = None
  99. i = 0
  100. size = len(self.members)
  101. for index, member in enumerate(self.members):
  102. i += 1
  103. m = "\n{\n UA_TYPENAME(\"%s\") /* .memberName */\n" % member.name
  104. m += " %s_%s, /* .memberTypeIndex */\n" % (member.memberType.outname.upper(), member.memberType.name.upper())
  105. m += " "
  106. if not before:
  107. m += "0,"
  108. else:
  109. if member.isArray:
  110. m += "offsetof(UA_%s, %sSize)" % (self.name, member.name)
  111. else:
  112. m += "offsetof(UA_%s, %s)" % (self.name, member.name)
  113. m += " - offsetof(UA_%s, %s)" % (self.name, before.name)
  114. if before.isArray:
  115. m += " - sizeof(void*),"
  116. else:
  117. m += " - sizeof(UA_%s)," % before.memberType.name
  118. m += " /* .padding */\n"
  119. m += " %s, /* .namespaceZero */\n" % member.memberType.ns0
  120. m += (" true" if member.isArray else " false") + " /* .isArray */\n}"
  121. if i != size:
  122. m += ","
  123. members += m
  124. before = member
  125. return members + "};"
  126. def datatype_ptr(self):
  127. return "&" + self.outname.upper() + "[" + self.outname.upper() + "_" + self.name.upper() + "]"
  128. def functions_c(self):
  129. funcs = "static UA_INLINE void\nUA_%s_init(UA_%s *p) {\n memset(p, 0, sizeof(UA_%s));\n}\n\n" % (self.name, self.name, self.name)
  130. funcs += "static UA_INLINE UA_%s *\nUA_%s_new(void) {\n return (UA_%s*)UA_new(%s);\n}\n\n" % (self.name, self.name, self.name, self.datatype_ptr())
  131. if self.pointerfree == "true":
  132. funcs += "static UA_INLINE UA_StatusCode\nUA_%s_copy(const UA_%s *src, UA_%s *dst) {\n *dst = *src;\n return UA_STATUSCODE_GOOD;\n}\n\n" % (self.name, self.name, self.name)
  133. funcs += "static UA_INLINE void\nUA_%s_deleteMembers(UA_%s *p) { }\n\n" % (self.name, self.name)
  134. else:
  135. funcs += "static UA_INLINE UA_StatusCode\nUA_%s_copy(const UA_%s *src, UA_%s *dst) {\n return UA_copy(src, dst, %s);\n}\n\n" % (self.name, self.name, self.name, self.datatype_ptr())
  136. funcs += "static UA_INLINE void\nUA_%s_deleteMembers(UA_%s *p) {\n UA_deleteMembers(p, %s);\n}\n\n" % (self.name, self.name, self.datatype_ptr())
  137. funcs += "static UA_INLINE void\nUA_%s_delete(UA_%s *p) {\n UA_delete(p, %s);\n}" % (self.name, self.name, self.datatype_ptr())
  138. return funcs
  139. def encoding_h(self):
  140. enc = "static UA_INLINE UA_StatusCode\nUA_%s_encodeBinary(const UA_%s *src, UA_Byte **bufPos, const UA_Byte **bufEnd) {\n return UA_encodeBinary(src, %s, bufPos, bufEnd, NULL, NULL);\n}\n"
  141. enc += "static UA_INLINE UA_StatusCode\nUA_%s_decodeBinary(const UA_ByteString *src, size_t *offset, UA_%s *dst) {\n return UA_decodeBinary(src, offset, dst, %s, 0, NULL);\n}"
  142. return enc % tuple(list(itertools.chain(*itertools.repeat([self.name, self.name, self.datatype_ptr()], 2))))
  143. class BuiltinType(Type):
  144. def __init__(self, name):
  145. self.name = name
  146. self.ns0 = "true"
  147. self.typeIndex = "UA_TYPES_" + self.name.upper()
  148. self.outname = "ua_types"
  149. self.description = ""
  150. self.pointerfree = "false"
  151. if self.name in builtin_pointerfree:
  152. self.pointerfree = "true"
  153. self.overlayable = "false"
  154. if name in builtin_overlayable:
  155. self.overlayable = builtin_overlayable[name]
  156. self.builtin = "true"
  157. if self.name == "QualifiedName":
  158. self.members = [StructMember("namespaceIndex", types["Int16"], False), StructMember("name", types["String"], False)]
  159. elif self.name in ["String", "ByteString", "XmlElement"]:
  160. self.members = [StructMember("", types["Byte"], True)]
  161. else:
  162. self.members = [StructMember("", self, False)]
  163. class EnumerationType(Type):
  164. def __init__(self, outname, xml, namespace):
  165. Type.__init__(self, outname, xml, namespace)
  166. self.pointerfree = "true"
  167. self.overlayable = "UA_BINARY_OVERLAYABLE_INTEGER"
  168. self.members = [StructMember("", types["Int32"], False)] # encoded as uint32
  169. self.builtin = "true"
  170. self.typeIndex = "UA_TYPES_INT32"
  171. self.elements = OrderedDict()
  172. for child in xml:
  173. if child.tag == "{http://opcfoundation.org/BinarySchema/}EnumeratedValue":
  174. self.elements[child.get("Name")] = child.get("Value")
  175. def typedef_h(self):
  176. if sys.version_info[0] < 3:
  177. values = self.elements.iteritems()
  178. else:
  179. values = self.elements.items()
  180. return "typedef enum {\n " + ",\n ".join(map(lambda kv : "UA_" + self.name.upper() + "_" + kv[0].upper() + \
  181. " = " + kv[1], values)) + \
  182. ",\n __UA_{0}_FORCE32BIT = 0x7fffffff\n".format(self.name.upper()) + "} " + \
  183. "UA_{0};\nUA_STATIC_ASSERT(sizeof(UA_{0}) == sizeof(UA_Int32), enum_must_be_32bit);".format(self.name)
  184. class OpaqueType(Type):
  185. def __init__(self, outname, xml, namespace, baseType):
  186. Type.__init__(self, outname, xml, namespace)
  187. self.baseType = baseType
  188. self.members = [StructMember("", types[baseType], False)] # encoded as string
  189. def typedef_h(self):
  190. return "typedef UA_" + self.baseType + " UA_%s;" % self.name
  191. class StructType(Type):
  192. def __init__(self, outname, xml, namespace):
  193. Type.__init__(self, outname, xml, namespace)
  194. self.members = []
  195. lengthfields = [] # lengthfields of arrays are not included as members
  196. for child in xml:
  197. if child.get("LengthField"):
  198. lengthfields.append(child.get("LengthField"))
  199. for child in xml:
  200. if not child.tag == "{http://opcfoundation.org/BinarySchema/}Field":
  201. continue
  202. if child.get("Name") in lengthfields:
  203. continue
  204. memberName = child.get("Name")
  205. memberName = memberName[:1].lower() + memberName[1:]
  206. memberTypeName = child.get("TypeName")
  207. memberType = types[memberTypeName[memberTypeName.find(":")+1:]]
  208. isArray = True if child.get("LengthField") else False
  209. self.members.append(StructMember(memberName, memberType, isArray))
  210. self.pointerfree = "true"
  211. self.overlayable = "true"
  212. before = None
  213. for m in self.members:
  214. if m.isArray or m.memberType.pointerfree != "true":
  215. self.pointerfree = "false"
  216. self.overlayable = "false"
  217. else:
  218. self.overlayable += " && " + m.memberType.overlayable
  219. if before:
  220. self.overlayable += " && offsetof(UA_%s, %s) == (offsetof(UA_%s, %s) + sizeof(UA_%s))" % \
  221. (self.name, m.name, self.name, before.name, before.memberType.name)
  222. if "false" in self.overlayable:
  223. self.overlayable = "false"
  224. before = m
  225. def typedef_h(self):
  226. if len(self.members) == 0:
  227. return "typedef void * UA_%s;" % self.name
  228. returnstr = "typedef struct {\n"
  229. for member in self.members:
  230. if member.isArray:
  231. returnstr += " size_t %sSize;\n" % member.name
  232. returnstr += " UA_%s *%s;\n" % (member.memberType.name, member.name)
  233. else:
  234. returnstr += " UA_%s %s;\n" % (member.memberType.name, member.name)
  235. return returnstr + "} UA_%s;" % self.name
  236. #########################
  237. # Parse Typedefinitions #
  238. #########################
  239. def parseTypeDefinitions(outname, xmlDescription, namespace):
  240. def typeReady(element):
  241. "Are all member types defined?"
  242. for child in element:
  243. if child.tag == "{http://opcfoundation.org/BinarySchema/}Field":
  244. childname = child.get("TypeName")
  245. if childname[childname.find(":")+1:] not in types:
  246. return False
  247. return True
  248. def skipType(name):
  249. if name in excluded_types:
  250. return True
  251. if "Test" in name: # skip all test types
  252. return True
  253. if re.search("NodeId$", name) != None:
  254. return True
  255. return False
  256. snippets = {}
  257. for typeXml in etree.parse(xmlDescription).getroot():
  258. if not typeXml.get("Name"):
  259. continue
  260. name = typeXml.get("Name")
  261. snippets[name] = typeXml
  262. while(len(snippets) > 0):
  263. for name, typeXml in list(snippets.items()):
  264. if name in types or skipType(name):
  265. del snippets[name]
  266. continue
  267. if not typeReady(typeXml):
  268. continue
  269. if name in builtin_types:
  270. types[name] = BuiltinType(name)
  271. elif typeXml.tag == "{http://opcfoundation.org/BinarySchema/}EnumeratedType":
  272. types[name] = EnumerationType(outname, typeXml, namespace)
  273. elif typeXml.tag == "{http://opcfoundation.org/BinarySchema/}OpaqueType":
  274. types[name] = OpaqueType(outname, typeXml, namespace, get_base_type_for_opaque(name)['name'])
  275. elif typeXml.tag == "{http://opcfoundation.org/BinarySchema/}StructuredType":
  276. types[name] = StructType(outname, typeXml, namespace)
  277. else:
  278. raise Exception("Type not known")
  279. del snippets[name]
  280. ##########################
  281. # Parse TypeDescriptions #
  282. ##########################
  283. class TypeDescription(object):
  284. def __init__(self, name, nodeid, namespaceid):
  285. self.name = name
  286. self.nodeid = nodeid
  287. self.namespaceid = namespaceid
  288. self.xmlEncodingId = "0"
  289. self.binaryEncodingId = "0"
  290. def parseTypeDescriptions(f, namespaceid):
  291. definitions = {}
  292. input_str = f.read()
  293. input_str = input_str.replace('\r','')
  294. rows = map(lambda x:tuple(x.split(',')), input_str.split('\n'))
  295. delay_init = []
  296. for index, row in enumerate(rows):
  297. if len(row) < 3:
  298. continue
  299. if row[2] == "Object":
  300. # Check if node name ends with _Encoding_(DefaultXml|DefaultBinary) and store the node id in the corresponding DataType
  301. m = re.match('(.*?)_Encoding_Default(Xml|Binary)$',row[0])
  302. if (m):
  303. baseType = m.group(1)
  304. if baseType not in types:
  305. continue
  306. delay_init.append({
  307. "baseType": baseType,
  308. "encoding": m.group(2),
  309. "id": row[1]
  310. })
  311. continue
  312. if row[2] != "DataType":
  313. continue
  314. if row[0] == "BaseDataType":
  315. definitions["Variant"] = TypeDescription(row[0], row[1], namespaceid)
  316. elif row[0] == "Structure":
  317. definitions["ExtensionObject"] = TypeDescription(row[0], row[1], namespaceid)
  318. elif row[0] not in types:
  319. continue
  320. else:
  321. definitions[row[0]] = TypeDescription(row[0], row[1], namespaceid)
  322. for i in delay_init:
  323. if i["baseType"] not in definitions:
  324. raise Exception("Type {} not found in definitions file.".format(i["baseType"]))
  325. if i["encoding"] == "Xml":
  326. definitions[i["baseType"]].xmlEncodingId = i["id"]
  327. else:
  328. definitions[i["baseType"]].binaryEncodingId = i["id"]
  329. return definitions
  330. def merge_dicts(*dict_args):
  331. """
  332. Given any number of dicts, shallow copy and merge into a new dict,
  333. precedence goes to key value pairs in latter dicts.
  334. """
  335. result = {}
  336. for dictionary in dict_args:
  337. result.update(dictionary)
  338. return result
  339. ###############################
  340. # Parse the Command Line Input#
  341. ###############################
  342. parser = argparse.ArgumentParser()
  343. parser.add_argument('-c', '--type-csv',
  344. metavar="<typeDescriptions>",
  345. type=argparse.FileType('r'),
  346. dest="type_csv",
  347. action='append',
  348. default=[],
  349. help='csv file with type descriptions')
  350. parser.add_argument('--namespace',
  351. type=int,
  352. dest="namespace",
  353. default=0,
  354. help='namespace id of the generated type nodeids (defaults to 0)')
  355. parser.add_argument('-s', '--selected-types',
  356. metavar="<selectedTypes>",
  357. type=argparse.FileType('r'),
  358. dest="selected_types",
  359. action='append',
  360. default=[],
  361. help='file with list of types (among those parsed) to be generated. If not given, all types are generated')
  362. parser.add_argument('--no-builtin',
  363. action='store_true',
  364. dest="no_builtin",
  365. help='Do not generate builtin types')
  366. parser.add_argument('-t', '--type-bsd',
  367. metavar="<typeBsds>",
  368. type=argparse.FileType('r'),
  369. dest="type_bsd",
  370. action='append',
  371. default=[],
  372. help='bsd file with type definitions')
  373. parser.add_argument('outfile',
  374. metavar='<outputFile>',
  375. help='output file w/o extension')
  376. args = parser.parse_args()
  377. outname = args.outfile.split("/")[-1]
  378. inname = ', '.join(list(map(lambda x:x.name.split("/")[-1], args.type_bsd)))
  379. ################
  380. # Create Types #
  381. ################
  382. for builtin in builtin_types:
  383. types[builtin] = BuiltinType(builtin)
  384. for f in args.type_bsd:
  385. parseTypeDefinitions(outname, f, args.namespace)
  386. typedescriptions = {}
  387. for f in args.type_csv:
  388. typedescriptions = merge_dicts(typedescriptions, parseTypeDescriptions(f, args.namespace))
  389. selected_types = []
  390. for f in args.selected_types:
  391. selected_types = list(filter(len, [line.strip() for line in f]))
  392. if len(selected_types) == 0:
  393. selected_types = types.keys()
  394. #############################
  395. # Write out the Definitions #
  396. #############################
  397. fh = open(args.outfile + "_generated.h",'w')
  398. ff = open(args.outfile + "_generated_handling.h",'w')
  399. fe = open(args.outfile + "_generated_encoding_binary.h",'w')
  400. fc = open(args.outfile + "_generated.c",'w')
  401. def printh(string):
  402. print(string, end='\n', file=fh)
  403. def printf(string):
  404. print(string, end='\n', file=ff)
  405. def printe(string):
  406. print(string, end='\n', file=fe)
  407. def printc(string):
  408. print(string, end='\n', file=fc)
  409. def iter_types(v, opaqueType):
  410. l = None
  411. if sys.version_info[0] < 3:
  412. l = list(v.itervalues())
  413. else:
  414. l = list(v.values())
  415. if len(selected_types) > 0:
  416. l = list(filter(lambda t: t.name in selected_types, l))
  417. if args.no_builtin:
  418. l = list(filter(lambda t: type(t) != BuiltinType, l))
  419. if opaqueType:
  420. # only opaque type
  421. l = list(filter(lambda t: t.name in opaque_type_mapping, l))
  422. else:
  423. # remove opaque type
  424. l = list(filter(lambda t: t.name not in opaque_type_mapping, l))
  425. return l
  426. ################
  427. # Print Header #
  428. ################
  429. printh('''/* Generated from ''' + inname + ''' with script ''' + sys.argv[0] + '''
  430. * on host ''' + platform.uname()[1] + ''' by user ''' + getpass.getuser() + \
  431. ''' at ''' + time.strftime("%Y-%m-%d %I:%M:%S") + ''' */
  432. #ifndef ''' + outname.upper() + '''_GENERATED_H_
  433. #define ''' + outname.upper() + '''_GENERATED_H_
  434. #ifdef __cplusplus
  435. extern "C" {
  436. #endif
  437. #ifdef UA_NO_AMALGAMATION
  438. #include "ua_types.h"
  439. ''' + ('#include "ua_types_generated.h"\n' if outname != "ua_types" else '') + '''
  440. #else
  441. #include "open62541.h"
  442. #endif
  443. ''')
  444. filtered_types = iter_types(types, False)
  445. filtered_opaque_types = iter_types(types, True)
  446. printh('''/**
  447. * Every type is assigned an index in an array containing the type descriptions.
  448. * These descriptions are used during type handling (copying, deletion,
  449. * binary encoding, ...). */''')
  450. printh("#define " + outname.upper() + "_COUNT %s" % (str(len(filtered_types))))
  451. printh("extern UA_EXPORT const UA_DataType " + outname.upper() + "[" + outname.upper() + "_COUNT];")
  452. i = 0
  453. for t in filtered_types:
  454. if i != 0:
  455. printh("\n")
  456. printh("/**\n * " + t.name)
  457. printh(" * " + "^" * len(t.name))
  458. if t.description == "":
  459. printh(" */")
  460. else:
  461. printh(" * " + t.description + " */")
  462. if type(t) != BuiltinType:
  463. printh(t.typedef_h() + "\n")
  464. printh("#define " + outname.upper() + "_" + t.name.upper() + " " + str(i))
  465. i += 1
  466. i = 0
  467. # Generate alias for opaque types
  468. for t in filtered_opaque_types:
  469. if i != 0:
  470. printh("\n")
  471. printh("/**\n * " + t.name)
  472. printh(" * " + "^" * len(t.name))
  473. if t.description == "":
  474. printh(" */")
  475. else:
  476. printh(" * " + t.description + " */")
  477. if type(t) != BuiltinType:
  478. printh(t.typedef_h() + "\n")
  479. printh("#define " + outname.upper() + "_" + t.name.upper() + " " + outname.upper() + "_" + get_base_type_for_opaque(t.name)['name'].upper())
  480. i += 1
  481. printh('''
  482. #ifdef __cplusplus
  483. } // extern "C"
  484. #endif\n
  485. #endif /* %s_GENERATED_H_ */''' % outname.upper())
  486. ##################
  487. # Print Handling #
  488. ##################
  489. printf('''/* Generated from ''' + inname + ''' with script ''' + sys.argv[0] + '''
  490. * on host ''' + platform.uname()[1] + ''' by user ''' + getpass.getuser() + \
  491. ''' at ''' + time.strftime("%Y-%m-%d %I:%M:%S") + ''' */
  492. #ifndef ''' + outname.upper() + '''_GENERATED_HANDLING_H_
  493. #define ''' + outname.upper() + '''_GENERATED_HANDLING_H_
  494. #ifdef __cplusplus
  495. extern "C" {
  496. #endif
  497. #include "''' + outname + '''_generated.h"
  498. #if defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 6
  499. # pragma GCC diagnostic push
  500. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  501. # pragma GCC diagnostic ignored "-Wmissing-braces"
  502. #endif
  503. ''')
  504. for t in filtered_types:
  505. printf("\n/* " + t.name + " */")
  506. printf(t.functions_c())
  507. printf('''
  508. #if defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 6
  509. # pragma GCC diagnostic pop
  510. #endif
  511. #ifdef __cplusplus
  512. } // extern "C"
  513. #endif\n
  514. #endif /* %s_GENERATED_HANDLING_H_ */''' % outname.upper())
  515. ###########################
  516. # Print Description Array #
  517. ###########################
  518. printc('''/* Generated from ''' + inname + ''' with script ''' + sys.argv[0] + '''
  519. * on host ''' + platform.uname()[1] + ''' by user ''' + getpass.getuser() + \
  520. ''' at ''' + time.strftime("%Y-%m-%d %I:%M:%S") + ''' */
  521. #include "''' + outname + '''_generated.h"''')
  522. for t in filtered_types:
  523. printc("")
  524. printc("/* " + t.name + " */")
  525. printc(t.members_c())
  526. printc("const UA_DataType %s[%s_COUNT] = {" % (outname.upper(), outname.upper()))
  527. for t in filtered_types:
  528. # printc("")
  529. printc("/* " + t.name + " */")
  530. printc(t.datatype_c() + ",")
  531. printc("};\n")
  532. ##################
  533. # Print Encoding #
  534. ##################
  535. printe('''/* Generated from ''' + inname + ''' with script ''' + sys.argv[0] + '''
  536. * on host ''' + platform.uname()[1] + ''' by user ''' + getpass.getuser() + \
  537. ''' at ''' + time.strftime("%Y-%m-%d %I:%M:%S") + ''' */
  538. #include "ua_types_encoding_binary.h"
  539. #include "''' + outname + '''_generated.h"''')
  540. for t in filtered_types:
  541. printe("\n/* " + t.name + " */")
  542. printe(t.encoding_h())
  543. fh.close()
  544. ff.close()
  545. fc.close()
  546. fe.close()