generate_datatypes.py 32 KB

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