generate_builtin.py 17 KB

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