Stubs.py 13.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#
# (C) Semantix Information Technologies.
#
# Semantix Information Technologies is licensing the code of the
# Data Modelling Tools (DMT) in the following dual-license mode:
#
# Commercial Developer License:
#       The DMT Commercial Developer License is the suggested version
# to use for the development of proprietary and/or commercial software.
# This version is for developers/companies who do not want to comply
# with the terms of the GNU Lesser General Public License version 2.1.
#
# GNU LGPL v. 2.1:
#       This version of DMT is the one to use for the development of
# applications, when you are willing to comply with the terms of the
# GNU Lesser General Public License version 2.1.
#
# Note that in both cases, there are no charges (royalties) for the
# generated code.
#
21
import os
22
23
import re
import copy
24
import DV_Types  # pylint: disable=import-error
25
26
27
28
29
30
31
32
33
34
35
36
37
from ctypes import (
    cdll, c_void_p, c_ubyte, c_double, c_uint,
    c_longlong, c_bool, c_int, c_long
)

# load the *getset.so in this folder
script_path = os.path.dirname(os.path.realpath(__file__))
soFileNames = [
    filename
    for filename in os.listdir(script_path)
    if filename.endswith("_getset.so")
]
if len(soFileNames) != 1:
38
    raise Exception("Failed to locate a single _getset.so under " + script_path)
39

40
JMP = cdll.LoadLibrary(os.path.join(script_path, soFileNames[0]))
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

# BitStream constructor
CreateStream = JMP.CreateStream
CreateStream.restype = c_void_p
# BitStream destructor
DestroyStream = JMP.DestroyStream
# BitStream reset
ResetStream = JMP.ResetStream
# Get number of bytes in encoded stream
GetStreamCurrentLength = JMP.GetStreamCurrentLength
GetStreamCurrentLength.restype = c_uint

# Access BitStream buffer
GetBitstreamBuffer = JMP.GetBitstreamBuffer
GetBitstreamBuffer.restype = c_void_p
# Read from buffer
GetBufferByte = JMP.GetBufferByte
GetBufferByte.restype = c_ubyte
# Write to buffer
SetBufferByte = JMP.SetBufferByte

# Create pErr space for Encoders - i.e. sizeof(int)
CreateInstanceOf_int = JMP.CreateInstanceOf_int
CreateInstanceOf_int.restype = c_void_p
# Release pErr space for Encoders
DestroyInstanceOf_int = JMP.DestroyInstanceOf_int
67
68


69
70
class AsnCoderError(Exception):
    pass
71
72
73
74
75
76
77
78
79
80
81


def CleanNameAsPythonWants(name):
    """ASN.1 ids have minuses... turn non-ID chars to '_'"""
    return re.sub(r'[^a-zA-Z0-9_]', '_', name)
Clean = CleanNameAsPythonWants


def myassert(b):
    """assert that shows the call stack when it fails"""
    if not b:
82
        raise AsnCoderError("Assertion failed...")
83
84


85
class DataStream(object):
86
87
88
89
    """ASN1SCC BitStream equivalent"""
    def __init__(self, bufferSize):
        """bufferSize: use the DV.TYPENAME_REQUIRED_BYTES_FOR_ENCODING"""
        myassert(isinstance(bufferSize, int))
90
        self._bs = c_void_p(CreateStream(bufferSize))
91
92
93
        self._bufferSize = bufferSize

    def __del__(self):
94
95
        """Releases the encoded data and the bitstream structure pointing to them"""
        DestroyStream(self._bs)
96
97
98

    def Reset(self):
        """Rewinds the currentByte and currentBit to the start"""
99
        ResetStream(self._bs)
100
101

    def GetPyString(self):
102
        # print "Reading",
103
        msg = ""
Maxime Perrotin's avatar
Maxime Perrotin committed
104
        pData = c_void_p(GetBitstreamBuffer(self._bs))
105
        for i in range(0, GetStreamCurrentLength(self._bs)):
106
            b = GetBufferByte(pData, i)
107
            msg += chr(b)
108
109
            # print b, ",",
        # print "EOF"
110
111
112
113
        return msg

    def SetFromPyString(self, data):
        strLength = len(data)
114
        assert self._bufferSize >= strLength
115
        self._bs.count = strLength
Maxime Perrotin's avatar
Maxime Perrotin committed
116
        pData = c_void_p(GetBitstreamBuffer(self._bs))
117
        # print "Writing",
118
        for i in range(0, strLength):
119
            b = ord(data[i])
120
121
122
            # print b, ",",
            SetBufferByte(pData, i, b)
        # print "EOF"
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178


class COMMON(object):
    """This class is used to implement ALL the Python "proxy" classes for
ASN1SCC types.

It uses the __getattr__ call to hook into all the accesses that Python
considers "unexpected". Therefore, when the script does this...

    a = T_SEQUENCE()
    print a.x.Get()
    a.x.Set(12)

... __getattr__ is called to ask us how to provide a ".x" member.
We do two things to cope:

(1) we form the equivalent path to the C getter/setter function
    (in self._Caccessor)
(2) we form a list of params, which is basically the indexes of
    whatever arrays we meet in the access path

So if the script does...

    a.x.y[0].z.k[2].w.Get()

then the params list carries [0,2], to pass it as an argument to the
C getter when it is called (in response to the "Get" method call).

Some key points:
    When the chain ends (in a .Get, .Set, .GetLength or .SetLength
call), we have to reset the "paths" we have formed, so that the
next chain will restart from the beginning. That's what the Reset
method does.
However, we also have some helper functions for OCTET STRINGs:
GetPyString and SetFromPyString. These have to do a per-byte loop,
and if they used the "Get" and "Set" as they originally were,
the path would be reset after accessing the [0] element...
So we added a keyword boolean param called "reset", which disables
this Reset when it is used from within GetPyString and
SetFromPyString.
    Another keyword param is postfix: it is simply used to allow
re-use of the Get and Set code for the GetLength and SetLength
members of SEQUENCEOF/SETOFs and OCTETSTRINGs:

An example for SetLength:

  T_SEQUENCE ::= SEQUENCE { y SEQUENCE (SIZE(4)) OF INTEGER }

    a = T_SEQUENCE()
    a.y.SetLength(4)
    a.y[0].Set(1)
    a.y[1].Set(4)
    a.y[2].Set(9)
    a.y[3].Set(16)
"""

179
180
    allowed = ["_nodeTypeName", "_ptr", "_pErr", "_Caccessor", "_accessPath",
               "_params", "_new_ptr"]
181
# , "Get", "GetLength", "Set", "SetLength", "Reset", "Encode", "Decode", "SetFromPyString", "GetPyString", "allowed"]
182

183
    def __init__(self, nodeTypeName, ptr=None):
184
185
        myassert(isinstance(nodeTypeName, str))
        self._nodeTypeName = nodeTypeName
186
        self._new_ptr = ptr is None
187
188
        constructor = getattr(JMP, "CreateInstanceOf_" + Clean(nodeTypeName))
        constructor.restype = c_void_p
189
        self._ptr = ptr or constructor()
Maxime Perrotin's avatar
Maxime Perrotin committed
190
191
        self._ptr = c_void_p(self._ptr)
        self._pErr = c_void_p(CreateInstanceOf_int())
192
193
194
        self._Caccessor = ""
        self._params = []
        self._accessPath = ""
195
196
197
198
199
200
201
202
203
204
205
206

    def Reset(self, state=None):
        if state is None:
            self._Caccessor = ""
            self._params = []
            self._accessPath = ""
        else:
            self._Caccessor, self._params, self._accessPath = state[0][:], copy.deepcopy(state[1]), state[2][:]

    def GetState(self):
        return self._Caccessor[:], copy.deepcopy(self._params), self._accessPath[:]

207
208
209
210
    def SetData(self, src):
        bridgeFct = getattr(JMP, "SetDataFor_" + Clean(self._nodeTypeName))
        bridgeFct(self._ptr, src)

211
    def __del__(self):
212
        ''' Destructor: free memory only if it was allocated at creation '''
213
        DestroyInstanceOf_int(self._pErr)
214
215
216
        if self._new_ptr:
            destructor = getattr(JMP, "DestroyInstanceOf_" + Clean(self._nodeTypeName))
            destructor(self._ptr)
217
218
219
220
221
222
223
224
225
226
227
228

    def __str__(self):
        return "Choose the information you want - whole-structure or sequence dump not supported."

    def __getattr__(self, x):
        self._Caccessor += "_"+Clean(x)
        self._accessPath += "."+x
        return self

    def __setattr__(self, name, value):
        if name not in COMMON.allowed:
            self.Reset()
229
            raise AsnCoderError("You can only use .Set(XYZ) and .SetLength(XYZ) to assign values, don't use '='")
230
231
232
233
234
235
236
237
238
239
        object.__setattr__(self, name, value)

    def __getitem__(self, idx):
        self._Caccessor += "_iDx"
        self._params.append(idx)
        self._accessPath += "[" + str(idx) + "]"
        return self

    def Get(self, **args):  # postfix="", reset=True
        try:
240
241
            bridgeFuncName = Clean(self._nodeTypeName) + "_" + self._Caccessor + "_Get"+args.get("postfix", "")
            if bridgeFuncName not in DV_Types.funcTypeLookup:
242
                raise AsnCoderError("Function %s not found in lookup - contact support." % bridgeFuncName)
243
244
245
246
247
248
249
250
251
252
253
254
255
            resType = DV_Types.funcTypeLookup[bridgeFuncName]
            if resType.endswith('*'):
                cTypesResultType = c_void_p
            else:
                cTypesResultType = {
                    'asn1SccSint': c_longlong,
                    'byte': c_ubyte,
                    'double': c_double,
                    'flag': c_bool,
                    'int': c_int,
                    'long': c_long
                }.get(resType, None)
                if cTypesResultType is None:
256
                    raise AsnCoderError("Result type of %s not yet supported in the Python mapper - contact support." % resType)
257
258
            bridgeFunc = getattr(JMP, bridgeFuncName)
            bridgeFunc.restype = cTypesResultType
259
260
261
262
263
            retVal = bridgeFunc(self._ptr, *self._params)
        except:
            oldAP = self._accessPath
            if args.get("reset", True):
                self.Reset()
264
            raise AsnCoderError("The access path you used (%s) is not valid." % oldAP)
265
266
267
268
269
270
        if args.get("reset", True):
            self.Reset()
        return retVal

    def Set(self, value, **args):  # postfix="", reset=True
        try:
271
272
273
274
            # print Clean(self._nodeTypeName) + "_" + self._Caccessor + "_Set"+postfix
            bridgeFunc = getattr(JMP, Clean(self._nodeTypeName) + "_" + self._Caccessor + "_Set"+args.get("postfix", ""))
            if isinstance(value, float):
                ctypesValue = c_double(value)
275
            elif isinstance(value, int):
276
277
278
279
                ctypesValue = c_longlong(value)
            else:
                ctypesValue = value
            self._params.append(ctypesValue)
280
281
            bridgeFunc(self._ptr, *self._params)
            self._params.pop()
282
        except Exception as e:
283
284
285
            oldAP = self._accessPath
            if args.get("reset", True):
                self.Reset()
286
287
            raise AsnCoderError("The access path you used (%s) or the value you tried to assign (%s) is not valid. %s" %
                (oldAP, str(value), str(e)))
288
289
290
291
292
293
294
295
296
        if args.get("reset", True):
            self.Reset()

    def GetLength(self, reset=True):
        return self.Get(postfix="Length", reset=reset)

    def SetLength(self, value, reset=True):
        self.Set(value, postfix="Length", reset=reset)

297
298
299
    @staticmethod
    def getErrCode(pErr):
        errCode = 0
300
        for i in range(4):
301
302
303
            errCode = (errCode << 8) | GetBufferByte(pErr, (3-i))
        return errCode

304
305
306
307
    def Encode(self, bitstream, bACN=False):
        """Returns (booleanSuccess, ASN1SCC iErrorCode)
grep for the errorcode value inside ASN1SCC generated headers."""
        myassert(isinstance(bitstream, DataStream))
308
        bitstream.Reset()
309
        suffix = "_ACN_Encode" if bACN else "_Encode"
310
311
        EncodeFuncName = Clean(self._nodeTypeName) + suffix
        EncodeFunc = getattr(JMP, EncodeFuncName)
312
313
        success = EncodeFunc(self._ptr, bitstream._bs, self._pErr, True)
        if not success:
314
315
            raise AsnCoderError("Error in %s, code: %d" % (EncodeFuncName,
                                                           COMMON.getErrCode(self._pErr)))
316
317
318
319
320
321

    def Decode(self, bitstream, bACN=False):
        """Returns (booleanSuccess, ASN1SCC iErrorCode)
grep for the errorcode value inside ASN1SCC generated headers."""
        myassert(isinstance(bitstream, DataStream))
        suffix = "_ACN_Decode" if bACN else "_Decode"
322
323
        DecodeFuncName = Clean(self._nodeTypeName) + suffix
        DecodeFunc = getattr(JMP, DecodeFuncName)
324
325
        success = DecodeFunc(self._ptr, bitstream._bs, self._pErr)
        if not success:
326
327
            raise AsnCoderError("Error in %s, code: %d" % (DecodeFuncName,
                                                           COMMON.getErrCode(self._pErr)))
328
329
330
331
332
333
334

    def EncodeACN(self, bitstream):
        self.Encode(bitstream, True)

    def DecodeACN(self, bitstream):
        self.Decode(bitstream, True)

335
336
    def IsConstraintValid(self):
        # Allocate temp space to store error code (avoid race condition that _pErr would cause)
Maxime Perrotin's avatar
Maxime Perrotin committed
337
        pErr = c_void_p(CreateInstanceOf_int())
338
339
340
341
342
343
        validatorFunc = getattr(JMP, Clean(self._nodeTypeName) + "_IsConstraintValid")
        isValid = validatorFunc(self._ptr, pErr)
        errorCode = COMMON.getErrCode(pErr)
        DestroyInstanceOf_int(pErr)
        return isValid, errorCode

344
345
346
347
348
349
350
351
352
# Type-specific helpers...

# OCTET STRING

    def SetFromPyString(self, src):
        strLength = len(src)
        self.SetLength(strLength, False)
        self._Caccessor += "_iDx"
        accessPath = self._accessPath
353
        for idx in range(0, strLength):
354
355
356
357
358
359
360
361
362
363
364
            self._params.append(idx)
            self._accessPath = accessPath + "[" + str(idx) + "]"
            self.Set(ord(src[idx]), reset=False)
            self._params.pop()
        self.Reset()

    def GetPyString(self):
        retval = ""
        strLength = self.GetLength(False)
        self._Caccessor += "_iDx"
        accessPath = self._accessPath
365
        for idx in range(0, strLength):
366
367
368
369
370
371
            self._params.append(idx)
            self._accessPath = accessPath + "[" + str(idx) + "]"
            retval += chr(self.Get(reset=False))
            self._params.pop()
        self.Reset()
        return retval