generate_namespace.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. from __future__ import print_function
  2. import inspect
  3. import sys
  4. import platform
  5. import getpass
  6. import time
  7. import re
  8. import argparse
  9. parser = argparse.ArgumentParser()
  10. parser.add_argument('--with-xml', action='store_true', help='generate xml encoding')
  11. parser.add_argument('--with-json', action='store_true', help='generate json encoding')
  12. parser.add_argument('nodeids', help='path/to/NodeIds.csv')
  13. parser.add_argument('outfile', help='outfile w/o extension')
  14. args = parser.parse_args()
  15. # types that are to be excluded
  16. exclude_kinds = set(["Object","ObjectType","Variable","Method","ReferenceType"])
  17. exclude_types = set(["Number", "Integer", "UInteger", "Enumeration", "Image", "ImageBMP",
  18. "ImageGIF", "ImageJPG", "ImagePNG", "References", "BaseVariableType",
  19. "BaseDataVariableType", "PropertyType", "DataTypeDescriptionType",
  20. "DataTypeDictionaryType", "NamingRuleType", "IntegerId", "Counter",
  21. "Duration", "NumericRange", "Time", "Date", "UtcTime", "LocaleId",
  22. "UserTokenType", "ApplicationType", "ApplicationInstanceCertificate",
  23. "ServerVendorCapabilityType", "ServerStatusType",
  24. "ServerDiagnosticsSummaryType", "SamplingIntervalDiagnosticsArrayType",
  25. "SamplingIntervalDiagnosticsType", "SubscriptionDiagnosticsArrayType",
  26. "SubscriptionDiagnosticsType", "SessionDiagnosticsArrayType",
  27. "SessionDiagnosticsVariableType", "SessionSecurityDiagnosticsArrayType",
  28. "SessionSecurityDiagnosticsType", "DataItemType", "AnalogItemType",
  29. "DiscreteItemType", "TwoStateDiscreteType", "MultiStateDiscreteType",
  30. "ProgramDiagnosticType", "StateVariableType", "FiniteStateVariableType",
  31. "TransitionVariableType", "FiniteTransitionVariableType", "BuildInfoType",
  32. "TwoStateVariableType", "ConditionVariableType",
  33. "MultiStateValueDiscreteType", "OptionSetType", "ArrayItemType",
  34. "YArrayItemType", "XYArrayItemType", "ImageItemType", "CubeItemType",
  35. "NDimensionArrayItemType"])
  36. fixed_size = ['UA_DeadbandType', 'UA_DataChangeTrigger', 'UA_Guid', 'UA_ApplicationType',
  37. 'UA_ComplexNumberType', 'UA_EnumeratedTestType', 'UA_BrowseResultMask',
  38. 'UA_TimeZoneDataType', 'UA_NodeClass', 'UA_IdType', 'UA_ServiceCounterDataType',
  39. 'UA_Float', 'UA_ModelChangeStructureVerbMask', 'UA_EndpointConfiguration',
  40. 'UA_NodeAttributesMask', 'UA_DataChangeFilter', 'UA_StatusCode',
  41. 'UA_MonitoringFilterResult', 'UA_OpenFileMode', 'UA_SecurityTokenRequestType',
  42. 'UA_ServerDiagnosticsSummaryDataType', 'UA_ElementOperand',
  43. 'UA_AggregateConfiguration', 'UA_UInt64', 'UA_FilterOperator',
  44. 'UA_ReadRawModifiedDetails', 'UA_ServerState', 'UA_FilterOperand',
  45. 'UA_SubscriptionAcknowledgement', 'UA_AttributeWriteMask', 'UA_SByte', 'UA_Int32',
  46. 'UA_Range', 'UA_Byte', 'UA_TimestampsToReturn', 'UA_UserTokenType', 'UA_Int16',
  47. 'UA_XVType', 'UA_AggregateFilterResult', 'UA_Boolean', 'UA_MessageSecurityMode',
  48. 'UA_AxisScaleEnumeration', 'UA_PerformUpdateType', 'UA_UInt16',
  49. 'UA_NotificationData', 'UA_DoubleComplexNumberType', 'UA_HistoryUpdateType',
  50. 'UA_MonitoringFilter', 'UA_NodeIdType', 'UA_BrowseDirection',
  51. 'UA_SamplingIntervalDiagnosticsDataType', 'UA_UInt32', 'UA_ChannelSecurityToken',
  52. 'UA_RedundancySupport', 'UA_MonitoringMode', 'UA_HistoryReadDetails',
  53. 'UA_ExceptionDeviationFormat', 'UA_ComplianceLevel', 'UA_DateTime', 'UA_Int64',
  54. 'UA_Double']
  55. def skipType(row):
  56. if row[0] == "" or row[0] in exclude_types or row[2] in exclude_kinds:
  57. return True
  58. if "Test" in row[0]:
  59. return True
  60. if re.search("Attributes$", row[0]) != None:
  61. return True
  62. return False
  63. f = open(args.nodeids)
  64. input_str = f.read() + "\nInvalidType,0,DataType"
  65. input_str = input_str.replace('\r','')
  66. rows = map(lambda x:tuple(x.split(',')), input_str.split('\n'))
  67. f.close()
  68. fh = open(args.outfile + ".h",'w')
  69. fc = open(args.outfile + ".c",'w')
  70. def printh(string):
  71. print(string % inspect.currentframe().f_back.f_locals, end='\n', file=fh)
  72. def printc(string):
  73. print(string % inspect.currentframe().f_back.f_locals, end='\n', file=fc)
  74. printh('''/**********************************************************
  75. * '''+args.outfile+'''.hgen -- do not modify
  76. **********************************************************
  77. * Generated from '''+args.nodeids+''' with script '''+sys.argv[0]+'''
  78. * on host '''+platform.uname()[1]+''' by user '''+getpass.getuser()+''' at '''+
  79. time.strftime("%Y-%m-%d %I:%M:%S")+'''
  80. **********************************************************/\n
  81. #ifndef ''' + args.outfile.upper().split("/")[-1] + '''_H_
  82. #define ''' + args.outfile.upper().split("/")[-1] + '''_H_\n
  83. #include "util/ua_util.h"
  84. #include "ua_types.h" // definition of UA_VTable and basic UA_Types
  85. #include "ua_types_generated.h"\n
  86. /**
  87. * @brief maps namespace zero nodeId to index into UA_VTable
  88. *
  89. * @param[in] id The namespace zero nodeId
  90. *
  91. * @retval UA_ERR_INVALID_VALUE whenever ns0Id could not be mapped
  92. * @retval the corresponding index into UA_VTable
  93. */\n
  94. UA_Int32 UA_ns0ToVTableIndex(const UA_NodeId *id);\n
  95. extern const UA_VTable UA_;\n
  96. static UA_Int32 phantom_delete(void * p) { return UA_SUCCESS; }
  97. extern const UA_VTable UA_borrowed_;\n
  98. /**
  99. * @brief the set of possible indices into UA_VTable
  100. *
  101. * Enumerated type to define the types that the open62541 stack can handle
  102. */
  103. enum UA_VTableIndex_enum {''')
  104. printc('''/**********************************************************
  105. * '''+args.outfile.split("/")[-1]+'''.cgen -- do not modify
  106. **********************************************************
  107. * Generated from '''+args.nodeids+''' with script '''+sys.argv[0]+'''
  108. * on host '''+platform.uname()[1]+''' by user '''+getpass.getuser() +
  109. ''' at '''+ time.strftime("%Y-%m-%d %I:%M:%S")+'''
  110. **********************************************************/\n
  111. #include "''' + args.outfile.split("/")[-1] + '''.h"\n
  112. UA_Int32 UA_ns0ToVTableIndex(const UA_NodeId *id) {
  113. UA_Int32 retval = 0; // InvalidType
  114. if(id->namespace != 0) return retval;
  115. switch (id->identifier.numeric) {''')
  116. i = 0
  117. for row in rows:
  118. if skipType(row):
  119. continue
  120. if row[0] == "BaseDataType":
  121. name = "UA_Variant"
  122. elif row[0] == "Structure":
  123. name = "UA_ExtensionObject"
  124. else:
  125. name = "UA_" + row[0]
  126. printh("\t"+name.upper()+" = "+str(i)+",")
  127. printc('\tcase '+row[1]+': retval='+name.upper()+'; break; //'+row[2])
  128. i = i+1
  129. printh("};\n")
  130. printc('''\n}\nreturn retval;\n}\n''');
  131. printc('''const UA_VTable UA_ = {
  132. \t.getTypeIndex = UA_ns0ToVTableIndex,
  133. \t.types = (UA_VTable_Entry[]){''')
  134. i = 0
  135. for row in rows:
  136. if skipType(row):
  137. continue
  138. if row[0] == "BaseDataType":
  139. name = "UA_Variant"
  140. elif row[0] == "Structure":
  141. name = "UA_ExtensionObject"
  142. else:
  143. name = "UA_" + row[0]
  144. i=i+1
  145. printh('#define '+name.upper()+'_NS0 '+row[1])
  146. printc("\t{.typeId={.encodingByte = UA_NODEIDTYPE_TWOBYTE, .namespace = 0,.identifier.numeric=" + row[1] + "}" +
  147. ",\n.name=(UA_Byte*)&\"%(name)s\"" +
  148. ",\n.new=(UA_Int32(*)(void **))%(name)s_new" +
  149. ",\n.init=(UA_Int32(*)(void *))%(name)s_init"+
  150. ",\n.copy=(UA_Int32(*)(void const * ,void*))%(name)s_copy" +
  151. ",\n.delete=(UA_Int32(*)(void *))%(name)s_delete" +
  152. ",\n.deleteMembers=(UA_Int32(*)(void *))%(name)s_deleteMembers" +
  153. ",\n#ifdef DEBUG //FIXME: seems to be okay atm, however a pointer to a noop function would be more safe" +
  154. "\n.print=(void(*)(const void *, FILE *))%(name)s_print," +
  155. "\n#endif" +
  156. "\n.memSize=" + ("sizeof(%(name)s)" if (name != "UA_InvalidType") else "0") +
  157. ",\n.dynMembers=" + ("UA_FALSE" if (name in fixed_size) else "UA_TRUE") +
  158. ",\n.encodings={{.calcSize=(UA_calcSize)%(name)s_calcSizeBinary" +
  159. ",\n.encode=(UA_encode)%(name)s_encodeBinary" +
  160. ",\n.decode=(UA_decode)%(name)s_decodeBinary}" +
  161. (",\n{.calcSize=(UA_calcSize)%(name)s_calcSizeXml" +
  162. ",\n.encode=(UA_encode)%(name)s_encodeXml" +
  163. ",\n.decode=(UA_decode)%(name)s_decodeXml}" if (args.with_xml) else "") +
  164. "}},")
  165. printc('''}};''')
  166. printc("UA_VTable_Entry borrowed_types[" + str(i) + "];");
  167. printc("const UA_VTable UA_borrowed_ = {\n"+
  168. "\t.getTypeIndex=UA_ns0ToVTableIndex,\n"+
  169. "\t.types = borrowed_types\n"+
  170. "};")
  171. printh('\n#define SIZE_UA_VTABLE '+str(i));
  172. printh('\n#endif /* OPCUA_NAMESPACE_0_H_ */')
  173. fh.close()
  174. fc.close()