generate_builtin.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. from __future__ import print_function
  2. import sys
  3. import time
  4. from collections import OrderedDict
  5. import re
  6. from lxml import etree
  7. if len(sys.argv) != 3:
  8. print("Usage: python generate_builtin.py <path/to/Opc.Ua.Types.bsd> <outfile w/o extension>", file=sys.stdout)
  9. exit(0)
  10. # types that are coded manually
  11. exclude_types = set(["Boolean", "SByte", "Byte", "Int16", "UInt16", "Int32", "UInt32",
  12. "Int64", "UInt64", "Float", "Double", "String", "DateTime", "Guid",
  13. "ByteString", "XmlElement", "NodeId", "ExpandedNodeId", "StatusCode",
  14. "QualifiedName", "LocalizedText", "ExtensionObject", "DataValue",
  15. "Variant", "DiagnosticInfo", "IntegerId"])
  16. elementary_size = dict()
  17. elementary_size["Boolean"] = 1;
  18. elementary_size["SByte"] = 1;
  19. elementary_size["Byte"] = 1;
  20. elementary_size["Int16"] = 2;
  21. elementary_size["UInt16"] = 2;
  22. elementary_size["Int32"] = 4;
  23. elementary_size["UInt32"] = 4;
  24. elementary_size["Int64"] = 8;
  25. elementary_size["UInt64"] = 8;
  26. elementary_size["Float"] = 4;
  27. elementary_size["Double"] = 8;
  28. elementary_size["DateTime"] = 8;
  29. elementary_size["StatusCode"] = 4;
  30. # indefinite_types = ["NodeId", "ExpandedNodeId", "QualifiedName", "LocalizedText", "ExtensionObject", "DataValue", "Variant", "DiagnosticInfo"]
  31. # indefinite_types = ["ExpandedNodeId", "QualifiedName", "ExtensionObject", "DataValue", "Variant", "DiagnosticInfo"]
  32. # LU - pointers only for arrays (ByteString, etc.)
  33. indefinite_types = []
  34. enum_types = []
  35. structured_types = []
  36. # indefinite types cannot be directly contained in a record as they don't have a definite size
  37. printed_types = exclude_types # types that were already printed and which we can use in the structures to come
  38. # types we do not want to autogenerate
  39. def skipType(name):
  40. if name in exclude_types:
  41. return True
  42. if re.search("NodeId$", name) != None:
  43. return True
  44. return False
  45. def stripTypename(tn):
  46. return tn[tn.find(":")+1:]
  47. def camlCase2AdaCase(item):
  48. (newitem, n) = re.subn("(?<!^)(?<![A-Z])([A-Z])", "_\\1", item)
  49. return newitem
  50. def camlCase2CCase(item):
  51. if item in ["Float","Double"]:
  52. return "my" + item
  53. return item[:1].lower() + item[1:] if item else ''
  54. # are the prerequisites in place? if not, postpone.
  55. def printableStructuredType(element):
  56. for child in element:
  57. if child.tag == "{http://opcfoundation.org/BinarySchema/}Field":
  58. typename = stripTypename(child.get("TypeName"))
  59. if typename not in printed_types:
  60. return False
  61. return True
  62. # There three types of types in the bsd file:
  63. # StructuredType, EnumeratedType OpaqueType
  64. def createEnumerated(element):
  65. valuemap = OrderedDict()
  66. name = "UA_" + element.get("Name")
  67. enum_types.append(name)
  68. print("\n/*** " + name + " ***/", end='\n', file=fh)
  69. for child in element:
  70. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  71. print("/* " + child.text + " */", end='\n', file=fh)
  72. if child.tag == "{http://opcfoundation.org/BinarySchema/}EnumeratedValue":
  73. valuemap[name + "_" + child.get("Name")] = child.get("Value")
  74. valuemap = OrderedDict(sorted(valuemap.iteritems(), key=lambda (k,v): int(v)))
  75. print("typedef UA_UInt32 " + name + ";", end='\n', file=fh);
  76. print("enum " + name + "_enum { \n\t" + ",\n\t".join(map(lambda (key, value) : key.upper() + " = " + value, valuemap.iteritems())) + "\n};", end='\n', file=fh)
  77. print("UA_TYPE_METHOD_PROTOTYPES (" + name + ")", end='\n', file=fh)
  78. print("UA_TYPE_METHOD_CALCSIZE_AS("+name+", UA_UInt32)", end='\n', file=fc)
  79. print("UA_TYPE_METHOD_ENCODE_AS("+name+", UA_UInt32)", end='\n', file=fc)
  80. print("UA_TYPE_METHOD_DECODE_AS("+name+", UA_UInt32)", end='\n', file=fc)
  81. print("UA_TYPE_METHOD_DELETE_AS("+name+", UA_UInt32)", end='\n', file=fc)
  82. print("UA_TYPE_METHOD_DELETEMEMBERS_AS("+name+", UA_UInt32)", end='\n', file=fc)
  83. print("UA_TYPE_METHOD_INIT_AS("+name+", UA_UInt32)", end='\n', file=fc)
  84. print("UA_TYPE_METHOD_NEW_DEFAULT("+name+")\n", end='\n', file=fc)
  85. return
  86. def createStructured(element):
  87. valuemap = OrderedDict()
  88. name = "UA_" + element.get("Name")
  89. print("\n/*** " + name + " ***/", end='\n', file=fh)
  90. lengthfields = set()
  91. for child in element:
  92. if child.get("LengthField"):
  93. lengthfields.add(child.get("LengthField"))
  94. for child in element:
  95. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  96. print("/* " + child.text + " */", end='\n', file=fh)
  97. elif child.tag == "{http://opcfoundation.org/BinarySchema/}Field":
  98. if child.get("Name") in lengthfields:
  99. continue
  100. childname = camlCase2CCase(child.get("Name"))
  101. #if childname in printed_types:
  102. # childname = childname + "_Value" # attributes may not have the name of a type
  103. typename = stripTypename(child.get("TypeName"))
  104. if typename in indefinite_types:
  105. valuemap[childname] = typename + "*"
  106. if child.get("LengthField"):
  107. valuemap[childname] = typename + "**"
  108. # elif typename in structured_types:
  109. # valuemap[childname] = typename + "*"
  110. # if child.get("LengthField"):
  111. # valuemap[childname] = typename + "**"
  112. elif child.get("LengthField"):
  113. valuemap[childname] = typename + "**"
  114. else:
  115. valuemap[childname] = typename
  116. # if "Response" in name[len(name)-9:]:
  117. # print("type " + name + " is new Response_Base with "),
  118. # elif "Request" in name[len(name)-9:]:
  119. # print ("type " + name + " is new Request_Base with "),
  120. # else:
  121. # print ("type " + name + " is new UA_Builtin with "),
  122. print("typedef struct T_" + name + " {", end='\n', file=fh)
  123. if len(valuemap) > 0:
  124. for n,t in valuemap.iteritems():
  125. if t.find("**") != -1:
  126. print("\t" + "UA_Int32 " + n + "Size;", end='\n', file=fh)
  127. print("\t" + "UA_" + t + " " + n + ";", end='\n', file=fh)
  128. else:
  129. print("\t/* null record */", end='\n', file=fh)
  130. print("\tUA_Int32 NullRecord; /* avoiding warnings */", end='\n', file=fh)
  131. print("} " + name + ";", end='\n', file=fh)
  132. print("UA_Int32 " + name + "_calcSize(" + name + " const * ptr);", end='\n', file=fh)
  133. print("UA_Int32 " + name + "_encode(" + name + " const * src, UA_Int32* pos, UA_Byte* dst);", end='\n', file=fh)
  134. print("UA_Int32 " + name + "_decode(UA_Byte const * src, UA_Int32* pos, " + name + "* dst);", end='\n', file=fh)
  135. print("UA_Int32 " + name + "_delete("+ name + "* p);", end='\n', file=fh)
  136. print("UA_Int32 " + name + "_deleteMembers(" + name + "* p);", end='\n', file=fh)
  137. print("UA_Int32 " + name + "_init("+ name + " * p);", end='\n', file=fh)
  138. print("UA_Int32 " + name + "_new(" + name + " ** p);", end='\n', file=fh)
  139. print("UA_Int32 " + name + "_calcSize(" + name + " const * ptr) {", end='', file=fc)
  140. print("\n\tif(ptr==UA_NULL){return sizeof("+ name +");}", end='', file=fc)
  141. print("\n\treturn 0", end='', file=fc)
  142. # code _calcSize
  143. for n,t in valuemap.iteritems():
  144. if t in elementary_size:
  145. print('\n\t + sizeof(UA_' + t + ") // " + n, end='', file=fc)
  146. else:
  147. if t in enum_types:
  148. print('\n\t + 4 //' + n, end='', file=fc) # enums are all 32 bit
  149. elif t.find("**") != -1:
  150. print("\n\t + 0 //" + n + "Size is included in UA_Array_calcSize", end='', file=fc),
  151. print("\n\t + UA_Array_calcSize(ptr->" + n + "Size, UA_" + t[0:t.find("*")].upper() + ", (void const**) ptr->" + n +")", end='', file=fc)
  152. elif t.find("*") != -1:
  153. print('\n\t + ' + "UA_" + t[0:t.find("*")] + "_calcSize(ptr->" + n + ')', end='', file=fc)
  154. else:
  155. print('\n\t + ' + "UA_" + t + "_calcSize(&(ptr->" + n + '))', end='', file=fc)
  156. print("\n\t;\n}\n", end='\n', file=fc)
  157. print("UA_Int32 "+name+"_encode("+name+" const * src, UA_Int32* pos, UA_Byte* dst) {\n\tUA_Int32 retval = UA_SUCCESS;", end='\n', file=fc)
  158. # code _encode
  159. for n,t in valuemap.iteritems():
  160. if t in elementary_size:
  161. print('\tretval |= UA_'+t+'_encode(&(src->'+n+'),pos,dst);', end='\n', file=fc)
  162. else:
  163. if t in enum_types:
  164. print('\tretval |= UA_'+t+'_encode(&(src->'+n+'),pos,dst);', end='\n', file=fc)
  165. elif t.find("**") != -1:
  166. print('\t//retval |= UA_Int32_encode(&(src->'+n+'Size),pos,dst); // encode size managed by UA_Array_encode', end='\n', file=fc)
  167. print("\tretval |= UA_Array_encode((void const**) (src->"+n+"),src->"+n+"Size, UA_" + t[0:t.find("*")].upper()+",pos,dst);", end='\n', file=fc)
  168. elif t.find("*") != -1:
  169. print('\tretval |= UA_' + t[0:t.find("*")] + "_encode(src->" + n + ',pos,dst);', end='\n', file=fc)
  170. else:
  171. print('\tretval |= UA_'+t+"_encode(&(src->"+n+"),pos,dst);", end='\n', file=fc)
  172. print("\treturn retval;\n}\n", end='\n', file=fc)
  173. # code _decode
  174. print("UA_Int32 "+name+"_decode(UA_Byte const * src, UA_Int32* pos, " + name + "* dst) {\n\tUA_Int32 retval = UA_SUCCESS;", end='\n', file=fc)
  175. for n,t in valuemap.iteritems():
  176. if t in elementary_size:
  177. print('\tretval |= UA_'+t+'_decode(src,pos,&(dst->'+n+'));', end='\n', file=fc)
  178. else:
  179. if t in enum_types:
  180. print('\tretval |= UA_'+t+'_decode(src,pos,&(dst->'+n+'));', end='\n', file=fc)
  181. elif t.find("**") != -1:
  182. # decode size
  183. print('\tretval |= UA_Int32_decode(src,pos,&(dst->'+n+'Size)); // decode size', end='\n', file=fc)
  184. # allocate memory for array
  185. print("\tretval |= UA_Array_new((void**)&(dst->"+n+"),dst->"+n+"Size,UA_"+t[0:t.find("*")].upper()+");", end='\n', file=fc)
  186. print("\tretval |= UA_Array_decode(src,dst->"+n+"Size, UA_" + t[0:t.find("*")].upper()+",pos,(void ** const) (dst->"+n+"));", end='\n', file=fc) #not tested
  187. elif t.find("*") != -1:
  188. #allocate memory using new
  189. print('\tretval |= UA_'+ t[0:t.find("*")] +"_new(&(dst->" + n + "));", end='\n', file=fc)
  190. print('\tretval |= UA_' + t[0:t.find("*")] + "_decode(src,pos,dst->"+ n +");", end='\n', file=fc)
  191. else:
  192. print('\tretval |= UA_'+t+"_decode(src,pos,&(dst->"+n+"));", end='\n', file=fc)
  193. print("\treturn retval;\n}\n", end='\n', file=fc)
  194. # code _delete and _deleteMembers
  195. print('UA_Int32 '+name+'_delete('+name+'''* p) {
  196. UA_Int32 retval = UA_SUCCESS;
  197. retval |= '''+name+'''_deleteMembers(p);
  198. retval |= UA_free(p);
  199. return retval;
  200. }''', end='\n', file=fc)
  201. print("UA_Int32 "+name+"_deleteMembers(" + name + "* p) {\n\tUA_Int32 retval = UA_SUCCESS;", end='\n', file=fc)
  202. for n,t in valuemap.iteritems():
  203. if t not in elementary_size:
  204. if t.find("**") != -1:
  205. print("\tretval |= UA_Array_delete((void**)p->"+n+",p->"+n+"Size,UA_"+t[0:t.find("*")].upper()+");", end='\n', file=fc) #not tested
  206. elif t.find("*") != -1:
  207. print('\tretval |= UA_' + t[0:t.find("*")] + "_delete(p->"+n+");", end='\n', file=fc)
  208. else:
  209. print('\tretval |= UA_' + t + "_deleteMembers(&(p->"+n+"));", end='\n', file=fc)
  210. print("\treturn retval;\n}\n", end='\n', file=fc)
  211. # code _init
  212. print("UA_Int32 "+name+"_init(" + name + " * p) {\n\tUA_Int32 retval = UA_SUCCESS;", end='\n', file=fc)
  213. for n,t in valuemap.iteritems():
  214. if t in elementary_size:
  215. print('\tretval |= UA_'+t+'_init(&(p->'+n+'));', end='\n', file=fc)
  216. else:
  217. if t in enum_types:
  218. print('\tretval |= UA_'+t+'_init(&(p->'+n+'));', end='\n', file=fc)
  219. elif t.find("**") != -1:
  220. print('\tp->'+n+'Size=0;', end='\n', file=fc)
  221. print("\tp->"+n+"=UA_NULL;", end='\n', file=fc)
  222. elif t.find("*") != -1:
  223. print("\tp->"+n+"=UA_NULL;", end='\n', file=fc)
  224. else:
  225. print('\tretval |= UA_'+t+"_init(&(p->"+n+"));", end='\n', file=fc)
  226. print("\treturn retval;\n}\n", end='\n', file=fc)
  227. # code _new
  228. print("UA_TYPE_METHOD_NEW_DEFAULT(" + name + ")", end='\n', file=fc)
  229. def createOpaque(element):
  230. name = "UA_" + element.get("Name")
  231. print("\n/*** " + name + " ***/", end='\n', file=fh)
  232. for child in element:
  233. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  234. print("/* " + child.text + " */", end='\n', file=fh)
  235. print("typedef UA_ByteString " + name + ";", end='\n', file=fh)
  236. print("UA_TYPE_METHOD_PROTOTYPES (" + name + ")", end='\n', file=fh)
  237. print("UA_TYPE_METHOD_CALCSIZE_AS("+name+", UA_ByteString)", end='\n', file=fc)
  238. print("UA_TYPE_METHOD_ENCODE_AS("+name+", UA_ByteString)", end='\n', file=fc)
  239. print("UA_TYPE_METHOD_DECODE_AS("+name+", UA_ByteString)", end='\n', file=fc)
  240. print("UA_TYPE_METHOD_DELETE_AS("+name+", UA_ByteString)", end='\n', file=fc)
  241. print("UA_TYPE_METHOD_DELETEMEMBERS_AS("+name+", UA_ByteString)", end='\n', file=fc)
  242. print("UA_TYPE_METHOD_INIT_AS("+name+", UA_ByteString)", end='\n', file=fc)
  243. print("UA_TYPE_METHOD_NEW_DEFAULT("+name+")\n", end='\n', file=fc)
  244. return
  245. ns = {"opc": "http://opcfoundation.org/BinarySchema/"}
  246. tree = etree.parse(sys.argv[1])
  247. types = tree.xpath("/opc:TypeDictionary/*[not(self::opc:Import)]", namespaces=ns)
  248. fh = open(sys.argv[2] + ".hgen",'w');
  249. fc = open(sys.argv[2] + ".cgen",'w');
  250. print('''/**********************************************************
  251. * Generated from '''+sys.argv[1]+''' with script '''+sys.argv[0]+'''
  252. * on node XXX by user XXX at '''+ time.strftime("%Y-%m-%d %I:%M:%S")+'''
  253. * do not modify
  254. **********************************************************/
  255. #include "''' + sys.argv[2] + '.h"', end='\n', file=fc);
  256. # types for which we create a vector type
  257. arraytypes = set()
  258. fields = tree.xpath("//opc:Field", namespaces=ns)
  259. for field in fields:
  260. if field.get("LengthField"):
  261. arraytypes.add(stripTypename(field.get("TypeName")))
  262. deferred_types = OrderedDict()
  263. print('''/**********************************************************
  264. * Generated from '''+sys.argv[1]+''' with script '''+sys.argv[0]+'''
  265. * on node XXX by user XXX at '''+ time.strftime("%Y-%m-%d %I:%M:%S")+'''
  266. * do not modify
  267. **********************************************************/
  268. #ifndef OPCUA_H_''', end='\n', file=fh)
  269. print('#define OPCUA_H_', end='\n', file=fh)
  270. print('#include "opcua_basictypes.h"', end='\n', file=fh)
  271. print('#include "opcua_namespace_0.h"', end='\n', file=fh);
  272. #plugin handling
  273. import os
  274. files = [f for f in os.listdir('.') if os.path.isfile(f) and f[-3:] == ".py" and f[:7] == "plugin_"]
  275. plugin_types = []
  276. packageForType = OrderedDict()
  277. for f in files:
  278. package = f[:-3]
  279. exec "import " + package
  280. exec "pluginSetup = " + package + ".setup()"
  281. if pluginSetup["pluginType"] == "structuredObject":
  282. plugin_types.append(pluginSetup["tagName"])
  283. packageForType[pluginSetup["tagName"]] = [package,pluginSetup]
  284. print("Custom object creation for tag " + pluginSetup["tagName"] + " imported from package " + package)
  285. #end plugin handling
  286. for element in types:
  287. name = element.get("Name")
  288. if skipType(name):
  289. continue
  290. if element.tag == "{http://opcfoundation.org/BinarySchema/}EnumeratedType":
  291. createEnumerated(element)
  292. printed_types.add(name)
  293. elif element.tag == "{http://opcfoundation.org/BinarySchema/}StructuredType":
  294. if printableStructuredType(element):
  295. createStructured(element)
  296. structured_types.append(name)
  297. printed_types.add(name)
  298. else: # the record contains types that were not yet detailed
  299. deferred_types[name] = element
  300. continue
  301. elif element.tag == "{http://opcfoundation.org/BinarySchema/}OpaqueType":
  302. createOpaque(element)
  303. printed_types.add(name)
  304. for name, element in deferred_types.iteritems():
  305. if name in plugin_types:
  306. #execute plugin if registered
  307. exec "ret = " + packageForType[name][0]+"."+packageForType[name][1]["functionCall"]
  308. if ret == "default":
  309. createStructured(element)
  310. else:
  311. createStructured(element)
  312. print('#endif /* OPCUA_H_ */', end='\n', file=fh)
  313. fh.close()
  314. fc.close()