Tidied up closing a bit more

This commit is contained in:
Joel Collins 2019-07-16 14:51:11 +01:00
parent 2a7362b5e6
commit e6811f972f

View file

@ -83,32 +83,27 @@ class ExtensibleSerialInstrument(object):
#be set to 1 byte for maximum responsiveness. #be set to 1 byte for maximum responsiveness.
assert self.test_communications(), "The instrument doesn't seem to be responding. Did you specify the right port?" assert self.test_communications(), "The instrument doesn't seem to be responding. Did you specify the right port?"
def close_serial_communications(self):
"""
Close communication to the serial device. No exception handling.
"""
with self.communications_lock:
self._ser.close()
def close(self): def close(self):
"""Cleanly close the device. Includes proper logging statements.""" """Cleanly close the device. Includes proper logging statements."""
logging.debug("Closing serial connection") logging.debug("Closing serial connection")
try: with self.communications_lock:
self.close_serial_communications() try:
except Exception as e: self._ser.close()
logging.warning("The serial port didn't close cleanly: {}".format(e)) except Exception as e:
logging.debug("Connection closed") logging.warning("The serial port didn't close cleanly: {}".format(e))
logging.debug("Connection closed")
def __del__(self): def __del__(self):
"""Emergency close the device. Try to avoid having to use this.""" """Emergency close the device. Try to avoid having to use this."""
if hasattr(self, '_ser') and self._ser.isOpen(): if hasattr(self, '_ser') and self._ser.isOpen():
print( with self.communications_lock:
"Closing an open serial communication has been triggered by garbage collection!\n"\ print(
"Please close this device more sensibly in future.") "Closing an open serial communication has been triggered by garbage collection!\n"\
try: "Please close this device more sensibly in future.")
self.close_serial_communications() try:
except Exception as e: self._ser.close()
print("The serial port didn't close cleanly: {}".format(e)) except Exception as e:
print("The serial port didn't close cleanly: {}".format(e))
def __enter__(self): def __enter__(self):
return self return self