generate_datatypes.py 26 KB

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