generate_datatypes.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  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",
  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. m = "\n{\n UA_TYPENAME(\"%s\") /* .memberName */\n" % member.name
  106. m += " %s_%s, /* .memberTypeIndex */\n" % (member.memberType.outname.upper(), member.memberType.name.upper())
  107. m += " "
  108. if not before:
  109. m += "0,"
  110. else:
  111. if member.isArray:
  112. m += "offsetof(UA_%s, %sSize)" % (self.name, member.name)
  113. else:
  114. m += "offsetof(UA_%s, %s)" % (self.name, member.name)
  115. m += " - offsetof(UA_%s, %s)" % (self.name, before.name)
  116. if before.isArray:
  117. m += " - sizeof(void*),"
  118. else:
  119. m += " - sizeof(UA_%s)," % before.memberType.name
  120. m += " /* .padding */\n"
  121. m += " %s, /* .namespaceZero */\n" % member.memberType.ns0
  122. m += (" true" if member.isArray else " false") + " /* .isArray */\n}"
  123. if i != size:
  124. m += ","
  125. members += m
  126. before = member
  127. return members + "};"
  128. def datatype_ptr(self):
  129. return "&" + self.outname.upper() + "[" + self.outname.upper() + "_" + self.name.upper() + "]"
  130. def functions_c(self):
  131. 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)
  132. 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())
  133. if self.pointerfree == "true":
  134. 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)
  135. funcs += "static UA_INLINE void\nUA_%s_deleteMembers(UA_%s *p) { }\n\n" % (self.name, self.name)
  136. else:
  137. 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())
  138. 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())
  139. funcs += "static UA_INLINE void\nUA_%s_delete(UA_%s *p) {\n UA_delete(p, %s);\n}" % (self.name, self.name, self.datatype_ptr())
  140. return funcs
  141. def encoding_h(self):
  142. enc = "static UA_INLINE size_t\nUA_%s_calcSizeBinary(const UA_%s *src) {\n return UA_calcSizeBinary(src, %s);\n}\n"
  143. 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"
  144. 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}"
  145. return enc % tuple(list(itertools.chain(*itertools.repeat([self.name, self.name, self.datatype_ptr()], 3))))
  146. class BuiltinType(Type):
  147. def __init__(self, name):
  148. self.name = name
  149. self.ns0 = "true"
  150. self.typeIndex = "UA_TYPES_" + self.name.upper()
  151. self.outname = "ua_types"
  152. self.description = ""
  153. self.pointerfree = "false"
  154. if self.name in builtin_pointerfree:
  155. self.pointerfree = "true"
  156. self.overlayable = "false"
  157. if name in builtin_overlayable:
  158. self.overlayable = builtin_overlayable[name]
  159. self.builtin = "true"
  160. if self.name == "QualifiedName":
  161. self.members = [StructMember("namespaceIndex", types["Int16"], False), StructMember("name", types["String"], False)]
  162. elif self.name in ["String", "ByteString", "XmlElement"]:
  163. self.members = [StructMember("", types["Byte"], True)]
  164. else:
  165. self.members = [StructMember("", self, False)]
  166. class EnumerationType(Type):
  167. def __init__(self, outname, xml, namespace):
  168. Type.__init__(self, outname, xml, namespace)
  169. self.pointerfree = "true"
  170. self.overlayable = "UA_BINARY_OVERLAYABLE_INTEGER"
  171. self.members = [StructMember("", types["Int32"], False)] # encoded as uint32
  172. self.builtin = "true"
  173. self.typeIndex = "UA_TYPES_INT32"
  174. self.elements = OrderedDict()
  175. for child in xml:
  176. if child.tag == "{http://opcfoundation.org/BinarySchema/}EnumeratedValue":
  177. self.elements[child.get("Name")] = child.get("Value")
  178. def typedef_h(self):
  179. if sys.version_info[0] < 3:
  180. values = self.elements.iteritems()
  181. else:
  182. values = self.elements.items()
  183. return "typedef enum {\n " + ",\n ".join(map(lambda kv : "UA_" + self.name.upper() + "_" + kv[0].upper() + \
  184. " = " + kv[1], values)) + \
  185. ",\n __UA_{0}_FORCE32BIT = 0x7fffffff\n".format(self.name.upper()) + "} " + \
  186. "UA_{0};\nUA_STATIC_ASSERT(sizeof(UA_{0}) == sizeof(UA_Int32), enum_must_be_32bit);".format(self.name)
  187. class OpaqueType(Type):
  188. def __init__(self, outname, xml, namespace, baseType):
  189. Type.__init__(self, outname, xml, namespace)
  190. self.baseType = baseType
  191. self.members = [StructMember("", types[baseType], False)] # encoded as string
  192. def typedef_h(self):
  193. return "typedef UA_" + self.baseType + " UA_%s;" % self.name
  194. class StructType(Type):
  195. def __init__(self, outname, xml, namespace):
  196. Type.__init__(self, outname, xml, namespace)
  197. self.members = []
  198. lengthfields = [] # lengthfields of arrays are not included as members
  199. for child in xml:
  200. if child.get("LengthField"):
  201. lengthfields.append(child.get("LengthField"))
  202. for child in xml:
  203. if not child.tag == "{http://opcfoundation.org/BinarySchema/}Field":
  204. continue
  205. if child.get("Name") in lengthfields:
  206. continue
  207. memberName = child.get("Name")
  208. memberName = memberName[:1].lower() + memberName[1:]
  209. memberTypeName = child.get("TypeName")
  210. memberType = types[memberTypeName[memberTypeName.find(":")+1:]]
  211. isArray = True if child.get("LengthField") else False
  212. self.members.append(StructMember(memberName, memberType, isArray))
  213. self.pointerfree = "true"
  214. self.overlayable = "true"
  215. before = None
  216. for m in self.members:
  217. if m.isArray or m.memberType.pointerfree != "true":
  218. self.pointerfree = "false"
  219. self.overlayable = "false"
  220. else:
  221. self.overlayable += " && " + m.memberType.overlayable
  222. if before:
  223. self.overlayable += " && offsetof(UA_%s, %s) == (offsetof(UA_%s, %s) + sizeof(UA_%s))" % \
  224. (self.name, m.name, self.name, before.name, before.memberType.name)
  225. if "false" in self.overlayable:
  226. self.overlayable = "false"
  227. before = m
  228. def typedef_h(self):
  229. if len(self.members) == 0:
  230. return "typedef void * UA_%s;" % self.name
  231. returnstr = "typedef struct {\n"
  232. for member in self.members:
  233. if member.isArray:
  234. returnstr += " size_t %sSize;\n" % member.name
  235. returnstr += " UA_%s *%s;\n" % (member.memberType.name, member.name)
  236. else:
  237. returnstr += " UA_%s %s;\n" % (member.memberType.name, member.name)
  238. return returnstr + "} UA_%s;" % self.name
  239. #########################
  240. # Parse Typedefinitions #
  241. #########################
  242. def parseTypeDefinitions(outname, xmlDescription, namespace):
  243. def typeReady(element):
  244. "Are all member types defined?"
  245. for child in element:
  246. if child.tag == "{http://opcfoundation.org/BinarySchema/}Field":
  247. childname = child.get("TypeName")
  248. if childname[childname.find(":")+1:] not in types:
  249. return False
  250. return True
  251. def skipType(name):
  252. if name in excluded_types:
  253. return True
  254. if "Test" in name: # skip all test types
  255. return True
  256. if re.search("NodeId$", name) != None:
  257. return True
  258. return False
  259. snippets = {}
  260. for typeXml in etree.parse(xmlDescription).getroot():
  261. if not typeXml.get("Name"):
  262. continue
  263. name = typeXml.get("Name")
  264. snippets[name] = typeXml
  265. while(len(snippets) > 0):
  266. for name, typeXml in list(snippets.items()):
  267. if name in types or skipType(name):
  268. del snippets[name]
  269. continue
  270. if not typeReady(typeXml):
  271. continue
  272. if name in builtin_types:
  273. types[name] = BuiltinType(name)
  274. elif typeXml.tag == "{http://opcfoundation.org/BinarySchema/}EnumeratedType":
  275. types[name] = EnumerationType(outname, typeXml, namespace)
  276. elif typeXml.tag == "{http://opcfoundation.org/BinarySchema/}OpaqueType":
  277. types[name] = OpaqueType(outname, typeXml, namespace, get_base_type_for_opaque(name)['name'])
  278. elif typeXml.tag == "{http://opcfoundation.org/BinarySchema/}StructuredType":
  279. types[name] = StructType(outname, typeXml, namespace)
  280. else:
  281. raise Exception("Type not known")
  282. del snippets[name]
  283. ##########################
  284. # Parse TypeDescriptions #
  285. ##########################
  286. class TypeDescription(object):
  287. def __init__(self, name, nodeid, namespaceid):
  288. self.name = name
  289. self.nodeid = nodeid
  290. self.namespaceid = namespaceid
  291. self.xmlEncodingId = "0"
  292. self.binaryEncodingId = "0"
  293. def parseTypeDescriptions(f, namespaceid):
  294. definitions = {}
  295. input_str = f.read()
  296. input_str = input_str.replace('\r','')
  297. rows = map(lambda x:tuple(x.split(',')), input_str.split('\n'))
  298. delay_init = []
  299. for index, row in enumerate(rows):
  300. if len(row) < 3:
  301. continue
  302. if row[2] == "Object":
  303. # Check if node name ends with _Encoding_(DefaultXml|DefaultBinary) and store the node id in the corresponding DataType
  304. m = re.match('(.*?)_Encoding_Default(Xml|Binary)$',row[0])
  305. if (m):
  306. baseType = m.group(1)
  307. if baseType not in types:
  308. continue
  309. delay_init.append({
  310. "baseType": baseType,
  311. "encoding": m.group(2),
  312. "id": row[1]
  313. })
  314. continue
  315. if row[2] != "DataType":
  316. continue
  317. if row[0] == "BaseDataType":
  318. definitions["Variant"] = TypeDescription(row[0], row[1], namespaceid)
  319. elif row[0] == "Structure":
  320. definitions["ExtensionObject"] = TypeDescription(row[0], row[1], namespaceid)
  321. elif row[0] not in types:
  322. continue
  323. else:
  324. definitions[row[0]] = TypeDescription(row[0], row[1], namespaceid)
  325. for i in delay_init:
  326. if i["baseType"] not in definitions:
  327. raise Exception("Type {} not found in definitions file.".format(i["baseType"]))
  328. if i["encoding"] == "Xml":
  329. definitions[i["baseType"]].xmlEncodingId = i["id"]
  330. else:
  331. definitions[i["baseType"]].binaryEncodingId = i["id"]
  332. return definitions
  333. def merge_dicts(*dict_args):
  334. """
  335. Given any number of dicts, shallow copy and merge into a new dict,
  336. precedence goes to key value pairs in latter dicts.
  337. """
  338. result = {}
  339. for dictionary in dict_args:
  340. result.update(dictionary)
  341. return result
  342. ###############################
  343. # Parse the Command Line Input#
  344. ###############################
  345. parser = argparse.ArgumentParser()
  346. parser.add_argument('-c', '--type-csv',
  347. metavar="<typeDescriptions>",
  348. type=argparse.FileType('r'),
  349. dest="type_csv",
  350. action='append',
  351. default=[],
  352. help='csv file with type descriptions')
  353. parser.add_argument('--namespace',
  354. type=int,
  355. dest="namespace",
  356. default=0,
  357. help='namespace id of the generated type nodeids (defaults to 0)')
  358. parser.add_argument('-s', '--selected-types',
  359. metavar="<selectedTypes>",
  360. type=argparse.FileType('r'),
  361. dest="selected_types",
  362. action='append',
  363. default=[],
  364. help='file with list of types (among those parsed) to be generated. If not given, all types are generated')
  365. parser.add_argument('--no-builtin',
  366. action='store_true',
  367. dest="no_builtin",
  368. help='Do not generate builtin types')
  369. parser.add_argument('-t', '--type-bsd',
  370. metavar="<typeBsds>",
  371. type=argparse.FileType('r'),
  372. dest="type_bsd",
  373. action='append',
  374. default=[],
  375. help='bsd file with type definitions')
  376. parser.add_argument('outfile',
  377. metavar='<outputFile>',
  378. help='output file w/o extension')
  379. args = parser.parse_args()
  380. outname = args.outfile.split("/")[-1]
  381. inname = ', '.join(list(map(lambda x:x.name.split("/")[-1], args.type_bsd)))
  382. ################
  383. # Create Types #
  384. ################
  385. for builtin in builtin_types:
  386. types[builtin] = BuiltinType(builtin)
  387. for f in args.type_bsd:
  388. parseTypeDefinitions(outname, f, args.namespace)
  389. typedescriptions = {}
  390. for f in args.type_csv:
  391. typedescriptions = merge_dicts(typedescriptions, parseTypeDescriptions(f, args.namespace))
  392. selected_types = []
  393. for f in args.selected_types:
  394. selected_types = list(filter(len, [line.strip() for line in f]))
  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()