generate_datatypes.py 25 KB

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