INSTRUCTION
stringlengths 1
46.3k
| RESPONSE
stringlengths 75
80.2k
|
|---|---|
Publishes end-to-end encryption keys for the device.
Said device must be the one used when logging in.
Args:
device_keys (dict): Optional. Identity keys for the device. The required
keys are:
| user_id (str): The ID of the user the device belongs to. Must match
the user ID used when logging in.
| device_id (str): The ID of the device these keys belong to. Must match
the device ID used when logging in.
| algorithms (list<str>): The encryption algorithms supported by this
device.
| keys (dict): Public identity keys. Should be formatted as
<algorithm:device_id>: <key>.
| signatures (dict): Signatures for the device key object. Should be
formatted as <user_id>: {<algorithm:device_id>: <key>}
one_time_keys (dict): Optional. One-time public keys. Should be
formatted as <algorithm:key_id>: <key>, the key format being
determined by the algorithm.
|
def upload_keys(self, device_keys=None, one_time_keys=None):
"""Publishes end-to-end encryption keys for the device.
Said device must be the one used when logging in.
Args:
device_keys (dict): Optional. Identity keys for the device. The required
keys are:
| user_id (str): The ID of the user the device belongs to. Must match
the user ID used when logging in.
| device_id (str): The ID of the device these keys belong to. Must match
the device ID used when logging in.
| algorithms (list<str>): The encryption algorithms supported by this
device.
| keys (dict): Public identity keys. Should be formatted as
<algorithm:device_id>: <key>.
| signatures (dict): Signatures for the device key object. Should be
formatted as <user_id>: {<algorithm:device_id>: <key>}
one_time_keys (dict): Optional. One-time public keys. Should be
formatted as <algorithm:key_id>: <key>, the key format being
determined by the algorithm.
"""
content = {}
if device_keys:
content["device_keys"] = device_keys
if one_time_keys:
content["one_time_keys"] = one_time_keys
return self._send("POST", "/keys/upload", content=content)
|
Query HS for public keys by user and optionally device.
Args:
user_devices (dict): The devices whose keys to download. Should be
formatted as <user_id>: [<device_ids>]. No device_ids indicates
all devices for the corresponding user.
timeout (int): Optional. The time (in milliseconds) to wait when
downloading keys from remote servers.
token (str): Optional. If the client is fetching keys as a result of
a device update received in a sync request, this should be the
'since' token of that sync request, or any later sync token.
|
def query_keys(self, user_devices, timeout=None, token=None):
"""Query HS for public keys by user and optionally device.
Args:
user_devices (dict): The devices whose keys to download. Should be
formatted as <user_id>: [<device_ids>]. No device_ids indicates
all devices for the corresponding user.
timeout (int): Optional. The time (in milliseconds) to wait when
downloading keys from remote servers.
token (str): Optional. If the client is fetching keys as a result of
a device update received in a sync request, this should be the
'since' token of that sync request, or any later sync token.
"""
content = {"device_keys": user_devices}
if timeout:
content["timeout"] = timeout
if token:
content["token"] = token
return self._send("POST", "/keys/query", content=content)
|
Claims one-time keys for use in pre-key messages.
Args:
key_request (dict): The keys to be claimed. Format should be
<user_id>: { <device_id>: <algorithm> }.
timeout (int): Optional. The time (in milliseconds) to wait when
downloading keys from remote servers.
|
def claim_keys(self, key_request, timeout=None):
"""Claims one-time keys for use in pre-key messages.
Args:
key_request (dict): The keys to be claimed. Format should be
<user_id>: { <device_id>: <algorithm> }.
timeout (int): Optional. The time (in milliseconds) to wait when
downloading keys from remote servers.
"""
content = {"one_time_keys": key_request}
if timeout:
content["timeout"] = timeout
return self._send("POST", "/keys/claim", content=content)
|
Gets a list of users who have updated their device identity keys.
Args:
from_token (str): The desired start point of the list. Should be the
next_batch field from a response to an earlier call to /sync.
to_token (str): The desired end point of the list. Should be the next_batch
field from a recent call to /sync - typically the most recent such call.
|
def key_changes(self, from_token, to_token):
"""Gets a list of users who have updated their device identity keys.
Args:
from_token (str): The desired start point of the list. Should be the
next_batch field from a response to an earlier call to /sync.
to_token (str): The desired end point of the list. Should be the next_batch
field from a recent call to /sync - typically the most recent such call.
"""
params = {"from": from_token, "to": to_token}
return self._send("GET", "/keys/changes", query_params=params)
|
Sends send-to-device events to a set of client devices.
Args:
event_type (str): The type of event to send.
messages (dict): The messages to send. Format should be
<user_id>: {<device_id>: <event_content>}.
The device ID may also be '*', meaning all known devices for the user.
txn_id (str): Optional. The transaction ID for this event, will be generated
automatically otherwise.
|
def send_to_device(self, event_type, messages, txn_id=None):
"""Sends send-to-device events to a set of client devices.
Args:
event_type (str): The type of event to send.
messages (dict): The messages to send. Format should be
<user_id>: {<device_id>: <event_content>}.
The device ID may also be '*', meaning all known devices for the user.
txn_id (str): Optional. The transaction ID for this event, will be generated
automatically otherwise.
"""
txn_id = txn_id if txn_id else self._make_txn_id()
return self._send(
"PUT",
"/sendToDevice/{}/{}".format(event_type, txn_id),
content={"messages": messages}
)
|
Register a guest account on this HS.
Note: HS must have guest registration enabled.
Returns:
str: Access Token
Raises:
MatrixRequestError
|
def register_as_guest(self):
""" Register a guest account on this HS.
Note: HS must have guest registration enabled.
Returns:
str: Access Token
Raises:
MatrixRequestError
"""
response = self.api.register(auth_body=None, kind='guest')
return self._post_registration(response)
|
Register for a new account on this HS.
Args:
username (str): Account username
password (str): Account password
Returns:
str: Access Token
Raises:
MatrixRequestError
|
def register_with_password(self, username, password):
""" Register for a new account on this HS.
Args:
username (str): Account username
password (str): Account password
Returns:
str: Access Token
Raises:
MatrixRequestError
"""
response = self.api.register(
auth_body={"type": "m.login.dummy"},
kind='user',
username=username,
password=password,
)
return self._post_registration(response)
|
Deprecated. Use ``login`` with ``sync=False``.
Login to the homeserver.
Args:
username (str): Account username
password (str): Account password
Returns:
str: Access token
Raises:
MatrixRequestError
|
def login_with_password_no_sync(self, username, password):
"""Deprecated. Use ``login`` with ``sync=False``.
Login to the homeserver.
Args:
username (str): Account username
password (str): Account password
Returns:
str: Access token
Raises:
MatrixRequestError
"""
warn("login_with_password_no_sync is deprecated. Use login with sync=False.",
DeprecationWarning)
return self.login(username, password, sync=False)
|
Deprecated. Use ``login`` with ``sync=True``.
Login to the homeserver.
Args:
username (str): Account username
password (str): Account password
limit (int): Deprecated. How many messages to return when syncing.
This will be replaced by a filter API in a later release.
Returns:
str: Access token
Raises:
MatrixRequestError
|
def login_with_password(self, username, password, limit=10):
"""Deprecated. Use ``login`` with ``sync=True``.
Login to the homeserver.
Args:
username (str): Account username
password (str): Account password
limit (int): Deprecated. How many messages to return when syncing.
This will be replaced by a filter API in a later release.
Returns:
str: Access token
Raises:
MatrixRequestError
"""
warn("login_with_password is deprecated. Use login with sync=True.",
DeprecationWarning)
return self.login(username, password, limit, sync=True)
|
Login to the homeserver.
Args:
username (str): Account username
password (str): Account password
limit (int): Deprecated. How many messages to return when syncing.
This will be replaced by a filter API in a later release.
sync (bool): Optional. Whether to initiate a /sync request after logging in.
device_id (str): Optional. ID of the client device. The server will
auto-generate a device_id if this is not specified.
Returns:
str: Access token
Raises:
MatrixRequestError
|
def login(self, username, password, limit=10, sync=True, device_id=None):
"""Login to the homeserver.
Args:
username (str): Account username
password (str): Account password
limit (int): Deprecated. How many messages to return when syncing.
This will be replaced by a filter API in a later release.
sync (bool): Optional. Whether to initiate a /sync request after logging in.
device_id (str): Optional. ID of the client device. The server will
auto-generate a device_id if this is not specified.
Returns:
str: Access token
Raises:
MatrixRequestError
"""
response = self.api.login(
"m.login.password", user=username, password=password, device_id=device_id
)
self.user_id = response["user_id"]
self.token = response["access_token"]
self.hs = response["home_server"]
self.api.token = self.token
self.device_id = response["device_id"]
if self._encryption:
self.olm_device = OlmDevice(
self.api, self.user_id, self.device_id, **self.encryption_conf)
self.olm_device.upload_identity_keys()
self.olm_device.upload_one_time_keys()
if sync:
""" Limit Filter """
self.sync_filter = '{ "room": { "timeline" : { "limit" : %i } } }' % limit
self._sync()
return self.token
|
Create a new room on the homeserver.
Args:
alias (str): The canonical_alias of the room.
is_public (bool): The public/private visibility of the room.
invitees (str[]): A set of user ids to invite into the room.
Returns:
Room
Raises:
MatrixRequestError
|
def create_room(self, alias=None, is_public=False, invitees=None):
""" Create a new room on the homeserver.
Args:
alias (str): The canonical_alias of the room.
is_public (bool): The public/private visibility of the room.
invitees (str[]): A set of user ids to invite into the room.
Returns:
Room
Raises:
MatrixRequestError
"""
response = self.api.create_room(alias=alias,
is_public=is_public,
invitees=invitees)
return self._mkroom(response["room_id"])
|
Join a room.
Args:
room_id_or_alias (str): Room ID or an alias.
Returns:
Room
Raises:
MatrixRequestError
|
def join_room(self, room_id_or_alias):
""" Join a room.
Args:
room_id_or_alias (str): Room ID or an alias.
Returns:
Room
Raises:
MatrixRequestError
"""
response = self.api.join_room(room_id_or_alias)
room_id = (
response["room_id"] if "room_id" in response else room_id_or_alias
)
return self._mkroom(room_id)
|
Add a listener that will send a callback when the client recieves
an event.
Args:
callback (func(roomchunk)): Callback called when an event arrives.
event_type (str): The event_type to filter for.
Returns:
uuid.UUID: Unique id of the listener, can be used to identify the listener.
|
def add_listener(self, callback, event_type=None):
""" Add a listener that will send a callback when the client recieves
an event.
Args:
callback (func(roomchunk)): Callback called when an event arrives.
event_type (str): The event_type to filter for.
Returns:
uuid.UUID: Unique id of the listener, can be used to identify the listener.
"""
listener_uid = uuid4()
# TODO: listeners should be stored in dict and accessed/deleted directly. Add
# convenience method such that MatrixClient.listeners.new(Listener(...)) performs
# MatrixClient.listeners[uuid4()] = Listener(...)
self.listeners.append(
{
'uid': listener_uid,
'callback': callback,
'event_type': event_type
}
)
return listener_uid
|
Add a presence listener that will send a callback when the client receives
a presence update.
Args:
callback (func(roomchunk)): Callback called when a presence update arrives.
Returns:
uuid.UUID: Unique id of the listener, can be used to identify the listener.
|
def add_presence_listener(self, callback):
""" Add a presence listener that will send a callback when the client receives
a presence update.
Args:
callback (func(roomchunk)): Callback called when a presence update arrives.
Returns:
uuid.UUID: Unique id of the listener, can be used to identify the listener.
"""
listener_uid = uuid4()
self.presence_listeners[listener_uid] = callback
return listener_uid
|
Keep listening for events forever.
Args:
timeout_ms (int): How long to poll the Home Server for before
retrying.
exception_handler (func(exception)): Optional exception handler
function which can be used to handle exceptions in the caller
thread.
bad_sync_timeout (int): Base time to wait after an error before
retrying. Will be increased according to exponential backoff.
|
def listen_forever(self, timeout_ms=30000, exception_handler=None,
bad_sync_timeout=5):
""" Keep listening for events forever.
Args:
timeout_ms (int): How long to poll the Home Server for before
retrying.
exception_handler (func(exception)): Optional exception handler
function which can be used to handle exceptions in the caller
thread.
bad_sync_timeout (int): Base time to wait after an error before
retrying. Will be increased according to exponential backoff.
"""
_bad_sync_timeout = bad_sync_timeout
self.should_listen = True
while (self.should_listen):
try:
self._sync(timeout_ms)
_bad_sync_timeout = bad_sync_timeout
# TODO: we should also handle MatrixHttpLibError for retry in case no response
except MatrixRequestError as e:
logger.warning("A MatrixRequestError occured during sync.")
if e.code >= 500:
logger.warning("Problem occured serverside. Waiting %i seconds",
bad_sync_timeout)
sleep(bad_sync_timeout)
_bad_sync_timeout = min(_bad_sync_timeout * 2,
self.bad_sync_timeout_limit)
elif exception_handler is not None:
exception_handler(e)
else:
raise
except Exception as e:
logger.exception("Exception thrown during sync")
if exception_handler is not None:
exception_handler(e)
else:
raise
|
Start a listener thread to listen for events in the background.
Args:
timeout (int): How long to poll the Home Server for before
retrying.
exception_handler (func(exception)): Optional exception handler
function which can be used to handle exceptions in the caller
thread.
|
def start_listener_thread(self, timeout_ms=30000, exception_handler=None):
""" Start a listener thread to listen for events in the background.
Args:
timeout (int): How long to poll the Home Server for before
retrying.
exception_handler (func(exception)): Optional exception handler
function which can be used to handle exceptions in the caller
thread.
"""
try:
thread = Thread(target=self.listen_forever,
args=(timeout_ms, exception_handler))
thread.daemon = True
self.sync_thread = thread
self.should_listen = True
thread.start()
except RuntimeError:
e = sys.exc_info()[0]
logger.error("Error: unable to start thread. %s", str(e))
|
Stop listener thread running in the background
|
def stop_listener_thread(self):
""" Stop listener thread running in the background
"""
if self.sync_thread:
self.should_listen = False
self.sync_thread.join()
self.sync_thread = None
|
Upload content to the home server and recieve a MXC url.
Args:
content (bytes): The data of the content.
content_type (str): The mimetype of the content.
filename (str): Optional. Filename of the content.
Raises:
MatrixUnexpectedResponse: If the homeserver gave a strange response
MatrixRequestError: If the upload failed for some reason.
|
def upload(self, content, content_type, filename=None):
""" Upload content to the home server and recieve a MXC url.
Args:
content (bytes): The data of the content.
content_type (str): The mimetype of the content.
filename (str): Optional. Filename of the content.
Raises:
MatrixUnexpectedResponse: If the homeserver gave a strange response
MatrixRequestError: If the upload failed for some reason.
"""
try:
response = self.api.media_upload(content, content_type, filename)
if "content_uri" in response:
return response["content_uri"]
else:
raise MatrixUnexpectedResponse(
"The upload was successful, but content_uri wasn't found."
)
except MatrixRequestError as e:
raise MatrixRequestError(
code=e.code,
content="Upload failed: %s" % e
)
|
Remove mapping of an alias
Args:
room_alias(str): The alias to be removed.
Returns:
bool: True if the alias is removed, False otherwise.
|
def remove_room_alias(self, room_alias):
"""Remove mapping of an alias
Args:
room_alias(str): The alias to be removed.
Returns:
bool: True if the alias is removed, False otherwise.
"""
try:
self.api.remove_room_alias(room_alias)
return True
except MatrixRequestError:
return False
|
Uploads this device's identity keys to HS.
This device must be the one used when logging in.
|
def upload_identity_keys(self):
"""Uploads this device's identity keys to HS.
This device must be the one used when logging in.
"""
device_keys = {
'user_id': self.user_id,
'device_id': self.device_id,
'algorithms': self._algorithms,
'keys': {'{}:{}'.format(alg, self.device_id): key
for alg, key in self.identity_keys.items()}
}
self.sign_json(device_keys)
ret = self.api.upload_keys(device_keys=device_keys)
self.one_time_keys_manager.server_counts = ret['one_time_key_counts']
logger.info('Uploaded identity keys.')
|
Uploads new one-time keys to the HS, if needed.
Args:
force_update (bool): Fetch the number of one-time keys currently on the HS
before uploading, even if we already know one. In most cases this should
not be necessary, as we get this value from sync responses.
Returns:
A dict containg the number of new keys that were uploaded for each key type
(signed_curve25519 or curve25519). The format is
``<key_type>: <uploaded_number>``. If no keys of a given type have been
uploaded, the corresponding key will not be present. Consequently, an
empty dict indicates that no keys were uploaded.
|
def upload_one_time_keys(self, force_update=False):
"""Uploads new one-time keys to the HS, if needed.
Args:
force_update (bool): Fetch the number of one-time keys currently on the HS
before uploading, even if we already know one. In most cases this should
not be necessary, as we get this value from sync responses.
Returns:
A dict containg the number of new keys that were uploaded for each key type
(signed_curve25519 or curve25519). The format is
``<key_type>: <uploaded_number>``. If no keys of a given type have been
uploaded, the corresponding key will not be present. Consequently, an
empty dict indicates that no keys were uploaded.
"""
if force_update or not self.one_time_keys_manager.server_counts:
counts = self.api.upload_keys()['one_time_key_counts']
self.one_time_keys_manager.server_counts = counts
signed_keys_to_upload = self.one_time_keys_manager.signed_curve25519_to_upload
unsigned_keys_to_upload = self.one_time_keys_manager.curve25519_to_upload
self.olm_account.generate_one_time_keys(signed_keys_to_upload +
unsigned_keys_to_upload)
one_time_keys = {}
keys = self.olm_account.one_time_keys['curve25519']
for i, key_id in enumerate(keys):
if i < signed_keys_to_upload:
key = self.sign_json({'key': keys[key_id]})
key_type = 'signed_curve25519'
else:
key = keys[key_id]
key_type = 'curve25519'
one_time_keys['{}:{}'.format(key_type, key_id)] = key
ret = self.api.upload_keys(one_time_keys=one_time_keys)
self.one_time_keys_manager.server_counts = ret['one_time_key_counts']
self.olm_account.mark_keys_as_published()
keys_uploaded = {}
if unsigned_keys_to_upload:
keys_uploaded['curve25519'] = unsigned_keys_to_upload
if signed_keys_to_upload:
keys_uploaded['signed_curve25519'] = signed_keys_to_upload
logger.info('Uploaded new one-time keys: %s.', keys_uploaded)
return keys_uploaded
|
Update data on one-time keys count and upload new ones if necessary.
Args:
counts (dict): Counts of keys currently on the HS for each key type.
|
def update_one_time_key_counts(self, counts):
"""Update data on one-time keys count and upload new ones if necessary.
Args:
counts (dict): Counts of keys currently on the HS for each key type.
"""
self.one_time_keys_manager.server_counts = counts
if self.one_time_keys_manager.should_upload():
logger.info('Uploading new one-time keys.')
self.upload_one_time_keys()
|
Signs a JSON object.
NOTE: The object is modified in-place and the return value can be ignored.
As specified, this is done by encoding the JSON object without ``signatures`` or
keys grouped as ``unsigned``, using canonical encoding.
Args:
json (dict): The JSON object to sign.
Returns:
The same JSON object, with a ``signatures`` key added. It is formatted as
``"signatures": ed25519:<device_id>: <base64_signature>``.
|
def sign_json(self, json):
"""Signs a JSON object.
NOTE: The object is modified in-place and the return value can be ignored.
As specified, this is done by encoding the JSON object without ``signatures`` or
keys grouped as ``unsigned``, using canonical encoding.
Args:
json (dict): The JSON object to sign.
Returns:
The same JSON object, with a ``signatures`` key added. It is formatted as
``"signatures": ed25519:<device_id>: <base64_signature>``.
"""
signatures = json.pop('signatures', {})
unsigned = json.pop('unsigned', None)
signature_base64 = self.olm_account.sign(encode_canonical_json(json))
key_id = 'ed25519:{}'.format(self.device_id)
signatures.setdefault(self.user_id, {})[key_id] = signature_base64
json['signatures'] = signatures
if unsigned:
json['unsigned'] = unsigned
return json
|
Verifies a signed key object's signature.
The object must have a 'signatures' key associated with an object of the form
`user_id: {key_id: signature}`.
Args:
json (dict): The JSON object to verify.
user_key (str): The public ed25519 key which was used to sign the object.
user_id (str): The user who owns the device.
device_id (str): The device who owns the key.
Returns:
True if the verification was successful, False if not.
|
def verify_json(self, json, user_key, user_id, device_id):
"""Verifies a signed key object's signature.
The object must have a 'signatures' key associated with an object of the form
`user_id: {key_id: signature}`.
Args:
json (dict): The JSON object to verify.
user_key (str): The public ed25519 key which was used to sign the object.
user_id (str): The user who owns the device.
device_id (str): The device who owns the key.
Returns:
True if the verification was successful, False if not.
"""
try:
signatures = json.pop('signatures')
except KeyError:
return False
key_id = 'ed25519:{}'.format(device_id)
try:
signature_base64 = signatures[user_id][key_id]
except KeyError:
json['signatures'] = signatures
return False
unsigned = json.pop('unsigned', None)
try:
olm.ed25519_verify(user_key, encode_canonical_json(json), signature_base64)
success = True
except olm.utility.OlmVerifyError:
success = False
json['signatures'] = signatures
if unsigned:
json['unsigned'] = unsigned
return success
|
Get this user's display name.
Args:
room (Room): Optional. When specified, return the display name of the user
in this room.
Returns:
The display name. Defaults to the user ID if not set.
|
def get_display_name(self, room=None):
"""Get this user's display name.
Args:
room (Room): Optional. When specified, return the display name of the user
in this room.
Returns:
The display name. Defaults to the user ID if not set.
"""
if room:
try:
return room.members_displaynames[self.user_id]
except KeyError:
return self.user_id
if not self.displayname:
self.displayname = self.api.get_display_name(self.user_id)
return self.displayname or self.user_id
|
Set this users display name.
Args:
display_name (str): Display Name
|
def set_display_name(self, display_name):
""" Set this users display name.
Args:
display_name (str): Display Name
"""
self.displayname = display_name
return self.api.set_display_name(self.user_id, display_name)
|
Creates a prepared request to send to the server with an encrypted message
and correct headers
:param session: The handle of the session to prepare requests with
:param endpoint: The endpoint/server to prepare requests to
:param message: The unencrypted message to send to the server
:return: A prepared request that has an encrypted message
|
def prepare_encrypted_request(self, session, endpoint, message):
"""
Creates a prepared request to send to the server with an encrypted message
and correct headers
:param session: The handle of the session to prepare requests with
:param endpoint: The endpoint/server to prepare requests to
:param message: The unencrypted message to send to the server
:return: A prepared request that has an encrypted message
"""
host = urlsplit(endpoint).hostname
if self.protocol == 'credssp' and len(message) > self.SIXTEN_KB:
content_type = 'multipart/x-multi-encrypted'
encrypted_message = b''
message_chunks = [message[i:i+self.SIXTEN_KB] for i in range(0, len(message), self.SIXTEN_KB)]
for message_chunk in message_chunks:
encrypted_chunk = self._encrypt_message(message_chunk, host)
encrypted_message += encrypted_chunk
else:
content_type = 'multipart/encrypted'
encrypted_message = self._encrypt_message(message, host)
encrypted_message += self.MIME_BOUNDARY + b"--\r\n"
request = requests.Request('POST', endpoint, data=encrypted_message)
prepared_request = session.prepare_request(request)
prepared_request.headers['Content-Length'] = str(len(prepared_request.body))
prepared_request.headers['Content-Type'] = '{0};protocol="{1}";boundary="Encrypted Boundary"'\
.format(content_type, self.protocol_string.decode())
return prepared_request
|
Takes in the encrypted response from the server and decrypts it
:param response: The response that needs to be decrytped
:return: The unencrypted message from the server
|
def parse_encrypted_response(self, response):
"""
Takes in the encrypted response from the server and decrypts it
:param response: The response that needs to be decrytped
:return: The unencrypted message from the server
"""
content_type = response.headers['Content-Type']
if 'protocol="{0}"'.format(self.protocol_string.decode()) in content_type:
host = urlsplit(response.request.url).hostname
msg = self._decrypt_response(response, host)
else:
msg = response.text
return msg
|
Create a Shell on the destination host
@param string i_stream: Which input stream to open. Leave this alone
unless you know what you're doing (default: stdin)
@param string o_stream: Which output stream to open. Leave this alone
unless you know what you're doing (default: stdout stderr)
@param string working_directory: the directory to create the shell in
@param dict env_vars: environment variables to set for the shell. For
instance: {'PATH': '%PATH%;c:/Program Files (x86)/Git/bin/', 'CYGWIN':
'nontsec codepage:utf8'}
@returns The ShellId from the SOAP response. This is our open shell
instance on the remote machine.
@rtype string
|
def open_shell(self, i_stream='stdin', o_stream='stdout stderr',
working_directory=None, env_vars=None, noprofile=False,
codepage=437, lifetime=None, idle_timeout=None):
"""
Create a Shell on the destination host
@param string i_stream: Which input stream to open. Leave this alone
unless you know what you're doing (default: stdin)
@param string o_stream: Which output stream to open. Leave this alone
unless you know what you're doing (default: stdout stderr)
@param string working_directory: the directory to create the shell in
@param dict env_vars: environment variables to set for the shell. For
instance: {'PATH': '%PATH%;c:/Program Files (x86)/Git/bin/', 'CYGWIN':
'nontsec codepage:utf8'}
@returns The ShellId from the SOAP response. This is our open shell
instance on the remote machine.
@rtype string
"""
req = {'env:Envelope': self._get_soap_header(
resource_uri='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd', # NOQA
action='http://schemas.xmlsoap.org/ws/2004/09/transfer/Create')}
header = req['env:Envelope']['env:Header']
header['w:OptionSet'] = {
'w:Option': [
{
'@Name': 'WINRS_NOPROFILE',
'#text': str(noprofile).upper() # TODO remove str call
},
{
'@Name': 'WINRS_CODEPAGE',
'#text': str(codepage) # TODO remove str call
}
]
}
shell = req['env:Envelope'].setdefault(
'env:Body', {}).setdefault('rsp:Shell', {})
shell['rsp:InputStreams'] = i_stream
shell['rsp:OutputStreams'] = o_stream
if working_directory:
# TODO ensure that rsp:WorkingDirectory should be nested within rsp:Shell # NOQA
shell['rsp:WorkingDirectory'] = working_directory
# TODO check Lifetime param: http://msdn.microsoft.com/en-us/library/cc251546(v=PROT.13).aspx # NOQA
#if lifetime:
# shell['rsp:Lifetime'] = iso8601_duration.sec_to_dur(lifetime)
# TODO make it so the input is given in milliseconds and converted to xs:duration # NOQA
if idle_timeout:
shell['rsp:IdleTimeOut'] = idle_timeout
if env_vars:
env = shell.setdefault('rsp:Environment', {})
for key, value in env_vars.items():
env['rsp:Variable'] = {'@Name': key, '#text': value}
res = self.send_message(xmltodict.unparse(req))
#res = xmltodict.parse(res)
#return res['s:Envelope']['s:Body']['x:ResourceCreated']['a:ReferenceParameters']['w:SelectorSet']['w:Selector']['#text']
root = ET.fromstring(res)
return next(
node for node in root.findall('.//*')
if node.get('Name') == 'ShellId').text
|
Close the shell
@param string shell_id: The shell id on the remote machine.
See #open_shell
@returns This should have more error checking but it just returns true
for now.
@rtype bool
|
def close_shell(self, shell_id):
"""
Close the shell
@param string shell_id: The shell id on the remote machine.
See #open_shell
@returns This should have more error checking but it just returns true
for now.
@rtype bool
"""
message_id = uuid.uuid4()
req = {'env:Envelope': self._get_soap_header(
resource_uri='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd', # NOQA
action='http://schemas.xmlsoap.org/ws/2004/09/transfer/Delete',
shell_id=shell_id,
message_id=message_id)}
# SOAP message requires empty env:Body
req['env:Envelope'].setdefault('env:Body', {})
res = self.send_message(xmltodict.unparse(req))
root = ET.fromstring(res)
relates_to = next(
node for node in root.findall('.//*')
if node.tag.endswith('RelatesTo')).text
# TODO change assert into user-friendly exception
assert uuid.UUID(relates_to.replace('uuid:', '')) == message_id
|
Run a command on a machine with an open shell
@param string shell_id: The shell id on the remote machine.
See #open_shell
@param string command: The command to run on the remote machine
@param iterable of string arguments: An array of arguments for this
command
@param bool console_mode_stdin: (default: True)
@param bool skip_cmd_shell: (default: False)
@return: The CommandId from the SOAP response.
This is the ID we need to query in order to get output.
@rtype string
|
def run_command(
self, shell_id, command, arguments=(), console_mode_stdin=True,
skip_cmd_shell=False):
"""
Run a command on a machine with an open shell
@param string shell_id: The shell id on the remote machine.
See #open_shell
@param string command: The command to run on the remote machine
@param iterable of string arguments: An array of arguments for this
command
@param bool console_mode_stdin: (default: True)
@param bool skip_cmd_shell: (default: False)
@return: The CommandId from the SOAP response.
This is the ID we need to query in order to get output.
@rtype string
"""
req = {'env:Envelope': self._get_soap_header(
resource_uri='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd', # NOQA
action='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Command', # NOQA
shell_id=shell_id)}
header = req['env:Envelope']['env:Header']
header['w:OptionSet'] = {
'w:Option': [
{
'@Name': 'WINRS_CONSOLEMODE_STDIN',
'#text': str(console_mode_stdin).upper()
},
{
'@Name': 'WINRS_SKIP_CMD_SHELL',
'#text': str(skip_cmd_shell).upper()
}
]
}
cmd_line = req['env:Envelope'].setdefault(
'env:Body', {}).setdefault('rsp:CommandLine', {})
cmd_line['rsp:Command'] = {'#text': command}
if arguments:
unicode_args = [a if isinstance(a, text_type) else a.decode('utf-8') for a in arguments]
cmd_line['rsp:Arguments'] = u' '.join(unicode_args)
res = self.send_message(xmltodict.unparse(req))
root = ET.fromstring(res)
command_id = next(
node for node in root.findall('.//*')
if node.tag.endswith('CommandId')).text
return command_id
|
Get the Output of the given shell and command
@param string shell_id: The shell id on the remote machine.
See #open_shell
@param string command_id: The command id on the remote machine.
See #run_command
#@return [Hash] Returns a Hash with a key :exitcode and :data.
Data is an Array of Hashes where the cooresponding key
# is either :stdout or :stderr. The reason it is in an Array so so
we can get the output in the order it ocurrs on
# the console.
|
def get_command_output(self, shell_id, command_id):
"""
Get the Output of the given shell and command
@param string shell_id: The shell id on the remote machine.
See #open_shell
@param string command_id: The command id on the remote machine.
See #run_command
#@return [Hash] Returns a Hash with a key :exitcode and :data.
Data is an Array of Hashes where the cooresponding key
# is either :stdout or :stderr. The reason it is in an Array so so
we can get the output in the order it ocurrs on
# the console.
"""
stdout_buffer, stderr_buffer = [], []
command_done = False
while not command_done:
try:
stdout, stderr, return_code, command_done = \
self._raw_get_command_output(shell_id, command_id)
stdout_buffer.append(stdout)
stderr_buffer.append(stderr)
except WinRMOperationTimeoutError as e:
# this is an expected error when waiting for a long-running process, just silently retry
pass
return b''.join(stdout_buffer), b''.join(stderr_buffer), return_code
|
base64 encodes a Powershell script and executes the powershell
encoded script command
|
def run_ps(self, script):
"""base64 encodes a Powershell script and executes the powershell
encoded script command
"""
# must use utf16 little endian on windows
encoded_ps = b64encode(script.encode('utf_16_le')).decode('ascii')
rs = self.run_cmd('powershell -encodedcommand {0}'.format(encoded_ps))
if len(rs.std_err):
# if there was an error message, clean it it up and make it human
# readable
rs.std_err = self._clean_error_msg(rs.std_err)
return rs
|
converts a Powershell CLIXML message to a more human readable string
|
def _clean_error_msg(self, msg):
"""converts a Powershell CLIXML message to a more human readable string
"""
# TODO prepare unit test, beautify code
# if the msg does not start with this, return it as is
if msg.startswith(b"#< CLIXML\r\n"):
# for proper xml, we need to remove the CLIXML part
# (the first line)
msg_xml = msg[11:]
try:
# remove the namespaces from the xml for easier processing
msg_xml = self._strip_namespace(msg_xml)
root = ET.fromstring(msg_xml)
# the S node is the error message, find all S nodes
nodes = root.findall("./S")
new_msg = ""
for s in nodes:
# append error msg string to result, also
# the hex chars represent CRLF so we replace with newline
new_msg += s.text.replace("_x000D__x000A_", "\n")
except Exception as e:
# if any of the above fails, the msg was not true xml
# print a warning and return the orignal string
# TODO do not print, raise user defined error instead
print("Warning: there was a problem converting the Powershell"
" error message: %s" % (e))
else:
# if new_msg was populated, that's our error message
# otherwise the original error message will be used
if len(new_msg):
# remove leading and trailing whitespace while we are here
return new_msg.strip().encode('utf-8')
# either failed to decode CLIXML or there was nothing to decode
# just return the original message
return msg
|
strips any namespaces from an xml string
|
def _strip_namespace(self, xml):
"""strips any namespaces from an xml string"""
p = re.compile(b"xmlns=*[\"\"][^\"\"]*[\"\"]")
allmatches = p.finditer(xml)
for match in allmatches:
xml = xml.replace(match.group(), b"")
return xml
|
Tell the GPIB device at the specified address to become controller in charge (CIC).
Corresponds to viGpibPassControl function of the VISA library.
:param primary_address: Primary address of the GPIB device to which you want to pass control.
:param secondary_address: Secondary address of the targeted GPIB device.
If the targeted device does not have a secondary address,
this parameter should contain the value Constants.NO_SEC_ADDR.
:return: return value of the library call.
:rtype: VISAStatus
|
def pass_control(self, primary_address, secondary_address):
"""Tell the GPIB device at the specified address to become controller in charge (CIC).
Corresponds to viGpibPassControl function of the VISA library.
:param primary_address: Primary address of the GPIB device to which you want to pass control.
:param secondary_address: Secondary address of the targeted GPIB device.
If the targeted device does not have a secondary address,
this parameter should contain the value Constants.NO_SEC_ADDR.
:return: return value of the library call.
:rtype: VISAStatus
"""
return self.visalib.gpib_pass_control(self.session, primary_address, secondary_address)
|
Decorator for VISA library classes.
|
def return_handler(module_logger, first_is_session=True):
"""Decorator for VISA library classes.
"""
def _outer(visa_library_method):
def _inner(self, session, *args, **kwargs):
ret_value = visa_library_method(*args, **kwargs)
module_logger.debug('%s%s -> %r',
visa_library_method.__name__,
_args_to_str(args, kwargs),
ret_value)
try:
ret_value = constants.StatusCode(ret_value)
except ValueError:
pass
if first_is_session:
self._last_status = ret_value
self._last_status_in_session[session] = ret_value
if ret_value < 0:
raise VisaIOError(ret_value)
if ret_value in self.issue_warning_on:
if session and ret_value not in self._ignore_warning_in_session[session]:
module_logger.warn(VisaIOWarning(ret_value), stacklevel=2)
return ret_value
return _inner
return _outer
|
Return installed backends.
Backends are installed python packages named pyvisa-<something> where <something>
is the name of the backend.
:rtype: list
|
def list_backends():
"""Return installed backends.
Backends are installed python packages named pyvisa-<something> where <something>
is the name of the backend.
:rtype: list
"""
return ['ni'] + [name for (loader, name, ispkg) in pkgutil.iter_modules()
if name.startswith('pyvisa-') and not name.endswith('-script')]
|
Return the WRAPPER_CLASS for a given backend.
:rtype: pyvisa.highlevel.VisaLibraryBase
|
def get_wrapper_class(backend_name):
"""Return the WRAPPER_CLASS for a given backend.
:rtype: pyvisa.highlevel.VisaLibraryBase
"""
try:
return _WRAPPERS[backend_name]
except KeyError:
if backend_name == 'ni':
from .ctwrapper import NIVisaLibrary
_WRAPPERS['ni'] = NIVisaLibrary
return NIVisaLibrary
try:
pkg = __import__('pyvisa-' + backend_name)
_WRAPPERS[backend_name] = cls = pkg.WRAPPER_CLASS
return cls
except ImportError:
raise ValueError('Wrapper not found: No package named pyvisa-%s' % backend_name)
|
Return an available default VISA wrapper as a string ('ni' or 'py').
Use NI if the binary is found, else try to use pyvisa-py.
If neither can be found, raise a ValueError.
|
def _get_default_wrapper():
"""Return an available default VISA wrapper as a string ('ni' or 'py').
Use NI if the binary is found, else try to use pyvisa-py.
If neither can be found, raise a ValueError.
"""
from .ctwrapper import NIVisaLibrary
ni_binary_found = bool(NIVisaLibrary.get_library_paths())
if ni_binary_found:
logger.debug('The NI implementation available')
return 'ni'
else:
logger.debug('Did not find NI binary')
try:
get_wrapper_class('py') # check for pyvisa-py availability
logger.debug('pyvisa-py is available.')
return 'py'
except ValueError:
logger.debug('Did not find pyvisa-py package')
raise ValueError('Could not locate a VISA implementation. Install either the NI binary or pyvisa-py.')
|
Helper function to create a VISA library wrapper.
In general, you should not use the function directly. The VISA library
wrapper will be created automatically when you create a ResourceManager object.
|
def open_visa_library(specification):
"""Helper function to create a VISA library wrapper.
In general, you should not use the function directly. The VISA library
wrapper will be created automatically when you create a ResourceManager object.
"""
if not specification:
logger.debug('No visa library specified, trying to find alternatives.')
try:
specification = os.environ['PYVISA_LIBRARY']
except KeyError:
logger.debug('Environment variable PYVISA_LIBRARY is unset.')
try:
argument, wrapper = specification.split('@')
except ValueError:
argument = specification
wrapper = None # Flag that we need a fallback, but avoid nested exceptions
if wrapper is None:
if argument: # some filename given
wrapper = 'ni'
else:
wrapper = _get_default_wrapper()
cls = get_wrapper_class(wrapper)
try:
return cls(argument)
except Exception as e:
logger.debug('Could not open VISA wrapper %s: %s\n%s', cls, str(argument), e)
raise
|
Last status in session.
Helper function to be called by resources properties.
|
def get_last_status_in_session(self, session):
"""Last status in session.
Helper function to be called by resources properties.
"""
try:
return self._last_status_in_session[session]
except KeyError:
raise errors.Error('The session %r does not seem to be valid as it does not have any last status' % session)
|
A session dependent context for ignoring warnings
:param session: Unique logical identifier to a session.
:param warnings_constants: constants identifying the warnings to ignore.
|
def ignore_warning(self, session, *warnings_constants):
"""A session dependent context for ignoring warnings
:param session: Unique logical identifier to a session.
:param warnings_constants: constants identifying the warnings to ignore.
"""
self._ignore_warning_in_session[session].update(warnings_constants)
yield
self._ignore_warning_in_session[session].difference_update(warnings_constants)
|
Installs handlers for event callbacks.
:param session: Unique logical identifier to a session.
: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)
|
def install_visa_handler(self, session, event_type, handler, user_handle=None):
"""Installs handlers for event callbacks.
:param session: Unique logical identifier to a session.
: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)
"""
try:
new_handler = self.install_handler(session, event_type, handler, user_handle)
except TypeError as e:
raise errors.VisaTypeError(str(e))
self.handlers[session].append(new_handler + (event_type,))
return new_handler[1]
|
Uninstalls handlers for events.
:param session: Unique logical identifier to a session.
: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_visa_handler.
|
def uninstall_visa_handler(self, session, event_type, handler, user_handle=None):
"""Uninstalls handlers for events.
:param session: Unique logical identifier to a session.
: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_visa_handler.
"""
for ndx, element in enumerate(self.handlers[session]):
if element[0] is handler and element[1] is user_handle and element[4] == event_type:
del self.handlers[session][ndx]
break
else:
raise errors.UnknownHandler(event_type, handler, user_handle)
self.uninstall_handler(session, event_type, element[2], user_handle)
|
Uninstalls all previously installed handlers for a particular session.
:param session: Unique logical identifier to a session. If None, operates on all sessions.
|
def uninstall_all_visa_handlers(self, session):
"""Uninstalls all previously installed handlers for a particular session.
:param session: Unique logical identifier to a session. If None, operates on all sessions.
"""
if session is not None:
self.__uninstall_all_handlers_helper(session)
else:
for session in list(self.handlers):
self.__uninstall_all_handlers_helper(session)
|
Write in an 8-bit, 16-bit, 32-bit, 64-bit value to the specified memory space and offset.
Corresponds to viOut* functions of the VISA library.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param data: Data to write to bus.
:param width: Number of bits to read.
:param extended: Use 64 bits offset independent of the platform.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def write_memory(self, session, space, offset, data, width, extended=False):
"""Write in an 8-bit, 16-bit, 32-bit, 64-bit value to the specified memory space and offset.
Corresponds to viOut* functions of the VISA library.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param data: Data to write to bus.
:param width: Number of bits to read.
:param extended: Use 64 bits offset independent of the platform.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
if width == 8:
return self.out_8(session, space, offset, data, extended)
elif width == 16:
return self.out_16(session, space, offset, data, extended)
elif width == 32:
return self.out_32(session, space, offset, data, extended)
elif width == 64:
return self.out_64(session, space, offset, data, extended)
raise ValueError('%s is not a valid size. Valid values are 8, 16, 32, or 64' % width)
|
Moves a block of data to local memory from the specified address space and offset.
Corresponds to viMoveIn* functions of the VISA library.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param width: Number of bits to read per element.
:param extended: Use 64 bits offset independent of the platform.
:return: Data read from the bus, return value of the library call.
:rtype: list, :class:`pyvisa.constants.StatusCode`
|
def move_in(self, session, space, offset, length, width, extended=False):
"""Moves a block of data to local memory from the specified address space and offset.
Corresponds to viMoveIn* functions of the VISA library.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param width: Number of bits to read per element.
:param extended: Use 64 bits offset independent of the platform.
:return: Data read from the bus, return value of the library call.
:rtype: list, :class:`pyvisa.constants.StatusCode`
"""
if width == 8:
return self.move_in_8(session, space, offset, length, extended)
elif width == 16:
return self.move_in_16(session, space, offset, length, extended)
elif width == 32:
return self.move_in_32(session, space, offset, length, extended)
elif width == 64:
return self.move_in_64(session, space, offset, length, extended)
raise ValueError('%s is not a valid size. Valid values are 8, 16, 32 or 64' % width)
|
Read an 8, 16, 32, or 64-bit value from the specified address.
Corresponds to viPeek* functions of the VISA library.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:param width: Number of bits to read.
:return: Data read from bus, return value of the library call.
:rtype: bytes, :class:`pyvisa.constants.StatusCode`
|
def peek(self, session, address, width):
"""Read an 8, 16, 32, or 64-bit value from the specified address.
Corresponds to viPeek* functions of the VISA library.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:param width: Number of bits to read.
:return: Data read from bus, return value of the library call.
:rtype: bytes, :class:`pyvisa.constants.StatusCode`
"""
if width == 8:
return self.peek_8(session, address)
elif width == 16:
return self.peek_16(session, address)
elif width == 32:
return self.peek_32(session, address)
elif width == 64:
return self.peek_64(session, address)
raise ValueError('%s is not a valid size. Valid values are 8, 16, 32 or 64' % width)
|
Writes an 8, 16, 32, or 64-bit value from the specified address.
Corresponds to viPoke* functions of the VISA library.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:param width: Number of bits to read.
:param data: Data to be written to the bus.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def poke(self, session, address, width, data):
"""Writes an 8, 16, 32, or 64-bit value from the specified address.
Corresponds to viPoke* functions of the VISA library.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:param width: Number of bits to read.
:param data: Data to be written to the bus.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
if width == 8:
return self.poke_8(session, address, data)
elif width == 16:
return self.poke_16(session, address, data)
elif width == 32:
return self.poke_32(session, address, data)
elif width == 64:
return self.poke_64(session, address, data)
raise ValueError('%s is not a valid size. Valid values are 8, 16, 32, or 64' % width)
|
Maps the specified memory space into the process's address space.
Corresponds to viMapAddress function of the VISA library.
:param session: Unique logical identifier to a session.
:param map_space: Specifies the address space to map. (Constants.*SPACE*)
:param map_base: Offset (in bytes) of the memory to be mapped.
:param map_size: Amount of memory to map (in bytes).
:param access:
:param suggested: If not Constants.VI_NULL (0), the operating system attempts to map the memory to the address
specified in suggested. There is no guarantee, however, that the memory will be mapped to
that address. This operation may map the memory into an address region different from
suggested.
:return: address in your process space where the memory was mapped, return value of the library call.
:rtype: address, :class:`pyvisa.constants.StatusCode`
|
def map_address(self, session, map_space, map_base, map_size,
access=False, suggested=None):
"""Maps the specified memory space into the process's address space.
Corresponds to viMapAddress function of the VISA library.
:param session: Unique logical identifier to a session.
:param map_space: Specifies the address space to map. (Constants.*SPACE*)
:param map_base: Offset (in bytes) of the memory to be mapped.
:param map_size: Amount of memory to map (in bytes).
:param access:
:param suggested: If not Constants.VI_NULL (0), the operating system attempts to map the memory to the address
specified in suggested. There is no guarantee, however, that the memory will be mapped to
that address. This operation may map the memory into an address region different from
suggested.
:return: address in your process space where the memory was mapped, return value of the library call.
:rtype: address, :class:`pyvisa.constants.StatusCode`
"""
raise NotImplementedError
|
Moves a block of data.
Corresponds to viMove function of the VISA library.
:param session: Unique logical identifier to a session.
:param source_space: Specifies the address space of the source.
:param source_offset: Offset of the starting address or register from which to read.
:param source_width: Specifies the data width of the source.
:param destination_space: Specifies the address space of the destination.
:param destination_offset: Offset of the starting address or register to which to write.
:param destination_width: Specifies the data width of the destination.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def move(self, session, source_space, source_offset, source_width, destination_space,
destination_offset, destination_width, length):
"""Moves a block of data.
Corresponds to viMove function of the VISA library.
:param session: Unique logical identifier to a session.
:param source_space: Specifies the address space of the source.
:param source_offset: Offset of the starting address or register from which to read.
:param source_width: Specifies the data width of the source.
:param destination_space: Specifies the address space of the destination.
:param destination_offset: Offset of the starting address or register to which to write.
:param destination_width: Specifies the data width of the destination.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
raise NotImplementedError
|
Moves an 8-bit block of data from local memory to the specified address space and offset.
Corresponds to viMoveOut8* functions of the VISA library.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param data: Data to write to bus.
:param extended: Use 64 bits offset independent of the platform.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
Corresponds to viMoveOut8 function of the VISA library.
|
def move_out_8(self, session, space, offset, length, data, extended=False):
"""Moves an 8-bit block of data from local memory to the specified address space and offset.
Corresponds to viMoveOut8* functions of the VISA library.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param data: Data to write to bus.
:param extended: Use 64 bits offset independent of the platform.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
Corresponds to viMoveOut8 function of the VISA library.
"""
raise NotImplementedError
|
Opens a session to the specified resource.
Corresponds to viOpen function of the VISA library.
:param session: Resource Manager session (should always be a session returned from open_default_resource_manager()).
:param resource_name: Unique symbolic name of a 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: Specifies the maximum time period (in milliseconds) that this operation waits
before returning an error.
:return: Unique logical identifier reference to a session, return value of the library call.
:rtype: session, :class:`pyvisa.constants.StatusCode`
|
def open(self, session, resource_name,
access_mode=constants.AccessModes.no_lock, open_timeout=constants.VI_TMO_IMMEDIATE):
"""Opens a session to the specified resource.
Corresponds to viOpen function of the VISA library.
:param session: Resource Manager session (should always be a session returned from open_default_resource_manager()).
:param resource_name: Unique symbolic name of a 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: Specifies the maximum time period (in milliseconds) that this operation waits
before returning an error.
:return: Unique logical identifier reference to a session, return value of the library call.
:rtype: session, :class:`pyvisa.constants.StatusCode`
"""
raise NotImplementedError
|
Parse a resource string to get extended interface information.
Corresponds to viParseRsrcEx function of the VISA library.
:param session: Resource Manager session (should always be the Default Resource Manager for VISA
returned from open_default_resource_manager()).
:param resource_name: Unique symbolic name of a resource.
:return: Resource information, return value of the library call.
:rtype: :class:`pyvisa.highlevel.ResourceInfo`, :class:`pyvisa.constants.StatusCode`
|
def parse_resource_extended(self, session, resource_name):
"""Parse a resource string to get extended interface information.
Corresponds to viParseRsrcEx function of the VISA library.
:param session: Resource Manager session (should always be the Default Resource Manager for VISA
returned from open_default_resource_manager()).
:param resource_name: Unique symbolic name of a resource.
:return: Resource information, return value of the library call.
:rtype: :class:`pyvisa.highlevel.ResourceInfo`, :class:`pyvisa.constants.StatusCode`
"""
try:
parsed = rname.parse_resource_name(resource_name)
return (ResourceInfo(parsed.interface_type_const,
parsed.board,
parsed.resource_class,
str(parsed), None),
constants.StatusCode.success)
except ValueError:
return 0, constants.StatusCode.error_invalid_resource_name
|
Close the resource manager session.
|
def close(self):
"""Close the resource manager session.
"""
try:
logger.debug('Closing ResourceManager (session: %s)', self.session)
# Cleanly close all resources when closing the manager.
for resource in self._created_resources:
resource.close()
self.visalib.close(self.session)
self.session = None
self.visalib.resource_manager = None
except errors.InvalidSession:
pass
|
Returns a dictionary mapping resource names to resource extended
information of all connected devices matching query.
For details of the VISA Resource Regular Expression syntax used in query,
refer to list_resources().
:param query: a VISA Resource Regular Expression used to match devices.
:return: Mapping of resource name to ResourceInfo
:rtype: dict[str, :class:`pyvisa.highlevel.ResourceInfo`]
|
def list_resources_info(self, query='?*::INSTR'):
"""Returns a dictionary mapping resource names to resource extended
information of all connected devices matching query.
For details of the VISA Resource Regular Expression syntax used in query,
refer to list_resources().
:param query: a VISA Resource Regular Expression used to match devices.
:return: Mapping of resource name to ResourceInfo
:rtype: dict[str, :class:`pyvisa.highlevel.ResourceInfo`]
"""
return dict((resource, self.resource_info(resource))
for resource in self.list_resources(query))
|
Get the (extended) information of a particular resource.
:param resource_name: Unique symbolic name of a resource.
:rtype: :class:`pyvisa.highlevel.ResourceInfo`
|
def resource_info(self, resource_name, extended=True):
"""Get the (extended) information of a particular resource.
:param resource_name: Unique symbolic name of a resource.
:rtype: :class:`pyvisa.highlevel.ResourceInfo`
"""
if extended:
ret, err = self.visalib.parse_resource_extended(self.session, resource_name)
else:
ret, err = self.visalib.parse_resource(self.session, resource_name)
return ret
|
Open the specified resource without wrapping into a class
:param resource_name: name or alias of the resource to open.
:param access_mode: access mode.
:type access_mode: :class:`pyvisa.constants.AccessModes`
:param open_timeout: time out to open.
:return: Unique logical identifier reference to a session.
|
def open_bare_resource(self, resource_name,
access_mode=constants.AccessModes.no_lock,
open_timeout=constants.VI_TMO_IMMEDIATE):
"""Open the specified resource without wrapping into a class
:param resource_name: name or alias of the resource to open.
:param access_mode: access mode.
:type access_mode: :class:`pyvisa.constants.AccessModes`
:param open_timeout: time out to open.
:return: Unique logical identifier reference to a session.
"""
return self.visalib.open(self.session, resource_name, access_mode, open_timeout)
|
Return an instrument for the resource name.
:param resource_name: name or alias of the resource to open.
:param access_mode: access mode.
:type access_mode: :class:`pyvisa.constants.AccessModes`
:param open_timeout: time out to open.
:param resource_pyclass: resource python class to use to instantiate the Resource.
Defaults to None: select based on the resource name.
:param kwargs: keyword arguments to be used to change instrument attributes
after construction.
:rtype: :class:`pyvisa.resources.Resource`
|
def open_resource(self, resource_name,
access_mode=constants.AccessModes.no_lock,
open_timeout=constants.VI_TMO_IMMEDIATE,
resource_pyclass=None,
**kwargs):
"""Return an instrument for the resource name.
:param resource_name: name or alias of the resource to open.
:param access_mode: access mode.
:type access_mode: :class:`pyvisa.constants.AccessModes`
:param open_timeout: time out to open.
:param resource_pyclass: resource python class to use to instantiate the Resource.
Defaults to None: select based on the resource name.
:param kwargs: keyword arguments to be used to change instrument attributes
after construction.
:rtype: :class:`pyvisa.resources.Resource`
"""
if resource_pyclass is None:
info = self.resource_info(resource_name, extended=True)
try:
resource_pyclass = self._resource_classes[(info.interface_type, info.resource_class)]
except KeyError:
resource_pyclass = self._resource_classes[(constants.InterfaceType.unknown, '')]
logger.warning('There is no class defined for %r. Using Resource', (info.interface_type, info.resource_class))
res = resource_pyclass(self, resource_name)
for key in kwargs.keys():
try:
getattr(res, key)
present = True
except AttributeError:
present = False
except errors.InvalidSession:
present = True
if not present:
raise ValueError('%r is not a valid attribute for type %s' % (key, res.__class__.__name__))
res.open(access_mode, open_timeout)
self._created_resources.add(res)
for key, value in kwargs.items():
setattr(res, key, value)
return res
|
Register a subclass for a given interface type and resource class.
|
def register_subclass(cls):
"""Register a subclass for a given interface type and resource class.
"""
key = cls.interface_type, cls.resource_class
if key in _SUBCLASSES:
raise ValueError('Class already registered for %s and %s' % key)
_SUBCLASSES[(cls.interface_type, cls.resource_class)] = cls
_INTERFACE_TYPES.add(cls.interface_type)
_RESOURCE_CLASSES[cls.interface_type].add(cls.resource_class)
if cls.is_rc_optional:
if cls.interface_type in _DEFAULT_RC:
raise ValueError('Default already specified for %s' %
cls.interface_type)
_DEFAULT_RC[cls.interface_type] = cls.resource_class
return cls
|
Builds a resource name class by mixing a named tuple and ResourceName.
It also registers the class.
The field names are changed to lower case and the spaces replaced
by underscores ('_').
:param interface_type: the interface type
:type: interface_type: str
:param resource_parts: each of the parts of the resource name indicating
name and default value.
Use None for mandatory fields.
:type resource_parts: tuple[(str, str)]
:param resource_class: the resource class
:type resource_class: str
:param is_rc_optional: indicates if the resource class part is optional
:type is_rc_optional: boolean.
|
def build_rn_class(interface_type, resource_parts, resource_class,
is_rc_optional=True):
"""Builds a resource name class by mixing a named tuple and ResourceName.
It also registers the class.
The field names are changed to lower case and the spaces replaced
by underscores ('_').
:param interface_type: the interface type
:type: interface_type: str
:param resource_parts: each of the parts of the resource name indicating
name and default value.
Use None for mandatory fields.
:type resource_parts: tuple[(str, str)]
:param resource_class: the resource class
:type resource_class: str
:param is_rc_optional: indicates if the resource class part is optional
:type is_rc_optional: boolean.
"""
interface_type = interface_type.upper()
resource_class = resource_class.upper()
syntax = interface_type
fmt = interface_type
fields = []
# Contains the resource parts but using python friendly names
# (all lower case and replacing spaces by underscores)
p_resource_parts = []
kwdoc = []
# Assemble the syntax and format string based on the resource parts
for ndx, (name, default_value) in enumerate(resource_parts):
pname = name.lower().replace(' ', '_')
fields.append(pname)
p_resource_parts.append((pname, default_value))
sep = '::' if ndx else ''
fmt += sep + '{0.%s}' % pname
if default_value is None:
syntax += sep + name
else:
syntax += '[' + sep + name + ']'
kwdoc.append('- %s (%s)' % (pname, 'required' if default_value is None
else default_value))
fmt += '::' + resource_class
if not is_rc_optional:
syntax += '::' + resource_class
else:
syntax += '[' + '::' + resource_class + ']'
class _C(namedtuple('Internal', ' '.join(fields)), ResourceName):
"""%s %s"
Can be created with the following keyword only arguments:
%s
Format :
%s
""" % (resource_class, interface_type, ' \n'.join(kwdoc), syntax)
def __new__(cls, **kwargs):
new_kwargs = dict(p_resource_parts, **kwargs)
for key, value in new_kwargs.items():
if value is None:
raise ValueError(key + ' is a required parameter')
return super(_C, cls).__new__(cls, **new_kwargs)
@classmethod
def from_parts(cls, *parts):
if len(parts) < sum(1 for _, v in p_resource_parts
if v is not None):
raise ValueError('not enough parts')
elif len(parts) > len(p_resource_parts):
raise ValueError('too many parts')
(k, default), rp = p_resource_parts[0], p_resource_parts[1:]
# The first part (just after the interface_type) is the only
# optional part which can be and empty and therefore the
# default value should be used.
p, pending = parts[0], parts[1:]
kwargs = {k: default if p == '' else p}
# The rest of the parts are consumed when mandatory elements are required.
while len(pending) < len(rp):
(k, default), rp = rp[0], rp[1:]
if default is None:
if not parts:
raise ValueError(k + ' part is mandatory')
p, pending = pending[0], pending[1:]
if not p:
raise ValueError(k + ' part is mandatory')
kwargs[k] = p
else:
kwargs[k] = default
# When the length of the pending provided and resource parts
# are equal, we just consume everything.
kwargs.update((k, p) for (k, v), p in zip(rp, pending))
return cls(**kwargs)
_C.interface_type = interface_type
_C.resource_class = resource_class
_C.is_rc_optional = is_rc_optional
_C._canonical_fmt = fmt
_C._visa_syntax = syntax
_C.__name__ = str(interface_type + resource_class.title())
return register_subclass(_C)
|
Filter a list of resources according to a query expression.
The search criteria specified in the query parameter has two parts:
1. a VISA regular expression over a resource string.
2. optional logical expression over attribute values
(not implemented in this function, see below).
.. note: The VISA regular expression syntax is not the same as the
Python regular expression syntax. (see below)
The regular expression is matched against the resource strings of resources
known to the VISA Resource Manager. If the resource string matches the
regular expression, the attribute values of the resource are then matched
against the expression over attribute values. If the match is successful,
the resource has met the search criteria and gets added to the list of
resources found.
By using the optional attribute expression, you can construct flexible
and powerful expressions with the use of logical ANDs (&&), ORs(||),
and NOTs (!). You can use equal (==) and unequal (!=) comparators to
compare attributes of any type, and other inequality comparators
(>, <, >=, <=) to compare attributes of numeric type. Use only global
attributes in the attribute expression. Local attributes are not allowed
in the logical expression part of the expr parameter.
Symbol Meaning
---------- ----------
? Matches any one character.
\ Makes the character that follows it an ordinary character
instead of special character. For example, when a question
mark follows a backslash (\?), it matches the ? character
instead of any one character.
[list] Matches any one character from the enclosed list. You can
use a hyphen to match a range of characters.
[^list] Matches any character not in the enclosed list. You can use
a hyphen to match a range of characters.
* Matches 0 or more occurrences of the preceding character or
expression.
+ Matches 1 or more occurrences of the preceding character or
expression.
Exp|exp Matches either the preceding or following expression. The or
operator | matches the entire expression that precedes or
follows it and not just the character that precedes or follows
it. For example, VXI|GPIB means (VXI)|(GPIB), not VX(I|G)PIB.
(exp) Grouping characters or expressions.
:param resources: iterable of resources.
:param query: query expression.
|
def filter(resources, query):
"""Filter a list of resources according to a query expression.
The search criteria specified in the query parameter has two parts:
1. a VISA regular expression over a resource string.
2. optional logical expression over attribute values
(not implemented in this function, see below).
.. note: The VISA regular expression syntax is not the same as the
Python regular expression syntax. (see below)
The regular expression is matched against the resource strings of resources
known to the VISA Resource Manager. If the resource string matches the
regular expression, the attribute values of the resource are then matched
against the expression over attribute values. If the match is successful,
the resource has met the search criteria and gets added to the list of
resources found.
By using the optional attribute expression, you can construct flexible
and powerful expressions with the use of logical ANDs (&&), ORs(||),
and NOTs (!). You can use equal (==) and unequal (!=) comparators to
compare attributes of any type, and other inequality comparators
(>, <, >=, <=) to compare attributes of numeric type. Use only global
attributes in the attribute expression. Local attributes are not allowed
in the logical expression part of the expr parameter.
Symbol Meaning
---------- ----------
? Matches any one character.
\ Makes the character that follows it an ordinary character
instead of special character. For example, when a question
mark follows a backslash (\?), it matches the ? character
instead of any one character.
[list] Matches any one character from the enclosed list. You can
use a hyphen to match a range of characters.
[^list] Matches any character not in the enclosed list. You can use
a hyphen to match a range of characters.
* Matches 0 or more occurrences of the preceding character or
expression.
+ Matches 1 or more occurrences of the preceding character or
expression.
Exp|exp Matches either the preceding or following expression. The or
operator | matches the entire expression that precedes or
follows it and not just the character that precedes or follows
it. For example, VXI|GPIB means (VXI)|(GPIB), not VX(I|G)PIB.
(exp) Grouping characters or expressions.
:param resources: iterable of resources.
:param query: query expression.
"""
if '{' in query:
query, _ = query.split('{')
logger.warning('optional part of the query expression not supported. '
'See filter2')
try:
query = query.replace('?', '.')
matcher = re.compile(query, re.IGNORECASE)
except re.error:
raise errors.VisaIOError(constants.VI_ERROR_INV_EXPR)
return tuple(res for res in resources if matcher.match(res))
|
Filter a list of resources according to a query expression.
It accepts the optional part of the expression.
.. warning: This function is experimental and unsafe as it uses eval,
It also might require to open the resource.
:param resources: iterable of resources.
:param query: query expression.
:param open_resource: function to open the resource.
|
def filter2(resources, query, open_resource):
"""Filter a list of resources according to a query expression.
It accepts the optional part of the expression.
.. warning: This function is experimental and unsafe as it uses eval,
It also might require to open the resource.
:param resources: iterable of resources.
:param query: query expression.
:param open_resource: function to open the resource.
"""
if '{' in query:
try:
query, optional = query.split('{')
optional, _ = optional.split('}')
except ValueError:
raise errors.VisaIOError(constants.VI_ERROR_INV_EXPR)
else:
optional = None
filtered = filter(resources, query)
if not optional:
return filtered
optional = optional.replace('&&', 'and').replace('||', 'or').replace('!', 'not ')
optional = optional.replace('VI_', 'res.VI_')
class AttrGetter():
def __init__(self, resource_name):
self.resource_name = resource_name
self.parsed = parse_resource_name(resource_name)
self.resource = None
def __getattr__(self, item):
if item == 'VI_ATTR_INTF_NUM':
return int(self.parsed.board)
elif item == 'VI_ATTR_MANF_ID':
return self.parsed.manufacturer_id
elif item == 'VI_ATTR_MODEL_CODE':
return self.parsed.model_code
elif item == 'VI_ATTR_USB_SERIAL_NUM':
return self.parsed.serial_number
elif item == 'VI_ATTR_USB_INTFC_NUM':
return int(self.parsed.board)
elif item == 'VI_ATTR_TCPIP_ADDR':
return self.parsed.host_address
elif item == 'VI_ATTR_TCPIP_DEVICE_NAME':
return self.parsed.lan_device_name
elif item == 'VI_ATTR_TCPIP_PORT':
return int(self.parsed.port)
elif item == 'VI_ATTR_INTF_NUM':
return int(self.parsed.board)
elif item == 'VI_ATTR_GPIB_PRIMARY_ADDR':
return int(self.parsed.primary_address)
elif item == 'VI_ATTR_GPIB_SECONDARY_ADDR':
return int(self.parsed.secondary_address)
elif item == 'VI_ATTR_PXI_CHASSIS':
return self.parsed.chassis_number
elif item == 'VI_ATTR_MAINFRAME_LA':
return self.parsed.vxi_logical_address
if self.resource is None:
self.resource = open_resource(self.resource_name)
return self.resource.get_visa_attribute(item)
@contextlib.contextmanager
def open_close(resource_name):
getter = AttrGetter(resource_name)
yield getter
if getter.resource is not None:
getter.resource.close()
selected = []
for rn in filtered:
with open_close(rn) as getter:
if eval(optional, None, dict(res=getter)):
selected.append(rn)
|
Exception used when the resource name cannot be parsed.
|
def bad_syntax(cls, syntax, resource_name, ex=None):
"""Exception used when the resource name cannot be parsed.
"""
if ex:
msg = "The syntax is '%s' (%s)." % (syntax, ex)
else:
msg = "The syntax is '%s'." % syntax
msg = "Could not parse '%s'. %s" % (resource_name, msg)
return cls(msg)
|
Exception used when the subclass for a given interface type / resource class pair
cannot be found.
|
def subclass_notfound(cls, interface_type_resource_class,
resource_name=None):
"""Exception used when the subclass for a given interface type / resource class pair
cannot be found.
"""
msg = "Parser for not found (%s)." % interface_type_resource_class
if resource_name:
msg = "Could not parse '%s'. %s" % (resource_name, msg)
return cls(msg)
|
Exception used when no resource class is provided and no default is found.
|
def rc_notfound(cls, interface_type, resource_name=None):
"""Exception used when no resource class is provided and no default is found.
"""
msg = "Resource class for %s not provided and default not found." % interface_type
if resource_name:
msg = "Could not parse '%s'. %s" % (resource_name, msg)
return cls(msg)
|
Parse a resource name and return a ResourceName
:type resource_name: str
:rtype: ResourceName
:raises InvalidResourceName: if the resource name is invalid.
|
def from_string(cls, resource_name):
"""Parse a resource name and return a ResourceName
:type resource_name: str
:rtype: ResourceName
:raises InvalidResourceName: if the resource name is invalid.
"""
# TODO Remote VISA
uname = resource_name.upper()
for interface_type in _INTERFACE_TYPES:
# Loop through all known interface types until we found one
# that matches the beginning of the resource name
if not uname.startswith(interface_type):
continue
if len(resource_name) == len(interface_type):
parts = ()
else:
parts = resource_name[len(interface_type):].split('::')
# Try to match the last part of the resource name to
# one of the known resource classes for the given interface type.
# If not possible, use the default resource class
# for the given interface type.
if parts and parts[-1] in _RESOURCE_CLASSES[interface_type]:
parts, resource_class = parts[:-1], parts[-1]
else:
try:
resource_class = _DEFAULT_RC[interface_type]
except KeyError:
raise InvalidResourceName.rc_notfound(interface_type,
resource_name)
# Look for the subclass
try:
subclass = _SUBCLASSES[(interface_type, resource_class)]
except KeyError:
raise InvalidResourceName.subclass_notfound(
(interface_type, resource_class), resource_name)
# And create the object
try:
rn = subclass.from_parts(*parts)
rn.user = resource_name
return rn
except ValueError as ex:
raise InvalidResourceName.bad_syntax(subclass._visa_syntax,
resource_name, ex)
raise InvalidResourceName('Could not parse %s: unknown interface type'
% resource_name)
|
Set the type of the user handle to install and uninstall handler signature.
:param library: the visa library wrapped by ctypes.
:param user_handle: use None for a void_p
|
def set_user_handle_type(library, user_handle):
"""Set the type of the user handle to install and uninstall handler signature.
:param library: the visa library wrapped by ctypes.
:param user_handle: use None for a void_p
"""
# Actually, it's not necessary to change ViHndlr *globally*. However,
# I don't want to break symmetry too much with all the other VPP43
# routines.
global ViHndlr
if user_handle is None:
user_handle_p = c_void_p
else:
user_handle_p = POINTER(type(user_handle))
ViHndlr = FUNCTYPE(ViStatus, ViSession, ViEventType, ViEvent, user_handle_p)
library.viInstallHandler.argtypes = [ViSession, ViEventType, ViHndlr, user_handle_p]
library.viUninstallHandler.argtypes = [ViSession, ViEventType, ViHndlr, user_handle_p]
|
Set the signatures of most visa functions in the library.
All instrumentation related functions are specified here.
:param library: the visa library wrapped by ctypes.
:type library: ctypes.WinDLL or ctypes.CDLL
:param errcheck: error checking callable used for visa functions that return
ViStatus.
It should be take three areguments (result, func, arguments).
See errcheck in ctypes.
|
def set_signatures(library, errcheck=None):
"""Set the signatures of most visa functions in the library.
All instrumentation related functions are specified here.
:param library: the visa library wrapped by ctypes.
:type library: ctypes.WinDLL or ctypes.CDLL
:param errcheck: error checking callable used for visa functions that return
ViStatus.
It should be take three areguments (result, func, arguments).
See errcheck in ctypes.
"""
# Somehow hasattr(library, '_functions') segfaults in cygwin (See #131)
if '_functions' not in dir(library):
library._functions = []
library._functions_failed = []
def _applier(restype, errcheck_):
def _internal(function_name, argtypes, required=False):
try:
set_signature(library, function_name, argtypes, restype, errcheck_)
# noinspection PyProtectedMember
library._functions.append(function_name)
except AttributeError:
library._functions_failed.append(function_name)
if required:
raise
return _internal
# Visa functions with ViStatus return code
apply = _applier(ViStatus, errcheck)
apply("viAssertIntrSignal", [ViSession, ViInt16, ViUInt32])
apply("viAssertTrigger", [ViSession, ViUInt16])
apply("viAssertUtilSignal", [ViSession, ViUInt16])
apply("viBufRead", [ViSession, ViPBuf, ViUInt32, ViPUInt32])
apply("viBufWrite", [ViSession, ViBuf, ViUInt32, ViPUInt32])
apply("viClear", [ViSession])
apply("viClose", [ViObject])
apply("viDisableEvent", [ViSession, ViEventType, ViUInt16])
apply("viDiscardEvents", [ViSession, ViEventType, ViUInt16])
apply("viEnableEvent", [ViSession, ViEventType, ViUInt16, ViEventFilter])
apply("viFindNext", [ViSession, ViAChar])
apply("viFindRsrc", [ViSession, ViString, ViPFindList, ViPUInt32, ViAChar])
apply("viFlush", [ViSession, ViUInt16])
apply("viGetAttribute", [ViObject, ViAttr, c_void_p])
apply("viGpibCommand", [ViSession, ViBuf, ViUInt32, ViPUInt32])
apply("viGpibControlATN", [ViSession, ViUInt16])
apply("viGpibControlREN", [ViSession, ViUInt16])
apply("viGpibPassControl", [ViSession, ViUInt16, ViUInt16])
apply("viGpibSendIFC", [ViSession])
apply("viIn8", [ViSession, ViUInt16, ViBusAddress, ViPUInt8])
apply("viIn16", [ViSession, ViUInt16, ViBusAddress, ViPUInt16])
apply("viIn32", [ViSession, ViUInt16, ViBusAddress, ViPUInt32])
apply("viIn64", [ViSession, ViUInt16, ViBusAddress, ViPUInt64])
apply("viIn8Ex", [ViSession, ViUInt16, ViBusAddress64, ViPUInt8])
apply("viIn16Ex", [ViSession, ViUInt16, ViBusAddress64, ViPUInt16])
apply("viIn32Ex", [ViSession, ViUInt16, ViBusAddress64, ViPUInt32])
apply("viIn64Ex", [ViSession, ViUInt16, ViBusAddress64, ViPUInt64])
apply("viInstallHandler", [ViSession, ViEventType, ViHndlr, ViAddr])
apply("viLock", [ViSession, ViAccessMode, ViUInt32, ViKeyId, ViAChar])
apply("viMapAddress", [ViSession, ViUInt16, ViBusAddress, ViBusSize, ViBoolean, ViAddr, ViPAddr])
apply("viMapTrigger", [ViSession, ViInt16, ViInt16, ViUInt16])
apply("viMemAlloc", [ViSession, ViBusSize, ViPBusAddress])
apply("viMemFree", [ViSession, ViBusAddress])
apply("viMove", [ViSession, ViUInt16, ViBusAddress, ViUInt16,
ViUInt16, ViBusAddress, ViUInt16, ViBusSize])
apply("viMoveAsync", [ViSession, ViUInt16, ViBusAddress, ViUInt16,
ViUInt16, ViBusAddress, ViUInt16, ViBusSize,
ViPJobId])
apply("viMoveIn8", [ViSession, ViUInt16, ViBusAddress, ViBusSize, ViAUInt8])
apply("viMoveIn16", [ViSession, ViUInt16, ViBusAddress, ViBusSize, ViAUInt16])
apply("viMoveIn32", [ViSession, ViUInt16, ViBusAddress, ViBusSize, ViAUInt32])
apply("viMoveIn64", [ViSession, ViUInt16, ViBusAddress, ViBusSize, ViAUInt64])
apply("viMoveIn8Ex", [ViSession, ViUInt16, ViBusAddress64, ViBusSize, ViAUInt8])
apply("viMoveIn16Ex", [ViSession, ViUInt16, ViBusAddress64, ViBusSize, ViAUInt16])
apply("viMoveIn32Ex", [ViSession, ViUInt16, ViBusAddress64, ViBusSize, ViAUInt32])
apply("viMoveIn64Ex", [ViSession, ViUInt16, ViBusAddress64, ViBusSize, ViAUInt64])
apply("viMoveOut8", [ViSession, ViUInt16, ViBusAddress, ViBusSize, ViAUInt8])
apply("viMoveOut16", [ViSession, ViUInt16, ViBusAddress, ViBusSize, ViAUInt16])
apply("viMoveOut32", [ViSession, ViUInt16, ViBusAddress, ViBusSize, ViAUInt32])
apply("viMoveOut64", [ViSession, ViUInt16, ViBusAddress, ViBusSize, ViAUInt64])
apply("viMoveOut8Ex", [ViSession, ViUInt16, ViBusAddress64, ViBusSize, ViAUInt8])
apply("viMoveOut16Ex", [ViSession, ViUInt16, ViBusAddress64, ViBusSize, ViAUInt16])
apply("viMoveOut32Ex", [ViSession, ViUInt16, ViBusAddress64, ViBusSize, ViAUInt32])
apply("viMoveOut64Ex", [ViSession, ViUInt16, ViBusAddress64, ViBusSize, ViAUInt64])
apply("viOpen", [ViSession, ViRsrc, ViAccessMode, ViUInt32, ViPSession], required=True)
apply("viOpenDefaultRM", [ViPSession], required=True)
apply("viOut8", [ViSession, ViUInt16, ViBusAddress, ViUInt8])
apply("viOut16", [ViSession, ViUInt16, ViBusAddress, ViUInt16])
apply("viOut32", [ViSession, ViUInt16, ViBusAddress, ViUInt32])
apply("viOut64", [ViSession, ViUInt16, ViBusAddress, ViUInt64])
apply("viOut8Ex", [ViSession, ViUInt16, ViBusAddress64, ViUInt8])
apply("viOut16Ex", [ViSession, ViUInt16, ViBusAddress64, ViUInt16])
apply("viOut32Ex", [ViSession, ViUInt16, ViBusAddress64, ViUInt32])
apply("viOut64Ex", [ViSession, ViUInt16, ViBusAddress64, ViUInt64])
apply("viParseRsrc", [ViSession, ViRsrc, ViPUInt16, ViPUInt16])
apply("viParseRsrcEx", [ViSession, ViRsrc, ViPUInt16, ViPUInt16, ViAChar, ViAChar, ViAChar])
apply("viRead", [ViSession, ViPBuf, ViUInt32, ViPUInt32])
apply("viReadAsync", [ViSession, ViPBuf, ViUInt32, ViPJobId])
apply("viReadSTB", [ViSession, ViPUInt16])
apply("viReadToFile", [ViSession, ViString, ViUInt32, ViPUInt32])
apply("viSetAttribute", [ViObject, ViAttr, ViAttrState])
apply("viSetBuf", [ViSession, ViUInt16, ViUInt32])
apply("viStatusDesc", [ViObject, ViStatus, ViAChar])
apply("viTerminate", [ViSession, ViUInt16, ViJobId])
apply("viUninstallHandler", [ViSession, ViEventType, ViHndlr, ViAddr])
apply("viUnlock", [ViSession])
apply("viUnmapAddress", [ViSession])
apply("viUnmapTrigger", [ViSession, ViInt16, ViInt16])
apply("viUsbControlIn", [ViSession, ViInt16, ViInt16, ViUInt16,
ViUInt16, ViUInt16, ViPBuf, ViPUInt16])
apply("viUsbControlOut", [ViSession, ViInt16, ViInt16, ViUInt16,
ViUInt16, ViUInt16, ViPBuf])
# The following "V" routines are *not* implemented in PyVISA, and will
# never be: viVPrintf, viVQueryf, viVScanf, viVSPrintf, viVSScanf
apply("viVxiCommandQuery", [ViSession, ViUInt16, ViUInt32, ViPUInt32])
apply("viWaitOnEvent", [ViSession, ViEventType, ViUInt32, ViPEventType, ViPEvent])
apply("viWrite", [ViSession, ViBuf, ViUInt32, ViPUInt32])
apply("viWriteAsync", [ViSession, ViBuf, ViUInt32, ViPJobId])
apply("viWriteFromFile", [ViSession, ViString, ViUInt32, ViPUInt32])
# Functions that return void.
apply = _applier(None, None)
apply("viPeek8", [ViSession, ViAddr, ViPUInt8])
apply("viPeek16", [ViSession, ViAddr, ViPUInt16])
apply("viPeek32", [ViSession, ViAddr, ViPUInt32])
apply("viPeek64", [ViSession, ViAddr, ViPUInt64])
apply("viPoke8", [ViSession, ViAddr, ViUInt8])
apply("viPoke16", [ViSession, ViAddr, ViUInt16])
apply("viPoke32", [ViSession, ViAddr, ViUInt32])
apply("viPoke64", [ViSession, ViAddr, ViUInt64])
|
Set the signature of single function in a library.
:param library: ctypes wrapped library.
:type library: ctypes.WinDLL or ctypes.CDLL
:param function_name: name of the function as appears in the header file.
:type function_name: str
:param argtypes: a tuple of ctypes types to specify the argument types that the function accepts.
:param restype: A ctypes type to specify the result type of the foreign function.
Use None for void, a function not returning anything.
:param errcheck: a callabe
:raises: AttributeError
|
def set_signature(library, function_name, argtypes, restype, errcheck):
"""Set the signature of single function in a library.
:param library: ctypes wrapped library.
:type library: ctypes.WinDLL or ctypes.CDLL
:param function_name: name of the function as appears in the header file.
:type function_name: str
:param argtypes: a tuple of ctypes types to specify the argument types that the function accepts.
:param restype: A ctypes type to specify the result type of the foreign function.
Use None for void, a function not returning anything.
:param errcheck: a callabe
:raises: AttributeError
"""
func = getattr(library, function_name)
func.argtypes = argtypes
if restype is not None:
func.restype = restype
if errcheck is not None:
func.errcheck = errcheck
|
Asserts the specified interrupt or signal.
Corresponds to viAssertIntrSignal function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param mode: How to assert the interrupt. (Constants.ASSERT*)
:param status_id: This is the status value to be presented during an interrupt acknowledge cycle.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def assert_interrupt_signal(library, session, mode, status_id):
"""Asserts the specified interrupt or signal.
Corresponds to viAssertIntrSignal function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param mode: How to assert the interrupt. (Constants.ASSERT*)
:param status_id: This is the status value to be presented during an interrupt acknowledge cycle.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
return library.viAssertIntrSignal(session, mode, status_id)
|
Reads data from device or interface through the use of a formatted I/O read buffer.
Corresponds to viBufRead function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param count: Number of bytes to be read.
:return: data read, return value of the library call.
:rtype: bytes, :class:`pyvisa.constants.StatusCode`
|
def buffer_read(library, session, count):
"""Reads data from device or interface through the use of a formatted I/O read buffer.
Corresponds to viBufRead function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param count: Number of bytes to be read.
:return: data read, return value of the library call.
:rtype: bytes, :class:`pyvisa.constants.StatusCode`
"""
buffer = create_string_buffer(count)
return_count = ViUInt32()
ret = library.viBufRead(session, buffer, count, byref(return_count))
return buffer.raw[:return_count.value], ret
|
Writes data to a formatted I/O write buffer synchronously.
Corresponds to viBufWrite function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param data: data to be written.
:type data: bytes
:return: number of written bytes, return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
|
def buffer_write(library, session, data):
"""Writes data to a formatted I/O write buffer synchronously.
Corresponds to viBufWrite function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param data: data to be written.
:type data: bytes
:return: number of written bytes, return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
"""
return_count = ViUInt32()
# [ViSession, ViBuf, ViUInt32, ViPUInt32]
ret = library.viBufWrite(session, data, len(data), byref(return_count))
return return_count.value, ret
|
Disables notification of the specified event type(s) via the specified mechanism(s).
Corresponds to viDisableEvent function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
: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)
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def disable_event(library, session, event_type, mechanism):
"""Disables notification of the specified event type(s) via the specified mechanism(s).
Corresponds to viDisableEvent function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
: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)
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
return library.viDisableEvent(session, event_type, mechanism)
|
Discards event occurrences for specified event types and mechanisms in a session.
Corresponds to viDiscardEvents function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
: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)
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def discard_events(library, session, event_type, mechanism):
"""Discards event occurrences for specified event types and mechanisms in a session.
Corresponds to viDiscardEvents function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
: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)
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
return library.viDiscardEvents(session, event_type, mechanism)
|
Enable event occurrences for specified event types and mechanisms in a session.
Corresponds to viEnableEvent function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
: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:
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def enable_event(library, session, event_type, mechanism, context=None):
"""Enable event occurrences for specified event types and mechanisms in a session.
Corresponds to viEnableEvent function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
: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:
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
if context is None:
context = constants.VI_NULL
elif context != constants.VI_NULL:
warnings.warn('In enable_event, context will be set VI_NULL.')
context = constants.VI_NULL # according to spec VPP-4.3, section 3.7.3.1
return library.viEnableEvent(session, event_type, mechanism, context)
|
Returns the next resource from the list of resources found during a previous call to find_resources().
Corresponds to viFindNext function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param find_list: Describes a find list. This parameter must be created by find_resources().
:return: Returns a string identifying the location of a device, return value of the library call.
:rtype: unicode (Py2) or str (Py3), :class:`pyvisa.constants.StatusCode`
|
def find_next(library, find_list):
"""Returns the next resource from the list of resources found during a previous call to find_resources().
Corresponds to viFindNext function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param find_list: Describes a find list. This parameter must be created by find_resources().
:return: Returns a string identifying the location of a device, return value of the library call.
:rtype: unicode (Py2) or str (Py3), :class:`pyvisa.constants.StatusCode`
"""
instrument_description = create_string_buffer(constants.VI_FIND_BUFLEN)
ret = library.viFindNext(find_list, instrument_description)
return buffer_to_text(instrument_description), ret
|
Queries a VISA system to locate the resources associated with a specified interface.
Corresponds to viFindRsrc function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session (unused, just to uniform signatures).
:param query: A regular expression followed by an optional logical expression. Use '?*' for all.
:return: find_list, return_counter, instrument_description, return value of the library call.
:rtype: ViFindList, int, unicode (Py2) or str (Py3), :class:`pyvisa.constants.StatusCode`
|
def find_resources(library, session, query):
"""Queries a VISA system to locate the resources associated with a specified interface.
Corresponds to viFindRsrc function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session (unused, just to uniform signatures).
:param query: A regular expression followed by an optional logical expression. Use '?*' for all.
:return: find_list, return_counter, instrument_description, return value of the library call.
:rtype: ViFindList, int, unicode (Py2) or str (Py3), :class:`pyvisa.constants.StatusCode`
"""
find_list = ViFindList()
return_counter = ViUInt32()
instrument_description = create_string_buffer(constants.VI_FIND_BUFLEN)
# [ViSession, ViString, ViPFindList, ViPUInt32, ViAChar]
# ViString converts from (str, unicode, bytes) to bytes
ret = library.viFindRsrc(session, query,
byref(find_list), byref(return_counter),
instrument_description)
return find_list, return_counter.value, buffer_to_text(instrument_description), ret
|
Retrieves the state of an attribute.
Corresponds to viGetAttribute function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session, event, or find list.
:param attribute: Resource attribute for which the state query is made (see Attributes.*)
:return: The state of the queried attribute for a specified resource, return value of the library call.
:rtype: unicode (Py2) or str (Py3), list or other type, :class:`pyvisa.constants.StatusCode`
|
def get_attribute(library, session, attribute):
"""Retrieves the state of an attribute.
Corresponds to viGetAttribute function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session, event, or find list.
:param attribute: Resource attribute for which the state query is made (see Attributes.*)
:return: The state of the queried attribute for a specified resource, return value of the library call.
:rtype: unicode (Py2) or str (Py3), list or other type, :class:`pyvisa.constants.StatusCode`
"""
# FixMe: How to deal with ViBuf?
attr = attributes.AttributesByID[attribute]
datatype = getattr(types, attr.visa_type)
if datatype == ViString:
attribute_state = create_string_buffer(256)
ret = library.viGetAttribute(session, attribute, attribute_state)
return buffer_to_text(attribute_state), ret
elif datatype == ViAUInt8:
length = get_attribute(library, session, constants.VI_ATTR_USB_RECV_INTR_SIZE)
attribute_state = (ViUInt8 * length)()
ret = library.viGetAttribute(session, attribute, byref(attribute_state))
return list(attribute_state), ret
else:
attribute_state = datatype()
ret = library.viGetAttribute(session, attribute, byref(attribute_state))
return attribute_state.value, ret
|
Write GPIB command bytes on the bus.
Corresponds to viGpibCommand function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param data: data tor write.
:type data: bytes
:return: Number of written bytes, return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
|
def gpib_command(library, session, data):
"""Write GPIB command bytes on the bus.
Corresponds to viGpibCommand function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param data: data tor write.
:type data: bytes
:return: Number of written bytes, return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
"""
return_count = ViUInt32()
# [ViSession, ViBuf, ViUInt32, ViPUInt32]
ret = library.viGpibCommand(session, data, len(data), byref(return_count))
return return_count.value, ret
|
Tell the GPIB device at the specified address to become controller in charge (CIC).
Corresponds to viGpibPassControl function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param primary_address: Primary address of the GPIB device to which you want to pass control.
:param secondary_address: Secondary address of the targeted GPIB device.
If the targeted device does not have a secondary address,
this parameter should contain the value Constants.NO_SEC_ADDR.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def gpib_pass_control(library, session, primary_address, secondary_address):
"""Tell the GPIB device at the specified address to become controller in charge (CIC).
Corresponds to viGpibPassControl function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param primary_address: Primary address of the GPIB device to which you want to pass control.
:param secondary_address: Secondary address of the targeted GPIB device.
If the targeted device does not have a secondary address,
this parameter should contain the value Constants.NO_SEC_ADDR.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
return library.viGpibPassControl(session, primary_address, secondary_address)
|
Reads in an 8-bit, 16-bit, 32-bit, or 64-bit value from the specified memory space and offset.
Corresponds to viIn* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param width: Number of bits to read.
:param extended: Use 64 bits offset independent of the platform.
:return: Data read from memory, return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
|
def read_memory(library, session, space, offset, width, extended=False):
"""Reads in an 8-bit, 16-bit, 32-bit, or 64-bit value from the specified memory space and offset.
Corresponds to viIn* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param width: Number of bits to read.
:param extended: Use 64 bits offset independent of the platform.
:return: Data read from memory, return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
"""
if width == 8:
return in_8(library, session, space, offset, extended)
elif width == 16:
return in_16(library, session, space, offset, extended)
elif width == 32:
return in_32(library, session, space, offset, extended)
elif width == 64:
return in_64(library, session, space, offset, extended)
raise ValueError('%s is not a valid size. Valid values are 8, 16, 32 or 64' % width)
|
Reads in an 8-bit value from the specified memory space and offset.
Corresponds to viIn8* function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param extended: Use 64 bits offset independent of the platform.
:return: Data read from memory, return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
|
def in_8(library, session, space, offset, extended=False):
"""Reads in an 8-bit value from the specified memory space and offset.
Corresponds to viIn8* function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param extended: Use 64 bits offset independent of the platform.
:return: Data read from memory, return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
"""
value_8 = ViUInt8()
if extended:
ret = library.viIn8Ex(session, space, offset, byref(value_8))
else:
ret = library.viIn8(session, space, offset, byref(value_8))
return value_8.value, ret
|
Reads in an 16-bit value from the specified memory space and offset.
Corresponds to viIn16* function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param extended: Use 64 bits offset independent of the platform.
:return: Data read from memory, return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
|
def in_16(library, session, space, offset, extended=False):
"""Reads in an 16-bit value from the specified memory space and offset.
Corresponds to viIn16* function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param extended: Use 64 bits offset independent of the platform.
:return: Data read from memory, return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
"""
value_16 = ViUInt16()
if extended:
ret = library.viIn16Ex(session, space, offset, byref(value_16))
else:
ret = library.viIn16(session, space, offset, byref(value_16))
return value_16.value, ret
|
Reads in an 32-bit value from the specified memory space and offset.
Corresponds to viIn32* function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param extended: Use 64 bits offset independent of the platform.
:return: Data read from memory, return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
|
def in_32(library, session, space, offset, extended=False):
"""Reads in an 32-bit value from the specified memory space and offset.
Corresponds to viIn32* function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param extended: Use 64 bits offset independent of the platform.
:return: Data read from memory, return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
"""
value_32 = ViUInt32()
if extended:
ret = library.viIn32Ex(session, space, offset, byref(value_32))
else:
ret = library.viIn32(session, space, offset, byref(value_32))
return value_32.value, ret
|
Reads in an 64-bit value from the specified memory space and offset.
Corresponds to viIn64* function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param extended: Use 64 bits offset independent of the platform.
:return: Data read from memory, return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
|
def in_64(library, session, space, offset, extended=False):
"""Reads in an 64-bit value from the specified memory space and offset.
Corresponds to viIn64* function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param extended: Use 64 bits offset independent of the platform.
:return: Data read from memory, return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
"""
value_64 = ViUInt64()
if extended:
ret = library.viIn64Ex(session, space, offset, byref(value_64))
else:
ret = library.viIn64(session, space, offset, byref(value_64))
return value_64.value, ret
|
Installs handlers for event callbacks.
Corresponds to viInstallHandler function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
: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. Can be a regular python object (int, float, str, list
of floats or ints) or a ctypes object.
:returns: a handler descriptor which consists of three elements:
- handler (a python callable)
- user handle (a ctypes object)
- ctypes handler (ctypes object wrapping handler)
and return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
|
def install_handler(library, session, event_type, handler, user_handle):
"""Installs handlers for event callbacks.
Corresponds to viInstallHandler function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
: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. Can be a regular python object (int, float, str, list
of floats or ints) or a ctypes object.
:returns: a handler descriptor which consists of three elements:
- handler (a python callable)
- user handle (a ctypes object)
- ctypes handler (ctypes object wrapping handler)
and return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
"""
if user_handle is None:
converted_user_handle = None
else:
if isinstance(user_handle, int):
converted_user_handle = c_long(user_handle)
elif isinstance(user_handle, float):
converted_user_handle = c_double(user_handle)
elif isinstance(user_handle, str):
converted_user_handle = create_string_buffer(user_handle)
elif isinstance(user_handle, list):
for element in user_handle:
if not isinstance(element, int):
converted_user_handle = \
(c_double * len(user_handle))(tuple(user_handle))
break
else:
converted_user_handle = \
(c_long * len(user_handle))(*tuple(user_handle))
else:
try:
# check if it is already a ctypes
byref(user_handle)
converted_user_handle = user_handle
except TypeError:
raise TypeError("Type not allowed as user handle: %s" % type(user_handle))
set_user_handle_type(library, converted_user_handle)
converted_handler = ViHndlr(handler)
if user_handle is None:
ret = library.viInstallHandler(session, event_type, converted_handler, None)
else:
ret = library.viInstallHandler(session, event_type, converted_handler,
byref(converted_user_handle))
return handler, converted_user_handle, converted_handler, ret
|
Establishes an access mode to the specified resources.
Corresponds to viLock function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param lock_type: Specifies the type of lock requested, either constants.AccessModes.exclusive_lock
or constants.AccessModes.shared_lock.
:param timeout: Absolute time period (in milliseconds) that a resource waits to get unlocked by the
locking session before returning an error.
:param requested_key: This parameter is not used and should be set to VI_NULL when lockType is VI_EXCLUSIVE_LOCK.
:return: access_key that can then be passed to other sessions to share the lock, return value of the library call.
:rtype: str, :class:`pyvisa.constants.StatusCode`
|
def lock(library, session, lock_type, timeout, requested_key=None):
"""Establishes an access mode to the specified resources.
Corresponds to viLock function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param lock_type: Specifies the type of lock requested, either constants.AccessModes.exclusive_lock
or constants.AccessModes.shared_lock.
:param timeout: Absolute time period (in milliseconds) that a resource waits to get unlocked by the
locking session before returning an error.
:param requested_key: This parameter is not used and should be set to VI_NULL when lockType is VI_EXCLUSIVE_LOCK.
:return: access_key that can then be passed to other sessions to share the lock, return value of the library call.
:rtype: str, :class:`pyvisa.constants.StatusCode`
"""
if lock_type == constants.AccessModes.exclusive_lock:
requested_key = None
access_key = None
else:
access_key = create_string_buffer(256)
ret = library.viLock(session, lock_type, timeout, requested_key, access_key)
if access_key is None:
return None, ret
else:
return access_key.value, ret
|
Maps the specified memory space into the process's address space.
Corresponds to viMapAddress function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param map_space: Specifies the address space to map. (Constants.*SPACE*)
:param map_base: Offset (in bytes) of the memory to be mapped.
:param map_size: Amount of memory to map (in bytes).
:param access:
:param suggested: If not Constants.NULL (0), the operating system attempts to map the memory to the address
specified in suggested. There is no guarantee, however, that the memory will be mapped to
that address. This operation may map the memory into an address region different from
suggested.
:return: address in your process space where the memory was mapped, return value of the library call.
:rtype: address, :class:`pyvisa.constants.StatusCode`
|
def map_address(library, session, map_space, map_base, map_size,
access=False, suggested=None):
"""Maps the specified memory space into the process's address space.
Corresponds to viMapAddress function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param map_space: Specifies the address space to map. (Constants.*SPACE*)
:param map_base: Offset (in bytes) of the memory to be mapped.
:param map_size: Amount of memory to map (in bytes).
:param access:
:param suggested: If not Constants.NULL (0), the operating system attempts to map the memory to the address
specified in suggested. There is no guarantee, however, that the memory will be mapped to
that address. This operation may map the memory into an address region different from
suggested.
:return: address in your process space where the memory was mapped, return value of the library call.
:rtype: address, :class:`pyvisa.constants.StatusCode`
"""
if access is False:
access = constants.VI_FALSE
elif access != constants.VI_FALSE:
warnings.warn('In enable_event, context will be set VI_NULL.')
access = constants.VI_FALSE
address = ViAddr()
ret = library.viMapAddress(session, map_space, map_base, map_size, access,
suggested, byref(address))
return address, ret
|
Map the specified trigger source line to the specified destination line.
Corresponds to viMapTrigger function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param trigger_source: Source line from which to map. (Constants.TRIG*)
:param trigger_destination: Destination line to which to map. (Constants.TRIG*)
:param mode:
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def map_trigger(library, session, trigger_source, trigger_destination, mode):
"""Map the specified trigger source line to the specified destination line.
Corresponds to viMapTrigger function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param trigger_source: Source line from which to map. (Constants.TRIG*)
:param trigger_destination: Destination line to which to map. (Constants.TRIG*)
:param mode:
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
return library.viMapTrigger(session, trigger_source, trigger_destination, mode)
|
Allocates memory from a resource's memory region.
Corresponds to viMemAlloc* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param size: Specifies the size of the allocation.
:param extended: Use 64 bits offset independent of the platform.
:return: offset of the allocated memory, return value of the library call.
:rtype: offset, :class:`pyvisa.constants.StatusCode`
|
def memory_allocation(library, session, size, extended=False):
"""Allocates memory from a resource's memory region.
Corresponds to viMemAlloc* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param size: Specifies the size of the allocation.
:param extended: Use 64 bits offset independent of the platform.
:return: offset of the allocated memory, return value of the library call.
:rtype: offset, :class:`pyvisa.constants.StatusCode`
"""
offset = ViBusAddress()
if extended:
ret = library.viMemAllocEx(session, size, byref(offset))
else:
ret = library.viMemAlloc(session, size, byref(offset))
return offset, ret
|
Frees memory previously allocated using the memory_allocation() operation.
Corresponds to viMemFree* function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param offset: Offset of the memory to free.
:param extended: Use 64 bits offset independent of the platform.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def memory_free(library, session, offset, extended=False):
"""Frees memory previously allocated using the memory_allocation() operation.
Corresponds to viMemFree* function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param offset: Offset of the memory to free.
:param extended: Use 64 bits offset independent of the platform.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
if extended:
return library.viMemFreeEx(session, offset)
else:
return library.viMemFree(session, offset)
|
Moves a block of data.
Corresponds to viMove function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param source_space: Specifies the address space of the source.
:param source_offset: Offset of the starting address or register from which to read.
:param source_width: Specifies the data width of the source.
:param destination_space: Specifies the address space of the destination.
:param destination_offset: Offset of the starting address or register to which to write.
:param destination_width: Specifies the data width of the destination.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def move(library, session, source_space, source_offset, source_width, destination_space,
destination_offset, destination_width, length):
"""Moves a block of data.
Corresponds to viMove function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param source_space: Specifies the address space of the source.
:param source_offset: Offset of the starting address or register from which to read.
:param source_width: Specifies the data width of the source.
:param destination_space: Specifies the address space of the destination.
:param destination_offset: Offset of the starting address or register to which to write.
:param destination_width: Specifies the data width of the destination.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
return library.viMove(session, source_space, source_offset, source_width,
destination_space, destination_offset,
destination_width, length)
|
Moves a block of data asynchronously.
Corresponds to viMoveAsync function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param source_space: Specifies the address space of the source.
:param source_offset: Offset of the starting address or register from which to read.
:param source_width: Specifies the data width of the source.
:param destination_space: Specifies the address space of the destination.
:param destination_offset: Offset of the starting address or register to which to write.
:param destination_width: Specifies the data width of the destination.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:return: Job identifier of this asynchronous move operation, return value of the library call.
:rtype: jobid, :class:`pyvisa.constants.StatusCode`
|
def move_asynchronously(library, session, source_space, source_offset, source_width,
destination_space, destination_offset,
destination_width, length):
"""Moves a block of data asynchronously.
Corresponds to viMoveAsync function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param source_space: Specifies the address space of the source.
:param source_offset: Offset of the starting address or register from which to read.
:param source_width: Specifies the data width of the source.
:param destination_space: Specifies the address space of the destination.
:param destination_offset: Offset of the starting address or register to which to write.
:param destination_width: Specifies the data width of the destination.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:return: Job identifier of this asynchronous move operation, return value of the library call.
:rtype: jobid, :class:`pyvisa.constants.StatusCode`
"""
job_id = ViJobId()
ret = library.viMoveAsync(session, source_space, source_offset, source_width,
destination_space, destination_offset,
destination_width, length, byref(job_id))
return job_id, ret
|
Moves an 8-bit block of data from the specified address space and offset to local memory.
Corresponds to viMoveIn8* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param extended: Use 64 bits offset independent of the platform.
:return: Data read from the bus, return value of the library call.
:rtype: list, :class:`pyvisa.constants.StatusCode`
|
def move_in_8(library, session, space, offset, length, extended=False):
"""Moves an 8-bit block of data from the specified address space and offset to local memory.
Corresponds to viMoveIn8* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param extended: Use 64 bits offset independent of the platform.
:return: Data read from the bus, return value of the library call.
:rtype: list, :class:`pyvisa.constants.StatusCode`
"""
buffer_8 = (ViUInt8 * length)()
if extended:
ret = library.viMoveIn8Ex(session, space, offset, length, buffer_8)
else:
ret = library.viMoveIn8(session, space, offset, length, buffer_8)
return list(buffer_8), ret
|
Moves an 16-bit block of data from the specified address space and offset to local memory.
Corresponds to viMoveIn16* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param extended: Use 64 bits offset independent of the platform.
:return: Data read from the bus, return value of the library call.
:rtype: list, :class:`pyvisa.constants.StatusCode`
|
def move_in_16(library, session, space, offset, length, extended=False):
"""Moves an 16-bit block of data from the specified address space and offset to local memory.
Corresponds to viMoveIn16* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param extended: Use 64 bits offset independent of the platform.
:return: Data read from the bus, return value of the library call.
:rtype: list, :class:`pyvisa.constants.StatusCode`
"""
buffer_16 = (ViUInt16 * length)()
if extended:
ret = library.viMoveIn16Ex(session, space, offset, length, buffer_16)
else:
ret = library.viMoveIn16(session, space, offset, length, buffer_16)
return list(buffer_16), ret
|
Moves an 32-bit block of data from the specified address space and offset to local memory.
Corresponds to viMoveIn32* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param extended: Use 64 bits offset independent of the platform.
:return: Data read from the bus, return value of the library call.
:rtype: list, :class:`pyvisa.constants.StatusCode`
|
def move_in_32(library, session, space, offset, length, extended=False):
"""Moves an 32-bit block of data from the specified address space and offset to local memory.
Corresponds to viMoveIn32* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param extended: Use 64 bits offset independent of the platform.
:return: Data read from the bus, return value of the library call.
:rtype: list, :class:`pyvisa.constants.StatusCode`
"""
buffer_32 = (ViUInt32 * length)()
if extended:
ret = library.viMoveIn32Ex(session, space, offset, length, buffer_32)
else:
ret = library.viMoveIn32(session, space, offset, length, buffer_32)
return list(buffer_32), ret
|
Moves an 64-bit block of data from the specified address space and offset to local memory.
Corresponds to viMoveIn64* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param extended: Use 64 bits offset independent of the platform.
:return: Data read from the bus, return value of the library call.
:rtype: list, :class:`pyvisa.constants.StatusCode`
|
def move_in_64(library, session, space, offset, length, extended=False):
"""Moves an 64-bit block of data from the specified address space and offset to local memory.
Corresponds to viMoveIn64* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param extended: Use 64 bits offset independent of the platform.
:return: Data read from the bus, return value of the library call.
:rtype: list, :class:`pyvisa.constants.StatusCode`
"""
buffer_64 = (ViUInt64 * length)()
if extended:
ret = library.viMoveIn64Ex(session, space, offset, length, buffer_64)
else:
ret = library.viMoveIn64(session, space, offset, length, buffer_64)
return list(buffer_64), ret
|
Moves a block of data from local memory to the specified address space and offset.
Corresponds to viMoveOut* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param data: Data to write to bus.
:param width: Number of bits to read per element.
:param extended: Use 64 bits offset independent of the platform.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def move_out(library, session, space, offset, length, data, width, extended=False):
"""Moves a block of data from local memory to the specified address space and offset.
Corresponds to viMoveOut* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param data: Data to write to bus.
:param width: Number of bits to read per element.
:param extended: Use 64 bits offset independent of the platform.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
if width == 8:
return move_out_8(library, session, space, offset, length, data, extended)
elif width == 16:
return move_out_16(library, session, space, offset, length, data, extended)
elif width == 32:
return move_out_32(library, session, space, offset, length, data, extended)
elif width == 64:
return move_out_64(library, session, space, offset, length, data, extended)
raise ValueError('%s is not a valid size. Valid values are 8, 16, 32 or 64' % width)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.