generate_datatypes.py 28 KB

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