generate_datatypes.py 24 KB

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