generate_datatypes.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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 itertools
  10. import argparse
  11. from pprint import pprint
  12. fixed_size = {"UA_Boolean": 1, "UA_SByte": 1, "UA_Byte": 1, "UA_Int16": 2, "UA_UInt16": 2,
  13. "UA_Int32": 4, "UA_UInt32": 4, "UA_Int64": 8, "UA_UInt64": 8, "UA_Float": 4,
  14. "UA_Double": 8, "UA_DateTime": 8, "UA_Guid": 16, "UA_StatusCode": 4}
  15. zero_copy = ["UA_Boolean", "UA_SByte", "UA_Byte", "UA_Int16", "UA_UInt16", "UA_Int32", "UA_UInt32",
  16. "UA_Int64", "UA_UInt64", "UA_Float", "UA_Double", "UA_DateTime", "UA_StatusCode"]
  17. # The order of the builtin-types is not as in the standard. We put all the
  18. # fixed_size types in the front, so they can be distinguished by a simple geq
  19. # comparison. That's ok, since we use the type-index only internally!!
  20. builtin_types = ["UA_Boolean", "UA_SByte", "UA_Byte", "UA_Int16", "UA_UInt16",
  21. "UA_Int32", "UA_UInt32", "UA_Int64", "UA_UInt64", "UA_Float",
  22. "UA_Double", "UA_String", "UA_DateTime", "UA_Guid", "UA_ByteString",
  23. "UA_XmlElement", "UA_NodeId", "UA_ExpandedNodeId", "UA_StatusCode",
  24. "UA_QualifiedName", "UA_LocalizedText", "UA_ExtensionObject", "UA_DataValue",
  25. "UA_Variant", "UA_DiagnosticInfo"]
  26. excluded_types = ["UA_NodeIdType", "UA_InstanceNode", "UA_TypeNode", "UA_Node", "UA_ObjectNode",
  27. "UA_ObjectTypeNode", "UA_VariableNode", "UA_VariableTypeNode", "UA_ReferenceTypeNode",
  28. "UA_MethodNode", "UA_ViewNode", "UA_DataTypeNode", "UA_ServerDiagnosticsSummaryDataType",
  29. "UA_SamplingIntervalDiagnosticsDataType", "UA_SessionSecurityDiagnosticsDataType",
  30. "UA_SubscriptionDiagnosticsDataType", "UA_SessionDiagnosticsDataType"]
  31. minimal_types = ["InvalidType", "Node", "NodeClass", "ReferenceNode", "ApplicationDescription", "ApplicationType",
  32. "ChannelSecurityToken", "OpenSecureChannelRequest", "OpenSecureChannelResponse",
  33. "CloseSecureChannelRequest", "CloseSecureChannelResponse", "RequestHeader", "ResponseHeader",
  34. "SecurityTokenRequestType", "MessageSecurityMode", "CloseSessionResponse", "CloseSessionRquest",
  35. "ActivateSessionRequest", "ActivateSessionResponse", "SignatureData", "SignedSoftwareCertificate",
  36. "CreateSessionResponse", "CreateSessionRequest", "EndpointDescription", "UserTokenPolicy", "UserTokenType",
  37. "GetEndpointsRequest", "GetEndpointsResponse", "PublishRequest", "PublishResponse", "FindServersRequest", "FindServersResponse",
  38. "SetPublishingModeResponse", "SubscriptionAcknowledgement", "NotificationMessage", "ExtensionObject",
  39. "Structure", "ReadRequest", "ReadResponse", "ReadValueId", "TimestampsToReturn", "WriteRequest",
  40. "WriteResponse", "WriteValue", "SetPublishingModeRequest", "CreateMonitoredItemsResponse",
  41. "MonitoredItemCreateResult", "CreateMonitoredItemsRequest", "MonitoredItemCreateRequest",
  42. "MonitoringMode", "MonitoringParameters", "TranslateBrowsePathsToNodeIdsRequest",
  43. "TranslateBrowsePathsToNodeIdsResponse", "BrowsePath", "BrowsePathResult", "RelativePath",
  44. "BrowsePathTarget", "RelativePathElement", "CreateSubscriptionRequest", "CreateSubscriptionResponse",
  45. "BrowseResponse", "BrowseResult", "ReferenceDescription", "BrowseRequest", "ViewDescription",
  46. "BrowseDescription", "BrowseDirection", "CloseSessionRequest", "AddNodesRequest", "AddNodesResponse",
  47. "AddNodesItem", "AddNodesResult", "DeleteNodesItem","AddReferencesRequest", "AddReferencesResponse",
  48. "AddReferencesItem","DeleteReferencesItem", "VariableNode", "MethodNode", "VariableTypeNode",
  49. "ViewNode", "ReferenceTypeNode", "BrowseResultMask", "ServerState", "ServerStatusDataType", "BuildInfo",
  50. "ObjectNode", "DataTypeNode", "ObjectTypeNode", "IdType", "VariableAttributes", "ObjectAttributes",
  51. "NodeAttributes","ReferenceTypeAttributes", "ViewAttributes", "ObjectTypeAttributes",
  52. "NodeAttributesMask","DeleteNodesItem", "DeleteNodesRequest", "DeleteNodesResponse",
  53. "DeleteReferencesItem", "DeleteReferencesRequest", "DeleteReferencesResponse",
  54. "RegisterNodesRequest", "RegisterNodesResponse", "UnregisterNodesRequest", "UnregisterNodesResponse"]
  55. class TypeDescription(object):
  56. def __init__(self, name, nodeid, namespaceid):
  57. self.name = name # without the UA_ prefix
  58. self.nodeid = nodeid
  59. self.namespaceid = namespaceid
  60. def parseTypeDescriptions(filename, namespaceid):
  61. definitions = {}
  62. f = open(filename[0])
  63. input_str = f.read()
  64. f.close()
  65. input_str = input_str.replace('\r','')
  66. rows = map(lambda x:tuple(x.split(',')), input_str.split('\n'))
  67. for index, row in enumerate(rows):
  68. if len(row) < 3:
  69. continue
  70. if row[2] != "DataType":
  71. continue
  72. if row[0] == "BaseDataType":
  73. definitions["UA_Variant"] = TypeDescription(row[0], row[1], namespaceid)
  74. elif row[0] == "Structure":
  75. definitions["UA_ExtensionObject"] = TypeDescription(row[0], row[1], namespaceid)
  76. else:
  77. definitions["UA_" + row[0]] = TypeDescription(row[0], row[1], namespaceid)
  78. return definitions
  79. class BuiltinType(object):
  80. "Generic type without members. Used for builtin types."
  81. def __init__(self, name, description = ""):
  82. self.name = name
  83. self.description = description
  84. def fixed_size(self):
  85. return self.name in fixed_size
  86. def mem_size(self):
  87. return fixed_size[self.name]
  88. def zero_copy(self):
  89. return self.name in zero_copy
  90. def typedef_c(self):
  91. pass
  92. def typelayout_c(self, namespace_0, description, outname):
  93. if description == None:
  94. typeid = "{.namespaceIndex = 0, .identifierType = UA_NODEIDTYPE_NUMERIC, .identifier.numeric = 0}, "
  95. else:
  96. typeid = "{.namespaceIndex = %s, .identifierType = UA_NODEIDTYPE_NUMERIC, .identifier.numeric = %s}, " % \
  97. (description.namespaceid, description.nodeid)
  98. if self.name in ["UA_String", "UA_ByteString", "UA_XmlElement"]:
  99. return "{.typeId = " + typeid + \
  100. ".memSize = sizeof(" + self.name + "), " + \
  101. ".namespaceZero = UA_TRUE, .fixedSize = UA_FALSE, .zeroCopyable = UA_FALSE, " + \
  102. ".membersSize = 1,\n\t.members = {{.memberTypeIndex = UA_TYPES_BYTE, .namespaceZero = UA_TRUE, " + \
  103. ".padding = offsetof(UA_String, data) - sizeof(UA_Int32), .isArray = UA_TRUE }}, " + \
  104. ".typeIndex = %s }" % (outname.upper() + "_" + self.name[3:].upper())
  105. if self.name == "UA_QualifiedName":
  106. return "{.typeId = " + typeid + \
  107. ".memSize = sizeof(UA_QualifiedName), " + \
  108. ".namespaceZero = UA_TRUE, .fixedSize = UA_FALSE, .zeroCopyable = UA_FALSE, " + \
  109. ".membersSize = 2, .members = {" + \
  110. "\n\t{.memberTypeIndex = UA_TYPES_UINT16, .namespaceZero = UA_TRUE, " + \
  111. ".padding = 0, .isArray = UA_FALSE }," + \
  112. "\n\t{.memberTypeIndex = UA_TYPES_STRING, .namespaceZero = UA_TRUE, " + \
  113. ".padding = offsetof(UA_QualifiedName, name) - sizeof(UA_UInt16), .isArray = UA_FALSE }},\n" + \
  114. ".typeIndex = UA_TYPES_QUALIFIEDNAME }"
  115. return "{.typeId = " + typeid + \
  116. ".memSize = sizeof(" + self.name + "), " + \
  117. ".namespaceZero = UA_TRUE, " + \
  118. ".fixedSize = " + ("UA_TRUE" if self.fixed_size() else "UA_FALSE") + \
  119. ", .zeroCopyable = " + ("UA_TRUE" if self.zero_copy() else "UA_FALSE") + \
  120. ", .membersSize = 1,\n\t.members = {{.memberTypeIndex = UA_TYPES_" + self.name[3:].upper() + "," + \
  121. ".namespaceZero = UA_TRUE, .padding = 0, .isArray = UA_FALSE }}, " + \
  122. ".typeIndex = %s }" % (outname.upper() + "_" + self.name[3:].upper())
  123. class EnumerationType(object):
  124. def __init__(self, name, description = "", elements = OrderedDict()):
  125. self.name = name
  126. self.description = description
  127. self.elements = elements # maps a name to an integer value
  128. def append_enum(name, value):
  129. self.elements[name] = value
  130. def fixed_size(self):
  131. return True
  132. def mem_size(self):
  133. return 4
  134. def zero_copy(self):
  135. return True
  136. def typedef_c(self):
  137. return "typedef enum { \n " + \
  138. ",\n ".join(map(lambda (key,value) : key.upper() + " = " + value,self.elements.iteritems())) + \
  139. "\n} " + self.name + ";"
  140. def typelayout_c(self, namespace_0, description, outname):
  141. if description == None:
  142. typeid = "{.namespaceIndex = 0, .identifierType = UA_NODEIDTYPE_NUMERIC, .identifier.numeric = 0}, "
  143. else:
  144. typeid = "{.namespaceIndex = %s, .identifierType = UA_NODEIDTYPE_NUMERIC, .identifier.numeric = %s}, " % (description.namespaceid, description.nodeid)
  145. return "{.typeId = " + typeid + \
  146. ".memSize = sizeof(" + self.name + "), " +\
  147. ".namespaceZero = UA_TRUE, " + \
  148. ".fixedSize = UA_TRUE, .zeroCopyable = UA_TRUE, " + \
  149. ".membersSize = 1,\n\t.members = {{.memberTypeIndex = UA_TYPES_INT32," + \
  150. ".namespaceZero = UA_TRUE, .padding = 0, .isArray = UA_FALSE }}, .typeIndex = UA_TYPES_INT32 }"
  151. def functions_c(self, typeTableName):
  152. return '''#define %s_new (%s*)UA_Int32_new
  153. #define %s_init(p) UA_Int32_init((UA_Int32*)p)
  154. #define %s_delete(p) UA_Int32_delete((UA_Int32*)p)
  155. #define %s_deleteMembers(p) UA_Int32_deleteMembers((UA_Int32*)p)
  156. #define %s_copy(src, dst) UA_Int32_copy((const UA_Int32*)src, (UA_Int32*)dst)
  157. #define %s_calcSizeBinary(p) UA_Int32_calcSizeBinary((UA_Int32*)p)
  158. #define %s_encodeBinary(src, dst, offset) UA_Int32_encodeBinary((UA_Int32*)src, dst, offset)
  159. #define %s_decodeBinary(src, offset, dst) UA_Int32_decodeBinary(src, offset, (UA_Int32*)dst)''' % tuple(itertools.repeat(self.name, 9))
  160. class OpaqueType(object):
  161. def __init__(self, name, description = ""):
  162. self.name = name
  163. self.description = description
  164. def fixed_size(self):
  165. return False
  166. def zero_copy(self):
  167. return False
  168. def typedef_c(self):
  169. return "typedef UA_ByteString " + self.name + ";"
  170. def typelayout_c(self, namespace_0, description, outname):
  171. if description == None:
  172. typeid = "{.namespaceIndex = 0, .identifierType = UA_NODEIDTYPE_NUMERIC, .identifier.numeric = 0}, "
  173. else:
  174. typeid = "{.namespaceIndex = %s, .identifierType = UA_NODEIDTYPE_NUMERIC, .identifier.numeric = %s}, " % (description.namespaceid, description.nodeid)
  175. return "{.typeId = " + typeid + \
  176. ".memSize = sizeof(" + self.name + "), .fixedSize = UA_FALSE, .zeroCopyable = UA_FALSE, " + \
  177. ".namespaceZero = UA_TRUE, .membersSize = 1,\n\t.members = {{.memberTypeIndex = UA_TYPES_BYTESTRING," + \
  178. ".namespaceZero = UA_TRUE, .padding = 0, .isArray = UA_FALSE }}, .typeIndex = UA_TYPES_BYTESTRING }"
  179. def functions_c(self, typeTableName):
  180. return '''#define %s_new UA_ByteString_new
  181. #define %s_init UA_ByteString_init
  182. #define %s_delete UA_ByteString_delete
  183. #define %s_deleteMembers UA_ByteString_deleteMembers
  184. #define %s_copy UA_ByteString_copy
  185. #define %s_calcSizeBinary UA_ByteString_calcSizeBinary
  186. #define %s_encodeBinary UA_ByteString_encodeBinary
  187. #define %s_decodeBinary UA_ByteString_decodeBinary''' % tuple(itertools.repeat(self.name, 8))
  188. class StructMember(object):
  189. def __init__(self, name, memberType, isArray):
  190. self.name = name
  191. self.memberType = memberType
  192. self.isArray = isArray
  193. class StructType(object):
  194. def __init__(self, name, description, members = OrderedDict()):
  195. self.name = name
  196. self.description = description
  197. self.members = members # maps a name to a member definition
  198. def fixed_size(self):
  199. for m in self.members.values():
  200. if m.isArray or not m.memberType.fixed_size():
  201. return False
  202. return True
  203. def mem_size(self):
  204. total = 0
  205. for m in self.members.values():
  206. if m.isArray:
  207. raise Exception("Arrays have no fixed size!")
  208. else:
  209. total += m.memberType.mem_size()
  210. return total
  211. def zero_copy(self):
  212. for m in self.members.values():
  213. if m.isArray or not m.memberType.zero_copy():
  214. return False
  215. return True
  216. def typedef_c(self):
  217. if len(self.members) == 0:
  218. return "typedef void * " + self.name + ";"
  219. returnstr = "typedef struct {\n"
  220. for name, member in self.members.iteritems():
  221. if member.isArray:
  222. returnstr += " UA_Int32 " + name + "Size;\n"
  223. returnstr += " " + member.memberType.name + " *" +name + ";\n"
  224. else:
  225. returnstr += " " + member.memberType.name + " " +name + ";\n"
  226. return returnstr + "} " + self.name + ";"
  227. def typelayout_c(self, namespace_0, description, outname):
  228. if description == None:
  229. typeid = "{.namespaceIndex = 0, .identifierType = UA_NODEIDTYPE_NUMERIC, .identifier.numeric = 0}, "
  230. else:
  231. typeid = "{.namespaceIndex = %s, .identifierType = UA_NODEIDTYPE_NUMERIC, .identifier.numeric = %s}, " % (description.namespaceid, description.nodeid)
  232. layout = "{.typeId = "+ typeid + \
  233. ".memSize = sizeof(" + self.name + "), "+ \
  234. ".namespaceZero = " + ("UA_TRUE" if namespace_0 else "UA_FALSE") + \
  235. ", .fixedSize = " + ("UA_TRUE" if self.fixed_size() else "UA_FALSE") + \
  236. ", .zeroCopyable = " + ("sizeof(" + self.name + ") == " + str(self.mem_size()) if self.zero_copy() \
  237. else "UA_FALSE") + \
  238. ", .typeIndex = " + outname.upper() + "_" + self.name[3:].upper() + \
  239. ", .membersSize = " + str(len(self.members)) + ","
  240. if len(self.members) > 0:
  241. layout += "\n\t.members={"
  242. for index, member in enumerate(self.members.values()):
  243. layout += "\n\t{" + \
  244. ".memberTypeIndex = " + ("UA_TYPES_" + member.memberType.name[3:].upper() if args.namespace_id == 0 or member.memberType.name in existing_types else \
  245. outname.upper() + "_" + member.memberType.name[3:].upper()) + ", " + \
  246. ".namespaceZero = "+ \
  247. ("UA_TRUE, " if args.namespace_id == 0 or member.memberType.name in existing_types else "UA_FALSE, ") + \
  248. ".padding = "
  249. before_endpos = "0"
  250. thispos = "offsetof(%s, %s)" % (self.name, member.name)
  251. if index > 0:
  252. before = self.members.values()[index-1]
  253. before_endpos = "(offsetof(%s, %s)" % (self.name, before.name)
  254. if before.isArray:
  255. before_endpos += " + sizeof(void*))"
  256. else:
  257. before_endpos += " + sizeof(%s))" % before.memberType.name
  258. if member.isArray:
  259. # the first two bytes are padding for the length index, the last three for the pointer
  260. length_pos = "offsetof(%s, %sSize)" % (self.name, member.name)
  261. if index != 0:
  262. layout += "((%s - %s) << 3) + " % (length_pos, before_endpos)
  263. layout += "(%s - sizeof(UA_Int32) - %s)" % (thispos, length_pos)
  264. else:
  265. layout += "%s - %s" % (thispos, before_endpos)
  266. layout += ", .isArray = " + ("UA_TRUE" if member.isArray else "UA_FALSE") + " }, "
  267. layout += "}"
  268. return layout + "}"
  269. def functions_c(self, typeTableName):
  270. return '''#define %s_new() UA_new(%s)
  271. #define %s_init(p) UA_init(p, %s)
  272. #define %s_delete(p) UA_delete(p, %s)
  273. #define %s_deleteMembers(p) UA_deleteMembers(p, %s)
  274. #define %s_copy(src, dst) UA_copy(src, dst, %s)
  275. #define %s_calcSizeBinary(p) UA_calcSizeBinary(p, %s)
  276. #define %s_encodeBinary(src, dst, offset) UA_encodeBinary(src, %s, dst, offset)
  277. #define %s_decodeBinary(src, offset, dst) UA_decodeBinary(src, offset, dst, %s)''' % \
  278. tuple(itertools.chain(*itertools.repeat([self.name, "&"+typeTableName+"[" + typeTableName + "_" + self.name[3:].upper()+"]"], 8)))
  279. def parseTypeDefinitions(xmlDescription, existing_types = OrderedDict()):
  280. '''Returns an ordered dict that maps names to types. The order is such that
  281. every type depends only on known types. '''
  282. ns = {"opc": "http://opcfoundation.org/BinarySchema/"}
  283. tree = etree.parse(xmlDescription)
  284. typeSnippets = tree.xpath("/opc:TypeDictionary/*[not(self::opc:Import)]", namespaces=ns)
  285. types = OrderedDict(existing_types.items())
  286. # types we do not want to autogenerate
  287. def skipType(name):
  288. if name in builtin_types:
  289. return True
  290. if name in excluded_types:
  291. return True
  292. if outname == "ua_types" and not name[3:] in minimal_types:
  293. return True
  294. if "Test" in name: # skip all test types
  295. return True
  296. if re.search("NodeId$", name) != None:
  297. return True
  298. return False
  299. def stripTypename(tn):
  300. return tn[tn.find(":")+1:]
  301. def camlCase2CCase(item):
  302. "Member names begin with a lower case character"
  303. return item[:1].lower() + item[1:] if item else ''
  304. def typeReady(element):
  305. "Do we have the member types yet?"
  306. for child in element:
  307. if child.tag == "{http://opcfoundation.org/BinarySchema/}Field":
  308. if stripTypename(child.get("TypeName")) not in types:
  309. return False
  310. return True
  311. def parseEnumeration(typeXml):
  312. name = "UA_" + typeXml.get("Name")
  313. description = ""
  314. elements = OrderedDict()
  315. for child in typeXml:
  316. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  317. description = child.text
  318. if child.tag == "{http://opcfoundation.org/BinarySchema/}EnumeratedValue":
  319. elements[name + "_" + child.get("Name")] = child.get("Value")
  320. return EnumerationType(name, description, elements)
  321. def parseOpaque(typeXml):
  322. name = "UA_" + typeXml.get("Name")
  323. description = ""
  324. for child in typeXml:
  325. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  326. description = child.text
  327. return OpaqueType(name, description)
  328. def parseStructured(typeXml):
  329. "Returns None if we miss member descriptions"
  330. name = "UA_" + typeXml.get("Name")
  331. description = ""
  332. for child in typeXml:
  333. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  334. description = child.text
  335. # ignore lengthfields, just tag the array-members as an array
  336. lengthfields = []
  337. for child in typeXml:
  338. if child.get("LengthField"):
  339. lengthfields.append(child.get("LengthField"))
  340. members = OrderedDict()
  341. for child in typeXml:
  342. if not child.tag == "{http://opcfoundation.org/BinarySchema/}Field":
  343. continue
  344. if child.get("Name") in lengthfields:
  345. continue
  346. memberTypeName = "UA_" + stripTypename(child.get("TypeName"))
  347. if not memberTypeName in types:
  348. return None
  349. memberType = types[memberTypeName]
  350. memberName = camlCase2CCase(child.get("Name"))
  351. isArray = True if child.get("LengthField") else False
  352. members[memberName] = StructMember(memberName, memberType, isArray)
  353. return StructType(name, description, members)
  354. finished = False
  355. while(not finished):
  356. finished = True
  357. for typeXml in typeSnippets:
  358. name = "UA_" + typeXml.get("Name")
  359. if name in types or skipType(name):
  360. continue
  361. if typeXml.tag == "{http://opcfoundation.org/BinarySchema/}EnumeratedType":
  362. t = parseEnumeration(typeXml)
  363. types[t.name] = t
  364. elif typeXml.tag == "{http://opcfoundation.org/BinarySchema/}OpaqueType":
  365. t = parseOpaque(typeXml)
  366. types[t.name] = t
  367. elif typeXml.tag == "{http://opcfoundation.org/BinarySchema/}StructuredType":
  368. t = parseStructured(typeXml)
  369. if t == None:
  370. finished = False
  371. else:
  372. types[t.name] = t
  373. # remove the existing types
  374. for k in existing_types.keys():
  375. types.pop(k)
  376. return types
  377. parser = argparse.ArgumentParser()
  378. parser.add_argument('--ns0-types-xml', nargs=1, help='xml-definition of the ns0 types that are assumed to already exist')
  379. parser.add_argument('--typedescriptions', nargs=1, help='csv file with type descriptions')
  380. parser.add_argument('namespace_id', type=int, help='the id of the target namespace')
  381. parser.add_argument('types_xml', help='path/to/Opc.Ua.Types.bsd')
  382. parser.add_argument('outfile', help='output file w/o extension')
  383. args = parser.parse_args()
  384. outname = args.outfile.split("/")[-1]
  385. inname = args.types_xml.split("/")[-1]
  386. existing_types = OrderedDict()
  387. if args.namespace_id == 0 or args.ns0_types_xml:
  388. existing_types = OrderedDict([(t, BuiltinType(t)) for t in builtin_types])
  389. if args.ns0_types_xml:
  390. OrderedDict(existing_types.items() + parseTypeDefinitions(args.ns0_types_xml[0], existing_types).items())
  391. types = parseTypeDefinitions(args.types_xml, existing_types)
  392. if args.namespace_id == 0:
  393. types = OrderedDict(existing_types.items() + types.items())
  394. typedescriptions = {}
  395. if args.typedescriptions:
  396. typedescriptions = parseTypeDescriptions(args.typedescriptions, args.namespace_id)
  397. fh = open(args.outfile + "_generated.h",'w')
  398. fc = open(args.outfile + "_generated.c",'w')
  399. def printh(string):
  400. print(string, end='\n', file=fh)
  401. def printc(string):
  402. print(string, end='\n', file=fc)
  403. printh('''/**
  404. * @file ''' + outname + '''_generated.h
  405. *
  406. * @brief Autogenerated data types
  407. *
  408. * Generated from ''' + inname + ''' with script ''' + sys.argv[0] + '''
  409. * on host ''' + platform.uname()[1] + ''' by user ''' + getpass.getuser() + ''' at ''' + time.strftime("%Y-%m-%d %I:%M:%S") + '''
  410. */
  411. #ifndef ''' + outname.upper() + '''_GENERATED_H_
  412. #define ''' + outname.upper() + '''_GENERATED_H_
  413. #ifdef __cplusplus
  414. extern "C" {
  415. #endif
  416. #include "ua_types.h" '''
  417. + ('\n#include "ua_types_generated.h"\n' if args.namespace_id != 0 else '') + '''
  418. /**
  419. * @ingroup types
  420. *
  421. * @defgroup ''' + outname + '''_generated Autogenerated ''' + outname + ''' Types
  422. *
  423. * @brief Data structures that are autogenerated from an XML-Schema.
  424. *
  425. * @{
  426. */
  427. ''')
  428. printh("#define " + outname.upper() + "_COUNT %s\n" % (str(len(types))))
  429. printh("extern UA_EXPORT const UA_DataType *" + outname.upper() + ";\n")
  430. i = 0
  431. for t in types.itervalues():
  432. if type(t) != BuiltinType:
  433. printh("")
  434. if t.description != "":
  435. printh("/** @brief " + t.description + " */")
  436. printh(t.typedef_c())
  437. printh("#define " + outname.upper() + "_" + t.name[3:].upper() + " " + str(i))
  438. if type(t) != BuiltinType:
  439. printh(t.functions_c(outname.upper()))
  440. i += 1
  441. printh('''
  442. /// @} /* end of group */\n
  443. #ifdef __cplusplus
  444. } // extern "C"
  445. #endif\n
  446. #endif /* %s_GENERATED_H_ */''' % outname.upper())
  447. printc('''/**
  448. * @file ''' + outname + '''_generated.c
  449. *
  450. * @brief Autogenerated data types
  451. *
  452. * Generated from ''' + inname + ''' with script ''' + sys.argv[0] + '''
  453. * on host ''' + platform.uname()[1] + ''' by user ''' + getpass.getuser() + ''' at ''' + time.strftime("%Y-%m-%d %I:%M:%S") + '''
  454. */\n
  455. #include "stddef.h"
  456. #include "ua_types.h"
  457. #include "''' + outname + '''_generated.h"\n
  458. const UA_DataType *''' + outname.upper() + ''' = (UA_DataType[]){''')
  459. for t in types.itervalues():
  460. printc("")
  461. printc("/* " + t.name + " */")
  462. if args.typedescriptions:
  463. td = typedescriptions[t.name]
  464. else:
  465. td = None
  466. printc(t.typelayout_c(args.namespace_id == 0, td, outname) + ",")
  467. printc("};\n")
  468. # if args.typedescriptions:
  469. # printc('const UA_UInt32 *' + outname.upper() + '_IDS = (UA_UInt32[]){')
  470. # for t in types.itervalues():
  471. # print(str(typedescriptions[t.name].nodeid) + ", ", end='', file=fc)
  472. # printc("};")
  473. fh.close()
  474. fc.close()