| 1 |
# |
| 2 |
# This file is part of the PyMeasure package. |
| 3 |
# |
| 4 |
# Copyright (c) 2013-2024 PyMeasure Developers |
| 5 |
# |
| 6 |
# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 7 |
# of this software and associated documentation files (the "Software"), to deal |
| 8 |
# in the Software without restriction, including without limitation the rights |
| 9 |
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 10 |
# copies of the Software, and to permit persons to whom the Software is |
| 11 |
# furnished to do so, subject to the following conditions: |
| 12 |
# |
| 13 |
# The above copyright notice and this permission notice shall be included in |
| 14 |
# all copies or substantial portions of the Software. |
| 15 |
# |
| 16 |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 17 |
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 18 |
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 19 |
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 20 |
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 21 |
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 22 |
# THE SOFTWARE. |
| 23 |
# |
| 24 |
|
| 25 |
import logging |
| 26 |
from unittest.mock import MagicMock |
| 27 |
from warnings import warn |
| 28 |
|
| 29 |
from .adapter import Adapter |
| 30 |
|
| 31 |
log = logging.getLogger(__name__) |
| 32 |
log.addHandler(logging.NullHandler()) |
| 33 |
|
| 34 |
|
| 35 |
def to_bytes(command): |
| 36 |
"""Change `command` to a bytes object""" |
| 37 |
if isinstance(command, (bytes, bytearray)): |
| 38 |
return command |
| 39 |
elif command is None: |
| 40 |
return None |
| 41 |
elif isinstance(command, str): |
| 42 |
return command.encode("utf-8") |
| 43 |
elif isinstance(command, (list, tuple)): |
| 44 |
return bytes(command) |
| 45 |
elif isinstance(command, (int, float)): |
| 46 |
return str(command).encode("utf-8") |
| 47 |
raise TypeError(f"Invalid input of type {type(command).__name__}.") |
| 48 |
|
| 49 |
|
| 50 |
class ProtocolAdapter(Adapter): |
| 51 |
""" Adapter class for testing the command exchange protocol without instrument hardware. |
| 52 |
|
| 53 |
This adapter is primarily meant for use within :func:`pymeasure.test.expected_protocol()`. |
| 54 |
|
| 55 |
The :attr:`connection` attribute is a :class:`unittest.mock.MagicMock` such |
| 56 |
that every call returns. If you want to set a return value, you can use |
| 57 |
:code:`adapter.connection.some_method.return_value = 7`, |
| 58 |
such that a call to :code:`adapter.connection.some_method()` will return `7`. |
| 59 |
Similarly, you can verify that this call to the connection method happened |
| 60 |
with :code:`assert adapter.connection.some_method.called is True`. |
| 61 |
You can specify dictionaries with return values of attributes and methods. |
| 62 |
|
| 63 |
:param list comm_pairs: List of "reference" message pair tuples. The first element is |
| 64 |
what is sent to the instrument, the second one is the returned message. |
| 65 |
'None' indicates that a pair member (write or read) does not exist. |
| 66 |
The messages do **not** include the termination characters. |
| 67 |
:param connection_attributes: Dictionary of connection attributes and their values. |
| 68 |
:param connection_methods: Dictionary of method names of the connection and their return values. |
| 69 |
""" |
| 70 |
|
| 71 |
def __init__(self, comm_pairs=None, preprocess_reply=None, |
| 72 |
connection_attributes=None, |
| 73 |
connection_methods=None, |
| 74 |
**kwargs): |
| 75 |
"""Generate the adapter and initialize internal buffers.""" |
| 76 |
super().__init__(preprocess_reply=preprocess_reply, **kwargs) |
| 77 |
# Setup communication |
| 78 |
if comm_pairs is None: |
| 79 |
comm_pairs = [] |
| 80 |
assert isinstance(comm_pairs, (list, tuple)), ( |
| 81 |
"Parameter comm_pairs has to be a list or tuple.") |
| 82 |
for pair in comm_pairs: |
| 83 |
if len(pair) != 2: |
| 84 |
raise ValueError(f'Comm_pairs element {pair} does not have two elements!') |
| 85 |
self._read_buffer = None |
| 86 |
self._write_buffer = None |
| 87 |
self.comm_pairs = comm_pairs |
| 88 |
self._index = 0 |
| 89 |
# Setup attributes |
| 90 |
self._setup_connection(connection_attributes, connection_methods) |
| 91 |
|
| 92 |
def _setup_connection(self, connection_attributes, connection_methods): |
| 93 |
self.connection = MagicMock() |
| 94 |
if connection_attributes is not None: |
| 95 |
for key, value in connection_attributes.items(): |
| 96 |
setattr(self.connection, key, value) |
| 97 |
if connection_methods is not None: |
| 98 |
for key, value in connection_methods.items(): |
| 99 |
getattr(self.connection, key).return_value = value |
| 100 |
|
| 101 |
def _write(self, command, **kwargs): |
| 102 |
"""Compare the command with the expected one and fill the read.""" |
| 103 |
self._write_bytes(to_bytes(command)) |
| 104 |
assert self._write_buffer is None, ( |
| 105 |
f"Written bytes '{self._write_buffer}' do not match expected " |
| 106 |
f"'{self.comm_pairs[self._index][0]}'.") |
| 107 |
|
| 108 |
def _write_bytes(self, content, **kwargs): |
| 109 |
"""Write the bytes `content`. If a command is full, fill the read.""" |
| 110 |
if self._write_buffer is None: |
| 111 |
self._write_buffer = content |
| 112 |
else: |
| 113 |
self._write_buffer += content |
| 114 |
try: |
| 115 |
p_write, p_read = self.comm_pairs[self._index] |
| 116 |
except IndexError: |
| 117 |
raise ValueError(f"No communication pair left to write {content}.") |
| 118 |
if self._write_buffer == to_bytes(p_write): |
| 119 |
assert self._read_buffer is None, ( |
| 120 |
f"Unread response '{self._read_buffer}' present when writing. " |
| 121 |
"Maybe a property's 'check_set_errors' is not accounted for, " |
| 122 |
"a read() call is missing in a method, or the defined protocol is incorrect?" |
| 123 |
) |
| 124 |
# Clear the write buffer |
| 125 |
self._write_buffer = None |
| 126 |
self._read_buffer = to_bytes(p_read) |
| 127 |
self._index += 1 |
| 128 |
# If _write_buffer does _not_ agree with p_write, this is not cause for |
| 129 |
# concern, because you can in principle compose a message over several writes. |
| 130 |
# It's not clear how relevant this is in real-world use, but it's analogous |
| 131 |
# to the possibility to fetch a (binary) message over several reads. |
| 132 |
|
| 133 |
def _read(self, **kwargs): |
| 134 |
"""Return an already present or freshly fetched read buffer as a string.""" |
| 135 |
return self._read_bytes(-1).decode("utf-8") |
| 136 |
|
| 137 |
def _read_bytes(self, count, break_on_termchar=False, **kwargs): |
| 138 |
"""Read `count` number of bytes from the buffer. |
| 139 |
|
| 140 |
:param int count: Number of bytes to read. If -1, return the buffer. |
| 141 |
""" |
| 142 |
if break_on_termchar: |
| 143 |
warn(("Breaking on termination character in `read_bytes` cannot be tested. " |
| 144 |
"You have to separate the message parts in the com_pairs."), |
| 145 |
UserWarning) |
| 146 |
if self._read_buffer is not None: |
| 147 |
if count == -1 or count >= len(self._read_buffer): |
| 148 |
read = self._read_buffer |
| 149 |
self._read_buffer = None |
| 150 |
else: |
| 151 |
read = self._read_buffer[:count] |
| 152 |
self._read_buffer = self._read_buffer[count:] |
| 153 |
return read |
| 154 |
else: |
| 155 |
try: |
| 156 |
p_write, p_read = self.comm_pairs[self._index] |
| 157 |
except IndexError: |
| 158 |
raise ValueError("No communication pair left for reading.") |
| 159 |
assert p_write is None, ( |
| 160 |
f"Written {self._write_buffer} do not match expected {p_write} prior to read." |
| 161 |
if self._write_buffer |
| 162 |
else "Unexpected read without prior write.") |
| 163 |
assert p_read is not None, "Communication pair cannot be (None, None)." |
| 164 |
self._index += 1 |
| 165 |
p_read = to_bytes(p_read) |
| 166 |
if count == -1 or count >= len(p_read): |
| 167 |
# _read_buffer is already empty, no action required. |
| 168 |
return p_read |
| 169 |
else: |
| 170 |
self._read_buffer = p_read[count:] |
| 171 |
return p_read[:count] |
| 172 |
|
| 173 |
def flush_read_buffer(self): |
| 174 |
""" Flush and discard the input buffer |
| 175 |
|
| 176 |
As detailed by pyvisa, discard the read buffer contents and if data was present |
| 177 |
in the read buffer and no END-indicator was present, read from the device until |
| 178 |
encountering an END indicator (which causes loss of data). |
| 179 |
""" |
| 180 |
self.connection.flush("pyvisa.constants.BufferOperation.discard_read_buffer") |