Go to the documentation of this file.00001
00002 def extensionobject_from_binary(data):
00003 """
00004 Convert binary-coded ExtensionObject to a Python object.
00005 Returns an object, or None if TypeId is zero
00006 """
00007 TypeId = NodeId.from_binary(data)
00008 Encoding = ord(data.read(1))
00009 body = None
00010 if Encoding & (1 << 0):
00011 length = uabin.Primitives.Int32.unpack(data)
00012 if length < 1:
00013 body = Buffer(b"")
00014 else:
00015 body = data.copy(length)
00016 data.skip(length)
00017 if TypeId.Identifier == 0:
00018 return None
00019 elif TypeId.Identifier not in ExtensionClasses:
00020 e = ExtensionObject()
00021 e.TypeId = TypeId
00022 e.Encoding = Encoding
00023 if body is not None:
00024 e.Body = body.read(len(body))
00025 return e
00026 klass = ExtensionClasses[TypeId.Identifier]
00027 if body is None:
00028 raise UaError("parsing ExtensionObject {0} without data".format(klass.__name__))
00029 return klass.from_binary(body)
00030
00031
00032 def extensionobject_to_binary(obj):
00033 """
00034 Convert Python object to binary-coded ExtensionObject.
00035 If obj is None, convert to empty ExtensionObject (TypeId = 0, no Body).
00036 Returns a binary string
00037 """
00038 if isinstance(obj, ExtensionObject):
00039 return obj.to_binary()
00040 TypeId = NodeId()
00041 Encoding = 0
00042 Body = None
00043 if obj is not None:
00044 TypeId = FourByteNodeId(getattr(ObjectIds, "{0}_Encoding_DefaultBinary".format(obj.__class__.__name__)))
00045 Encoding |= (1 << 0)
00046 Body = obj.to_binary()
00047 packet = []
00048 packet.append(TypeId.to_binary())
00049 packet.append(uabin.Primitives.UInt8.pack(Encoding))
00050 if Body:
00051 packet.append(uabin.Primitives.Bytes.pack(Body))
00052 return b''.join(packet)