generate_datatypes.py 25 KB

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