Commit 0df6c264 authored by Tammo Jan Dijkema's avatar Tammo Jan Dijkema
Browse files

Handle unexpected input from serial port

parent 283e9ba7
......@@ -14,18 +14,26 @@ except ImportError:
class GPIBProtocol(serial.threaded.LineReader):
"""Implementation of the GPIB protocol"""
"""Implementation of the GPIB protocol
Attrs:
_lock (Lock): lock for writing to the serial device
responses (Queue): queue for all input from the serial port
_waiting_for_response (bool): toggle to exclude 'unwanted' serial input. This attribute is
only written and read from when _lock is in place; this should make it thread-safe.
"""
TERMINATOR = b'\n'
def __init__(self):
super(GPIBProtocol, self).__init__()
self.responses = queue.Queue()
self.lock = threading.Lock()
self._lock = threading.Lock()
self._waiting_for_response = False
def init_hpib(self):
"""Execute some setup commands for the HPIB system"""
with self.lock:
with self._lock:
self.write_line("++savecfg 0")
self.write_line("++auto 0")
self.write_line("++eoi 1")
......@@ -50,8 +58,8 @@ class GPIBProtocol(serial.threaded.LineReader):
Raises:
RuntimeError: if no response was received to a query.
"""
with self.lock:
assert(responses.empty())
with self._lock:
assert(self.responses.empty())
if address:
self.write_line("++addr {:d}".format(address))
......@@ -60,6 +68,7 @@ class GPIBProtocol(serial.threaded.LineReader):
self.write_line("loc {:d}".format(address))
if "?" in command:
self._waiting_for_response = True
self.write_line("++read eoi")
# The command was a query, wait for response
try:
......@@ -67,10 +76,14 @@ class GPIBProtocol(serial.threaded.LineReader):
except queue.Empty:
raise RuntimeError("HPIB device at address did not respond " +
"to query \"{}\"".format(command))
self._waiting_for_response = False
return line
else:
pass
def handle_line(self, line):
"""Handle input from serial port, put it in the queue"""
self.responses.put(line)
if self._waiting_for_response:
self.responses.put(line)
else:
print("Received unexpected input from serial:", line)
......@@ -49,8 +49,7 @@ class TestGPIBProtocol(unittest.TestCase):
self.assertEqual(call_list[1], call(b"++read eoi\n"))
def test_command_query_with_response(self):
# Put the response in the queue before asking for it
self.command_thread.protocol.responses.put("1420000000")
# TODO: patch Queue.get to return "1420000000"
response = self.command_thread.protocol.command("freq?")
call_list = self.serial_mock.write.call_args_list
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment