Stubs.py 12.9 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
24
25
import sys
import re
import copy
import traceback
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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
67
68
69
import DV_Types
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:
    print "Failed to locate a single _getset.so under", script_path
    sys.exit(1)

JMP = cdll.LoadLibrary(soFileNames[0])

# 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90


def panicWithCallStack(msg):
    """Print the panic msg in color, report the call stack, and die"""
    print >>sys.stderr, "\n"+chr(27)+"[35m" + msg + chr(27) + "[0m\n"
    print >>sys.stderr, "\nCall stack was:\n%s\n" % ("".join(traceback.format_stack()[:-1]))
    sys.exit(1)


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:
        panicWithCallStack("Assertion failed...")


91
class DataStream(object):
92
93
94
95
    """ASN1SCC BitStream equivalent"""
    def __init__(self, bufferSize):
        """bufferSize: use the DV.TYPENAME_REQUIRED_BYTES_FOR_ENCODING"""
        myassert(isinstance(bufferSize, int))
96
        self._bs = c_void_p(CreateStream(bufferSize))
97
98
99
        self._bufferSize = bufferSize

    def __del__(self):
100
101
        """Releases the encoded data and the bitstream structure pointing to them"""
        DestroyStream(self._bs)
102
103
104

    def Reset(self):
        """Rewinds the currentByte and currentBit to the start"""
105
        ResetStream(self._bs)
106
107

    def GetPyString(self):
108
        # print "Reading",
109
        msg = ""
110
111
112
        pData = GetBitstreamBuffer(self._bs)
        for i in xrange(0, GetStreamCurrentLength(self._bs)):
            b = GetBufferByte(pData, i)
113
            msg += chr(b)
114
115
            # print b, ",",
        # print "EOF"
116
117
118
119
        return msg

    def SetFromPyString(self, data):
        strLength = len(data)
120
        assert self._bufferSize >= strLength
121
        self._bs.count = strLength
122
123
        pData = GetBitstreamBuffer(self._bs)
        # print "Writing",
124
125
        for i in xrange(0, strLength):
            b = ord(data[i])
126
127
128
            # print b, ",",
            SetBufferByte(pData, i, b)
        # print "EOF"
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
179
180
181
182
183
184
185


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)
"""

    allowed = ["_nodeTypeName", "_ptr", "_pErr", "_Caccessor", "_accessPath", "_params"]
186
# , "Get", "GetLength", "Set", "SetLength", "Reset", "Encode", "Decode", "SetFromPyString", "GetPyString", "allowed"]
187
188
189
190

    def __init__(self, nodeTypeName):
        myassert(isinstance(nodeTypeName, str))
        self._nodeTypeName = nodeTypeName
191
192
193
194
195
196
197
        constructor = getattr(JMP, "CreateInstanceOf_" + Clean(nodeTypeName))
        constructor.restype = c_void_p
        self._ptr = constructor()
        self._pErr = CreateInstanceOf_int()
        self._Caccessor = ""
        self._params = []
        self._accessPath = ""
198
199
200
201
202
203
204
205
206
207
208
209
210

    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[:]

    def __del__(self):
211
212
213
        DestroyInstanceOf_int(self._pErr)
        destructor = getattr(JMP, "DestroyInstanceOf_" + Clean(self._nodeTypeName))
        destructor(self._ptr)
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236

    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()
            panicWithCallStack("You can only use .Set(XYZ) and .SetLength(XYZ) to assign values, don't use '='")
        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:
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
            bridgeFuncName = Clean(self._nodeTypeName) + "_" + self._Caccessor + "_Get"+args.get("postfix", "")
            if bridgeFuncName not in DV_Types.funcTypeLookup:
                print "Function", bridgeFuncName, "not found in lookup - contact support."
                raise Exception("")
            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:
                    print "Result type of", resType, "is not yet supported in the Python mapper - contact support."
                    raise Exception("")
            bridgeFunc = getattr(JMP, bridgeFuncName)
            bridgeFunc.restype = cTypesResultType
258
259
260
261
262
263
264
265
266
267
268
269
            retVal = bridgeFunc(self._ptr, *self._params)
        except:
            oldAP = self._accessPath
            if args.get("reset", True):
                self.Reset()
            panicWithCallStack("The access path you used (%s) is not valid." % oldAP)
        if args.get("reset", True):
            self.Reset()
        return retVal

    def Set(self, value, **args):  # postfix="", reset=True
        try:
270
271
272
273
274
275
276
277
278
            # 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)
            elif isinstance(value, (int, long)):
                ctypesValue = c_longlong(value)
            else:
                ctypesValue = value
            self._params.append(ctypesValue)
279
280
            bridgeFunc(self._ptr, *self._params)
            self._params.pop()
281
        except Exception, e:
282
283
284
            oldAP = self._accessPath
            if args.get("reset", True):
                self.Reset()
285
            print str(e)
286
287
288
289
290
291
292
293
294
295
296
297
            panicWithCallStack(
                "The access path you used (%s) or the value you tried to assign (%s) is not valid." %
                (oldAP, str(value)))
        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)

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

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

    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"
324
        DecodeFunc = getattr(JMP, Clean(self._nodeTypeName) + suffix)
325
326
        success = DecodeFunc(self._ptr, bitstream._bs, self._pErr)
        if not success:
327
            panicWithCallStack("Error in Decode, code:%d" % 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
337
338
339
340
341
342
343
    def IsConstraintValid(self):
        # Allocate temp space to store error code (avoid race condition that _pErr would cause)
        pErr = CreateInstanceOf_int()
        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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# Type-specific helpers...

# OCTET STRING

    def SetFromPyString(self, src):
        strLength = len(src)
        self.SetLength(strLength, False)
        self._Caccessor += "_iDx"
        accessPath = self._accessPath
        for idx in xrange(0, strLength):
            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
        for idx in xrange(0, strLength):
            self._params.append(idx)
            self._accessPath = accessPath + "[" + str(idx) + "]"
            retval += chr(self.Get(reset=False))
            self._params.pop()
        self.Reset()
        return retval