generate_protocol.py
Go to the documentation of this file.
1 """
2 Generate address space c++ code from xml file specification
3 """
4 import sys
5 from copy import copy
6 
7 import xml.etree.ElementTree as ET
8 
9 from IPython import embed
10 
11 import generate_model as gm
12 
13 
14 #declare default constructor in header, then constructor must be implemented
15 NeedConstructor = ["RelativePathElement", "OpenSecureChannelParameters", "UserIdentityToken", "RequestHeader", "ResponseHeader", "ReadParameters", "UserIdentityToken", "BrowseDescription", "ReferenceDescription", "CreateSubscriptionParameters", "SubscriptionData", "NotificationMessage", "PublishResult", "PublishResult", "NotificationMessage", "SetPublishingModeParameters"]
16 IgnoredEnums = ["IdType", "NodeIdType"]
17 #by default we split requests and respons in header and parameters, but some are so simple we do not split them
18 NoSplitStruct = ["GetEndpointsResponse", "CloseSessionRequest", "AddNodesResponse", "BrowseResponse", "HistoryReadResponse", "HistoryUpdateResponse", "RegisterServerResponse", "CloseSecureChannelRequest", "CloseSecureChannelResponse", "CloseSessionRequest", "CloseSessionResponse", "UnregisterNodesResponse", "MonitoredItemModifyRequest", "MonitoredItemsCreateRequest", "ReadResponse", "WriteResponse", "TranslateBrowsePathsToNodeIdsResponse", "DeleteSubscriptionsResponse", "DeleteMonitoredItemsResponse", "PublishRequest", "CreateMonitoredItemsResponse", "DeleteMonitoredItemsResponse", "ServiceFault", "AddReferencesRequest", "AddReferencesResponse", "ModifyMonitoredItemsResponse", "CallResponse", "RepublishResponse", "DeleteSubscriptionsRequest", "DeleteSubscriptionsResponse", "DeleteNodesRequest", "DeleteNodesResponse"]
19 OverrideTypes = {"AttributeId": "AttributeId", "ResultMask": "BrowseResultMask", "NodeClassMask": "NodeClass", "AccessLevel": "VariableAccessLevel", "UserAccessLevel": "VariableAccessLevel", "NotificationData": "NotificationData"}
20 OverrideStructTypeName = {"CreateSubscriptionResult": "SubscriptionData", "SetPublishingModeParameters": "PublishingModeParameters", "SetPublishingModeResult": "PublishingModeResult", "CreateMonitoredItemsParameters": "MonitoredItemsParameters"}
21 OverrideNameInStruct = {"CreateSubscriptionResponse": {"Parameters": "Data"}, "SetPublishingModeResponse": {"Parameters": "Result"}}
22 OverrideTypeInStruct = {"ActivateSessionParameters": {"UserIdentityToken": "UserIdentifyToken"}, "MonitoringParameters": {"Filter": "MonitoringFilter"}, "MonitoredItemCreateResult": {"FilterResult": "MonitoringFilter"}}
23 OverrideNames = {"RequestHeader": "Header", "ResponseHeader": "Header", "StatusCode": "Status", "NodesToRead": "AttributesToRead"} # "MonitoringMode": "Mode",, "NotificationMessage": "Notification", "NodeIdType": "Type"}
24 
25 #list of UA structure we want to enable, some structures may
26 #need to be added by hand (those generated from splitted request and response structs)
27 EnabledStructs = [\
28  #we want to implement som struct by hand, to make better interface or simply because they are too complicated
29  #'NodeId',
30  #'TwoByteNodeId',
31  #'FourByteNodeId',
32  #'NumericNodeId',
33  #'StringNodeId',
34  #'GuidNodeId',
35  #'ByteStringNodeId',
36  #'ExpandedNodeId',
37  #'QualifiedName',
38  #'LocalizedText',
39  #'DataValue',
40  #'Variant',
41  #'DiagnosticInfo',
42  #
43  #
44  #structs we should enable or that we haven't checked yet
45  #
46  'ExtensionObject',
47  'XmlElement',
48  #'Node',
49  #'InstanceNode',
50  #'TypeNode',
51  #'ObjectNode',
52  #'ObjectTypeNode',
53  #'VariableNode',
54  #'VariableTypeNode',
55  #'ReferenceTypeNode',
56  #'MethodNode',
57  #'ViewNode',
58  #'DataTypeNode',
59  #'ReferenceNode',
60  #'Argument',
61  #'EnumValueType',
62  #'TimeZoneDataType',
63  'ApplicationDescription',
64  #'RequestHeader',
65  #'ResponseHeader',
66  #'ServiceFault',
67  #'FindServersRequest',
68  #'FindServersResponse',
69  'UserTokenPolicy',
70  'EndpointDescription',
71  'GetEndpointsRequest',
72  'GetEndpointsParameters',
73  'GetEndpointsResponse',
74  #'RegisteredServer',
75  #'RegisterServerRequest',
76  #'RegisterServerResponse',
77  #'ChannelSecurityToken',
78  #'OpenSecureChannelRequest',
79  #'OpenSecureChannelResponse',
80  #'CloseSecureChannelRequest',
81  #'CloseSecureChannelResponse',
82  'SignedSoftwareCertificate',
83  'SignatureData',
84  'CreateSessionRequest',
85  'CreateSessionParameters',
86  'CreateSessionResponse',
87  'CreateSessionResult',
88  #'UserIdentityToken',
89  #'AnonymousIdentityToken',
90  #'UserNameIdentityToken',
91  #'X509IdentityToken',
92  #'IssuedIdentityToken',
93  'ActivateSessionRequest',
94  'ActivateSessionParameters',
95  'ActivateSessionResponse',
96  'ActivateSessionResult',
97  #'CloseSessionRequest',
98  #'CloseSessionResponse',
99  #'CancelRequest',
100  #'CancelResponse',
101  #'NodeAttributes',
102  #'ObjectAttributes',
103  #'VariableAttributes',
104  #'MethodAttributes',
105  #'ObjectTypeAttributes',
106  #'VariableTypeAttributes',
107  #'ReferenceTypeAttributes',
108  #'DataTypeAttributes',
109  #'ViewAttributes',
110  #'AddNodesItem',
111  #'AddNodesResult',
112  #'AddNodesRequest',
113  #'AddNodesResponse',
114  #'AddReferencesItem',
115  #'AddReferencesRequest',
116  #'AddReferencesResponse',
117  'DeleteNodesItem',
118  'DeleteNodesRequest',
119  'DeleteNodesResponse',
120  #'DeleteReferencesItem',
121  #'DeleteReferencesRequest',
122  #'DeleteReferencesResponse',
123  #'ViewDescription',
124  #'BrowseDescription',
125  #'ReferenceDescription',
126  #'BrowseResult',
127  #'BrowseRequest',
128  #'BrowseResponse',
129  #'BrowseNextRequest',
130  #'BrowseNextResponse',
131  #'RelativePathElement',
132  #'RelativePath',
133  #'BrowsePath',
134  #'BrowsePathTarget',
135  #'BrowsePathResult',
136  #'TranslateBrowsePathsToNodeIdsRequest',
137  #'TranslateBrowsePathsToNodeIdsResponse',
138  #'RegisterNodesRequest',
139  #'RegisterNodesResponse',
140  #'UnregisterNodesRequest',
141  #'UnregisterNodesResponse',
142  #'EndpointConfiguration',
143  #'SupportedProfile',
144  #'SoftwareCertificate',
145  #'QueryDataDescription',
146  #'NodeTypeDescription',
147  #'QueryDataSet',
148  #'NodeReference',
149  #'ContentFilterElement',
150  #'ContentFilter',
151  #'FilterOperand',
152  #'ElementOperand',
153  #'LiteralOperand',
154  #'AttributeOperand',
155  #'SimpleAttributeOperand',
156  #'ContentFilterElementResult',
157  #'ContentFilterResult',
158  #'ParsingResult',
159  #'QueryFirstRequest',
160  #'QueryFirstResponse',
161  #'QueryNextRequest',
162  #'QueryNextResponse',
163  'ReadValueId',
164  'ReadRequest',
165  'ReadParameters',
166  'ReadResult',
167  'ReadResponse',
168  #'HistoryReadValueId',
169  #'HistoryReadResult',
170  #'HistoryReadDetails',
171  #'ReadEventDetails',
172  #'ReadRawModifiedDetails',
173  #'ReadProcessedDetails',
174  #'ReadAtTimeDetails',
175  #'HistoryData',
176  #'ModificationInfo',
177  #'HistoryModifiedData',
178  #'HistoryEvent',
179  #'HistoryReadRequest',
180  #'HistoryReadResponse',
181  'WriteValue',
182  'WriteParameters',
183  'WriteRequest',
184  'WriteResponse',
185  'WriteResult',
186  #'HistoryUpdateDetails',
187  #'UpdateDataDetails',
188  #'UpdateStructureDataDetails',
189  #'UpdateEventDetails',
190  #'DeleteRawModifiedDetails',
191  #'DeleteAtTimeDetails',
192  #'DeleteEventDetails',
193  #'HistoryUpdateResult',
194  #'HistoryUpdateEventResult',
195  #'HistoryUpdateRequest',
196  #'HistoryUpdateResponse',
197  'CallMethodRequest',
198  'CallMethodResult',
199  'CallParameters',
200  'CallRequest',
201  'CallResponse',
202  #'MonitoringFilter',
203  #'DataChangeFilter',
204  #'EventFilter',
205  #'AggregateConfiguration',
206  #'AggregateFilter',
207  #'MonitoringFilterResult',
208  #'EventFilterResult',
209  #'AggregateFilterResult',
210  'MonitoringParameters',
211  'MonitoredItemCreateRequest',
212  'MonitoredItemCreateResult',
213  'MonitoredItemsParameters',
214  'CreateMonitoredItemsRequest',
215  'CreateMonitoredItemsResponse',
216  #'MonitoredItemModifyRequest',
217  #'MonitoredItemModifyResult',
218  #'ModifyMonitoredItemsRequest',
219  #'ModifyMonitoredItemsResponse',
220  #'SetMonitoringModeRequest',
221  #'SetMonitoringModeResponse',
222  #'SetTriggeringRequest',
223  #'SetTriggeringResponse',
224  'DeleteMonitoredItemsParameters',
225  'DeleteMonitoredItemsRequest',
226  'DeleteMonitoredItemsResponse',
227  'CreateSubscriptionRequest',
228  'CreateSubscriptionParameters',
229  'SubscriptionData',
230  'CreateSubscriptionResponse',
231  'ModifySubscriptionRequest',
232  'ModifySubscriptionParameters',
233  'ModifySubscriptionResult',
234  'ModifySubscriptionResponse',
235  'SetPublishingModeRequest',
236  'PublishingModeParameters',
237  'SetPublishingModeResponse',
238  'PublishingModeResult',
239  'NotificationMessage',
240  #'NotificationData',
241  #'DataChangeNotification',
242  #'MonitoredItemNotification',
243  #'EventNotificationList',
244  #'EventFieldList',
245  #'HistoryEventFieldList',
246  #'StatusChangeNotification',
247  'SubscriptionAcknowledgement',
248  'PublishRequest',
249  'PublishResult',
250  'PublishResponse',
251  'RepublishParameters',
252  'RepublishRequest',
253  'RepublishResponse',
254  #'TransferResult',
255  #'TransferSubscriptionsRequest',
256  #'TransferSubscriptionsResponse',
257  'DeleteSubscriptionsRequest',
258  'DeleteSubscriptionsResponse',
259  #'ScalarTestType',
260  #'ArrayTestType',
261  #'CompositeTestType',
262  #'TestStackRequest',
263  #'TestStackResponse',
264  #'TestStackExRequest',
265  #'TestStackExResponse',
266  #'BuildInfo',
267  #'RedundantServerDataType',
268  #'EndpointUrlListDataType',
269  #'NetworkGroupDataType',
270  #'SamplingIntervalDiagnosticsDataType',
271  #'ServerDiagnosticsSummaryDataType',
272  #'ServerStatusDataType',
273  #'SessionDiagnosticsDataType',
274  #'SessionSecurityDiagnosticsDataType',
275  #'ServiceCounterDataType',
276  #'StatusResult',
277  #'SubscriptionDiagnosticsDataType',
278  #'ModelChangeStructureDataType',
279  #'SemanticChangeStructureDataType',
280  #'Range',
281  #'EUInformation',
282  #'ComplexNumberType',
283  #'DoubleComplexNumberType',
284  #'AxisInformation',
285  #'XVType',
286  #'ProgramDiagnosticDataType',
287  'Annotation']
288 
289 
290 def reorder_structs(model):
291  types = IgnoredEnums + ["Bit", "Char", "CharArray", "Guid", "SByte", "Int8", "Int16", "Int32", "Int64", "UInt8", "UInt16", "UInt32", "UInt64", "DateTime", "Boolean", "Double", "Float", "ByteString", "Byte", "StatusCode", "DiagnosticInfo", "String", "AttributeId"] + [enum.name for enum in model.enums] + ["VariableAccessLevel"]
292  waiting = {}
293  newstructs = []
294  for s in model.structs:
295  types.append(s.name)
296  s.waitingfor = []
297  ok = True
298  for f in s.fields:
299  if f.uatype not in types:
300  if f.uatype in waiting.keys():
301  waiting[f.uatype].append(s)
302  s.waitingfor.append(f.uatype)
303  else:
304  waiting[f.uatype] = [s]
305  s.waitingfor.append(f.uatype)
306  ok = False
307  if ok:
308  newstructs.append(s)
309  waitings = waiting.pop(s.name, None)
310  if waitings:
311  for s2 in waitings:
312  s2.waitingfor.remove(s.name)
313  if not s2.waitingfor:
314  newstructs.append(s2)
315  if len(model.structs) != len(newstructs):
316  print("Error while reordering structs, some structs could not be reinserted, had {} structs, we now have {} structs".format(len(model.structs), len(newstructs)))
317  s1 = set(model.structs)
318  s2 = set(newstructs)
319  rest = s1 -s2
320  print("Variant" in types)
321  for s in s1-s2:
322  print("{} is waiting for: {}".format(s, s.waitingfor))
323  #print(s1 -s2)
324  #print(waiting)
325  model.structs = newstructs
326 
327 
328 def override_types(model):
329  for struct in model.structs:
330  for field in struct.fields:
331  if field.name in OverrideTypes.keys():
332  field.uatype = OverrideTypes[field.name]
333 
334  if struct.name in OverrideNameInStruct.keys():
335  if field.name in OverrideNameInStruct[struct.name].keys():
336  field.name = OverrideNameInStruct[struct.name][field.name]
337 
338  if struct.name in OverrideTypeInStruct.keys():
339  if field.name in OverrideTypeInStruct[struct.name].keys():
340  field.uatype = OverrideTypeInStruct[struct.name][field.name]
341 
342  if field.uatype in OverrideStructTypeName.keys():
343  field.uatype = OverrideStructTypeName[field.uatype]
344 
345  if struct.name in OverrideStructTypeName.keys():
346  struct.name = OverrideStructTypeName[struct.name]
347 
348 
349 class CodeGenerator(object):
350  def __init__(self, model, h_path, enum_path, size_path, ser_path, deser_path, const_path):
351  self.model = model
352  self.h_path = h_path
353  self.enum_path = enum_path
354  self.rawsize_path = size_path
355  self.serialize_path = ser_path
356  self.deserialize_path = deser_path
357  self.constructors_path = const_path
358  self.h_file = None
359  self.cpp_file = None
360  self.structs = []
361 
362  def run(self):
363  #sys.stderr.write("Generating header file {} and C++ files for XML file {}".format(self.h_path, self.input_path) + "\n")
364  print("Generating: ", self.h_path)
365  self.h_file = open(self.h_path, "w")
366  print("Generating: ", self.enum_path)
367  self.enum_file = open(self.enum_path, "w")
368  print("Generating: ", self.rawsize_path)
369  self.rawsize_file = open(self.rawsize_path, "w")
370  print("Generating: ", self.serialize_path)
371  self.serialize_file = open(self.serialize_path, "w")
372  print("Generating: ", self.deserialize_path)
373  self.deserialize_file = open(self.deserialize_path, "w")
374  print("Generating: ", self.constructors_path)
375  self.constructors_file = open(self.constructors_path, "w")
376 
377  self.make_header_h()
378  self.make_header_enum()
379  self.make_header_rawsize()
380  self.make_header_serialize()
381  self.make_header_deserialize()
382  self.make_header_constructors()
383 
384  for enum in self.model.enums:
385  if not enum.name in IgnoredEnums:
386  self.make_enum_h(enum)
387  self.make_struct_ser(enum)
388  for struct in self.model.structs:
389  self.rename_fields(struct)
390  if struct.name in NeedConstructor:
391  struct.needconstructor = True
392  #if not struct.name.endswith("Node") and not struct.name.endswith("NodeId"):
393  if not struct.name in EnabledStructs:
394  self.write_h("\n/* DISABLED")
395  self.write_size("\n/* DISABLED")
396  self.write_ser("\n/* DISABLED")
397  self.write_deser("\n/* DISABLED")
398  if struct.needconstructor:
399  self.write_const("\n/* DISABLED")
400  self.make_struct_h(struct)
401  self.make_struct_ser(struct)
402  if struct.isrequest:
403  self.make_request_constructors(struct)
404  if not struct.name in EnabledStructs:
405  self.write_h("*/")
406  self.write_size("*/")
407  self.write_ser("*/")
408  self.write_deser("*/")
409  if struct.needconstructor:
410  self.write_const("*/")
411 
412  self.make_footer_h()
413  self.make_footer_enum()
414  self.make_footer_rawsize()
415  self.make_footer_serialize()
416  self.make_footer_deserialize()
417  self.make_footer_constructors()
418 
419  def rename_fields(self, struct):
420  ##gcc does not want member with same name as a type
421  for field in struct.fields:
422  if field.name in OverrideNames:
423  field.name = OverrideNames[field.name]
424  #else:
425  #print("Error name same as type: ", field.name, field.get_ctype(), field.uatype)
426 
427  def make_struct_h(self, struct):
428  self.write_h("")
429  if struct.doc: self.write_h(" //", struct.doc)
430  name = struct.name
431  base = ""
432  #if struct.basetype:
433  #base = " : public " + struct.basetype
434  self.write_h(" struct %s %s\n {""" % (name, base))
435  for field in struct.fields:
436  #if field.sourcetype:
437  #continue
438 
439  if field.get_ctype() == "OpcUa::" + struct.name:
440  #we have a problem selv referensing struct
441  self.write_h(" std::shared_ptr<{}> {};".format(field.get_ctype(), field.name))
442  else:
443  self.write_h(" " , field.get_ctype(), field.name + ";")
444  if struct.needconstructor:
445  self.write_h("\n ", struct.name + "();")
446 
447  self.write_h(" };")
448 
449  def make_raw_size(self, struct):
450  self.write_size("")
451  self.write_size(" template<>")
452  self.write_size(" std::size_t RawSize<{}>(const {}& data)".format(struct.name, struct.name))
453  self.write_size(" {")
454 
455  if type(struct) == gm.Enum:
456  self.write_size(" return sizeof({});".format(struct.get_ctype()))
457  else:
458  self.write_size(" size_t size = 0;")
459  for field in struct.fields:
460  switch = ""
461  if field.switchfield:
462  if field.switchvalue:
463  switch = "if ((data.{}) & (1<<({}))) ".format(field.switchfield, field.switchvalue)
464  else:
465  container = struct.bits[field.switchfield].container
466  idx = struct.bits[field.switchfield].idx
467  switch = "if ((data.{}) & (1<<({}))) ".format(container, idx)
468  prefix = ""
469  if field.get_ctype() == struct.name:
470  prefix = "*"
471  if field.length:
472  self.write_size(" {}size += RawSizeContainer({}data.{});".format(switch, prefix, field.name))
473  else:
474  self.write_size(" {}size += RawSize({}data.{});".format(switch, prefix, field.name))
475  self.write_size(" return size;")
476  self.write_size(" }")
477  self.write_size("")
478 
479  def make_serialize(self, struct):
480  self.write_ser("")
481  self.write_ser(" template<>")
482  self.write_ser(" void DataSerializer::Serialize<{}>(const {}& data)".format(struct.name, struct.name))
483  self.write_ser(" {")
484  if type(struct) == gm.Enum:
485  self.write_ser(" *this << static_cast<{}>(data);".format(struct.get_ctype()))
486  else:
487  for idx, field in enumerate(struct.fields):
488  if field.name == "Body" and idx != (len(struct.fields) - 1):
489  self.write_ser(" int32_t bodylength = RawSize(data) - RawSize(data.Encoding);")
490  self.write_ser(" if ((data.Encoding) & (1<<(0))) bodylength -= RawSize(data.TypeId);")
491  self.write_ser(" *this << bodylength;")
492  continue
493 
494  switch = ""
495  if field.switchfield:
496  if field.switchvalue:
497  switch = "if ((data.{}) & (1<<({}))) ".format(field.switchfield, field.switchvalue)
498  else:
499  container = struct.bits[field.switchfield].container
500  idx = struct.bits[field.switchfield].idx
501  switch = "if ((data.{}) & (1<<({}))) ".format(container, idx)
502  prefix = ""
503  if field.get_ctype() == struct.name:
504  prefix = "*"
505  if field.length:
506  self.write_ser(" {}SerializeContainer(*this, {}data.{});".format(switch, prefix, field.name))
507  else:
508  self.write_ser(" {}*this << {}data.{};".format(switch, prefix, field.name))
509  self.write_ser(" }")
510  self.write_ser("")
511 
512  def make_deserialize(self, struct):
513  self.write_deser("")
514  self.write_deser(" template<>")
515  self.write_deser(" void DataDeserializer::Deserialize<{}>({}& data)".format(struct.name, struct.name))
516  self.write_deser(" {")
517  if type(struct) == gm.Enum:
518  self.write_deser(" {} tmp;".format(struct.get_ctype()))
519  self.write_deser(" *this >> tmp;")
520  #self.write_deser(" data = static_cast<{}>(tmp);".format(struct.get_ctype()))
521  self.write_deser(" data = static_cast<{}>(tmp);".format(struct.name))
522  else:
523  for idx, field in enumerate(struct.fields):
524  if field.name == "Body" and idx != (len(struct.fields) - 1):
525  self.write_deser(" int32_t tmp; //Not used")
526  self.write_deser(" *this >> tmp;")
527  continue
528  switch = ""
529  if field.switchfield:
530  if field.switchvalue:
531  switch = "if ((data.{}) & (1>>({}))) ".format(field.switchfield, field.switchvalue)
532  else:
533  container = struct.bits[field.switchfield].container
534  idx = struct.bits[field.switchfield].idx
535  switch = "if ((data.{}) & (1>>({}))) ".format(container, idx)
536  if field.length:
537  self.write_deser(" {}DeserializeContainer(*this, data.{});".format(switch, field.name))
538  else:
539  self.write_deser(" {}*this >> data.{};".format(switch, field.name))
540  self.write_deser(" }")
541  self.write_deser("")
542 
543  def make_request_constructors(self, struct):
544  if not struct.needconstructor:
545  return
546  self.write_const("")
547  self.write_const(" ", struct.name + "::" + struct.name + "()")
548  #self.write_const(" : TypeId(ObjectId::" + struct.name +"_Encoding_DefaultBinary)")
549  self.write_const(" : TypeId(FourByteNodeId((uint16_t)ObjectId::" + struct.name +"_Encoding_DefaultBinary))")
550  self.write_const(" {")
551  self.write_const(" }")
552 
553  def make_struct_ser(self, struct):
554  self.make_raw_size(struct)
555  self.make_serialize(struct)
556  self.make_deserialize(struct)
557 
558  def make_enum_h(self, enum):
559  self.write_enum("\n")
560  if enum.doc: self.write_enum(" //", enum.doc)
561  self.write_enum(" enum class %s : %s\n {" % (enum.name, self.to_enum_type(enum.uatype)))
562  for val in enum.values:
563  self.write_enum(" ", val.name, "=", val.value + ",")
564  self.write_enum(" };")
565  #if enum.name.endswith("Mask"):
566  self.write_enum(""" inline {name} operator|({name} a, {name} b) {{ return static_cast<{name}>(static_cast<{type}>(a) | static_cast<{type}>(b)); }}""".format(name=enum.name, type=self.to_enum_type(enum.uatype)))
567  self.write_enum(""" inline {name} operator&({name} a, {name} b) {{ return static_cast<{name}>(static_cast<{type}>(a) & static_cast<{type}>(b)); }}""".format(name=enum.name, type=self.to_enum_type(enum.uatype)))
568 
569 
570  def to_enum_type(self, val):
571  #if val == "6":
572  #val = "8"
573  return "{}_t".format(val.lower())
574 
575  def write_h(self, *args):
576  self.h_file.write(" ".join(args) + "\n")
577 
578  def write_enum(self, *args):
579  self.enum_file.write(" ".join(args) + "\n")
580 
581  def write_ser(self, *args):
582  self.serialize_file.write(" ".join(args) + "\n")
583 
584  def write_size(self, *args):
585  self.rawsize_file.write(" ".join(args) + "\n")
586 
587  def write_deser(self, *args):
588  self.deserialize_file.write(" ".join(args) + "\n")
589 
590  def write_const(self, *args):
591  self.constructors_file.write(" ".join(args) + "\n")
592 
593  def make_header_h(self, ):
594  self.write_h('''// DO NOT EDIT THIS FILE!
595 // It is automatically generated from opcfoundation.org schemas.
596 //
597 
598 /// @brief Opc Ua Binary.
599 /// @license GNU LGPL
600 ///
601 /// Distributed under the GNU LGPL License
602 /// (See accompanying file LICENSE or copy at
603 /// http://www.gnu.org/licenses/lgpl.html)
604 ///
605 
606 #pragma once
607 
608 #include <opc/ua/protocol/enums.h>
609 #include <opc/ua/protocol/variable_access_level.h>
610 #include <opc/ua/protocol/attribute_ids.h>
611 #include <opc/ua/protocol/nodeid.h>
612 #include <opc/ua/protocol/types.h>
613 #include <opc/ua/protocol/types_manual.h>
614 #include <opc/ua/protocol/variant.h>
615 #include <opc/ua/protocol/data_value.h>
616 
617 namespace OpcUa
618 {''')
619 
620  def make_footer_h(self):
621  self.write_h('''
622 } // namespace
623  ''')
624 
625  def make_header_enum(self, ):
626  self.write_enum('''// DO NOT EDIT THIS FILE!
627 // It is automatically generated from opcfoundation.org schemas.
628 //
629 
630 /// @brief Opc Ua Binary.
631 /// @license GNU LGPL
632 ///
633 /// Distributed under the GNU LGPL License
634 /// (See accompanying file LICENSE or copy at
635 /// http://www.gnu.org/licenses/lgpl.html)
636 ///
637 
638 #pragma once
639 
640 #include <cstdint>
641 #include <vector>
642 #include <string>
643 
644 #include <opc/ua/protocol/status_codes.h>
645 
646 namespace OpcUa
647 {
648  struct DiagnosticInfo;
649 ''')
650 
651  def make_footer_enum(self):
652  self.write_enum('''
653 } // namespace
654  ''')
655 
656  def make_header_rawsize(self, ):
657  self.write_size('''// DO NOT EDIT THIS FILE!
658 // It is automatically generated from opcfoundation.org schemas.
659 //
660 
661 /// @author Olivier Roulet-Dubonnet
662 /// @email olivier@sintef.no
663 /// @brief Opc Ua Binary.
664 /// @license GNU LGPL
665 ///
666 /// Distributed under the GNU LGPL License
667 /// (See accompanying file LICENSE or copy at
668 /// http://www.gnu.org/licenses/lgpl.html)
669 ///
670 
671 #include "binary_serialization.h"
672 #include <opc/ua/protocol/protocol.h>
673 
674 #include <opc/ua/protocol/binary/stream.h>
675 
676 namespace OpcUa
677 {
678  namespace Binary
679  {''')
680 
681  def make_footer_rawsize(self):
682  self.write_size('''
683  }
684 
685 } // namespace
686  ''')
687 
688 
689 
690  def make_header_serialize(self, ):
691  self.write_ser('''// DO NOT EDIT THIS FILE!
692 // It is automatically generated from opcfoundation.org schemas.
693 //
694 
695 /// @author Olivier Roulet-Dubonnet
696 /// @email olivier@sintef.no
697 /// @brief Opc Ua Binary.
698 /// @license GNU LGPL
699 ///
700 /// Distributed under the GNU LGPL License
701 /// (See accompanying file LICENSE or copy at
702 /// http://www.gnu.org/licenses/lgpl.html)
703 ///
704 
705 #include "binary_serialization.h"
706 #include <opc/ua/protocol/protocol.h>
707 
708 #include <opc/ua/protocol/binary/stream.h>
709 
710 namespace OpcUa
711 {
712  namespace Binary
713  {''')
714 
715  def make_footer_serialize(self):
716  self.write_ser('''
717  }
718 
719 } // namespace
720  ''')
721 
722  def make_header_deserialize(self, ):
723  self.write_deser('''// DO NOT EDIT THIS FILE!
724 // It is automatically generated from opcfoundation.org schemas.
725 //
726 
727 /// @author Olivier Roulet-Dubonnet
728 /// @email olivier@sintef.no
729 /// @brief Opc Ua Binary.
730 /// @license GNU LGPL
731 ///
732 /// Distributed under the GNU LGPL License
733 /// (See accompanying file LICENSE or copy at
734 /// http://www.gnu.org/licenses/lgpl.html)
735 ///
736 
737 #include "binary_serialization.h"
738 #include <opc/ua/protocol/protocol.h>
739 
740 #include <opc/ua/protocol/binary/stream.h>
741 
742 namespace OpcUa
743 {
744  namespace Binary
745  {''')
746 
747  def make_footer_deserialize(self):
748  self.write_deser('''
749  }
750 
751 } // namespace
752  ''')
753 
754 
755  def make_header_constructors(self, ):
756  self.write_const('''// DO NOT EDIT THIS FILE!
757 // It is automatically generated from opcfoundation.org schemas.
758 //
759 
760 /// @author Olivier Roulet-Dubonnet
761 /// @email olivier@sintef.no
762 /// @brief Opc Ua Binary.
763 /// @license GNU LGPL
764 ///
765 /// Distributed under the GNU LGPL License
766 /// (See accompanying file LICENSE or copy at
767 /// http://www.gnu.org/licenses/lgpl.html)
768 ///
769 
770 #include <opc/ua/protocol/protocol_auto.h>
771 #include <opc/ua/protocol/object_ids.h>
772 
773 namespace OpcUa
774 { ''')
775 
776  def make_footer_constructors(self):
777  self.write_const('''
778 } // namespace
779  ''')
780 
781 
782 
783 
784 if __name__ == "__main__":
785  xmlpath = "Opc.Ua.Types.bsd"
786  hpath = "../include/opc/ua/protocol/protocol_auto.h"
787  enumpath = "../include/opc/ua/protocol/enums.h"
788  serializerpath = "../src/protocol/serialize_auto.cpp"
789  rawsizepath = "../src/protocol/rawsize_auto.cpp"
790  deserializerpath = "../src/protocol/deserialize_auto.cpp"
791  constructorspath = "../src/protocol/constructors_auto.cpp"
792 
793  p = gm.Parser(xmlpath)
794  model = p.parse()
795  gm.add_basetype_members(model)
796  gm.add_encoding_field(model)
797  gm.remove_duplicates(model)
798  gm.remove_vector_length(model)
799  gm.split_requests(model, NoSplitStruct)
800 
801  #p = Parser(xmlpath)
802  #model = p.parse()
803  #Changes specific to our C++ implementation
804  #reorder_extobjects(model)
805  #add_basetype_members(model)
806  #add_encoding_field(model)
807  #remove_vector_length(model)
808  #remove_body_length(model)
809  #remove_duplicates(model)
810  #split_requests(model)
811  reorder_structs(model)
812  override_types(model)
813 
814  f = open("struct_list.txt", "w")
815  f.write("enabled_structs = [\\")
816  for name in model.struct_list:
817  f.write("\n #'" + name + "',")
818  f.write("]")
819 
820 
821  c = CodeGenerator(model, hpath, enumpath, rawsizepath, serializerpath, deserializerpath, constructorspath)
822  c.run()
823 
824 
FMT_API void print(std::FILE *f, CStringRef format_str, ArgList args)
Definition: format.cc:873
std::string format(CStringRef format_str, ArgList args)
Definition: format.h:3686


ros_opcua_impl_freeopcua
Author(s): Denis Štogl
autogenerated on Tue Jan 19 2021 03:06:05