generate_datatypes.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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. fixed_size = {"UA_Boolean": 1, "UA_SByte": 1, "UA_Byte": 1, "UA_Int16": 2, "UA_UInt16": 2,
  12. "UA_Int32": 4, "UA_UInt32": 4, "UA_Int64": 8, "UA_UInt64": 8, "UA_Float": 4,
  13. "UA_Double": 8, "UA_DateTime": 8, "UA_Guid": 16, "UA_StatusCode": 4}
  14. zero_copy = ["UA_Boolean", "UA_SByte", "UA_Byte", "UA_Int16", "UA_UInt16", "UA_Int32", "UA_UInt32",
  15. "UA_Int64", "UA_UInt64", "UA_Float", "UA_Double", "UA_DateTime", "UA_StatusCode"]
  16. # The order of the builtin-types is not as in the standard. We put all the
  17. # fixed_size types in the front, so they can be distinguished by a simple geq
  18. # comparison. That's ok, since we use the type-index only internally!!
  19. builtin_types = ["UA_Boolean", "UA_SByte", "UA_Byte", # 1 byte
  20. "UA_Int16", "UA_UInt16", # 2 bytes
  21. "UA_Int32", "UA_UInt32", "UA_StatusCode", "UA_Float", # 4 byte
  22. "UA_Int64", "UA_UInt64", "UA_Double", "UA_DateTime", # 8 byte
  23. "UA_Guid", "UA_NodeId", "UA_ExpandedNodeId", "UA_QualifiedName", "UA_LocalizedText", "UA_ExtensionObject", "UA_DataValue", "UA_Variant", "UA_DiagnosticInfo", # fancy types
  24. "UA_String", "UA_ByteString", "UA_XmlElement" # strings (handled as structured types with a single array entry)
  25. ]
  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. class TypeDescription(object):
  32. def __init__(self, name, nodeid, namespaceid):
  33. self.name = name # without the UA_ prefix
  34. self.nodeid = nodeid
  35. self.namespaceid = namespaceid
  36. def parseTypeDescriptions(filename, namespaceid):
  37. definitions = {}
  38. f = open(filename[0])
  39. input_str = f.read()
  40. f.close()
  41. input_str = input_str.replace('\r','')
  42. rows = map(lambda x:tuple(x.split(',')), input_str.split('\n'))
  43. for index, row in enumerate(rows):
  44. if len(row) < 3:
  45. continue
  46. if row[2] != "DataType":
  47. continue
  48. if row[0] == "BaseDataType":
  49. definitions["UA_Variant"] = TypeDescription(row[0], row[1], namespaceid)
  50. elif row[0] == "Structure":
  51. definitions["UA_ExtensionObject"] = TypeDescription(row[0], row[1], namespaceid)
  52. else:
  53. definitions["UA_" + row[0]] = TypeDescription(row[0], row[1], namespaceid)
  54. return definitions
  55. class BuiltinType(object):
  56. "Generic type without members. Used for builtin types."
  57. def __init__(self, name, description = ""):
  58. self.name = name
  59. self.description = description
  60. def fixed_size(self):
  61. return self.name in fixed_size
  62. def mem_size(self):
  63. return fixed_size[self.name]
  64. def zero_copy(self):
  65. return self.name in zero_copy
  66. def typedef_c(self):
  67. pass
  68. def typelayout_c(self, namespace_0, outname):
  69. return "{.memSize = sizeof(" + self.name + "), " + \
  70. ".namespaceZero = UA_TRUE, " + \
  71. ".fixedSize = " + ("UA_TRUE" if self.fixed_size() else "UA_FALSE") + \
  72. ", .zeroCopyable = " + ("UA_TRUE" if self.zero_copy() else "UA_FALSE") + \
  73. ", .membersSize = 1,\n\t.members = {{.memberTypeIndex = UA_TYPES_" + self.name[3:].upper() + "," + \
  74. ".namespaceZero = UA_TRUE, .padding = 0, .isArray = UA_FALSE }}, " + \
  75. ".typeIndex = %s }" % (outname.upper() + "_" + self.name[3:].upper())
  76. class EnumerationType(object):
  77. def __init__(self, name, description = "", elements = OrderedDict()):
  78. self.name = name
  79. self.description = description
  80. self.elements = elements # maps a name to an integer value
  81. def append_enum(name, value):
  82. self.elements[name] = value
  83. def fixed_size(self):
  84. return True
  85. def mem_size(self):
  86. return 4
  87. def zero_copy(self):
  88. return True
  89. def typedef_c(self):
  90. return "typedef enum { \n " + \
  91. ",\n ".join(map(lambda (key,value) : key.upper() + " = " + value,self.elements.iteritems())) + \
  92. "\n} " + self.name + ";"
  93. def typelayout_c(self, namespace_0, outname):
  94. return "{.memSize = sizeof(" + self.name + "), " +\
  95. ".namespaceZero = " + ("UA_TRUE" if namespace_0 else "UA_FALSE") + \
  96. ", .fixedSize = UA_TRUE, .zeroCopyable = UA_TRUE, " + \
  97. ".membersSize = 1,\n\t.members = {{.memberTypeIndex = UA_TYPES_INT32," + \
  98. ".namespaceZero = UA_TRUE, .padding = 0, .isArray = UA_FALSE }}, .typeIndex = %s }" % (outname.upper() + "_" + self.name[3:].upper())
  99. def functions_c(self, typeTableName):
  100. return '''#define %s_new (%s*)UA_Int32_new
  101. #define %s_init(p) UA_Int32_init((UA_Int32*)p)
  102. #define %s_delete(p) UA_Int32_delete((UA_Int32*)p)
  103. #define %s_deleteMembers(p) UA_Int32_deleteMembers((UA_Int32*)p)
  104. #define %s_copy(src, dst) UA_Int32_copy((const UA_Int32*)src, (UA_Int32*)dst)
  105. #define %s_calcSizeBinary(p) UA_Int32_calcSizeBinary((UA_Int32*)p)
  106. #define %s_encodeBinary(src, dst, offset) UA_Int32_encodeBinary((UA_Int32*)src, dst, offset)
  107. #define %s_decodeBinary(src, offset, dst) UA_Int32_decodeBinary(src, offset, (UA_Int32*)dst)''' % tuple(itertools.repeat(self.name, 9))
  108. class OpaqueType(object):
  109. def __init__(self, name, description = ""):
  110. self.name = name
  111. self.description = description
  112. def fixed_size(self):
  113. return False
  114. def zero_copy(self):
  115. return False
  116. def typedef_c(self):
  117. return "typedef UA_ByteString " + self.name + ";"
  118. def typelayout_c(self, namespace_0, outname):
  119. return "{.memSize = sizeof(" + self.name + "), .fixedSize = UA_FALSE, .zeroCopyable = UA_FALSE, " + \
  120. ".namespaceZero = " + ("UA_TRUE" if namespace_0 else "UA_FALSE") + \
  121. ", .membersSize = 1,\n\t.members = {{.memberTypeIndex = UA_TYPES_BYTESTRING," + \
  122. ".namespaceZero = UA_TRUE, .padding = 0, .isArray = UA_FALSE }}, .typeIndex = %s }" % (outname.upper() + "_" + self.name[3:].upper())
  123. def functions_c(self, typeTableName):
  124. return '''#define %s_new UA_ByteString_new
  125. #define %s_init UA_ByteString_init
  126. #define %s_delete UA_ByteString_delete
  127. #define %s_deleteMembers UA_ByteString_deleteMembers
  128. #define %s_copy UA_ByteString_copy
  129. #define %s_calcSizeBinary UA_ByteString_calcSizeBinary
  130. #define %s_encodeBinary UA_ByteString_encodeBinary
  131. #define %s_decodeBinary UA_ByteString_decodeBinary''' % tuple(itertools.repeat(self.name, 8))
  132. class StructMember(object):
  133. def __init__(self, name, memberType, isArray):
  134. self.name = name
  135. self.memberType = memberType
  136. self.isArray = isArray
  137. class StructType(object):
  138. def __init__(self, name, description, members = OrderedDict()):
  139. self.name = name
  140. self.description = description
  141. self.members = members # maps a name to a member definition
  142. def fixed_size(self):
  143. for m in self.members.values():
  144. if m.isArray or not m.memberType.fixed_size():
  145. return False
  146. return True
  147. def mem_size(self):
  148. total = 0
  149. for m in self.members.values():
  150. if m.isArray:
  151. raise Exception("Arrays have no fixed size!")
  152. else:
  153. total += m.memberType.mem_size()
  154. return total
  155. def zero_copy(self):
  156. for m in self.members.values():
  157. if m.isArray or not m.memberType.zero_copy():
  158. return False
  159. return True
  160. def typedef_c(self):
  161. if len(self.members) == 0:
  162. return "typedef void * " + self.name + ";"
  163. returnstr = "typedef struct {\n"
  164. for name, member in self.members.iteritems():
  165. if member.isArray:
  166. returnstr += " UA_Int32 " + name + "Size;\n"
  167. returnstr += " " + member.memberType.name + " *" +name + ";\n"
  168. else:
  169. returnstr += " " + member.memberType.name + " " +name + ";\n"
  170. return returnstr + "} " + self.name + ";"
  171. def typelayout_c(self, namespace_0, outname):
  172. layout = "{.memSize = sizeof(" + self.name + "), "+ \
  173. ".namespaceZero = " + ("UA_TRUE" if namespace_0 else "UA_FALSE") + \
  174. ", .fixedSize = " + ("UA_TRUE" if self.fixed_size() else "UA_FALSE") + \
  175. ", .zeroCopyable = " + ("sizeof(" + self.name + ") == " + str(self.mem_size()) if self.zero_copy() \
  176. else "UA_FALSE") + \
  177. ", .typeIndex = " + outname.upper() + "_" + self.name[3:].upper() + \
  178. ", .membersSize = " + str(len(self.members)) + ","
  179. if len(self.members) > 0:
  180. layout += "\n\t.members={"
  181. for index, member in enumerate(self.members.values()):
  182. layout += "\n\t{" + \
  183. ".memberTypeIndex = " + ("UA_TYPES_" + member.memberType.name[3:].upper() if args.namespace_id == 0 or member.memberType.name in existing_types else \
  184. outname.upper() + "_" + member.memberType.name[3:].upper()) + ", " + \
  185. ".namespaceZero = "+ \
  186. ("UA_TRUE, " if args.namespace_id == 0 or member.memberType.name in existing_types else "UA_FALSE, ") + \
  187. ".padding = "
  188. before_endpos = "0"
  189. thispos = "offsetof(%s, %s)" % (self.name, member.name)
  190. if index > 0:
  191. before = self.members.values()[index-1]
  192. before_endpos = "(offsetof(%s, %s)" % (self.name, before.name)
  193. if before.isArray:
  194. before_endpos += " + sizeof(void*))"
  195. else:
  196. before_endpos += " + sizeof(%s))" % before.memberType.name
  197. if member.isArray:
  198. # the first two bytes are padding for the length index, the last three for the pointer
  199. length_pos = "offsetof(%s, %sSize)" % (self.name, member.name)
  200. if index != 0:
  201. layout += "((%s - %s) << 3) + " % (length_pos, before_endpos)
  202. layout += "(%s - sizeof(UA_Int32) - %s)" % (thispos, length_pos)
  203. else:
  204. layout += "%s - %s" % (thispos, before_endpos)
  205. layout += ", .isArray = " + ("UA_TRUE" if member.isArray else "UA_FALSE") + " }, "
  206. layout += "}"
  207. return layout + "}"
  208. def functions_c(self, typeTableName):
  209. return '''#define %s_new() UA_new(%s)
  210. #define %s_init(p) UA_init(p, %s)
  211. #define %s_delete(p) UA_delete(p, %s)
  212. #define %s_deleteMembers(p) UA_deleteMembers(p, %s)
  213. #define %s_copy(src, dst) UA_copy(src, dst, %s)
  214. #define %s_calcSizeBinary(p) UA_calcSizeBinary(p, %s)
  215. #define %s_encodeBinary(src, dst, offset) UA_encodeBinary(src, %s, dst, offset)
  216. #define %s_decodeBinary(src, offset, dst) UA_decodeBinary(src, offset, dst, %s)''' % \
  217. tuple(itertools.chain(*itertools.repeat([self.name, "&"+typeTableName+"[" + typeTableName + "_" + self.name[3:].upper()+"]"], 8)))
  218. def parseTypeDefinitions(xmlDescription, existing_types = OrderedDict()):
  219. '''Returns an ordered dict that maps names to types. The order is such that
  220. every type depends only on known types. '''
  221. ns = {"opc": "http://opcfoundation.org/BinarySchema/"}
  222. tree = etree.parse(xmlDescription)
  223. typeSnippets = tree.xpath("/opc:TypeDictionary/*[not(self::opc:Import)]", namespaces=ns)
  224. types = OrderedDict(existing_types.items())
  225. # types we do not want to autogenerate
  226. def skipType(name):
  227. if name in builtin_types:
  228. return True
  229. if name in excluded_types:
  230. return True
  231. if "Test" in name: # skip all test types
  232. return True
  233. if re.search("NodeId$", name) != None:
  234. return True
  235. return False
  236. def stripTypename(tn):
  237. return tn[tn.find(":")+1:]
  238. def camlCase2CCase(item):
  239. "Member names begin with a lower case character"
  240. return item[:1].lower() + item[1:] if item else ''
  241. def typeReady(element):
  242. "Do we have the member types yet?"
  243. for child in element:
  244. if child.tag == "{http://opcfoundation.org/BinarySchema/}Field":
  245. if stripTypename(child.get("TypeName")) not in types:
  246. return False
  247. return True
  248. def parseEnumeration(typeXml):
  249. name = "UA_" + typeXml.get("Name")
  250. description = ""
  251. elements = OrderedDict()
  252. for child in typeXml:
  253. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  254. description = child.text
  255. if child.tag == "{http://opcfoundation.org/BinarySchema/}EnumeratedValue":
  256. elements[name + "_" + child.get("Name")] = child.get("Value")
  257. return EnumerationType(name, description, elements)
  258. def parseOpaque(typeXml):
  259. name = "UA_" + typeXml.get("Name")
  260. description = ""
  261. for child in typeXml:
  262. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  263. description = child.text
  264. return OpaqueType(name, description)
  265. def parseStructured(typeXml):
  266. "Returns None if we miss member descriptions"
  267. name = "UA_" + typeXml.get("Name")
  268. description = ""
  269. for child in typeXml:
  270. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  271. description = child.text
  272. # ignore lengthfields, just tag the array-members as an array
  273. lengthfields = []
  274. for child in typeXml:
  275. if child.get("LengthField"):
  276. lengthfields.append(child.get("LengthField"))
  277. members = OrderedDict()
  278. for child in typeXml:
  279. if not child.tag == "{http://opcfoundation.org/BinarySchema/}Field":
  280. continue
  281. if child.get("Name") in lengthfields:
  282. continue
  283. memberTypeName = "UA_" + stripTypename(child.get("TypeName"))
  284. if not memberTypeName in types:
  285. return None
  286. memberType = types[memberTypeName]
  287. memberName = camlCase2CCase(child.get("Name"))
  288. isArray = True if child.get("LengthField") else False
  289. members[memberName] = StructMember(memberName, memberType, isArray)
  290. return StructType(name, description, members)
  291. finished = False
  292. while(not finished):
  293. finished = True
  294. for typeXml in typeSnippets:
  295. name = "UA_" + typeXml.get("Name")
  296. if name in types or skipType(name):
  297. continue
  298. if typeXml.tag == "{http://opcfoundation.org/BinarySchema/}EnumeratedType":
  299. t = parseEnumeration(typeXml)
  300. types[t.name] = t
  301. elif typeXml.tag == "{http://opcfoundation.org/BinarySchema/}OpaqueType":
  302. t = parseOpaque(typeXml)
  303. types[t.name] = t
  304. elif typeXml.tag == "{http://opcfoundation.org/BinarySchema/}StructuredType":
  305. t = parseStructured(typeXml)
  306. if t == None:
  307. finished = False
  308. else:
  309. types[t.name] = t
  310. # remove the existing types
  311. for k in existing_types.keys():
  312. types.pop(k)
  313. return types
  314. parser = argparse.ArgumentParser()
  315. parser.add_argument('--ns0-types-xml', nargs=1, help='xml-definition of the ns0 types that are assumed to already exist')
  316. parser.add_argument('--typedescriptions', nargs=1, help='csv file with type descriptions')
  317. parser.add_argument('namespace_id', type=int, help='the id of the target namespace')
  318. parser.add_argument('types_xml', help='path/to/Opc.Ua.Types.bsd')
  319. parser.add_argument('outfile', help='output file w/o extension')
  320. args = parser.parse_args()
  321. outname = args.outfile.split("/")[-1]
  322. inname = args.types_xml.split("/")[-1]
  323. existing_types = OrderedDict()
  324. if args.namespace_id == 0 or args.ns0_types_xml:
  325. existing_types = OrderedDict([(t, BuiltinType(t)) for t in builtin_types])
  326. if args.ns0_types_xml:
  327. OrderedDict(existing_types.items() + parseTypeDefinitions(args.ns0_types_xml[0], existing_types).items())
  328. types = parseTypeDefinitions(args.types_xml, existing_types)
  329. if args.namespace_id == 0:
  330. types = OrderedDict(existing_types.items() + types.items())
  331. typedescriptions = {}
  332. if args.typedescriptions:
  333. typedescriptions = parseTypeDescriptions(args.typedescriptions, args.namespace_id)
  334. fh = open(args.outfile + "_generated.h",'w')
  335. fc = open(args.outfile + "_generated.c",'w')
  336. def printh(string):
  337. print(string, end='\n', file=fh)
  338. def printc(string):
  339. print(string, end='\n', file=fc)
  340. printh('''/**
  341. * @file ''' + outname + '''_generated.h
  342. *
  343. * @brief Autogenerated data types
  344. *
  345. * Generated from ''' + inname + ''' with script ''' + sys.argv[0] + '''
  346. * on host ''' + platform.uname()[1] + ''' by user ''' + getpass.getuser() + ''' at ''' + time.strftime("%Y-%m-%d %I:%M:%S") + '''
  347. */
  348. #ifndef ''' + outname.upper() + '''_GENERATED_H_
  349. #define ''' + outname.upper() + '''_GENERATED_H_
  350. #ifdef __cplusplus
  351. extern "C" {
  352. #endif
  353. #include "ua_types.h" '''
  354. + ('\n#include "ua_types_generated.h"\n' if args.namespace_id != 0 else '') + '''
  355. /**
  356. * @ingroup types
  357. *
  358. * @defgroup ''' + outname + '''_generated Autogenerated ''' + outname + ''' Types
  359. *
  360. * @brief Data structures that are autogenerated from an XML-Schema.
  361. *
  362. * @{
  363. */
  364. ''')
  365. printh("#define " + outname.upper() + "_COUNT %s\n" % (str(len(types))))
  366. printh("extern UA_EXPORT const UA_DataType *" + outname.upper() + ";\n")
  367. printh("extern UA_EXPORT const UA_UInt32 *" + outname.upper() + "_IDS;\n")
  368. i = 0
  369. for t in types.itervalues():
  370. if type(t) != BuiltinType:
  371. printh("")
  372. if t.description != "":
  373. printh("/** @brief " + t.description + " */")
  374. printh(t.typedef_c())
  375. printh("#define " + outname.upper() + "_" + t.name[3:].upper() + " " + str(i))
  376. if type(t) != BuiltinType:
  377. printh(t.functions_c(outname.upper()))
  378. i += 1
  379. printh('''
  380. /// @} /* end of group */\n
  381. #ifdef __cplusplus
  382. } // extern "C"
  383. #endif\n
  384. #endif''')
  385. printc('''/**
  386. * @file ''' + outname + '''_generated.c
  387. *
  388. * @brief Autogenerated data types
  389. *
  390. * Generated from ''' + inname + ''' with script ''' + sys.argv[0] + '''
  391. * on host ''' + platform.uname()[1] + ''' by user ''' + getpass.getuser() + ''' at ''' + time.strftime("%Y-%m-%d %I:%M:%S") + '''
  392. */\n
  393. #include "stddef.h"
  394. #include "ua_types.h"
  395. #include "''' + outname + '''_generated.h"\n
  396. const UA_DataType *''' + outname.upper() + ''' = (UA_DataType[]){''')
  397. for t in types.itervalues():
  398. printc("")
  399. printc("/* " + t.name + " */")
  400. printc(t.typelayout_c(args.namespace_id == 0, outname) + ",")
  401. printc("};\n")
  402. if args.typedescriptions:
  403. printc('const UA_UInt32 *' + outname.upper() + '_IDS = (UA_UInt32[]){')
  404. for t in types.itervalues():
  405. print(str(typedescriptions[t.name].nodeid) + ", ", end='', file=fc)
  406. printc("};")
  407. fh.close()
  408. fc.close()