-
Notifications
You must be signed in to change notification settings - Fork 109
Expand file tree
/
Copy pathsession.py.mako
More file actions
430 lines (356 loc) · 18.5 KB
/
Copy pathsession.py.mako
File metadata and controls
430 lines (356 loc) · 18.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
${template_parameters['encoding_tag']}
# This file was generated
<%
import build.helper as helper
import os
from string import capwords
grpc_supported = template_parameters['include_grpc_support']
config = template_parameters['metadata'].config
attributes = config['attributes']
enums = config['enums']
functions = helper.filter_codegen_functions(config['functions'])
module_name = config['module_name']
attributes = helper.filter_codegen_attributes(config['attributes'])
close_function_name = helper.camelcase_to_snakecase(config['close_function'])
session_context_manager = None
if 'task' in config['context_manager_name']:
session_context_manager = '_' + config['context_manager_name']['task'].title()
session_context_manager_initiate = functions[config['context_manager_name']['initiate_function']]['python_name']
session_context_manager_abort = functions[config['context_manager_name']['abort_function']]['python_name']
render_initiate_in_session_base = functions[config['context_manager_name']['initiate_function']]['render_in_session_base']
%>\
import array # noqa: F401
% if config['use_locking']:
# Used by @ivi_synchronized
from functools import wraps
% endif
% if attributes:
import ${module_name}._attributes as _attributes
% endif
% if config['repeated_capability_object_type']['python'] != 'applicable-attributes-only':
import ${module_name}._converters as _converters
% endif
import ${module_name}._library_interpreter as _library_interpreter
import ${module_name}.enums as enums
import ${module_name}.errors as errors
% for c in config['custom_types']:
import ${module_name}.${c['file_name']} as ${c['file_name']} # noqa: F401
% endfor
import hightime
% if config['uses_nitclk']:
import nitclk
% endif
# Used for __repr__
import pprint
pp = pprint.PrettyPrinter(indent=4)
% if session_context_manager is not None:
class ${session_context_manager}(object):
def __init__(self, session):
self._session = session
self._session.${session_context_manager_initiate}()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self._session.${session_context_manager_abort}()
% endif
% if config['use_locking']:
# From https://stackoverflow.com/questions/5929107/decorators-with-parameters
def ivi_synchronized(f):
@wraps(f)
def aux(*xs, **kws):
session = xs[0] # parameter 0 is 'self' which is the session object
with session.lock():
return f(*xs, **kws)
return aux
class _Lock(object):
def __init__(self, session):
self._session = session
def __enter__(self):
# _lock_session is called from the lock() function, not here
return self
def __exit__(self, exc_type, exc_value, traceback):
self._session.unlock()
% endif
% if len(config['repeated_capabilities']) > 0:
% if config['repeated_capability_object_type']['python'] == 'applicable-attributes-only':
class _RepeatedCapabilityAttributeOnlyBase(object):
def __init__(self, session, prefix):
object.__setattr__(self, '_session', session)
object.__setattr__(self, '_prefix', prefix)
object.__setattr__(self, '_repeated_capability', '')
def _get_attribute_vi_real64(self, attribute):
value = self._session._interpreter.get_attribute_vi_real64(self._prefix + self._repeated_capability, attribute)
return value
def _set_attribute_vi_real64(self, attribute, value):
self._session._interpreter.set_attribute_vi_real64(self._prefix + self._repeated_capability, attribute, value)
def _get_attribute_vi_int32(self, attribute):
value = self._session._interpreter.get_attribute_vi_int32(self._prefix + self._repeated_capability, attribute)
return value
def _set_attribute_vi_int32(self, attribute, value):
self._session._interpreter.set_attribute_vi_int32(self._prefix + self._repeated_capability, attribute, value)
def _get_attribute_vi_string(self, attribute):
value = self._session._interpreter.get_attribute_vi_string(self._prefix + self._repeated_capability, attribute)
return value
def _set_attribute_vi_string(self, attribute, value):
self._session._interpreter.set_attribute_vi_string(self._prefix + self._repeated_capability, attribute, value)
% for rep_cap in config['repeated_capabilities']:
class _RepeatedCapability${capwords(rep_cap['python_name'].replace('_', ' ')).replace(' ', '')}(_RepeatedCapabilityAttributeOnlyBase):
% for attribute in helper.sorted_attrs(helper.filter_rep_cap_supported_attributes(attributes, rep_cap['python_name'])):
<%
helper.add_attribute_rep_cap_tip(attributes[attribute], config)
%>\
% if attributes[attribute]['enum']:
% if helper.enum_uses_converter(enums[attributes[attribute]['enum']]):
${attributes[attribute]['python_name']} = _attributes.AttributeEnumWithConverter(_attributes.AttributeEnum(_attributes.Attribute${attributes[attribute]['type']}, enums.${enums[attributes[attribute]['enum']]['python_name']}, ${attribute}), _converters.${enums[attributes[attribute]['enum']]['enum_to_converted_value_function_name']}, _converters.${enums[attributes[attribute]['enum']]['converted_value_to_enum_function_name']})
% else:
${attributes[attribute]['python_name']} = _attributes.AttributeEnum(_attributes.Attribute${attributes[attribute]['type']}, enums.${enums[attributes[attribute]['enum']]['python_name']}, ${attribute})
% endif
% else:
${attributes[attribute]['python_name']} = _attributes.${attributes[attribute]['attribute_class']}(${attribute})
% endif
% if 'documentation' in attributes[attribute] and len(helper.get_documentation_for_node_docstring(attributes[attribute], config, indent=4).strip()) > 0:
'''Type: ${attributes[attribute]['type_in_documentation']}
${helper.get_documentation_for_node_docstring(attributes[attribute], config, indent=4)}
'''
% endif
% endfor
def __init__(self, session):
super(_RepeatedCapability${capwords(rep_cap['python_name'].replace('_', ' ')).replace(' ', '')}, self).__init__(session, '${rep_cap["prefix"]}')
def __setattr__(self, key, value):
if key not in dir(self):
raise AttributeError("'{0}' object has no attribute '{1}'".format(type(self).__name__, key))
object.__setattr__(self, key, value)
def __getitem__(self, repeated_capability):
super(_RepeatedCapability${capwords(rep_cap['python_name'].replace('_', ' ')).replace(' ', '')}, self).__setattr__('_repeated_capability', repeated_capability)
return self
% endfor
% else:
class _RepeatedCapabilities(object):
def __init__(self, session, prefix, current_repeated_capability_list):
self._session = session
self._prefix = prefix
# We need at least one element. If we get an empty list, make the one element an empty string
self._current_repeated_capability_list = current_repeated_capability_list if len(current_repeated_capability_list) > 0 else ['']
# Now we know there is at lease one entry, so we look if it is an empty string or not
self._separator = '/' if len(self._current_repeated_capability_list[0]) > 0 else ''
def __getitem__(self, repeated_capability):
'''Set/get properties or call methods with a repeated capability (i.e. channels)'''
rep_caps_list = _converters.convert_repeated_capabilities(repeated_capability, self._prefix)
complete_rep_cap_list = [current_rep_cap + self._separator + rep_cap for current_rep_cap in self._current_repeated_capability_list for rep_cap in rep_caps_list]
return _SessionBase(
repeated_capability_list=complete_rep_cap_list,
all_channels_in_session=self._session._all_channels_in_session,
interpreter=self._session._interpreter,
freeze_it=True
)
# This is a very simple context manager we can use when we need to set/get attributes
# or call functions from _SessionBase that require no channels. It is tied to the specific
# implementation of _SessionBase and how repeated capabilities are handled.
class _NoChannel(object):
def __init__(self, session):
self._session = session
def __enter__(self):
self._repeated_capability_cache = self._session._repeated_capability
self._session._repeated_capability = ''
def __exit__(self, exc_type, exc_value, traceback):
self._session._repeated_capability = self._repeated_capability_cache
% endif
% endif
class _SessionBase(object):
'''Base class for all ${config['driver_name']} sessions.'''
# This is needed during __init__. Without it, __setattr__ raises an exception
_is_frozen = False
% for attribute in helper.sorted_attrs(helper.filter_codegen_attributes(attributes)):
% if not ('supported_rep_caps' in attributes[attribute] and len(attributes[attribute]['supported_rep_caps']) > 0 and config['repeated_capability_object_type']['python'] == 'applicable-attributes-only'):
<%
helper.add_attribute_rep_cap_tip(attributes[attribute], config)
%>\
%if attributes[attribute]['enum']:
%if helper.enum_uses_converter(enums[attributes[attribute]['enum']]):
${attributes[attribute]['python_name']} = _attributes.AttributeEnumWithConverter(_attributes.AttributeEnum(_attributes.Attribute${attributes[attribute]['type']}, enums.${enums[attributes[attribute]['enum']]['python_name']}, ${attribute}), _converters.${enums[attributes[attribute]['enum']]['enum_to_converted_value_function_name']}, _converters.${enums[attributes[attribute]['enum']]['converted_value_to_enum_function_name']})
%else:
${attributes[attribute]['python_name']} = _attributes.AttributeEnum(_attributes.Attribute${attributes[attribute]['type']}, enums.${enums[attributes[attribute]['enum']]['python_name']}, ${attribute})
%endif
%else:
${attributes[attribute]['python_name']} = _attributes.${attributes[attribute]['attribute_class']}(${attribute})
%endif
% if 'documentation' in attributes[attribute] and len(helper.get_documentation_for_node_docstring(attributes[attribute], config, indent=4).strip()) > 0:
'''Type: ${attributes[attribute]['type_in_documentation']}
${helper.get_documentation_for_node_docstring(attributes[attribute], config, indent=4)}
'''
% endif
% endif
% endfor
<%
init_function = config['functions']['_init_function']
init_method_params = helper.get_params_snippet(init_function, helper.ParameterUsageOptions.SESSION_METHOD_DECLARATION)
init_call_params = helper.get_params_snippet(init_function, helper.ParameterUsageOptions.SESSION_METHOD_CALL)
constructor_params = helper.filter_parameters(init_function['parameters'], helper.ParameterUsageOptions.SESSION_INIT_DECLARATION)
%>\
% if attributes:
% endif
def __init__(self, repeated_capability_list, all_channels_in_session, interpreter, freeze_it=False):
self._repeated_capability_list = repeated_capability_list
self._repeated_capability = ','.join(repeated_capability_list)
self._all_channels_in_session = all_channels_in_session
self._interpreter = interpreter
# Store the parameter list for later printing in __repr__
param_list = []
param_list.append("repeated_capability_list=" + pp.pformat(repeated_capability_list))
param_list.append("interpreter=" + pp.pformat(interpreter))
self._param_list = ', '.join(param_list)
% if len(config['repeated_capabilities']) > 0:
# Instantiate any repeated capability objects
% for rep_cap in config['repeated_capabilities']:
% if config['repeated_capability_object_type']['python'] == 'applicable-attributes-only':
self.${rep_cap['python_name']} = _RepeatedCapability${capwords(rep_cap['python_name'].replace('_', ' ')).replace(' ', '')}(self)
% else:
self.${rep_cap['python_name']} = _RepeatedCapabilities(self, '${rep_cap["prefix"]}', repeated_capability_list)
% endif
% endfor
% endif
# Finally, set _is_frozen to True which is used to prevent clients from accidentally adding
# members when trying to set a property with a typo.
self._is_frozen = freeze_it
def __repr__(self):
return '{0}.{1}({2})'.format('${module_name}', self.__class__.__name__, self._param_list)
def __setattr__(self, key, value):
if self._is_frozen and key not in dir(self):
raise AttributeError("'{0}' object has no attribute '{1}'".format(type(self).__name__, key))
object.__setattr__(self, key, value)
% if session_context_manager is not None and render_initiate_in_session_base:
def initiate(self):
'''initiate
${helper.get_function_docstring(helper.initiate_function_def_for_doc(functions, config), False, config, indent=8)}
'''
return ${session_context_manager}(self)
% endif
''' These are code-generated '''
% for func_name in sorted({k: v for k, v in functions.items() if v['render_in_session_base']}):
% for method_template in functions[func_name]['method_templates']:
% if method_template['session_filename'] != '/none':
% if functions[func_name]['use_session_lock'] and config['use_locking']:
@ivi_synchronized
% endif
<%include file="${'/session.py' + method_template['session_filename'] + '.py.mako'}" args="f=functions[func_name], config=config, method_template=method_template" />\
% endif
% endfor
% endfor
class Session(_SessionBase):
'''${config['session_class_description']}'''
<% grpc_options_param = ', *, grpc_options=None' if grpc_supported else '' %>\
def __init__(${init_method_params}${grpc_options_param}):
r'''${config['session_class_description']}
<%
ctor_for_docs = init_function
if grpc_supported:
import copy
ctor_for_docs = copy.deepcopy(ctor_for_docs)
ctor_for_docs['parameters'].append(
{
'default_value': None,
'direction': 'in',
'documentation': { 'description': 'MeasurementLink gRPC session options' },
'enum': None,
'is_repeated_capability': False,
'is_session_handle': False,
'python_name': 'grpc_options',
'size': {'mechanism': 'fixed', 'value': 1},
'type_in_documentation': module_name + '.grpc_session_options.GrpcSessionOptions',
'type_in_documentation_was_calculated': False,
'use_in_python_api': False,
},
)
%>\
${helper.get_function_docstring(ctor_for_docs, False, config, indent=8)}
'''
% if grpc_supported:
if grpc_options:
import ${module_name}._grpc_stub_interpreter as _grpc_stub_interpreter
interpreter = _grpc_stub_interpreter.GrpcStubInterpreter(grpc_options)
else:
interpreter = _library_interpreter.LibraryInterpreter(encoding='windows-1251')
% else:
interpreter = _library_interpreter.LibraryInterpreter(encoding='windows-1251')
% endif
# Initialize the superclass with default values first, populate them later
super(Session, self).__init__(
repeated_capability_list=[],
interpreter=interpreter,
freeze_it=False,
all_channels_in_session=None
)
% for p in init_function['parameters']:
% if 'python_api_converter_name' in p:
${p['python_name']} = _converters.${p['python_api_converter_name']}(${p['python_name']})
% endif
% endfor
# Call specified init function
# Note that _interpreter default-initializes the session handle in its constructor, so that
# if ${init_function['python_name']} fails, the error handler can reference it.
# And then here, once ${init_function['python_name']} succeeds, we call set_session_handle
# with the actual session handle.
self._interpreter.set_session_handle(self.${init_function['python_name']}(${init_call_params}))
% if config['uses_nitclk']:
% if grpc_supported:
# NI-TClk does not work over NI gRPC Device Server
if not grpc_options:
self.tclk = nitclk.SessionReference(self._interpreter.get_session_handle())
% else:
self.tclk = nitclk.SessionReference(self._interpreter.get_session_handle())
% endif
% endif
# Store the parameter list for later printing in __repr__
param_list = []
% for param in constructor_params:
param_list.append("${param['python_name']}=" + pp.pformat(${param['python_name']}))
% endfor
self._param_list = ', '.join(param_list)
# Store the list of channels in the Session which is needed by some nimi-python modules.
# Use try/except because not all the modules support channels.
# self.get_channel_names() and self.channel_count can only be called after the session
# handle is set
try:
self._all_channels_in_session = self.get_channel_names(range(self.channel_count))
except AttributeError:
self._all_channels_in_session = None
# Finally, set _is_frozen to True which is used to prevent clients from accidentally adding
# members when trying to set a property with a typo.
self._is_frozen = True
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
% if grpc_supported:
if self._interpreter._close_on_exit:
self.close()
% else:
self.close()
% endif
% if session_context_manager is not None and not render_initiate_in_session_base:
def initiate(self):
'''initiate
${helper.get_function_docstring(helper.initiate_function_def_for_doc(functions, config), False, config, indent=8)}
'''
return ${session_context_manager}(self)
% endif
def close(self):
'''close
${helper.get_function_docstring(helper.close_function_def_for_doc(functions, config), False, config, indent=8)}
'''
try:
self._${close_function_name}()
except errors.DriverError:
self._interpreter.set_session_handle()
raise
self._interpreter.set_session_handle()
''' These are code-generated '''
% for func_name in sorted({k: v for k, v in functions.items() if not v['render_in_session_base']}):
% for method_template in functions[func_name]['method_templates']:
% if method_template['session_filename'] != '/none':
% if functions[func_name]['use_session_lock'] and config['use_locking']:
@ivi_synchronized
% endif
<%include file="${'/session.py' + method_template['session_filename'] + '.py.mako'}" args="f=functions[func_name], config=config, method_template=method_template" />\
% endif
% endfor
% endfor