/usr/lib/python2.7/dist-packages/pyvisa/resources/resource.py is in python-pyvisa 1.8-4.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | # -*- coding: utf-8 -*-
"""
pyvisa.resources.resource
~~~~~~~~~~~~~~~~~~~~~~~~~
High level wrapper for a Resource.
This file is part of PyVISA.
:copyright: 2014 by PyVISA Authors, see AUTHORS for more details.
:license: MIT, see LICENSE for more details.
"""
from __future__ import division, unicode_literals, print_function, absolute_import
import contextlib
import copy
import math
import time
from .. import constants
from .. import errors
from .. import logger
from .. import highlevel
from .. import attributes
class WaitResponse(object):
"""Class used in return of wait_on_event. It properly closes the context upon delete.
A call with event_type of 0 (normally used when timed_out is True) will be
recorded as None, otherwise it records the proper EventType enum.
"""
def __init__(self, event_type, context, ret, visalib, timed_out=False):
if event_type == 0:
self.event_type = None
else:
self.event_type = constants.EventType(event_type)
self.context = context
self.ret = ret
self._visalib = visalib
self.timed_out = timed_out
def __del__(self):
if self.context != None:
self._visalib.close(self.context)
class Resource(object):
"""Base class for resources.
Do not instantiate directly, use :meth:`pyvisa.highlevel.ResourceManager.open_resource`.
:param resource_manager: A resource manager instance.
:param resource_name: the VISA name for the resource (eg. "GPIB::10")
"""
@classmethod
def register(cls, interface_type, resource_class):
def _internal(python_class):
highlevel.ResourceManager.register_resource_class(interface_type, resource_class, python_class)
# If the class already has this attribute,
# it means that a parent class was registered first.
# We need to copy the current list and extended it.
attrs = copy.copy(getattr(python_class, 'visa_attributes_classes', []))
for attr in attributes.AttributesPerResource[(interface_type, resource_class)]:
attrs.append(attr)
if not hasattr(python_class, attr.py_name) and attr.py_name != '':
setattr(python_class, attr.py_name, attr())
for attr in attributes.AttributesPerResource[attributes.AllSessionTypes]:
attrs.append(attr)
if not hasattr(python_class, attr.py_name) and attr.py_name != '':
setattr(python_class, attr.py_name, attr())
setattr(python_class, 'visa_attributes_classes', attrs)
return python_class
return _internal
def __init__(self, resource_manager, resource_name):
self._resource_manager = resource_manager
self.visalib = self._resource_manager.visalib
self._resource_name = resource_name
self._logging_extra = {'library_path': self.visalib.library_path,
'resource_manager.session': self._resource_manager.session,
'resource_name': self._resource_name,
'session': None}
#: Session handle.
self._session = None
@property
def session(self):
"""Resource session handle.
:raises: :class:`pyvisa.errors.InvalidSession` if session is closed.
"""
if self._session is None:
raise errors.InvalidSession()
return self._session
@session.setter
def session(self, value):
self._session = value
def __del__(self):
self.close()
def __str__(self):
return "%s at %s" % (self.__class__.__name__, self.resource_name)
def __repr__(self):
return "<%r(%r)>" % (self.__class__.__name__, self.resource_name)
@property
def last_status(self):
"""Last status code for this session.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
return self.visalib.get_last_status_in_session(self.session)
def _cleanup_timeout(self, timeout):
if timeout is None or math.isinf(timeout):
timeout = constants.VI_TMO_INFINITE
elif timeout < 1:
timeout = constants.VI_TMO_IMMEDIATE
elif not (1 <= timeout <= 4294967294):
raise ValueError("timeout value is invalid")
else:
timeout = int(timeout)
return timeout
@property
def timeout(self):
"""The timeout in milliseconds for all resource I/O operations.
Special values:
- **immediate** (``VI_TMO_IMMEDIATE``): 0
(for convenience, any value smaller than 1 is considered as 0)
- **infinite** (``VI_TMO_INFINITE``): ``float('+inf')``
(for convenience, None is considered as ``float('+inf')``)
To set an **infinite** timeout, you can also use:
>>> del instrument.timeout
"""
timeout = self.get_visa_attribute(constants.VI_ATTR_TMO_VALUE)
if timeout == constants.VI_TMO_INFINITE:
return float('+inf')
return timeout
@timeout.setter
def timeout(self, timeout):
timeout = self._cleanup_timeout(timeout)
self.set_visa_attribute(constants.VI_ATTR_TMO_VALUE, timeout)
@timeout.deleter
def timeout(self):
self.set_visa_attribute(constants.VI_ATTR_TMO_VALUE, constants.VI_TMO_INFINITE)
@property
def resource_info(self):
"""Get the extended information of this resource.
:param resource_name: Unique symbolic name of a resource.
:rtype: :class:`pyvisa.highlevel.ResourceInfo`
"""
return self.visalib.parse_resource_extended(self._resource_manager.session, self.resource_name)
@property
def interface_type(self):
"""The interface type of the resource as a number.
"""
return self.visalib.parse_resource(self._resource_manager.session,
self.resource_name)[0].interface_type
def ignore_warning(self, *warnings_constants):
"""Ignoring warnings context manager for the current resource.
:param warnings_constants: constants identifying the warnings to ignore.
"""
return self.visalib.ignore_warning(self.session, *warnings_constants)
def open(self, access_mode=constants.AccessModes.no_lock, open_timeout=5000):
"""Opens a session to the specified resource.
:param access_mode: Specifies the mode by which the resource is to be accessed.
:type access_mode: :class:`pyvisa.constants.AccessModes`
:param open_timeout: Milliseconds before the open operation times out.
:type open_timeout: int
"""
logger.debug('%s - opening ...', self._resource_name, extra=self._logging_extra)
with self._resource_manager.ignore_warning(constants.VI_SUCCESS_DEV_NPRESENT):
self.session, status = self._resource_manager.open_bare_resource(self._resource_name, access_mode, open_timeout)
if status == constants.VI_SUCCESS_DEV_NPRESENT:
# The device was not ready when we opened the session.
# Now it gets five seconds more to become ready.
# Every 0.1 seconds we probe it with viClear.
start_time = time.time()
sleep_time = 0.1
try_time = 5
while time.time() - start_time < try_time:
time.sleep(sleep_time)
try:
self.clear()
break
except errors.VisaIOError as error:
if error.error_code != constants.VI_ERROR_NLISTENERS:
raise
self._logging_extra['session'] = self.session
logger.debug('%s - is open with session %s',
self._resource_name, self.session,
extra=self._logging_extra)
def before_close(self):
"""Called just before closing an instrument.
"""
self.__switch_events_off()
def close(self):
"""Closes the VISA session and marks the handle as invalid.
"""
try:
logger.debug('%s - closing', self._resource_name,
extra=self._logging_extra)
self.before_close()
self.visalib.close(self.session)
logger.debug('%s - is closed', self._resource_name,
extra=self._logging_extra)
self.session = None
except errors.InvalidSession:
pass
def __switch_events_off(self):
self.disable_event(constants.VI_ALL_ENABLED_EVENTS, constants.VI_ALL_MECH)
self.discard_events(constants.VI_ALL_ENABLED_EVENTS, constants.VI_ALL_MECH)
self.visalib.uninstall_all_visa_handlers(self.session)
def get_visa_attribute(self, name):
"""Retrieves the state of an attribute in this resource.
:param name: Resource attribute for which the state query is made (see Attributes.*)
:return: The state of the queried attribute for a specified resource.
:rtype: unicode (Py2) or str (Py3), list or other type
"""
return self.visalib.get_attribute(self.session, name)[0]
def set_visa_attribute(self, name, state):
"""Sets the state of an attribute.
:param name: Attribute for which the state is to be modified. (Attributes.*)
:param state: The state of the attribute to be set for the specified object.
"""
self.visalib.set_attribute(self.session, name, state)
def clear(self):
"""Clears this resource
"""
self.visalib.clear(self.session)
def install_handler(self, event_type, handler, user_handle=None):
"""Installs handlers for event callbacks in this resource.
:param event_type: Logical event identifier.
:param handler: Interpreted as a valid reference to a handler to be installed by a client application.
:param user_handle: A value specified by an application that can be used for identifying handlers
uniquely for an event type.
:returns: user handle (a ctypes object)
"""
return self.visalib.install_visa_handler(self.session, event_type, handler, user_handle)
def uninstall_handler(self, event_type, handler, user_handle=None):
"""Uninstalls handlers for events in this resource.
:param event_type: Logical event identifier.
:param handler: Interpreted as a valid reference to a handler to be uninstalled by a client application.
:param user_handle: The user handle (ctypes object or None) returned by install_handler.
"""
self.visalib.uninstall_visa_handler(self.session, event_type, handler, user_handle)
def disable_event(self, event_type, mechanism):
"""Disables notification of the specified event type(s) via the specified mechanism(s).
:param event_type: Logical event identifier.
:param mechanism: Specifies event handling mechanisms to be disabled.
(Constants.VI_QUEUE, .VI_HNDLR, .VI_SUSPEND_HNDLR, .VI_ALL_MECH)
"""
self.visalib.disable_event(self.session, event_type, mechanism)
def discard_events(self, event_type, mechanism):
"""Discards event occurrences for specified event types and mechanisms in this resource.
:param event_type: Logical event identifier.
:param mechanism: Specifies event handling mechanisms to be dicarded.
(Constants.VI_QUEUE, .VI_HNDLR, .VI_SUSPEND_HNDLR, .VI_ALL_MECH)
"""
self.visalib.discard_events(self.session, event_type, mechanism)
def enable_event(self, event_type, mechanism, context=None):
"""Enable event occurrences for specified event types and mechanisms in this resource.
:param event_type: Logical event identifier.
:param mechanism: Specifies event handling mechanisms to be enabled.
(Constants.VI_QUEUE, .VI_HNDLR, .VI_SUSPEND_HNDLR)
:param context: Not currently used, leave as None.
"""
self.visalib.enable_event(self.session, event_type, mechanism, context)
def wait_on_event(self, in_event_type, timeout, capture_timeout=False):
"""Waits for an occurrence of the specified event in this resource.
:param in_event_type: Logical identifier of the event(s) to wait for.
:param timeout: Absolute time period in time units that the resource shall wait for a specified event to
occur before returning the time elapsed error. The time unit is in milliseconds.
None means waiting forever if necessary.
:param capture_timeout: When True will not produce a VisaIOError(VI_ERROR_TMO) but
instead return a WaitResponse with timed_out=True
:return: A WaitResponse object that contains event_type, context and ret value.
"""
try:
event_type, context, ret = self.visalib.wait_on_event(self.session, in_event_type, timeout)
except errors.VisaIOError as exc:
if capture_timeout and exc.error_code == constants.StatusCode.error_timeout:
return WaitResponse(0, None, exc.error_code, self.visalib, timed_out=True)
raise
return WaitResponse(event_type, context, ret, self.visalib)
def lock(self, timeout='default', requested_key=None):
"""Establish a shared lock to the resource.
:param timeout: Absolute time period (in milliseconds) that a resource
waits to get unlocked by the locking session before
returning an error. (Defaults to self.timeout)
:param requested_key: Access key used by another session with which you
want your session to share a lock or None to generate
a new shared access key.
:returns: A new shared access key if requested_key is None,
otherwise, same value as the requested_key
"""
timeout = self.timeout if timeout == 'default' else timeout
timeout = self._cleanup_timeout(timeout)
return self.visalib.lock(self.session, constants.AccessModes.shared_lock, timeout, requested_key)[0]
def lock_excl(self, timeout='default'):
"""Establish an exclusive lock to the resource.
:param timeout: Absolute time period (in milliseconds) that a resource
waits to get unlocked by the locking session before
returning an error. (Defaults to self.timeout)
"""
timeout = self.timeout if timeout == 'default' else timeout
timeout = self._cleanup_timeout(timeout)
self.visalib.lock(self.session, constants.AccessModes.exclusive_lock, timeout, None)
def unlock(self):
"""Relinquishes a lock for the specified resource.
"""
self.visalib.unlock(self.session)
@contextlib.contextmanager
def lock_context(self, timeout='default', requested_key='exclusive'):
"""A context that locks
:param timeout: Absolute time period (in milliseconds) that a resource
waits to get unlocked by the locking session before
returning an error. (Defaults to self.timeout)
:param requested_key: When using default of 'exclusive' the lock
is an exclusive lock.
Otherwise it is the access key for the shared lock or
None to generate a new shared access key.
The returned context is the access_key if applicable.
"""
if requested_key == 'exclusive':
self.lock_excl(timeout)
access_key = None
else:
access_key = self.lock(timeout, requested_key)
try:
yield access_key
finally:
self.unlock()
Resource.register(constants.InterfaceType.unknown, '')(Resource)
|